aboutsummaryrefslogtreecommitdiff
path: root/sword2/driver/render.cpp
blob: 63d3c84562892497cd84a78854c1d8d9d970656f (plain)
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
/* Copyright (C) 1994-2003 Revolution Software Ltd
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program 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.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * $Header$
 */

//=============================================================================
//
//	Filename	:	render.c
//	Created		:	26th September 1996
//	By			:	P.R.Porter
//
//	Summary		:	This module holds the functions which deal with rendering
//					the background and parallax layers, and controlling the
//					speed of the scroll (number of frames)
//
//	Version	Date		By		Description
//	------- ---------	---		-----------------------------------------------
//	1.0		26-Sep-96	PRP		The functions have been moved here from d_draw
//								because this is a more sensible place for them.
//
//	1.1		04-Oct-96	PRP		Added direct path to ddraw.h
//
//	1.2		09-Oct-96	PRP		Moved SOFTWARE_SCREEN_BUFFER into driver96.h,
//								and renamed to RD_SOFTWARESCREENBUFFER.
//
//	1.3		23-Oct-96	PRP		Moved definition of _parallaxLine structure to
//								render.h.  Got rid of the divide by zero error.
//
//	1.4		05-Nov-96	PRP		Moved defines of RENDERWIDE, RENDERDEEP, etc.,
//								to render.h
//
//	1.5		15-Nov-96	PRP		Definition of menu size is now obtained from
//								menu.h
//
//	1.6		18-Nov-96	PRP		Changed the direct draw interface to
//								IDirectDraw2.  Added the PlotPoint and 
//								DrawLine functions.
//
//	1,7		21-Nov-96	PRP		Implemented the DrawLine function.
//
//	1.8		24-Jan-97	PRP		Added parallaxScrollx and parallaxScrolly to 
//								define the offset for linking sprites to 
//								parallax layers.
//
//	1.9		06-Feb-97	PRP		Added rendering functions to draw from display
//								memory.  Made the code switchable so that if
//								the hardware is not available, the old software
//								rendering functions are used.
//
//	1.10	06-Feb-97	PRP		Fixed a bug with releasing the surfaces for a
//								room.
//
//	1.11	06-Feb-97	PRP		Implemented PlotPoint and DrawLine for hardware
//								version.
//
//	1.12	07-Feb-97	PRP		Implemented function to restore the background
//								layers.  Changed the layer rendering code to 
//								restore the layers when they've gone.
//
//	1.13	07-Feb-97	PRP		Fixed a bug in the layer renderer, which
//								dropped out when the first block in a layer was
//								blank.
//
//	1.14	10-Feb-97	PRP		Changed the calls to the direct draw error 
//								reporting code, and made the rendering dependant
//								upon the hardware functions availability.
//
//	1.15	12-Feb-97	PRP		Fixed rendering position bug.
//
//	1.16	18-Mar-97	PRP		Fixed the smooth scroll, and render timing.
//								Added a function to initialise the render timer
//
//	1.17	18-Mar-97	PRP		Added code to profile the rendering functions.
//
//	1.18	04-Apr-97	PRP		Restored the primary surface and back buffer
//								before the parallax layers.
//
//	1.19	07-Apr-97	PRP		No changes.
//
//	1.20	08-Apr-97	JEL		Made location wide and location deep global.
//
//	1.21	10-Apr-97	PRP		Added the return value RDERR_LOCKFAILED to 
//								the CopyScreenBuffer function.
//
//	1.22	11-Apr-97	PRP		Added function to clear the software render
//								buffer.
//
//	1.23	11-Apr-97	PRP		Fixed benign redefinition of type bug
//
//	1.24	13-Jun-97	PRP		Fixed switching between hardware and software
//								rendering during gameplay.
//
//	1.25	30-Jun-97	JEL		Tried to fix sc23 sprite position bug, but no changes made in the end
//
//	1.26	08-July-97	JEL		Fixed bug in RenderParallax for when not gotTheFocus, to prevent crash when switching task in NT
//
//	Functions
//	---------
//
//	---------------------------------------------------------------------------
//	
//	int32 RenderParallax(_parallax *p, int16 layer)
//
//	Draws a parallax layer at the current position determined by the scroll.
//	A parallax can be either foreground, background or the main screen.
//
//	---------------------------------------------------------------------------
//
//	int32 CopyScreenBuffer(void)
//
//	Copies the screen buffer to screen memory.  This function should be called
//	when the drawing should be done to the back buffer.  It only does this
//	when we are using a software screen buffer.
//
//	---------------------------------------------------------------------------
//
//	int32 SetScrollTarget(int16 sx, int16 sy)
//
//	Sets the scroll target position for the end of the game cycle.  The drivers
//	will then automatically scroll as many times as it can to reach this 
//	position in the allotted time.
//
//	--------------------------------------------------------------------------
//
//	int32 StartRenderCycle(void)
//
//	This function should be called when the game engine is ready to start
//	the render cycle.
//
//	--------------------------------------------------------------------------
//
//	int32 EndRenderCycle(BOOL *end)
//
//	This function should be called at the end of the render cycle.  If the
//	render cycle is to be terminated, the function sets *end to 1.  Otherwise,
//	the render cycle should continue.
//
//	--------------------------------------------------------------------------
//
//	int32 SetLocationMetrics(uint16 w, uint16 h)
//
//	This function tells the drivers the size of the background screen for the
//	current location.
//
//	--------------------------------------------------------------------------
//
//	int32 PlotPoint(uint16 x, uint16 y, uint8 colour)
//
//	Plots the point x,y in relation to the top left corner of the background.
//
//	--------------------------------------------------------------------------
//
//	int32 DrawLine(int16 x1, int16 y1, int16 x2, int16 y2, uint8 colour)
//
//	Draws a line from the point x1,y1 to x2,y2 of the specified colour.
//
//	--------------------------------------------------------------------------
//
//	int32 InitialiseBackgroundLayer(_parallax *p)
//
//	This function should be called five times with either the parallax layer
//	or a NULL pointer in order of background parallax to foreground parallax.
//
//	--------------------------------------------------------------------------
//
//	int32 CloseBackgroundLayer(void)
//
//	Should be called once after leaving a room to free up video memory.
//
//	--------------------------------------------------------------------------
//
//	int32 PlotDots(int16 x, int16 y, int16 count)
//
//	Plots 'count' dots at the position x,y.
//
//=============================================================================




