1 /* ScummVM - Graphic Adventure Engine
2  *
3  * ScummVM is the legal property of its developers, whose names
4  * are too numerous to list here. Please refer to the COPYRIGHT
5  * file distributed with this source distribution.
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11 
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16 
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20  *
21  */
22 
23 #include "startrek/iwfile.h"
24 #include "startrek/resource.h"
25 
26 namespace StarTrek {
27 
IWFile(StarTrekEngine * vm,const Common::String & filename)28 IWFile::IWFile(StarTrekEngine *vm, const Common::String &filename) {
29 	debug(6, "IW File: %s", filename.c_str());
30 
31 	_vm = vm;
32 
33 	Common::MemoryReadStreamEndian *file = _vm->_resource->loadFile(filename);
34 	_numEntries = file->readUint16();
35 
36 	assert(_numEntries < MAX_KEY_POSITIONS);
37 
38 	for (int i = 0; i < MAX_KEY_POSITIONS; i++) {
39 		int16 x = file->readUint16();
40 		int16 y = file->readUint16();
41 		_keyPositions[i] = Common::Point(x, y);
42 	}
43 
44 	for (int i = 0; i < _numEntries; i++) {
45 		file->read(_iwEntries[i], _numEntries);
46 	}
47 
48 	delete file;
49 }
50 
51 // FIXME: same issue with sorting as with "compareSpritesByLayer" in graphics.cpp.
iwSorter(const Common::Point & p1,const Common::Point & p2)52 bool iwSorter(const Common::Point &p1, const Common::Point &p2) {
53 	return p1.y < p2.y;
54 }
55 
getClosestKeyPosition(int16 x,int16 y)56 int IWFile::getClosestKeyPosition(int16 x, int16 y) {
57 	// This is a sorted list of indices from 0 to _numEntries-1.
58 	// The index is stored in Point.x, and the "cost" (distance from position) is stored
59 	// in Point.y for sorting purposes.
60 	Common::Point sortedIndices[MAX_KEY_POSITIONS];
61 
62 	for (int i = 0; i < _numEntries; i++) {
63 		sortedIndices[i].x = i;
64 		sortedIndices[i].y = (int16)sqrt((double)_keyPositions[i].sqrDist(Common::Point(x, y)));
65 	}
66 
67 	sort(sortedIndices, sortedIndices + _numEntries, &iwSorter);
68 
69 	// Iterate through positions from closest to furthest
70 	for (int i = 0; i < _numEntries; i++) {
71 		int index = sortedIndices[i].x;
72 		Common::Point dest = _keyPositions[index];
73 		if (_vm->directPathExists(x, y, dest.x, dest.y))
74 			return index;
75 	}
76 
77 	return -1;
78 }
79 
80 } // End of namespace StarTrek
81