#define WIN32_LEAN_AND_MEAN

//#include <windows.h>
//#include <windowsx.h>
//#include <mmsystem.h>
#include <stdio.h>

//#include "ddraw.h"

#include "stdafx.h"
#include "driver96.h"
#include "d_draw.h"
#include "rdwin.h"
#include "_mouse.h"
#include "render.h"
#include "menu.h"
#include "../sword2.h"



#define MILLISECSPERCYCLE 83



#if PROFILING == 1
int32 profileCopyScreenBuffer = 0;
int32 profileRenderLayers = 0;
int32 profileSpriteRender = 0;
int32 profileDecompression = 0;
#endif




uint8 myScreenBuffer[RENDERWIDE * RENDERDEEP];





// Scroll variables.  scrollx and scrolly hold the current scroll position, 
//	and scrollxTarget and scrollyTarget are the target position for the end
//	of the game cycle.

//int16		scrollx;
//int16		scrolly;
extern int16		scrollx;
extern int16		scrolly;
int16			parallaxScrollx;
int16			parallaxScrolly;
int16	locationWide;
int16	locationDeep;

static	int16	scrollxTarget;
static	int16	scrollyTarget;
static	int16	scrollxOld;
static	int16	scrollyOld;
static	uint16	layer = 0;



#define RENDERAVERAGETOTAL 4
int32 renderCountIndex = 0;
int32 renderTimeLog[RENDERAVERAGETOTAL] = {60, 60, 60, 60};
int32 initialTime;
int32 startTime;
int32 originTime;
int32 totalTime;
int32 renderAverageTime = 60;
int32 framesPerGameCycle;
int32 renderTooSlow;




#define BLOCKWIDTH 64
#define BLOCKHEIGHT 64
#define BLOCKWBITS 6
#define BLOCKHBITS 6
#define MAXLAYERS 5

uint8 xblocks[MAXLAYERS];
uint8 yblocks[MAXLAYERS];
uint8 restoreLayer[MAXLAYERS];

// Each layer is composed by several sub-blocks

Surface **blockSurfaces[MAXLAYERS] = { 0, 0, 0, 0, 0 };



void Surface::clear() {
	memset(_pixels, 0, _width * _height);
	g_sword2->_system->copy_rect(_pixels, _width, 0, 0, _width, _height);
}

void Surface::blit(Surface *s, ScummVM::Rect *r) {
	ScummVM::Rect clip_rect;

	clip_rect.left = 0;
	clip_rect.top = 0;
	clip_rect.right = 640;
	clip_rect.bottom = 480;

	blit(s, r, &clip_rect);
}

void Surface::blit(Surface *s, ScummVM::Rect *r, ScummVM::Rect *clip_rect) {
	if (r->top > clip_rect->bottom || r->left > clip_rect->right || r->bottom <= clip_rect->top || r->right <= clip_rect->left)
		return;

	byte *src = s->_pixels;

	if (r->top < clip_rect->top) {
		src -= s->_width * (r->top - clip_rect->top);
		r->top = clip_rect->top;
	}
	if (r->left < clip_rect->left) {
		src -= (r->left - clip_rect->left);
		r->left = clip_rect->left;
	}
	if (r->bottom > clip_rect->bottom)
		r->bottom = clip_rect->bottom;
	if (r->right > clip_rect->right)
		r->right = clip_rect->right;

	byte *dst = _pixels + r->top * _width + r->left;
	int i, j;

	// FIXME: We first render the data to the back buffer, and then copy
	// it to the backend. Since the same area will probably be copied
	// several times, as each new parallax layer is rendered, this may be
	// a bit inefficient.

	if (s->_colorKey >= 0) {
		for (i = 0; i < r->bottom - r->top; i++) {
			for (j = 0; j < r->right - r->left; j++) {
				if (src[j] != s->_colorKey)
					dst[j] = src[j];
			}
			src += s->_width;
			dst += _width;
		}
	} else {
		for (i = 0; i < r->bottom - r->top; i++) {
			memcpy(dst, src, r->right - r->left);
			src += s->_width;
			dst += _width;
		}
	}

	g_sword2->_system->copy_rect(_pixels + r->top * _width + r->left, _width, r->left, r->top, r->right - r->left, r->bottom - r->top);
}



int32 RestoreBackgroundLayer(_parallax *p, int16 l)
{
	int16 oldLayer = layer;
	int16 i;

	debug(0, "RestoreBackgroundLayer %d", l);

	layer = l;
	if (blockSurfaces[l]) {
		for (i = 0; i < xblocks[l] * yblocks[l]; i++)
			if (blockSurfaces[l][i])
				delete blockSurfaces[l][i];

		free(blockSurfaces[l]);
		blockSurfaces[l] = NULL;
	}
	RestoreSurfaces();
	InitialiseBackgroundLayer(p);
	layer = oldLayer;

/*
	int16 oldLayer = layer;
	int16 i;

	layer = l;
	if (blockSurfaces[l])
	{
		for (i=0; i<xblocks[l] * yblocks[l]; i++)
			if (*(blockSurfaces[l]+i))
				IDirectDrawSurface2_Release(*(blockSurfaces[l] + i));
		free(blockSurfaces[l]);
		blockSurfaces[l] = NULL;
	}
	RestoreSurfaces();
	InitialiseBackgroundLayer(p);
	layer = oldLayer;
*/
	return(RD_OK);

}






int32 PlotPoint(uint16 x, uint16 y, uint8 colour)

{
	warning("stub PlotPoint( %d, %d, %d )", x, y, colour);
/*
	int16 newx, newy;
	
	newx = x - scrollx;
	newy = y - scrolly;

	if ((newx < 0) || (newx > RENDERWIDE) || (newy < 0) || (newy > RENDERDEEP))
	{
		return(RD_OK);
	}
	if (renderCaps & RDBLTFX_ALLHARDWARE)
	{
		DDSURFACEDESC ddsd;
		HRESULT hr;

		ddsd.dwSize = sizeof(DDSURFACEDESC);
		hr = IDirectDrawSurface2_Lock(lpBackBuffer, NULL, &ddsd, DDLOCK_SURFACEMEMORYPTR | DDLOCK_WAIT, NULL);
		if (hr != DD_OK)
		{
			RestoreSurfaces();
			hr = IDirectDrawSurface2_Lock(lpBackBuffer, NULL, &ddsd, DDLOCK_SURFACEMEMORYPTR | DDLOCK_WAIT, NULL);
		}

		if (hr == DD_OK)
		{

			*((uint8 *) ddsd.lpSurface + (newy + 40) * ddsd.lPitch + newx) = colour;
			IDirectDrawSurface2_Unlock(lpBackBuffer, ddsd.lpSurface);
		}
	}
	else
		myScreenBuffer[newy * RENDERWIDE + newx] = colour;
*/	
	return(RD_OK);

}


// Uses Bressnham's incremental algorithm!
int32 DrawLine(int16 x0, int16 y0, int16 x1, int16 y1, uint8 colour)

{
	warning("stub DrawLine( %d, %d, %d, %d, %d )", x0, y0, x1, y1, colour);
/*
	int dx, dy;
	int dxmod, dymod;
	int ince, incne;
	int	d;
	int x, y;
	int addTo;
	DDSURFACEDESC ddsd;
	HRESULT hr;

	x1 -= scrollx;
	y1 -= scrolly;
	x0 -= scrollx;
	y0 -= scrolly;


	// Lock the surface if we're rendering to the back buffer.

	if (renderCaps & RDBLTFX_ALLHARDWARE)
	{
		ddsd.dwSize = sizeof(DDSURFACEDESC);
		hr = IDirectDrawSurface2_Lock(lpBackBuffer, NULL, &ddsd, DDLOCK_SURFACEMEMORYPTR | DDLOCK_WAIT, NULL);
		if (hr != DD_OK)
		{
			RestoreSurfaces();
			hr = IDirectDrawSurface2_Lock(lpBackBuffer, NULL, &ddsd, DDLOCK_SURFACEMEMORYPTR | DDLOCK_WAIT, NULL);
		}
		if (hr != DD_OK)
			return(RD_OK);

		(uint8 *) ddsd.lpSurface += (40 * ddsd.lPitch);

	}




	//Make sure we're going from left to right
	if (x1 < x0)
	{
		x = x1;
		x1 = x0;
		x0 = x;
		y = y1;
		y1 = y0;
		y0 = y;
	}
	dx = x1 - x0;
	dy = y1 - y0;
	
	if (dx < 0)
		dxmod = -dx;
	else
		dxmod = dx;

	if (dy < 0)
		dymod = -dy;
	else
		dymod = dy;

	if (dxmod >= dymod)
	{
		if (dy > 0)
		{
			d = 2 * dy - dx;
			ince = 2 * dy;
			incne = 2 * (dy - dx);
			x = x0;
			y = y0;
			if ((x >= 0) && (x < RENDERWIDE) && (y >= 0) && (y < RENDERDEEP))
				if (renderCaps & RDBLTFX_ALLHARDWARE)
					*((uint8 *) ddsd.lpSurface + y * ddsd.lPitch + x) = colour;
				else
					myScreenBuffer[y * RENDERWIDE + x] = colour;
			while (x < x1)
			{
				if (d <= 0)
				{
					d += ince;
					x += 1;
				}
				else
				{
					d += incne;
					x += 1;
					y += 1;
				}
				if ((x >= 0) && (x < RENDERWIDE) && (y >= 0) && (y < RENDERDEEP))
					if (renderCaps & RDBLTFX_ALLHARDWARE)
						*((uint8 *) ddsd.lpSurface + y * ddsd.lPitch + x) = colour;
					else
						myScreenBuffer[y * RENDERWIDE + x] = colour;
			}
		}
		else
		{
			addTo = y0;
			y0 = 0;
			y1 -= addTo;
			y1 = -y1;
			dy = y1 - y0;

			d = 2 * dy - dx;
			ince = 2 * dy;
			incne = 2 * (dy - dx);
			x = x0;
			y = y0;
			if ((x >= 0) && (x < RENDERWIDE) && (addTo - y >= 0) && (addTo - y < RENDERDEEP))
				if (renderCaps & RDBLTFX_ALLHARDWARE)
					*((uint8 *) ddsd.lpSurface + (addTo - y) * ddsd.lPitch + x) = colour;
				else
					myScreenBuffer[(addTo - y) * RENDERWIDE + x] = colour;
			while (x < x1)
			{
				if (d <= 0)
				{
					d += ince;
					x += 1;
				}
				else
				{
					d += incne;
					x += 1;
					y += 1;
				}
				if ((x >= 0) && (x < RENDERWIDE) && (addTo - y >= 0) && (addTo - y < RENDERDEEP))
					if (renderCaps & RDBLTFX_ALLHARDWARE)
						*((uint8 *) ddsd.lpSurface + (addTo - y) * ddsd.lPitch + x) = colour;
					else
						myScreenBuffer[(addTo - y) * RENDERWIDE + x] = colour;
			}

		}
	}
	else
	{
		//OK, y is now going to be the single increment.
		//	Ensure the line is going top to bottom
		if (y1 < y0)
		{
			x = x1;
			x1 = x0;
			x0 = x;
			y = y1;
			y1 = y0;
			y0 = y;
		}
		dx = x1 - x0;
		dy = y1 - y0;

		if (dx > 0)
		{
			d = 2 * dx - dy;
			ince = 2 * dx;
			incne = 2 * (dx - dy);
			x = x0;
			y = y0;
			if ((x >= 0) && (x < RENDERWIDE) && (y >= 0) && (y < RENDERDEEP))
				if (renderCaps & RDBLTFX_ALLHARDWARE)
					*((uint8 *) ddsd.lpSurface + y * ddsd.lPitch + x) = colour;
				else
					myScreenBuffer[y * RENDERWIDE + x] = colour;
			while (y < y1)
			{
				if (d <= 0)
				{
					d += ince;
					y += 1;
				}
				else
				{
					d += incne;
					x += 1;
					y += 1;
				}
				if ((x >= 0) && (x < RENDERWIDE) && (y >= 0) && (y < RENDERDEEP))
					if (renderCaps & RDBLTFX_ALLHARDWARE)
						*((uint8 *) ddsd.lpSurface + y * ddsd.lPitch + x) = colour;
					else
						myScreenBuffer[y * RENDERWIDE + x] = colour;
			}
		}
		else
		{
			addTo = x0;
			x0 = 0;
			x1 -= addTo;
			x1 = -x1;
			dx = x1 - x0;

			d = 2 * dx - dy;
			ince = 2 * dx;
			incne = 2 * (dx - dy);
			x = x0;
			y = y0;
			if ((addTo - x >= 0) && (addTo - x < RENDERWIDE) && (y >= 0) && (y < RENDERDEEP))
				if (renderCaps & RDBLTFX_ALLHARDWARE)
					*((uint8 *) ddsd.lpSurface + y * ddsd.lPitch + addTo - x) = colour;
				else
					myScreenBuffer[y * RENDERWIDE + addTo - x] = colour;
			while (y < y1)
			{
				if (d <= 0)
				{
					d += ince;
					y += 1;
				}
				else
				{
					d += incne;
					x += 1;
					y += 1;
				}
				if ((addTo - x >= 0) && (addTo - x < RENDERWIDE) && (y >= 0) && (y < RENDERDEEP))
					if (renderCaps & RDBLTFX_ALLHARDWARE)
						*((uint8 *) ddsd.lpSurface + y * ddsd.lPitch + addTo - x) = colour;
					else
						myScreenBuffer[y * RENDERWIDE + addTo - x] = colour;
			}

		}

	}

	if (renderCaps & RDBLTFX_ALLHARDWARE)
	{
		(uint8 *) ddsd.lpSurface -= (40 * ddsd.lPitch);
		IDirectDrawSurface2_Unlock(lpBackBuffer, ddsd.lpSurface);
	}
*/
	return(RD_OK);

}



int32 SetLocationMetrics(uint16 w, uint16 h)

{

	locationWide = w;
	locationDeep = h;

	return(RD_OK);

}



int32 RenderParallax(_parallax *p, int16 l) {
	int16 x, y;
	int16 i, j;
	ScummVM::Rect r;

	debug(0, "RenderParallax %d", l);

	if (locationWide == screenWide)
		x = 0;
	else
		x = ((int32) ((p->w - screenWide) * scrollx) / (int32) (locationWide - screenWide));

	if (locationDeep == (screenDeep - MENUDEEP * 2))
		y = 0;
	else
		y = ((int32) ((p->h - (screenDeep - MENUDEEP * 2)) * scrolly) / (int32) (locationDeep - (screenDeep - MENUDEEP * 2)));

	ScummVM::Rect clip_rect;

	// Leave enough space for the top and bottom menues

	clip_rect.left = 0;
	clip_rect.right = 640;
	clip_rect.top = 40;
	clip_rect.bottom = 440;

	for (j = 0; j < yblocks[l]; j++) {
		for (i = 0; i < xblocks[l]; i++) {
			if (blockSurfaces[l][i + j * xblocks[l]]) {
				r.left = i * BLOCKWIDTH - x;
				r.right = r.left + BLOCKWIDTH;
				r.top = j * BLOCKHEIGHT - y + 40;
				r.bottom = r.top + BLOCKHEIGHT;
				lpBackBuffer->blit(blockSurfaces[l][i + j * xblocks[l]], &r, &clip_rect);
			}
		}
	}

	parallaxScrollx = scrollx - x;
	parallaxScrolly = scrolly - y;

/*

#if PROFILING == 1

	long int startTime, endTime;

	QueryPerformanceCounter(&startTime);

#endif

	if ((renderCaps & RDBLTFX_ALLHARDWARE) || ((renderCaps & RDBLTFX_FGPARALLAX) && (l > 2)))
	{

		int16 x, y;
		int16 i, j;
		int16 restoreSurfaces = 0;
		HRESULT hr = 0;
		RECT r, rd;

		if (restoreLayer[l])
		{
			RestoreBackgroundLayer(p, l);
			restoreLayer[l] = 0;
		}

		if (locationWide == screenWide)
			x = 0;
		else
			x = ((int32) ((p->w - screenWide) * scrollx) / (int32) (locationWide - screenWide));

		if (locationDeep == (screenDeep - MENUDEEP*2))
			y = 0;
		else
			y = ((int32) ((p->h - (screenDeep - MENUDEEP*2)) * scrolly) / (int32) (locationDeep - (screenDeep - MENUDEEP*2)));


		while (TRUE)
		{
			j = 0;
			while (j < yblocks[l])
			{
				i = 0;
				while (i < xblocks[l])
				{
 					if (*(blockSurfaces[l] + i + j * xblocks[l]))
					{
						r.left = i * BLOCKWIDTH - x;
						r.right = r.left + BLOCKWIDTH;
						r.top = j * BLOCKHEIGHT - y + 40;
						r.bottom = r.top + BLOCKHEIGHT;
						rd.left = 0;
						rd.right = BLOCKWIDTH;
						rd.top = 0;
						rd.bottom = BLOCKHEIGHT;

						if ((r.left < 0) && (r.left > 0 - BLOCKWIDTH))
						{
							rd.left = 0 - r.left;
							r.left = 0;
						}
						if ((r.top < 40) && (r.top > 40 - BLOCKHEIGHT))
						{
							rd.top = 40 - r.top;
							r.top = 40;
						}
						if ((r.right > 640) && (r.right < 640 + BLOCKWIDTH))
						{
							rd.right = BLOCKWIDTH - (r.right - 640);
							r.right = 640;
						}
						if ((r.bottom > 440) && (r.bottom < 440 + BLOCKHEIGHT))
						{
							rd.bottom = BLOCKHEIGHT - (r.bottom - 440);
							r.bottom = 440;
						}
						hr = IDirectDrawSurface2_Blt(lpBackBuffer, &r, *(blockSurfaces[l] + i + j * xblocks[l]), &rd, DDBLT_WAIT | DDBLT_KEYSRC, NULL);
						if (hr == DDERR_INVALIDRECT)
							hr = 0;
						if (hr)
							break;
					}
					i++;
					if (hr)
						break;
				}
				j++;
				if (hr)
					break;
			}
			if (hr)
			{
				if (hr == DDERR_SURFACELOST)
				{
					if (gotTheFocus)
					{
						if (++restoreSurfaces == 4)
							return(RDERR_RESTORELAYERS);
						else
							RestoreBackgroundLayer(p, l);
					}
					else
						return(RD_OK);
				}
				else
					return(hr);

			}
			else
				break;
		}

		parallaxScrollx = scrollx - x;
		parallaxScrolly = scrolly - y;
	}
	else
	{
		uint8			zeros;
		uint16			count;
		uint16			skip;
		uint16			i, j;
		uint16			x;
		int32			px, py;
		uint8			*data;
		uint8			*dst;
		_parallaxLine	*line;

		if (locationWide == screenWide)
			px = 0;
		else
			px = ( (int32) ((p->w - screenWide) * scrollx) / (int32) (locationWide - screenWide));

		if (locationDeep == (screenDeep - MENUDEEP*2))
			py = 0;
		else
			py = ( (int32) ((p->h - (screenDeep - MENUDEEP*2)) * scrolly) / (int32) (locationDeep - (screenDeep - MENUDEEP*2)));


		for (i = py; i < py + (screenDeep - MENUDEEP * 2); i++)
		{
			if (p->offset[i] == 0)
				continue;

			line = (_parallaxLine *) ((uint8 *) p + p->offset[i]);
			data = (uint8 *) line + sizeof(_parallaxLine);
			x = line->offset;
			if (x > px)
				skip = x - px;
			else
				skip = 0;

			dst = myScreenBuffer + (i - py) * RENDERWIDE + skip;

			
			zeros = 0;
			if (line->packets == 0)
			{
				data += px;
				memcpy(dst, data, screenWide);
				continue;
			}

			for (j=0; j<line->packets; j++)
			{
				if (zeros)
				{
					if (x >= px)
					{
						dst += *data;
						x += *data;
					}
					else
					{
						x += *data;
						if (x > px)
						{
							dst += (x - px);
						}
					}
					data += 1;
					zeros = 0;
				}
				else
				{
					if (*data == 0)
					{
						data ++;
					}
					else if (x >= px)
					{
						if (x + *data <= px + screenWide)
						{
							count = *data++;
							memcpy(dst, data, count);
							data += count;
							dst += count;
							x += count;
						}
						else if (x < px + screenWide)
						{
							data++;
							count = screenWide - (x - px);
							memcpy(dst, data, count);
							j = line->packets;
						}
					}
					else
					{
						count = *data++;

						if (x + count > px)
						{
							skip = px - x;
							data += skip;
							count -= skip;
							memcpy(dst, data, count);
							data += count;
							dst += count;
							x += count + skip;
						}
						else
						{
							data += count;
							x += count;
							if (x > px)
							{
								dst += (x - px);
							}
						}
					}
					zeros = 1;
				}
			}
		}

		parallaxScrollx = scrollx - px;
		parallaxScrolly = scrolly - py;
	}

#if PROFILING == 1
	QueryPerformanceCounter(&endTime);
	profileRenderLayers += (endTime.LowPart - startTime.LowPart);
#endif
*/
	return(RD_OK);

}






/*
#define LOGSIZE 10
int32 previousTimeLog[LOGSIZE];
int32 renderCycleStartLog[LOGSIZE];
int32 lastRenderTimeLog[LOGSIZE];
int32 renderCycleEndLog[LOGSIZE];
int32 timeLeftLog[LOGSIZE];
int32 scrollxOldLog[LOGSIZE];
int32 scrollxLog[LOGSIZE];
int32 scrollxTargetLog[LOGSIZE];


void LogMe(int32 in)
{
	static int32 i;

	if (in == 0)
		i = 0;

	previousTimeLog[i] = previousTime;
	aveRenderCycleLog[i] = aveRenderCycle;
	renderCycleStartLog[i] = renderCycleStart;
	lastRenderTimeLog[i] = lastRenderTime;
	renderCycleEndLog[i] = renderCycleEnd;
	timeLeftLog[i] = timeLeft;
	scrollxOldLog[i] = scrollxOld;
	scrollxLog[i] = scrollx;
	scrollxTargetLog[i] = scrollxTarget;
	
	if (++i == LOGSIZE)
		i = 0;

}
*/


int32 InitialiseRenderCycle(void)

{

	initialTime = SVM_timeGetTime();
	originTime = initialTime;
	totalTime = initialTime + MILLISECSPERCYCLE;

	return(RD_OK);

}



int32 StartRenderCycle(void)

{


	scrollxOld = scrollx;
	scrollyOld = scrolly;

	startTime = SVM_timeGetTime();

	if (startTime + renderAverageTime >= totalTime)
	{
		scrollx = scrollxTarget;
		scrolly = scrollyTarget;
		renderTooSlow = 1;
	}
	else
	{
		scrollx = (int16) (scrollxOld + ((scrollxTarget - scrollxOld) * (startTime - initialTime + renderAverageTime)) / (totalTime - initialTime));
		scrolly = (int16) (scrollyOld + ((scrollyTarget - scrollyOld) * (startTime - initialTime + renderAverageTime)) / (totalTime - initialTime));
		renderTooSlow = 0;
	}

	framesPerGameCycle = 0;

	return(RD_OK);

}



int32 EndRenderCycle(BOOL *end)

{

	int32 time;

	time = SVM_timeGetTime();
	renderTimeLog[renderCountIndex] = time - startTime;
	startTime += renderTimeLog[renderCountIndex];
	renderAverageTime = (renderTimeLog[0] + renderTimeLog[1] + renderTimeLog[2] + renderTimeLog[3]) >> 2;

	framesPerGameCycle += 1;

	if (++renderCountIndex == RENDERAVERAGETOTAL)
		renderCountIndex = 0;

	if (renderTooSlow)
	{
		*end = TRUE;
		InitialiseRenderCycle();
	}
	else if (startTime + renderAverageTime >= totalTime)
	{
		*end = TRUE;
		originTime = totalTime;
		totalTime += MILLISECSPERCYCLE;
		initialTime = time;
	}
	else
	{
		*end = FALSE;
		scrollx = (int16) (scrollxOld + ((scrollxTarget - scrollxOld) * (startTime - initialTime + renderAverageTime)) / (totalTime - initialTime));
		scrolly = (int16) (scrollyOld + ((scrollyTarget - scrollyOld) * (startTime - initialTime + renderAverageTime)) / (totalTime - initialTime));
	}

	return(RD_OK);

}


int32 SetScrollTarget(int16 sx, int16 sy)

{

	scrollxTarget = sx;
	scrollyTarget = sy;

	return(RD_OK);

}

int32 CopyScreenBuffer(void)

{
	debug(0, "CopyScreenBuffer");

	// FIXME: The backend should keep track of dirty rects, but I have a
	// feeling each one may be drawn several times, so we may have do add
	// our own handling of them instead.

	g_sword2->_system->update_screen();

/*

	uint8			*dst, *src;
	int16			i;
	DDSURFACEDESC	ddDescription;
	HRESULT			hr;

#if PROFILING == 1
	static long int	endTime;
	long int	startTime;
	int32					lastEndTime, profileTotalTime;
#endif


#if PROFILING == 1
	QueryPerformanceCounter(&startTime);
//	time = timeGetTime();
#endif


	if (!(renderCaps & RDBLTFX_ALLHARDWARE))
	{
		ddDescription.dwSize = sizeof(ddDescription);
		hr = IDirectDrawSurface2_Lock(lpBackBuffer, NULL, &ddDescription, DDLOCK_SURFACEMEMORYPTR | DDLOCK_WAIT, NULL);
		if (hr != DD_OK)
		{
			RestoreSurfaces();
			hr = IDirectDrawSurface2_Lock(lpBackBuffer, NULL, &ddDescription, DDLOCK_SURFACEMEMORYPTR | DDLOCK_WAIT, NULL);
		}
		if (hr == DD_OK)
		{
			dst = (uint8 *) ddDescription.lpSurface + MENUDEEP * ddDescription.lPitch;
			src = myScreenBuffer;
			for (i=0; i<RENDERDEEP; i++)
			{
				memcpy(dst, src, screenWide);
				src += RENDERWIDE;
				dst += ddDescription.lPitch;
			}
			IDirectDrawSurface2_Unlock(lpBackBuffer, ddDescription.lpSurface);
		}
		else
		{
			return(RDERR_LOCKFAILED);
		}
	}

#if PROFILING == 1
	lastEndTime = endTime.LowPart;
	QueryPerformanceCounter(&endTime);
	profileCopyScreenBuffer = (int32) (endTime.LowPart - startTime.LowPart) / 1000;
	profileTotalTime = (endTime.LowPart - lastEndTime) / 1000;
	if ((profileTotalTime > 0) && (profileTotalTime < 5000))
		PlotDots(0, 5, (int16) profileTotalTime);
	PlotDots(0, 10, (int16) profileCopyScreenBuffer);
	PlotDots(0, 15, (int16) (profileRenderLayers / 1000));
	PlotDots(0, 20, (int16) (profileSpriteRender / 1000));
	PlotDots(0, 25, (int16) (profileDecompression / 1000));
	profileRenderLayers = 0;
	profileSpriteRender = 0;
	profileDecompression = 0;
#endif
*/
	return(RD_OK);
}



int32 InitialiseBackgroundLayer(_parallax *p) {
	uint8 *memchunk;
	uint32 *quaddata;
	uint8 zeros;
	uint16 count;
	uint16 i, j, k;
	uint16 x;
	uint8 *data;
	uint8 *dst;
	_parallaxLine *line;

	debug(0, "InitialiseBackgroundLayer");

	// This function is called to re-initialise the layers if they have
	// been lost. We know this if the layers have already been assigned.

	// TODO: Can layers still be lost, or is that a DirectDraw-ism?

	if (layer == MAXLAYERS)
		CloseBackgroundLayer();

	if (!p) {
		layer++;
		return RD_OK;
	}

	xblocks[layer] = (p->w + BLOCKWIDTH - 1) >> BLOCKWBITS;
	yblocks[layer] = (p->h + BLOCKHEIGHT - 1) >> BLOCKHBITS;

	blockSurfaces[layer] = (Surface **) calloc(xblocks[layer] * yblocks[layer], sizeof(Surface *));
	if (!blockSurfaces[layer])
		return RDERR_OUTOFMEMORY;

	// Decode the parallax layer into a large chunk of memory

	memchunk = (uint8 *) malloc(xblocks[layer] * BLOCKWIDTH * yblocks[layer] * BLOCKHEIGHT);
	if (!memchunk)
		return RDERR_OUTOFMEMORY;

	// We clear not the entire memory chunk, but enough of it to store
	// the entire parallax layer.

	memset(memchunk, 0, p->w * p->h);

	for (i = 0; i < p->h; i++) {
		if (p->offset[i] == 0)
			continue;

		line = (_parallaxLine *) ((uint8 *) p + p->offset[i]);
		data = (uint8 *) line + sizeof(_parallaxLine);
		x = line->offset;

		dst = memchunk + i * p->w + x;

		zeros = 0;
		if (line->packets == 0)	{
			memcpy(dst, data, p->w);
			continue;
		}

		for (j = 0; j < line->packets; j++) {
			if (zeros) {
				dst += *data;
				x += *data;
				data++;
				zeros = 0;
			} else if (*data == 0) {
				data++;
				zeros = 1;
			} else {
				count = *data++;
				memcpy(dst, data, count);
				data += count;
				dst += count;
				x += count;
				zeros = 1;
			}
		}
	}

	// Now create the surfaces!

	for (i = 0; i < xblocks[layer] * yblocks[layer]; i++) {
		bool block_has_data = false;

		data = memchunk + (p->w * BLOCKHEIGHT * (i / xblocks[layer])) + BLOCKWIDTH * (i % xblocks[layer]);

		quaddata = (uint32 *) data;

		for (j = 0; j < BLOCKHEIGHT; j++) {
			for (k = 0; k < BLOCKWIDTH / 4; k++) {
				if (*quaddata) {
					block_has_data = true;
					goto bailout;
				}
				quaddata++;
			}
			quaddata += ((p->w - BLOCKWIDTH) / 4);
		}

bailout:

		//  Only assign a surface to the block if it contains data.

		if (block_has_data) {
			blockSurfaces[layer][i] = new Surface(BLOCKWIDTH, BLOCKHEIGHT);
			blockSurfaces[layer][i]->setColorKey(0);

			//  Copy the data into the surfaces.
			dst = blockSurfaces[layer][i]->_pixels;
			for (j = 0; j < BLOCKHEIGHT; j++) {
				memcpy(dst, data, BLOCKWIDTH);
				data += p->w;
				dst += BLOCKWIDTH;
			}
		} else
			blockSurfaces[layer][i] = NULL;
	}
	free(memchunk);
	layer++;

/*
	uint8			*memchunk;
	uint32			*quaddata;
	uint8			zeros;
	uint16			count;
//	uint16			skip;
	uint16			i, j, k;
	uint16			x;
	uint8			*data;
	uint8			*dst;
	_parallaxLine	*line;
	HRESULT			hr;
	DDSURFACEDESC	ddsd;


	if ((renderCaps & RDBLTFX_ALLHARDWARE) || ((renderCaps & RDBLTFX_FGPARALLAX) && (layer > 2)))
	{

		//  This function is called to re-initialise the layers if they have been lost.
		//	We know this if the layers have already been assigned.
		if (layer == MAXLAYERS)
		{
			CloseBackgroundLayer();
		//	RestoreSurfaces();		// for the primary and back buffer.
		}
		

		if (p == NULL)
		{
			layer += 1;
			return(RD_OK);
		}

		xblocks[layer] = (p->w + BLOCKWIDTH - 1) >> BLOCKWBITS;
		yblocks[layer] = (p->h + BLOCKHEIGHT - 1) >> BLOCKHBITS;
		blockSurfaces[layer] = (LPDIRECTDRAWSURFACE *) malloc(xblocks[layer] * yblocks[layer] * sizeof(LPDIRECTDRAWSURFACE));
		if (blockSurfaces[layer] == NULL)
			return(RDERR_OUTOFMEMORY);

		// Decode the parallax layer into a large chunk of memory
		memchunk = (uint8 *) malloc(xblocks[layer] * BLOCKWIDTH * yblocks[layer] * BLOCKHEIGHT);
		if (memchunk == NULL)
			return(RDERR_OUTOFMEMORY);
		
		memset(memchunk, 0, p->w * p->h);

		for (i = 0; i < p->h; i++)
		{
			if (p->offset[i] == 0)
				continue;

			line = (_parallaxLine *) ((uint8 *) p + p->offset[i]);
			data = (uint8 *) line + sizeof(_parallaxLine);
			x = line->offset;
			
			dst = memchunk + i * p->w + x;

			zeros = 0;
			if (line->packets == 0)
			{
				memcpy(dst, data, p->w);
				continue;
			}

			for (j=0; j<line->packets; j++)
			{
				if (zeros)
				{
					dst += *data;
					x += *data;
					data += 1;
					zeros = 0;
				}
				else
				{
					if (*data == 0)
					{
						data ++;
						zeros = 1;
					}
					else
					{
						count = *data++;
						memcpy(dst, data, count);
						data += count;
						dst += count;
						x += count;
						zeros = 1;
					}
				}
			}
		}

		// Now create the surfaces!
		memset(&ddsd, 0, sizeof(DDSURFACEDESC));
		ddsd.dwSize = sizeof(DDSURFACEDESC);
		ddsd.dwFlags = DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT;
		ddsd.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN;
		if (dxHalCaps & RDCAPS_SRCBLTCKEY)
			ddsd.ddsCaps.dwCaps |= DDSCAPS_VIDEOMEMORY;
		else
			ddsd.ddsCaps.dwCaps |= DDSCAPS_SYSTEMMEMORY;

		ddsd.dwWidth = BLOCKWIDTH;
		ddsd.dwHeight = BLOCKHEIGHT;
		for (i=0; i<xblocks[layer] * yblocks[layer]; i++)
		{
			//  Only assign a surface to the block if it contains data.
			quaddata = (int32 *) (memchunk + (p->w * BLOCKHEIGHT * (i / xblocks[layer])) + BLOCKWIDTH * (i % xblocks[layer]));
			for (j=0; j<BLOCKHEIGHT; j++)
			{
				for (k=0; k<BLOCKWIDTH / 4; k++)
				{
					if (*quaddata)
						break;
					quaddata++;
				}
				quaddata += ((p->w - BLOCKWIDTH) / 4);
				if (k < BLOCKWIDTH / 4)
					break;
			}
			
			if (k < BLOCKWIDTH / 4)
			{
				hr = IDirectDraw2_CreateSurface(lpDD2, &ddsd, blockSurfaces[layer] + i, NULL);
				if (hr != DD_OK)
				{
					if (hr == DDERR_OUTOFVIDEOMEMORY)
					{
						ddsd.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN | DDSCAPS_SYSTEMMEMORY;
						hr = IDirectDraw2_CreateSurface(lpDD2, &ddsd, blockSurfaces[layer] + i, NULL);
					}
					if (hr != DD_OK)
					{
						DirectDrawError("Cannot create parallax surface", hr);
						return(hr);
					}
				}
				//	Set the surface blt source colour key
				hr = IDirectDrawSurface2_SetColorKey(*(blockSurfaces[layer] + i), DDCKEY_SRCBLT, &blackColorKey);

				//  Copy the data into the surfaces.
				memset(&ddsd, 0, sizeof(DDSURFACEDESC));
				ddsd.dwSize = sizeof(DDSURFACEDESC);
				hr = IDirectDrawSurface2_Lock(*(blockSurfaces[layer] + i), NULL, &ddsd, DDLOCK_SURFACEMEMORYPTR | DDLOCK_WAIT, NULL);
				if (hr != DD_OK)
				{
					IDirectDrawSurface2_Restore(*(blockSurfaces[layer] + i));
					hr = IDirectDrawSurface2_Lock(*(blockSurfaces[layer] + i), NULL, &ddsd, DDLOCK_SURFACEMEMORYPTR | DDLOCK_WAIT, NULL);
					if (hr != DD_OK)
					{
						DirectDrawError("Cannot lock parallax surface", hr);
						return(hr);
					}
				}

				data = memchunk + (p->w * BLOCKHEIGHT * (i / xblocks[layer])) + BLOCKWIDTH * (i % xblocks[layer]);
				dst = ddsd.lpSurface;
				for (j=0; j<BLOCKHEIGHT; j++)
				{
					memcpy(dst, data, BLOCKWIDTH);
					data += p->w;
					dst += ddsd.lPitch;
				}
				IDirectDrawSurface2_Unlock(*(blockSurfaces[layer] + i), ddsd.lpSurface);
			}
			else
			{
				*(blockSurfaces[layer] + i) = NULL;
			}
		}
		free(memchunk);
	}
	layer += 1;
*/
	return(RD_OK);

}


int32 CloseBackgroundLayer(void)

{
	debug(0, "CloseBackgroundLayer");

	int16 i, j;

	for (j = 0; j < MAXLAYERS; j++) {
		if (blockSurfaces[j]) {
			for (i = 0; i < xblocks[j] * yblocks[j]; i++)
				if (blockSurfaces[j][i])
					delete blockSurfaces[j][i];
			free(blockSurfaces[j]);
		}
	}

	layer = 0;
/*
	int16			i, j;

//	if (renderCaps & RDBLTFX_ALLHARDWARE)
//	{
		for (j=0; j<MAXLAYERS; j++)
		{
			if (blockSurfaces[j])
			{
				for (i=0; i<xblocks[j] * yblocks[j]; i++)
					if (*(blockSurfaces[j]+i))
						IDirectDrawSurface2_Release(*(blockSurfaces[j] + i));
				free(blockSurfaces[j]);
				blockSurfaces[j] = NULL;
			}
		}
		layer = 0;
//	}
*/
	return(RD_OK);

}


int32 EraseSoftwareScreenBuffer(void)
{
	memset(myScreenBuffer, 0, RENDERWIDE * RENDERDEEP);
	return(RD_OK);
}