107 Commits
Author SHA1 Message Date
aksdb 99749a5168 ✅ Add FPCUnit test suites for shared code and server
Introduces two headless FPCUnit runners under tests/ with 119 tests
covering the shared stream, cache, and packet layers, the MUL file
library, and the server config, region, account, and landscape
bounds logic. Each runner uses its own object output directory so
client and server PPUs with colliding unit names cannot pollute
each other's builds. Drone now builds and runs both suites before
packaging. Found on the way: two product defects fixed in the
previous commits.
2026-11-15 22:08:32 +01:00
aksdb ca8a0afc3b 🚨 Rename a local that shadowed the localization text property
The unit did not compile standalone because the serialize routine
declared a variable with the name of the published property.
2026-11-15 22:08:32 +01:00
aksdb 2b6f684505 🐛 Write full row byte counts when encoding land art
The land encoder passed word counts as byte counts to the stream
write, so every diamond row was truncated to half its length and
saved land tiles were unreadable.
2026-11-15 22:08:32 +01:00
aksdb 8f70a5cc98 🐛 Release large scale operation state on failure
The bitmask arrays, operations, and pending radar packets were only
released at the end of the straight-line handler, so any exception
leaked tens of megabytes per malformed request.
2026-11-15 22:08:32 +01:00
aksdb e38a487d56 🐛 Free the block parts when loading corrupt map data fails
A failed block creation leaked the already constructed halves and
the index.
2026-11-15 22:08:32 +01:00
aksdb 208ad57777 🐛 Validate radar map file data
Odd-sized radar color files, short static blocks, and tile IDs
beyond the color table read or wrote past their arrays at startup.
2026-11-15 22:08:32 +01:00
aksdb 6df8df9a9b 🐛 Validate tile IDs in static insertion
Sub-4000 filter entries underflowed to huge tile IDs, and placing
on top of statics with corrupt IDs indexed past the tiledata array.
2026-11-15 22:08:32 +01:00
aksdb 8731ec150c 🐛 Accept empty tile filters in large scale operations
An empty tile list is a valid no-filter request, but the
constructors dereferenced the empty array while reading it.
2026-11-15 22:08:32 +01:00
aksdb 45386dcbaf 🐛 Free the config document on validation failures
Invalid or outdated configuration leaked the parsed XML document
while aborting startup.
2026-11-15 22:08:32 +01:00
aksdb 5910178309 🐛 Free compression buffers when server-side compression fails 2026-11-15 22:08:32 +01:00
aksdb 0d1c61364b 🐛 Skip unauthenticated sockets in region update notifications
Region change notifications dereferenced the account of every
socket, crashing on connections that had not logged in.
2026-11-15 22:08:32 +01:00
aksdb b3a3b090b4 🔒 Handle missing accounts in user modification responses
Rejecting an empty username built the response packet from a nil
account reference.
2026-11-15 22:08:32 +01:00
aksdb 464c170e2d 🔒 Skip unauthenticated sockets in admin broadcasts
Any connection that had not finished logging in has no account, and
dereferencing it aborted the broadcast for all remaining admins.
2026-11-15 22:08:32 +01:00
aksdb 46aaec645c 🐛 Stop block requests with no coordinates from crashing
A truncated request packet produced an empty coordinate array whose
first element was dereferenced.
2026-11-15 22:08:32 +01:00
aksdb e12fe942b7 🔒 Validate compressed packets on the server
A client could declare an unbounded decompressed size to exhaust
server memory, nest compressed packets recursively, or send a
truncated inner packet whose handler read garbage.
2026-11-15 22:08:32 +01:00
aksdb 7acd461086 🐛 Stop broadcasting to unauthenticated sockets
Change and radar packets reached every connected socket, leaking
map edit activity to anyone who had opened a connection without
logging in. The state sweep also ran per loop tick; it now runs
once per second.
2026-11-15 22:08:32 +01:00
aksdb 4a7f525937 🚨 Keep the server receive queue consistent on errors
A handler exception left the stream locked and skipped the packet
dequeue, permanently desyncing the connection. Declared packet
sizes are now validated against a sane range, and clients sending
garbage are dropped instead of stalling the queue.
2026-11-15 22:08:32 +01:00
aksdb e74065fd49 🚨 Reject out-of-range block subscriptions
The off-by-one bounds check let a crafted free-block packet index
one past the subscription array and follow garbage memory as a
client list, corrupting the heap.
2026-11-15 22:08:32 +01:00
aksdb 0a939d4f35 🚨 Free login profile handles on read or write errors 2026-11-15 22:08:32 +01:00
aksdb ef124eb495 🚨 Default to no access when no access level is selected 2026-11-15 22:08:32 +01:00
aksdb b7235f8f93 🚨 Stop account saves with exactly 256 regions from losing them
The region count was clamped to 256 and wrapped to zero in the
byte field, truncating the account's region list server-side.
2026-11-15 22:08:32 +01:00
aksdb 74cf40118c 🚨 Truncate tile lists to the wire limit consistently
Serializing more than 65535 tiles wrote a wrapped count while
sending every tile, desynchronizing the server-side parse.
2026-11-15 22:08:32 +01:00
aksdb bd60c99dc3 🚨 Clean up large scale command form teardown
Executing with no areas leaked the built packet, and pending tile
selection listeners stayed registered after the form was destroyed.
2026-11-15 22:08:32 +01:00
aksdb 335cfc875c 🚨 Mark mouse-created areas as unsaved changes
Drawing a new area rectangle on the map did not arm the save
button, so the area was silently discarded on the next switch.
2026-11-15 22:08:32 +01:00
aksdb f8f56d6b2f 🚨 Unregister the region dialog from access change notices
FormDestroy never removed its listener, leaving a dangling method
pointer in the main form's listener list after teardown.
2026-11-15 22:08:32 +01:00
aksdb aaaad354b2 🚨 Drop the temp region node before refreshing the list
The region list refresh freed all tree nodes, leaving the pending
new-region pointer dangling while its save button stayed armed.
2026-11-15 22:08:32 +01:00
aksdb 4f6e034b5c 🚨 Save edits to the region being edited
When switching regions with unsaved changes, the save prompt ran
after the tree had already moved its selection, so the old region's
areas were written into the newly selected region on the server.
The save now targets the region whose areas are loaded in the
editor.
2026-11-15 22:08:32 +01:00
aksdb 9864157f33 🚨 Stop region saves with exactly 256 areas from wiping them
The count was clamped to 256 and then stored in a byte, wrapping to
zero, so the server replaced the region with an empty area list.
2026-11-15 22:08:32 +01:00
aksdb 818590ded0 ⚡ Cache tile list thumbnails in memory
The tile browser decoded art from disk and rebuilt the image on
every repaint of every visible cell; entries are now decoded once
and reused.
2026-11-15 22:08:32 +01:00
aksdb 75220f3dc4 ⚡ Set the light mode once per run of tiles
The render loop reissued the light state calls for every tile even
when the mode was unchanged.
2026-11-15 22:08:32 +01:00
aksdb fbfd8e627f 🚨 Clamp UOA design placement altitude in both directions
Moving a design only guarded the upper altitude bound, letting tile
altitudes wrap past the signed range.
2026-11-15 22:08:32 +01:00
aksdb 0092f6893e 🚨 Return an empty rectangle when no tile is selected
GetSelectedRect left its result undefined when called without a
current tile.
2026-11-15 22:08:32 +01:00
aksdb b47292a4bc 🚨 Guard location name serialization against empty strings
Saving or loading an unnamed location indexed the first character
of an empty string.
2026-11-15 22:08:32 +01:00
aksdb 4d9e02aaef 🚨 Ignore disconnect notices for unknown clients
Deleting at index -1 raised an exception and aborted the packet
dispatch when the list had already diverged.
2026-11-15 22:08:32 +01:00
aksdb 5f7e277721 🚨 Free detached DOM nodes when deleting random presets
RemoveChild detaches without owning the node; every deleted preset
or overwritten preset entry leaked it.
2026-11-15 22:08:32 +01:00
aksdb 481d6ac905 🚨 Free the edit target list when an edit action fails mid-way 2026-11-15 22:08:32 +01:00
aksdb dd20f4962d 🚨 Nil the label pointer when freeing a screen block label
Freeing without clearing left a dangling reference that a repeated
prepare pass would free again.
2026-11-15 22:08:32 +01:00
aksdb 1fbce3570d 🚨 Release the old material when re-highlighting a static
Hovering with hue highlighting reassigned the screen buffer material
without dropping the previous reference, leaking a GL texture on
every hover.
2026-11-15 22:08:32 +01:00
aksdb f09b8b7fbc 🚨 Validate radar map packet payloads
An empty radar map indexed an empty array, and update coordinates
from the server were written into the image without bounds checks.
2026-11-15 22:08:32 +01:00
aksdb fcb90dffbb 🚨 Handle empty or unreadable radar cache files
A zero-byte cache file indexed an empty array, and read errors
leaked the file stream.
2026-11-15 22:08:32 +01:00
aksdb 71865facd8 🚨 Make radar shutdown safe
Destroying the radar window dereferenced the image without a nil
check when creation had failed, and leaked the cache file stream on
write errors, skipping cleanup of the remaining objects.
2026-11-15 22:08:32 +01:00
aksdb 93c2af9d9f 🚨 Free the light config document and tolerate a missing file
LoadConfig leaked the parsed XML document on every call and aborted
startup when the color config file was absent.
2026-11-15 22:08:32 +01:00
aksdb 043a5a1ccf 🚨 Free the light collection when the light map update fails 2026-11-15 22:08:32 +01:00
aksdb 3dd9ce1d68 🚨 Mark the light manager as initialized
The flag was never set, so the framebuffer extension was reloaded on
every frame with lights enabled.
2026-11-15 22:08:32 +01:00
aksdb b90fbdf190 🚨 Clamp drawn tile altitudes to the valid range
Drawn statics could exceed the signed altitude range and wrap
around.
2026-11-15 22:08:32 +01:00
aksdb 1e44b51a06 🚨 Apply random elevation offsets in raise and lower modes
The random offset was computed first and then overwritten by the
raise and lower branches.
2026-11-15 22:08:32 +01:00
aksdb 78f945cee7 🚨 Expose the draw action hue
The draw action reads its hue field but no property ever exposed
it, so hue selection was silently ignored.
2026-11-15 22:08:32 +01:00
aksdb 3e562ff03d 🚨 Take the elevation target as a signed byte
The coordinate-based elevate overload accepted a word and silently
truncated it when writing the signed altitude byte.
2026-11-15 22:08:32 +01:00
aksdb 992666583d 🚨 Guard block requests without coordinates 2026-11-15 22:08:32 +01:00
aksdb 63ca31805e 🚨 Free compression buffers when packet compression fails
A compression error leaked the buffers and the wrapped packet,
whose ownership had already been transferred.
2026-11-15 22:08:32 +01:00
aksdb c4c95b0156 🚨 Validate decompressed packets before dispatch
A compressed packet could declare an unbounded decompressed size,
nest compressed packets recursively until stack overflow, or carry a
truncated inner packet whose handler then read uninitialized
memory.
2026-11-15 22:08:32 +01:00
aksdb d18e01c95c 🔒 Validate login response fields
The access level byte and landscape dimensions were trusted from
the network without checks.
2026-11-15 22:08:32 +01:00
aksdb c4f043a236 🚨 Isolate packet handler exceptions on the client
A handler exception left the packet in the queue, re-raising on
every receive until the app aborted. The connection is now dropped
cleanly with a log entry.
2026-11-15 22:06:51 +01:00
aksdb ad38619b9b 🚨 Validate packet lengths from the server
A declared length below the header size desynced the receive queue
and dispatched handlers on garbage, and an unbounded length could
grow the queue without limit.
2026-11-15 22:06:51 +01:00
aksdb 0222c01dc8 🚨 Stop double-freeing the connection packet handler at exit
Unit finalization already frees the handler table; freeing the
shared handler again from the datamodule corrupted the heap on
shutdown.
2026-11-15 22:06:51 +01:00
aksdb 997aa4991a 🚨 Stop the range selection helper from leaking
Abandoning a selection after the first click leaked the helper and
kept it registered for tile clicks. The helper now tracks the active
instance, copies coordinates instead of holding tile references that
can be evicted, and the listener dispatch tolerates removal during
iteration.
2026-11-15 22:06:51 +01:00
aksdb a1a40b6f61 🚨 Use the pointer-sized window call on 64-bit Windows
SetWindowLong truncates 64-bit window handles, breaking dialog
parenting on Win64 builds.
2026-11-15 22:06:51 +01:00
aksdb ee0667aff3 🚨 Skip empty font info tables
A truncated font resource indexed an empty array on load.
2026-11-15 22:06:51 +01:00
aksdb c6e1a10d3b 🚨 Check the arrow texture height, not the width twice 2026-11-15 22:06:51 +01:00
aksdb 7c3c4d89c4 🚨 Close the UOA design data file on shutdown
The design collection never freed its data stream, leaking the file
handle for every use.
2026-11-15 22:06:51 +01:00
aksdb d56149a4c1 🚨 Clamp imported UOA design values to their field ranges
Out-of-range tile, position, and hue values from a design file
truncated or raised range errors on import.
2026-11-15 22:06:51 +01:00
aksdb 9903de9c24 🚨 Guard animation texture deletion against empty frame lists
Destroying an animation material with no frames dereferenced an
empty array.
2026-11-15 22:06:51 +01:00
aksdb 6d0ae63be6 🚨 Clamp write permission areas to the landscape size
The write map trusted area coordinates from the login response and
could index a bits array far out of bounds with hostile data.
2026-11-15 22:06:51 +01:00
aksdb fa288fddf8 🚨 Harden the nodraw map loader
A parse error leaked the file handle and negative IDs from a
malformed file indexed the draw bitmap out of bounds.
2026-11-15 22:06:51 +01:00
aksdb 1335e3f40e 🚨 Validate tile and hue IDs from network data
Static materials indexed the tiledata array and hue table with
unchecked IDs from the server, crashing the client on malformed
packets.
2026-11-15 22:06:51 +01:00
aksdb 1dc371ed27 🚨 Free the block index when a landscape update fails mid-packet 2026-11-15 22:06:51 +01:00
aksdb 3df6ab93f6 🐛 Free the client statics decode buffer on malformed data 2026-11-15 22:06:51 +01:00
aksdb d9f7b126b6 🐛 Load client static blocks stored at offset zero
The client used the same offset-zero bug as the server loader,
dropping the first static block of a freshly written file.
2026-11-15 22:06:51 +01:00
aksdb 2cc0be66c9 🐛 Keep the screen buffer tail pointer valid on inserts
Inserting an item that sorted after everything left the tail
shortcut stale, so later appends unlinked existing nodes. This
leaked screen entries, their textures, and blocked cache eviction
forever.
2026-11-15 22:06:51 +01:00
aksdb b4a14683cb 🐛 Add half of the dominant slope to effective altitude
The altitude helper halved the smaller delta instead of the dominant
one, miscalculating draw priorities on every diagonal slope.
2026-11-15 22:06:51 +01:00
aksdb 3fed4cd5fc 🐛 Use the correct height for landscape draw range
The row loop iterated by width, dropping terrain rows whenever the
draw range was clipped asymmetrically at the map borders.
2026-11-15 22:06:51 +01:00
aksdb f4275217bb ⚡ Encode multimaps from scanlines instead of canvas pixels
Reading the canvas per pixel made writing a multimap orders of
magnitude slower than necessary.
2026-11-15 22:06:51 +01:00
aksdb d5c41c0816 🐛 Stop multimap decode from spinning on truncated data
A failed or zero-length run read left the decoder looping forever
without consuming input.
2026-11-15 22:06:51 +01:00
aksdb d3045de064 🐛 Validate animation data lookups against the entry count
Out-of-range IDs indexed the entry array unchecked and corrupted
memory instead of failing.
2026-11-15 22:06:51 +01:00
aksdb 32b8d99f3e 🐛 Report the encoded size of localization entries
GetSize counted characters while serialization writes UTF-8 bytes,
desynchronizing any offset arithmetic for non-ASCII text.
2026-11-15 22:06:51 +01:00
aksdb 81f837a746 🐛 Reject out-of-range hue lookups
The modulo silently wrapped invalid IDs to a wrong hue group instead
of failing.
2026-11-15 22:06:51 +01:00
aksdb d41520eca4 🐛 Free the hue decode buffer on malformed data 2026-11-15 22:06:51 +01:00
aksdb 13aae33a02 🐛 Skip empty entries when loading flat land art
An art index entry with lookup zero and no size made the decoder
copy the whole remaining art file.
2026-11-15 22:06:51 +01:00
aksdb 0c94cdb24b 🐛 Skip gump entries with no data
An index entry with a valid lookup but zero size copied the entire
rest of the gump file into memory before decoding garbage.
2026-11-15 22:06:51 +01:00
aksdb d2fb8a16ea 🐛 Handle truncated gump data safely
A zero run length or a short read at the end of the data left the
row decoder spinning forever, and runs that overshot the row width
wrote past the image buffer. The decode buffer is now freed on
errors as well.
2026-11-15 22:06:51 +01:00
aksdb 2c0eb0cebd 🐛 Deduplicate block event registrations
Registering the same change handler twice fired destroy and change
notifications twice for one block.
2026-11-15 22:06:51 +01:00
aksdb 9ed3862b4a 🐛 Validate tiledata lookups against the entry count
Out-of-range tile IDs indexed past the arrays and read arbitrary
memory instead of failing.
2026-11-15 22:06:51 +01:00
aksdb 6229d296df 🐛 Use version-aware offsets when writing High Seas tiledata
The write path always computed legacy offsets and sizes while the
loader detected and used the High Seas layout, so any tile edit on a
High Seas tiledata.mul shifted records and corrupted the file.
2026-11-15 22:06:50 +01:00
aksdb ee8dfe5adf 🐛 Free the statics decode buffer on malformed data
The constructor leaked its temporary stream when decoding raised on
corrupt static data.
2026-11-15 22:06:50 +01:00
aksdb d129a1b94f 🐛 Load static blocks stored at file offset zero
The lookup check treated offset 0 as empty, silently discarding the
first static block of a freshly written statics file.
2026-11-15 22:06:50 +01:00
aksdb c0121312ed 🐛 Stop map block clones from leaking their cells
Clone overwrote the freshly created cell array without freeing it,
leaking 64 cells per clone, and dropped the block header.
2026-11-15 22:06:50 +01:00
aksdb dab5f85816 🐛 Run the inherited destructor for animation groups
TAnimDataGroup.Destroy skipped the inherited call, so the base class
never fired its destroy notifications and leaked the handler state.
2026-11-15 22:06:50 +01:00
aksdb c8ef2ccf68 🐛 Free the animation data provider on shutdown
The manager released every provider except the animation data
provider, leaking its file stream and the whole animation table.
2026-11-15 22:06:50 +01:00
aksdb 23f323bee1 🐛 Create the texture save buffer for streamed textures
Textures loaded from file never had their buffer allocated, so any
save attempt crashed with an access violation.
2026-11-15 22:06:50 +01:00
aksdb ae9136d53a 🐛 Free the art decode buffer on malformed data
The constructor leaked its temporary stream whenever a decode
operation raised, for example on truncated or corrupt art data.
2026-11-15 22:06:50 +01:00
aksdb c1967a8a41 🐛 Fix art encoder writing corrupted images
The static RLE encoder read 16-bit pixels from the 32-bit working
image with a 16-bit stride, garbling every pixel and testing a green
channel bit as the visibility flag. The land encoder shifted every
diamond row to a constant or double-stride column. Both matched the
decoder on load and produced scrambled art on save. Also frees the
conversion image on the early exit paths.
2026-11-15 22:06:50 +01:00
aksdb c1f5215fb4 🐛 Stop linked list delete from storing a disposed node
Delete continued the loop with a dangling previous-node pointer after
disposing the matched entry. It now returns after the first match,
which is the behavior all callers rely on.
2026-11-15 22:06:50 +01:00
aksdb e527149f63 🐛 Check node type before treating XML children as text
Reading or updating a value whose first child was a comment or CDATA
node crashed with a failed class cast.
2026-11-15 22:06:50 +01:00
aksdb 39045b76c1 🐛 Fall back to default on invalid boolean config values
ReadBoolean raised an exception on malformed XML text instead of
using the supplied default.
2026-11-15 22:06:50 +01:00
aksdb 5e92d58a6e 🐛 Fix buffered stream flush losing data
Flush sized the base stream from its own overridden size, which
delegates to the base stream, so appended data was truncated or the
copy failed. Flushing a reader would have wiped the file; the reader
writes through immediately and needs no flush. Write now also
propagates short writes from the base stream.
2026-11-15 22:06:50 +01:00
aksdb 2bffd2204b 🐛 Guard fixed-length stream reads against short data
ReadStringFixed returned uninitialized memory on short reads and
crashed on negative lengths from untrusted input.
2026-11-15 22:06:50 +01:00
aksdb 1498437e26 🐛 Validate fifo stream bounds and locking
Seek accepted positions outside the queue, allowing reads before the
buffer, and negative counts reached Move with garbage sizes. Writing
to a locked stream silently dropped the lock window instead of
failing, which corrupts packet parsing.
2026-11-15 22:06:50 +01:00
aksdb a25c8296de ⚡ Pad fixed-length strings in one step
WriteStringFixed grew the string one character at a time, which is
quadratic in the target length.
2026-11-15 22:06:50 +01:00
aksdb 585fd92611 🐛 Fix out-of-bounds reads in stream string readers
The null and wide-string readers tested the terminator before the
bounds check, peeked one character past the window, and used a
lock-relative position against the absolute memory base. They also
advanced past a terminator that was never read, desyncing the parser
on malformed input. Reworked them to stay in bounds and to build the
result in linear time.
2026-11-15 22:06:50 +01:00
aksdb f381647149 🐛 Repair cache invariant after stores
StoreID left the last-entry pointer on the final node, so two
consecutive stores without an intervening query nil-dereferenced.
2026-11-15 22:06:50 +01:00
aksdb 4108ed5900 🐛 Fix cache last-entry corruption on hits
QueryID set the last-entry pointer to the moved node on every hit,
breaking the pointer-to-second-to-last invariant. StoreID then
orphaned tail entries, leaking cached objects and crashing on cache
destruction.
2026-11-15 22:06:50 +01:00
aksdb 98bfbd7b11 🐛 Reject cache manager sizes below 2
A size of 0 or 1 left the internal last-entry pointer nil, crashing on
the first store operation.
2026-11-15 22:01:27 +01:00
aksdb 3f47eba2da 🚨 Fix UfrmLogin not compiling 2024-11-03 16:32:35 +01:00
aksdb 4d92724f4e ✨ Support QT6 2024-11-03 16:32:09 +01:00
aksdb 23b4ebe214 🔨 Add project group 2024-11-03 16:31:41 +01:00
aksdb 3b6b8b6eb3 🚨 Fix cedserver paths 2024-11-03 16:31:17 +01:00
aksdb 27cf279503 🚨 Fix UfrmLargeScaleCommand not compiling 2024-11-03 16:31:04 +01:00
80 changed files with 4722 additions and 862 deletions
+7
View File
@@ -12,6 +12,13 @@ steps:
- ~/lazarus/lazbuild --lazarusdir=~/lazarus --build-mode="Release.win32" -B Server/cedserver.lpi
- ~/lazarus/lazbuild --lazarusdir=~/lazarus --build-mode="Release.Linux.x64" -B Server/cedserver.lpi
- name: Test
image: git.aksdb.de/aksdb/centred:builder-221016
commands:
- ~/lazarus/lazbuild --lazarusdir=~/lazarus -B tests/unittests.lpi
- tests/bin/unittests --all --format=plain
- ~/lazarus/lazbuild --lazarusdir=~/lazarus -B tests/unittests-server.lpi
- tests/bin/unittests-server --all --format=plain
- name: Package
image: git.aksdb.de/aksdb/centred:builder-221016
commands:
+2
View File
@@ -23,3 +23,5 @@ Setup/*
*.sh
*.exe
*.res
tests/bin/*
tests/obj-tests/*
+32
View File
@@ -0,0 +1,32 @@
<?xml version="1.0" encoding="UTF-8"?>
<CONFIG>
<ProjectGroup FileVersion="2">
<Targets>
<Target FileName="Tools/convertfontmap/ConvertFontMap.lpi"/>
<Target FileName="Client/CentrED.lpi">
<BuildModes>
<Mode Name="default" Compile="True"/>
<Mode Name="Release.Win32"/>
<Mode Name="Release.Win64"/>
<Mode Name="Release.Linux.x86"/>
<Mode Name="Release.Linux.x64"/>
<Mode Name="Debug.Win32"/>
<Mode Name="Debug.Linux.x86"/>
<Mode Name="Debug.Linux.x64"/>
</BuildModes>
</Target>
<Target FileName="Server/cedserver.lpi">
<BuildModes>
<Mode Name="default" Compile="True"/>
<Mode Name="Release.Win32"/>
<Mode Name="Release.Win64"/>
<Mode Name="Release.Linux.x86"/>
<Mode Name="Release.Linux.x64"/>
<Mode Name="Debug.Win32"/>
<Mode Name="Debug.Linux.x86"/>
<Mode Name="Debug.Linux.x64"/>
</BuildModes>
</Target>
</Targets>
</ProjectGroup>
</CONFIG>
+10 -9
View File
@@ -12,6 +12,9 @@
<Scaled Value="True"/>
<ResourceType Value="res"/>
<UseXPManifest Value="True"/>
<XPManifest>
<DpiAware Value="True"/>
</XPManifest>
<Icon Value="0"/>
</General>
<LazDoc Paths="../doc"/>
@@ -19,7 +22,7 @@
<UseVersionInfo Value="True"/>
<AutoIncrementBuild Value="True"/>
<MinorVersionNr Value="7"/>
<BuildNr Value="263"/>
<BuildNr Value="264"/>
<StringTable CompanyName="AKS DataBasis" FileDescription="UO CentrED" InternalName="CentrED" LegalCopyright="(c) 2022 Andreas Schneider and StaticZ" OriginalFilename="CentrED.exe" ProductName="CentrED" ProductVersion="0.7.0"/>
</VersionInfo>
<BuildModes Count="8">
@@ -101,6 +104,7 @@
<Linking>
<Debugging>
<GenerateDebugInfo Value="False"/>
<DebugInfoType Value="dsDwarf3"/>
<UseLineInfoUnit Value="False"/>
<StripSymbols Value="True"/>
</Debugging>
@@ -318,9 +322,10 @@
</Other>
</CompilerOptions>
</Item8>
<SharedMatrixOptions Count="2">
<SharedMatrixOptions Count="3">
<Item1 ID="851019893220" Modes="Release.Win32,Debug.Win32" Type="IDEMacro" MacroName="LCLWidgetType" Value="win32"/>
<Item2 ID="521965364444" Modes="Release.Linux.x86,Release.Linux.x64,Debug.Linux.x86,Debug.Linux.x64" Type="IDEMacro" MacroName="LCLWidgetType" Value="gtk2"/>
<Item3 ID="241840553479" Type="IDEMacro" MacroName="LCLWidgetType" Value="qt5"/>
</SharedMatrixOptions>
</BuildModes>
<PublishOptions>
@@ -330,11 +335,6 @@
<local>
<LaunchingApplication PathPlusParams="/usr/X11R6/bin/xterm -T &apos;Lazarus Run Output&apos; -e $(LazarusDir)/tools/runwait.sh $(TargetCmdLine)"/>
</local>
<environment>
<UserOverrides Count="1">
<Variable0 Name="HEAPTRC" Value="log=CentrED.trc"/>
</UserOverrides>
</environment>
<FormatVersion Value="2"/>
<Modes Count="1">
<Mode0 Name="default">
@@ -342,8 +342,9 @@
<LaunchingApplication PathPlusParams="/usr/X11R6/bin/xterm -T &apos;Lazarus Run Output&apos; -e $(LazarusDir)/tools/runwait.sh $(TargetCmdLine)"/>
</local>
<environment>
<UserOverrides Count="1">
<UserOverrides Count="2">
<Variable0 Name="HEAPTRC" Value="log=CentrED.trc"/>
<Variable1 Name="WAYLAND_DISPLAY"/>
</UserOverrides>
</environment>
</Mode0>
@@ -658,7 +659,7 @@
</CodeGeneration>
<Linking>
<Debugging>
<DebugInfoType Value="dsStabs"/>
<DebugInfoType Value="dsDwarf3"/>
</Debugging>
</Linking>
<Other>
+13 -14
View File
@@ -3,13 +3,13 @@ object frmFilter: TfrmFilter
Height = 615
Top = 171
Width = 290
ActiveControl = rgFilterType.RadioButton0
BorderIcons = [biSystemMenu, biMinimize]
BorderStyle = bsToolWindow
Caption = 'Filter'
ClientHeight = 615
ClientWidth = 290
Font.Height = -14
LCLVersion = '4.99.0.0'
OnCreate = FormCreate
OnDestroy = FormDestroy
OnShow = FormShow
@@ -30,16 +30,16 @@ object frmFilter: TfrmFilter
ChildSizing.ShrinkVertical = crsScaleChilds
ChildSizing.Layout = cclLeftToRightThenTopToBottom
ChildSizing.ControlsPerLine = 2
ClientHeight = 29
ClientWidth = 278
ClientHeight = 38
ClientWidth = 268
Columns = 2
ItemIndex = 0
Items.Strings = (
'Exclusive'
'Inclusive'
)
OnClick = rgFilterTypeClick
TabOrder = 0
OnClick = rgFilterTypeClick
end
object GroupBox1: TGroupBox
Left = 5
@@ -49,8 +49,8 @@ object frmFilter: TfrmFilter
Align = alClient
BorderSpacing.Around = 5
Caption = 'Tile filter'
ClientHeight = 303
ClientWidth = 278
ClientHeight = 312
ClientWidth = 268
TabOrder = 1
object Label1: TLabel
AnchorSideLeft.Control = GroupBox1
@@ -65,7 +65,6 @@ object frmFilter: TfrmFilter
Anchors = [akTop, akLeft, akRight]
BorderSpacing.Around = 5
Caption = 'Drag and Drop static tiles from the tile list on this list to add them to the filter.'
Color = clDefault
ParentColor = False
WordWrap = True
end
@@ -118,9 +117,9 @@ object frmFilter: TfrmFilter
DE00D86FDF00D86FDF00E0A223004AC6080000000000580000005870DF000C70
DF000000000000000000000000002070DF000000000000000000
}
OnClick = btnClearClick
ShowHint = True
ParentShowHint = False
OnClick = btnClearClick
end
object btnDelete: TSpeedButton
AnchorSideLeft.Control = GroupBox1
@@ -169,9 +168,9 @@ object frmFilter: TfrmFilter
DE0068B0E00068B0E0000E049300F8049500F2009500070102000F049500F804
0200F2000200080104000E040200F8040400F200040009010500
}
OnClick = btnDeleteClick
ShowHint = True
ParentShowHint = False
OnClick = btnDeleteClick
end
object vdtFilter: TLazVirtualDrawTree
Tag = 1
@@ -227,8 +226,8 @@ object frmFilter: TfrmFilter
Width = 101
BorderSpacing.Around = 5
Caption = 'Filter active'
OnChange = cbTileFilterChange
TabOrder = 1
OnChange = cbTileFilterChange
end
end
object GroupBox2: TGroupBox
@@ -239,8 +238,8 @@ object frmFilter: TfrmFilter
Align = alBottom
BorderSpacing.Around = 5
Caption = 'Hue filter'
ClientHeight = 189
ClientWidth = 278
ClientHeight = 198
ClientWidth = 268
TabOrder = 2
object cbHueFilter: TCheckBox
Left = 5
@@ -250,8 +249,8 @@ object frmFilter: TfrmFilter
Align = alTop
BorderSpacing.Around = 5
Caption = 'Filter active'
OnChange = cbHueFilterChange
TabOrder = 0
OnChange = cbHueFilterChange
end
object vdtHues: TLazVirtualDrawTree
Cursor = 63
@@ -275,7 +274,7 @@ object frmFilter: TfrmFilter
item
Position = 2
Text = 'Name'
Width = 193
Width = 195
end>
Header.DefaultHeight = 21
Header.Height = 36
+4 -4
View File
@@ -149,11 +149,11 @@ procedure TfrmFilter.vdtFilterDragDrop(Sender: TBaseVirtualTree;
Source: TObject; DataObject: IDataObject; Formats: TFormatArray;
Shift: TShiftState; Pt: TPoint; var Effect: Integer; Mode: TDropMode);
var
sourceTree: TVirtualDrawTree;
sourceTree: TLazVirtualDrawTree;
selected, node: PVirtualNode;
sourceTileInfo, targetTileInfo: PTileInfo;
begin
sourceTree := Source as TVirtualDrawTree;
sourceTree := Source as TLazVirtualDrawTree;
if (sourceTree <> Sender) and (sourceTree <> nil) and
(sourceTree.Tag = 1) then
begin
@@ -180,8 +180,8 @@ procedure TfrmFilter.vdtFilterDragOver(Sender: TBaseVirtualTree;
Source: TObject; Shift: TShiftState; State: TDragState; Pt: TPoint;
Mode: TDropMode; var Effect: Integer; var Accept: Boolean);
begin
if (Source <> Sender) and (Source is TVirtualDrawTree) and
(TVirtualDrawTree(Source).Tag = 1) then
if (Source <> Sender) and (Source is TLazVirtualDrawTree) and
(TLazVirtualDrawTree(Source).Tag = 1) then
begin
Accept := True;
end;
+4 -3
View File
@@ -92,6 +92,7 @@ type
property ForceZValue: ShortInt read FForceZValue write FForceZValue;
property RandomZ: Boolean read FRandomZ write FRandomZ;
property RandomZValue: Byte read FRandomZValue write FRandomZValue;
property Hue: Word read FHue write FHue;
constructor Create(ALandscape: TLandscape);
@@ -356,6 +357,7 @@ begin
worldItem.Z := FForceZValue;
if FRandomZ then
worldItem.Z := worldItem.Z + Random(FRandomZValue);
worldItem.Z := EnsureRange(worldItem.Z, -128, 127);
end;
end;
@@ -417,13 +419,12 @@ begin
Continue;
newZ := FZ;
if FRandomZ then
newZ := newZ + Random(FRandomZValue);
case FMode of
emRaise: newZ := item.Z + FZ;
emLower: newZ := item.Z - FZ;
end;
if FRandomZ then
newZ := newZ + Random(FRandomZValue);
newZ := EnsureRange(newZ, -128, 127);
+1
View File
@@ -185,6 +185,7 @@ begin
AFontInfo.Read(FSpaceWidth, SizeOf(FSpaceWidth));
SetLength(FFontInfo, (AFontInfo.Size - AFontInfo.Position) div
SizeOf(TFontInfo));
if Length(FFontInfo) > 0 then
AFontInfo.Read(FFontInfo[0], Length(FFontInfo) * SizeOf(TFontInfo));
end;
+4
View File
@@ -42,8 +42,12 @@ implementation
procedure SetWindowParent(AHandle, AParent: THANDLE);
begin
{$IFDEF LCLWin32}
{$IFDEF CPU64}
SetWindowLongPtr(AHandle, GWLP_HWNDPARENT, AParent);
{$ELSE}
SetWindowLong(AHandle, GWL_HWNDPARENT, AParent);
{$ENDIF}
{$ENDIF}
{$IFDEF LCLGtk}
gtk_window_set_transient_for(PGtkWindow(AHandle), PGtkWindow(AParent));
{$ENDIF}
+27 -8
View File
@@ -464,11 +464,14 @@ var
staticTiledata: TStaticTiledata;
hue: THue;
begin
if (AStaticItem.TileID < 0) or
(AStaticItem.TileID >= Integer(ResMan.Tiledata.StaticCount)) then
raise Exception.CreateFmt('Invalid static tile ID %d', [AStaticItem.TileID]);
staticTiledata := ResMan.Tiledata.StaticTiles[AStaticItem.TileID];
if AOverrideHue < 0 then
AOverrideHue := AStaticItem.Hue;
if AOverrideHue > 0 then
if (AOverrideHue > 0) and (AOverrideHue <= ResMan.Hue.Count) then
hue := ResMan.Hue.Hues[AOverrideHue - 1]
else
hue := nil;
@@ -519,10 +522,11 @@ begin
for i := 0 to 63 do
Cells[i] := TStaticItemList.Create;
if (AData <> nil) and (AIndex.Lookup > 0) and (AIndex.Size > 0) then
if (AData <> nil) and (AIndex.Lookup > -1) and (AIndex.Size > 0) then
begin
AData.Position := AIndex.Lookup;
block := TMemoryStream.Create;
try
block.CopyFrom(AData, AIndex.Size);
block.Position := 0;
for i := 1 to (AIndex.Size div 7) do
@@ -530,9 +534,11 @@ begin
item := TStaticItem.Create(Self, block, AX, AY);
Cells[(item.Y mod 8) * 8 + (item.X mod 8)].Add(item);
end;
finally
block.Free;
end;
end;
end;
constructor TSeperatedStaticBlock.Create(AData: TStream; AIndex: TGenericIndex);
begin
@@ -767,6 +773,7 @@ var
block: TBlock;
begin
index := TGenericIndex.Create(nil);
try
while ABuffer.Position < ABuffer.Size do
begin
ABuffer.Read(coords, SizeOf(TBlockCoords));
@@ -790,8 +797,10 @@ begin
if Assigned(FOnNewBlock) then FOnNewBlock(block);
end;
finally
index.Free;
end;
end;
procedure TLandscape.OnDrawMapPacket(ABuffer: TEnhancedMemoryStream);
var
@@ -1017,7 +1026,7 @@ begin
tempDrawList := TWorldItemList.Create(False);;
for x := AX to AX + AWidth do
begin
for y := AY to AY + AWidth do
for y := AY to AY + AHeight do
begin
if AMap then
begin
@@ -1075,10 +1084,10 @@ begin
south := GetLandAlt(ATile.X + 1, ATile.Y + 1, north);
east := GetLandAlt(ATile.X + 1, ATile.Y, north);
if Abs(north - south) >= Abs(west - east) then
Result := Min(north, south) + Abs(west - east) div 2
if Abs(north - south) > Abs(west - east) then
Result := Min(north, south) + Abs(north - south) div 2
else
Result := Min(north, south) + Abs(north - south) div 2;
Result := Min(north, south) + Abs(west - east) div 2;
end;
function TLandscape.GetLandAlt(AX, AY: Word; ADefault: ShortInt): ShortInt;
@@ -1189,6 +1198,7 @@ var
begin
AssignFile(noDrawFile, AFileName);
Reset(noDrawFile);
try
while not EOF(noDrawFile) do
begin
ReadLn(noDrawFile, line);
@@ -1207,6 +1217,8 @@ begin
Inc(id2, $4000);
end;
if id1 < 0 then
id1 := 0;
for i := id1 to id2 do
if i < FDrawMap.Size then
FDrawMap[i] := False;
@@ -1218,14 +1230,16 @@ begin
begin
if line[1] = 'S' then
Inc(id1, $4000);
if id1 < FDrawMap.Size then
if (id1 >= 0) and (id1 < FDrawMap.Size) then
FDrawMap[id1] := False;
end;
end;
end;
end;
finally
CloseFile(noDrawFile);
end;
end;
procedure TLandscape.MoveStatic(AStatic: TStaticItem; AX, AY: Word);
var
@@ -1313,6 +1327,10 @@ begin
y1 := AStream.ReadWord;
x2 := AStream.ReadWord;
y2 := AStream.ReadWord;
if (x1 >= FCellWidth) or (y1 >= FCellHeight) then
Continue;
if x2 >= FCellWidth then x2 := FCellWidth - 1;
if y2 >= FCellHeight then y2 := FCellHeight - 1;
for cellX := x1 to x2 do
for cellY := y1 to y2 do
FWriteMap[cellX * FCellHeight + cellY] := True;
@@ -1611,7 +1629,7 @@ begin
current := current^.Next;
end;
if FShortCuts[-1] = current^.Next then
if current^.Next = nil then
FShortCuts[-1] := Result; //Update last item
Result^.Next := current^.Next;
@@ -1817,6 +1835,7 @@ end;
destructor TAnimMaterial.Destroy;
begin
if Length(FTextures) > 0 then
glDeleteTextures(Length(FTextures), @FTextures[0]);
inherited Destroy;
end;
+10 -1
View File
@@ -268,6 +268,7 @@ end;
procedure TLightManager.InitGL;
begin
FUseFBO := Load_GL_EXT_framebuffer_object;
FInitialized := True;
end;
procedure TLightManager.UpdateLightMap(ALeft, AWidth, ATop, AHeight: Integer;
@@ -284,6 +285,7 @@ begin
{Logger.Send([lcClient, lcDebug], 'AWidth', AWidth);
Logger.Send([lcClient, lcDebug], 'AHeight', AHeight);}
lights := TWorldItemList.Create(False);
try
SetLength(tileMap, AWidth, AHeight);
for x := 0 to AWidth - 1 do
for y := 0 to AHeight - 1 do
@@ -319,8 +321,9 @@ begin
((tileMap[x,y] = nil) or (tileMap[x,y].Z < lights[i].Z + 5))) then
FLightSources.Add(TLightSource.Create(Self, lights[i]));
end;
finally
lights.Free;
end;
FValid := False;
//Logger.ExitMethod([lcClient, lcDebug], 'UpdateLightMap');
@@ -382,7 +385,10 @@ begin
//frmInitialize.SetStatusLabel(Format(frmInitialize.SplashLoading, ['ColorLight.xml']));
// Read xml file from your hard drive
if not FileExists(AFileName) then
Exit;
ReadXMLFile(XMLDoc, AFileName);
try
if LowerCase(XMLDoc.DocumentElement.NodeName) = 'colorlight' then
begin
iNode := XMLDoc.DocumentElement.FirstChild;
@@ -459,6 +465,9 @@ begin
iNode := iNode.NextSibling;
end;
end;
finally
XMLDoc.Free;
end;
end;
{ TLightSource }
+1 -1
View File
@@ -111,7 +111,7 @@ end;
procedure TGLArrow.UpdateTexture;
begin
if (FGraphic <> nil) and (FRealWidth > 0) and (FRealWidth > 0) then
if (FGraphic <> nil) and (FRealWidth > 0) and (FRealHeight > 0) then
begin
FTexture := CreateGLTextureFromImage(FGraphic.ImageDataPointer^, 0, 0, False);
+11 -2
View File
@@ -96,21 +96,30 @@ var
uncompStream: TEnhancedMemoryStream;
uncompBuffer: TDecompressionStream;
targetSize: Cardinal;
innerSize: Cardinal;
packetID: Byte;
begin
//writeln('compressed size: ', ABuffer.Size);
targetSize := ABuffer.ReadCardinal;
//writeln('uncompressed size: ', targetSize);
if (targetSize < 5) or (targetSize > 64 * 1024 * 1024) then Exit;
uncompBuffer := TDecompressionStream.Create(ABuffer);
uncompStream := TEnhancedMemoryStream.Create;
try
uncompStream.CopyFrom(uncompBuffer, targetSize);
uncompStream.Position := 0;
packetID := uncompStream.ReadByte;
if PacketHandlers[packetID] <> nil then
if (packetID <> $01) and (PacketHandlers[packetID] <> nil) then
begin
if PacketHandlers[PacketID].PacketLength = 0 then
uncompStream.Position := uncompStream.Position + 4;
begin
innerSize := uncompStream.ReadCardinal;
if (innerSize < 5) or
(uncompStream.Size - uncompStream.Position < innerSize - 5) then
Exit;
end else if uncompStream.Size - uncompStream.Position <
PacketHandlers[PacketID].PacketLength - 1 then
Exit;
uncompStream.Lock(uncompStream.Position, uncompStream.Size - uncompStream.Position);
PacketHandlers[PacketID].Process(uncompStream);
uncompStream.Unlock;
+9 -2
View File
@@ -98,7 +98,7 @@ type
TElevateStaticPacket = class(TStaticPacket)
constructor Create(AStaticItem: TStaticItem; ANewZ: ShortInt);
constructor Create(AX, AY: Word; AZ: ShortInt; ATileID: Word; AHue: Word;
ANewZ: Word);
ANewZ: ShortInt);
end;
{ TMoveStaticPacket }
@@ -171,13 +171,19 @@ var
begin
inherited Create($01, 0);
compBuffer := TEnhancedMemoryStream.Create;
try
compStream := TCompressionStream.Create(clMax, compBuffer);
try
sourceStream := APacket.Stream;
compStream.CopyFrom(sourceStream, 0);
finally
compStream.Free;
end;
FStream.WriteCardinal(sourceStream.Size);
FStream.CopyFrom(compBuffer, 0);
finally
compBuffer.Free;
end;
APacket.Free;
end;
@@ -204,6 +210,7 @@ end;
constructor TRequestBlocksPacket.Create(ACoords: TBlockCoordsArray);
begin
inherited Create($04, 0);
if Length(ACoords) > 0 then
FStream.Write(ACoords[0], Length(ACoords) * SizeOf(TBlockCoords));
end;
@@ -275,7 +282,7 @@ begin
end;
constructor TElevateStaticPacket.Create(AX, AY: Word; AZ: ShortInt;
ATileID: Word; AHue: Word; ANewZ: Word);
ATileID: Word; AHue: Word; ANewZ: ShortInt);
begin
inherited Create($09, 11);
FStream.WriteWord(AX);
+33 -35
View File
@@ -3,13 +3,13 @@
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License, Version 1.0 only
* (the "License"). You may not use this file except in compliance
* with the License.
* (the "License"). You may not use this file except in compliance with
* the License.
*
* You can obtain a copy of the license at
* http://www.opensource.org/licenses/cddl1.php.
* See the License for the specific language governing permissions
* and limitations under the License.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at
@@ -43,28 +43,29 @@ uses
UfrmMain, UWorldItem, math;
type
{ TRangeSelectionHelper }
TRangeSelectionHelper = class
constructor Create(ACallback: TSelectedRangeCallback);
destructor Destroy; override;
protected
FCallback: TSelectedRangeCallback;
FItem1: TWorldItem;
FItem2: TWorldItem;
FHasFirst: Boolean;
FX1, FY1: Word;
procedure TileSelected(AWorldItem: TWorldItem);
procedure Finish;
procedure Finish(AX2, AY2: Word);
public
procedure Run;
end;
procedure SelectRange(ACallback: TSelectedRangeCallback);
var
helper: TRangeSelectionHelper;
ActiveHelper: TRangeSelectionHelper = nil;
procedure SelectRange(ACallback: TSelectedRangeCallback);
begin
helper := TRangeSelectionHelper.Create(ACallback);
helper.Run;
//Cleanup will follow asynchroneously
FreeAndNil(ActiveHelper);
ActiveHelper := TRangeSelectionHelper.Create(ACallback);
ActiveHelper.Run;
end;
{ TRangeSelectionHelper }
@@ -72,42 +73,39 @@ end;
constructor TRangeSelectionHelper.Create(ACallback: TSelectedRangeCallback);
begin
FCallback := ACallback;
FItem1 := nil;
FItem2 := nil;
FHasFirst := False;
end;
destructor TRangeSelectionHelper.Destroy;
begin
if frmMain <> nil then
frmMain.UnregisterSelectionListener(@TileSelected);
inherited Destroy;
end;
procedure TRangeSelectionHelper.TileSelected(AWorldItem: TWorldItem);
begin
if FItem1 = nil then
FItem1 := AWorldItem
else if FItem2 = nil then
if not FHasFirst then
begin
FItem2 := AWorldItem;
Finish;
end;
FHasFirst := True;
FX1 := AWorldItem.X;
FY1 := AWorldItem.Y;
end else
Finish(AWorldItem.X, AWorldItem.Y);
end;
procedure TRangeSelectionHelper.Finish;
var
minX, minY: Word;
maxX, maxY: Word;
procedure TRangeSelectionHelper.Finish(AX2, AY2: Word);
begin
frmMain.UnregisterSelectionListener(@TileSelected);
minX := Min(FItem1.X, FItem2.X);
minY := Min(FItem1.Y, FItem2.Y);
maxX := Max(FItem1.X, FItem2.X);
maxY := Max(FItem1.Y, FItem2.Y);
FCallback(minX, minY, maxX, maxY);
Free; //We use this class only once, so it can cleanup after itself
FCallback(Min(FX1, AX2), Min(FY1, AY2), Max(FX1, AX2), Max(FY1, AY2));
if ActiveHelper = Self then
ActiveHelper := nil;
Free;
end;
procedure TRangeSelectionHelper.Run;
begin
//TODO show indicator and option to cancel
//TODO keep track of instance (global variable maybe?)
frmMain.RegisterSelectionListener(@TileSelected);
frmMain.SwitchToSelection;
end;
end.
+6 -4
View File
@@ -104,14 +104,14 @@ begin
raise Exception.Create('Unsupported binary version');
tile := TStaticItem.Create(nil);
tile.TileID := ReadInt;
tile.X := ReadInt;
tile.Y := ReadInt;
tile.TileID := EnsureRange(ReadInt, 0, $FFFF);
tile.X := EnsureRange(ReadInt, 0, $FFFF);
tile.Y := EnsureRange(ReadInt, 0, $FFFF);
tile.Z := EnsureRange(ReadInt, -128, 127);
ReadInt; // Level; unused
if version = 1 then
tile.Hue := ReadInt;
tile.Hue := EnsureRange(ReadInt, 0, $FFFF);
FTiles.Add(tile);
end;
@@ -176,6 +176,8 @@ end;
destructor TUoaDesigns.Destroy;
begin
Headers.Free;
FData.Free;
inherited Destroy;
end;
function TUoaDesigns.LoadDesign(AHeader: TUoaDesignHeader): TUoaDesign;
+30 -4
View File
@@ -79,7 +79,7 @@ uses
UfrmBoundaries, UfrmElevateSettings, UfrmConfirmation, UfrmMoveSettings,
UfrmAbout, UfrmHueSettings, UfrmRadar, UfrmLargeScaleCommand,
UfrmVirtualLayer, UfrmFilter, UfrmRegionControl, UfrmLightlevel,
UfrmChangePassword;
UfrmChangePassword, Logging;
{$I version.inc}
@@ -98,7 +98,6 @@ procedure TdmNetwork.DataModuleDestroy(Sender: TObject);
begin
FreeAndNil(FSendQueue);
FreeAndNil(FReceiveQueue);
FreeAndNil(PacketHandlers[$02]);
end;
procedure TdmNetwork.TCPClientConnect(aSocket: TLSocket);
@@ -164,6 +163,7 @@ procedure TdmNetwork.OnConnectionHandlingPacket(ABuffer: TEnhancedMemoryStream);
var
subID: Byte;
loginState: TLoginState;
levelByte: Byte;
width, height: Word;
serverState: TServerState;
begin
@@ -190,10 +190,19 @@ begin
frmInitialize.Repaint;
frmInitialize.lblStatus.Repaint;
Application.ProcessMessages;
FAccessLevel := TAccessLevel(ABuffer.ReadByte);
levelByte := ABuffer.ReadByte;
if levelByte in [0, 1, 2, 255] then
FAccessLevel := TAccessLevel(accessLevel)
else
FAccessLevel := alNone;
InitGameResourceManager(FDataDir);
width := ABuffer.ReadWord;
height := ABuffer.ReadWord;
if (width = 0) or (height = 0) then
begin
Disconnect;
Exit;
end;
ResMan.InitLandscape(width, height);
ResMan.Landscape.UpdateWriteMap(ABuffer);
@@ -265,16 +274,33 @@ begin
size := packetHandler.PacketLength;
if size = 0 then
begin
if FReceiveQueue.Size > 5 then
if FReceiveQueue.Size >= 5 then
size := FReceiveQueue.ReadCardinal
else
Break; //wait for more data
end;
if (size < 5) or (size > 32 * 1024 * 1024) then
begin
Disconnect;
FReceiveQueue.Clear;
Exit;
end;
if FReceiveQueue.Size >= size then
begin
FReceiveQueue.Lock(FReceiveQueue.Position, size - FReceiveQueue.Position); //prevent handler from reading too much
try
packetHandler.Process(FReceiveQueue);
except
on E: Exception do
begin
Logger.Send([lcClient, lcError], 'Packet handler exception: %s', [E.Message]);
FReceiveQueue.Unlock;
Disconnect;
FReceiveQueue.Clear;
Exit;
end;
end;
FReceiveQueue.Unlock;
FReceiveQueue.Dequeue(size);
end else
+1 -1
View File
@@ -127,7 +127,7 @@ begin
FStream.WriteStringNull(APassword);
FStream.WriteByte(Byte(AAccessLevel));
regionCount := Min(ARegions.Count, 256);
regionCount := Min(ARegions.Count, 255);
FStream.WriteByte(regionCount);
for i := 0 to regionCount - 1 do
+2
View File
@@ -103,6 +103,8 @@ begin
1: Result := alView;
2: Result := alNormal;
3: Result := alAdministrator;
else
Result := alNone;
end;
end;
File diff suppressed because it is too large Load Diff
+26 -10
View File
@@ -176,7 +176,7 @@ type
function FindNode(AActionID: Integer): PVirtualNode;
procedure TileSelection(AWorldItem: TWorldItem);
procedure OffsetSelection(AWorldItem: TWorldItem);
procedure SerializeTiles(ATileList: TVirtualDrawTree;
procedure SerializeTiles(ATileList: TLazVirtualDrawTree;
AStream: TEnhancedMemoryStream);
public
{ public declarations }
@@ -239,6 +239,8 @@ end;
procedure TfrmLargeScaleCommand.FormDestroy(Sender: TObject);
begin
frmRadarMap.Dependencies.Remove(pbArea);
frmMain.UnregisterSelectionListener(@TileSelection);
frmMain.UnregisterSelectionListener(@OffsetSelection);
end;
procedure TfrmLargeScaleCommand.mnuSelectTopLeftClick(Sender: TObject);
@@ -392,14 +394,21 @@ var
node: PVirtualNode;
areaInfo: ^TRect;
begin
areaCount := Min(vstArea.RootNodeCount, 255);
if areaCount = 0 then
begin
MessageDlg('Large Scale Command', 'No target areas selected.',
mtWarning, [mbOK], 0);
Exit;
end;
packet := TPacket.Create($0E, 0);
try
stream := packet.Stream;
stream.Position := stream.Size;
//Area
areaCount := Min(vstArea.RootNodeCount, 255);
stream.WriteByte(areaCount);
if areaCount = 0 then Exit;
i := 0;
node := vstArea.GetFirst;
while (node <> nil) and (i < areaCount) do
@@ -482,6 +491,10 @@ begin
stream.WriteBoolean(False);
dmNetwork.Send(TCompressedPacket.Create(packet));
except
packet.Free;
raise;
end;
Close;
end;
@@ -566,11 +579,11 @@ procedure TfrmLargeScaleCommand.vdtTerrainTilesDragDrop(Sender: TBaseVirtualTree
Source: TObject; DataObject: IDataObject; Formats: TFormatArray;
Shift: TShiftState; Pt: TPoint; var Effect: Integer; Mode: TDropMode);
var
sourceTree: TVirtualDrawTree;
sourceTree: TLazVirtualDrawTree;
selected, node: PVirtualNode;
sourceTileInfo, targetTileInfo: PTileInfo;
begin
sourceTree := Source as TVirtualDrawTree;
sourceTree := Source as TLazVirtualDrawTree;
if (sourceTree <> Sender) and (sourceTree <> nil) and
(sourceTree.Tag = 1) then
begin
@@ -597,8 +610,8 @@ procedure TfrmLargeScaleCommand.vdtTerrainTilesDragOver(Sender: TBaseVirtualTree
Source: TObject; Shift: TShiftState; State: TDragState; Pt: TPoint;
Mode: TDropMode; var Effect: Integer; var Accept: Boolean);
begin
if (Source <> Sender) and (Source is TVirtualDrawTree) and
(TVirtualDrawTree(Source).Tag = 1) then
if (Source <> Sender) and (Source is TLazVirtualDrawTree) and
(TLazVirtualDrawTree(Source).Tag = 1) then
begin
Accept := True;
end;
@@ -768,19 +781,22 @@ begin
WindowState := FOldWindowState;
end;
procedure TfrmLargeScaleCommand.SerializeTiles(ATileList: TVirtualDrawTree;
procedure TfrmLargeScaleCommand.SerializeTiles(ATileList: TLazVirtualDrawTree;
AStream: TEnhancedMemoryStream);
var
node: PVirtualNode;
tileInfo: PTileInfo;
i: Integer;
begin
AStream.WriteWord(ATileList.RootNodeCount);
AStream.WriteWord(Min(ATileList.RootNodeCount, High(Word)));
node := ATileList.GetFirst;
while node <> nil do
i := 0;
while (node <> nil) and (i < High(Word)) do
begin
tileInfo := ATileList.GetNodeData(node);
AStream.WriteWord(tileInfo^.ID);
node := ATileList.GetNext(node);
Inc(i);
end;
end;
+6
View File
@@ -128,11 +128,14 @@ begin
if InputQuery('Save profile', 'Enter the name of the profile:', profileName) then
begin
profile := TIniFile.Create(FProfilePath + profileName + '.ini');
try
profile.WriteString('Connection', 'Host', edHost.Text);
profile.WriteInteger('Connection', 'Port', edPort.Value);
profile.WriteString('Connection', 'Username', edUsername.Text);
profile.WriteString('Data', 'Path', edData.Text);
finally
profile.Free;
end;
cbProfile.ItemIndex := cbProfile.Items.IndexOf(profileName);
if cbProfile.ItemIndex = -1 then
begin
@@ -149,15 +152,18 @@ begin
if cbProfile.ItemIndex > -1 then
begin
profile := TIniFile.Create(FProfilePath + cbProfile.Text + '.ini');
try
edHost.Text := profile.ReadString('Connection', 'Host', '');
edPort.Value := profile.ReadInteger('Connection', 'Port', 2597);
edUsername.Text := profile.ReadString('Connection', 'Username', '');
edPassword.Text := '';
edData.Text := profile.ReadString('Data', 'Path', '');
edPassword.SetFocus;
finally
profile.Free;
end;
end;
end;
procedure TfrmLogin.FormClose(Sender: TObject; var CloseAction: TCloseAction);
begin
+73 -19
View File
@@ -37,7 +37,7 @@ uses
LCLIntf, UOverlayUI, UStatics, UEnhancedMemoryStream, ActnList,
XMLPropStorage, ImagingClasses, dateutils, UPlatformTypes, UMap, UPacket,
UGLFont, DOM, XMLRead, XMLWrite, strutils, ULightManager, fgl, UTiledata,
UActions, UUoaDesigns;
UActions, UUoaDesigns, UArt;
type
TAccessChangedListener = procedure(AAccessLevel: TAccessLevel) of object;
@@ -369,10 +369,14 @@ type
FCurrentUoaDesign: TUoaDesign;
FCurrentUoaDesignAnchor: TWorldItem;
FCurrentUoaTiles: TStaticItemList;
FArtListCache: array[0..High(Word)] of TArt;
FArtListCached: array[0..High(Word)] of Boolean;
FArtListMissing: array[0..High(Word)] of Boolean;
{ Methods }
procedure BuildTileList;
function ConfirmAction: Boolean;
procedure EnableActions(AEnabled: Boolean);
function GetCachedArt(AID: Word): TArt;
function FindRandomPreset(AName: String): TDOMElement;
procedure ForceUpdateCurrentTile;
procedure GetDrawOffset(AX, AY: Integer; out DrawX, DrawY: Integer); inline;
@@ -443,7 +447,7 @@ var
implementation
uses
UdmNetwork, UArt, UAdminHandling, UPackets,
UdmNetwork, UAdminHandling, UPackets,
UfrmAccountControl, UGraphicHelper, ImagingComponents, UfrmDrawSettings,
UfrmBoundaries, UfrmElevateSettings, UfrmConfirmation, UfrmMoveSettings,
UfrmAbout, UPacketHandlers, UfrmHueSettings, UfrmRadar, UfrmLargeScaleCommand,
@@ -729,7 +733,7 @@ var
tileX, tileY, newX, newY: Word;
targetBlocks: TBlockInfoList;
targetTile: TWorldItem;
selectionListener: TSelectionListener;
listenerIndex: Integer;
begin
Logger.EnterMethod([lcClient, lcDebug], 'MouseUp');
if Button <> mbLeft then
@@ -757,9 +761,9 @@ begin
mnuGrabTileIDClick(nil);
end;
for selectionListener in FSelectionListeners do
for listenerIndex := FSelectionListeners.Count - 1 downto 0 do
begin
selectionListener(CurrentTile);
FSelectionListeners[listenerIndex](CurrentTile);
end;
end;
@@ -801,6 +805,7 @@ begin
(not frmMoveSettings.cbAsk.Checked) or ConfirmAction then
begin
targetBlocks := TBlockInfoList.Create;
try
if SelectedTile = targetTile then
begin
blockInfo := nil;
@@ -901,11 +906,13 @@ begin
end;
end;
finally
targetBlocks.Free;
end;
end;
end;
end;
end;
acUndo.Enabled := FUndoList.Count > 0;
SelectedTile := nil;
FRepaintNeeded := True;
@@ -1068,7 +1075,7 @@ begin
if cbRandomPreset.ItemIndex > -1 then
begin
preset := TDOMElement(cbRandomPreset.Items.Objects[cbRandomPreset.ItemIndex]);
FRandomPresetsDoc.DocumentElement.RemoveChild(preset);
FRandomPresetsDoc.DocumentElement.RemoveChild(preset).Free;
cbRandomPreset.Items.Delete(cbRandomPreset.ItemIndex);
cbRandomPreset.ItemIndex := -1;
end;
@@ -1097,7 +1104,7 @@ begin
begin
children := presetElement.ChildNodes;
for i := children.Count - 1 downto 0 do
presetElement.RemoveChild(children[i]);
presetElement.RemoveChild(children[i]).Free;
end;
tileNode := vdtRandom.GetFirst;
@@ -1406,6 +1413,8 @@ begin
end;
procedure TfrmMain.FormDestroy(Sender: TObject);
var
i: Integer;
begin
CurrentTile := nil;
SelectedTile := nil;
@@ -1413,6 +1422,14 @@ begin
SaveLocations;
SaveRandomPresets;
for i := 0 to High(FArtListCache) do
if FArtListCached[i] and not FArtListMissing[i] then
FArtListCache[i].Free;
for i := 0 to High(FArtListCache) do
if PtrUInt(FArtListCache[i]) > 1 then
FArtListCache[i].Free;
FreeAndNil(FTextureManager);
FreeAndNil(FScreenBuffer);
FreeAndNil(FOverlayUI);
@@ -1725,6 +1742,23 @@ begin
FTileHint.FlagsRect, DT_WORDBREAK);
end;
function TfrmMain.GetCachedArt(AID: Word): TArt;
begin
if not FArtListCached[AID] then
begin
FArtListCached[AID] := True;
if ResMan.Art.Exists(AID) then
FArtListCache[AID] := ResMan.Art.GetArt(AID,
RGB2ARGB(vdtTiles.Canvas.Pixels[0, 0]), nil, False)
else
FArtListMissing[AID] := True;
end;
if FArtListMissing[AID] then
Result := nil
else
Result := FArtListCache[AID];
end;
procedure TfrmMain.vdtTilesDrawNode(Sender: TBaseVirtualTree;
const PaintInfo: TVTPaintInfo);
var
@@ -1750,14 +1784,9 @@ begin
end;
1:
begin
if ResMan.Art.Exists(tileInfo^.ID) then
begin
artEntry := ResMan.Art.GetArt(tileInfo^.ID,
RGB2ARGB(PaintInfo.Canvas.Pixels[PaintInfo.CellRect.Left,
PaintInfo.CellRect.Top]), nil, False);
artEntry := GetCachedArt(tileInfo^.ID);
if artEntry <> nil then
DisplayImage(PaintInfo.Canvas, PaintInfo.CellRect, artEntry.Graphic);
artEntry.Free;
end;
end;
2:
begin
@@ -1974,8 +2003,12 @@ begin
Stream.Read(locationInfo^.Y, SizeOf(Word));
stringLength := 0;
Stream.Read(stringLength, SizeOf(Integer));
if stringLength > 0 then
begin
SetLength(s, stringLength);
Stream.Read(s[1], stringLength);
end else
SetLength(s, 0);
locationInfo^.Name := s;
end;
@@ -2002,6 +2035,7 @@ begin
Stream.Write(locationInfo^.Y, SizeOf(Word));
stringLength := Length(locationInfo^.Name);
Stream.Write(stringLength, SizeOf(Integer));
if stringLength > 0 then
Stream.Write(locationInfo^.Name[1], stringLength);
end;
@@ -2352,13 +2386,16 @@ end;
procedure TfrmMain.MoveUoaDesign(AX, AY: Word; AZ: ShortInt);
var
offsetX, offsetY, offsetZ, maxZ: Integer;
offsetX, offsetY, offsetZ, maxZ, minZ: Integer;
item: TStaticItem;
begin
maxZ := Low(Integer);
minZ := High(Integer);
for item in FCurrentUoaDesign.Tiles do
if item.Z > maxZ then
maxZ := item.Z;
begin
if item.Z > maxZ then maxZ := item.Z;
if item.Z < minZ then minZ := item.Z;
end;
offsetX := AX - FCurrentUoaDesign.Header.Width div 2;
offsetY := AY - FCurrentUoaDesign.Header.Height div 2;
@@ -2372,6 +2409,8 @@ begin
offsetY := FLandscape.CellHeight - FCurrentUoaDesign.Header.Height;
if offsetZ + maxZ > 127 then
offsetZ := 127 - maxZ;
if offsetZ + minZ < -128 then
offsetZ := -128 - minZ;
for item in FCurrentUoaTiles do
begin
@@ -2526,7 +2565,7 @@ begin
ABlockInfo^.HighRes := nil;
ABlockInfo^.CheckRealQuad := False;
ABlockInfo^.Text.Free;
FreeAndNil(ABlockInfo^.Text);
if item is TMapCell then
begin
@@ -2715,6 +2754,7 @@ var
intensity, red, green, blue: GLfloat;
blockInfo: PBlockInfo;
item: TWorldItem;
lightMode: Integer;
begin
if not (sbsValid in FScreenBufferState) then
RebuildScreenBuffer;
@@ -2729,6 +2769,7 @@ begin
UpdateFilter;
blockInfo := nil;
lightMode := -1;
while FScreenBuffer.Iterate(blockInfo) do
begin
if blockInfo^.State = ssFiltered then
@@ -2739,11 +2780,19 @@ begin
if acSelect.Checked or item.CanBeEdited or (item is TVirtualTile) then
begin
intensity := 1.0;
if lightMode <> 0 then
begin
SetNormalLights;
lightMode := 0;
end;
end else
begin
intensity := 0.5;
if lightMode <> 1 then
begin
SetDarkLights;
lightMode := 1;
end;
end;
case blockInfo^.WalkRestriction of
@@ -3320,6 +3369,8 @@ procedure TfrmMain.UpdateSelection;
if ABlockInfo^.HueOverride <> AHighlighted then
begin
ABlockInfo^.HueOverride := AHighlighted;
if ABlockInfo^.LowRes <> nil then
ABlockInfo^.LowRes.DelRef;
if AHighlighted then
begin
ABlockInfo^.Hue := frmHueSettings.GetHue;
@@ -3540,7 +3591,9 @@ begin
$02:
begin
sender := ABuffer.ReadStringNull;
lbClients.Items.Delete(lbClients.Items.IndexOf(sender));
i := lbClients.Items.IndexOf(sender);
if i > -1 then
lbClients.Items.Delete(i);
if sender <> dmNetwork.Username then
WriteChatMessage('System', Format('User "%s" has disconnected.', [sender]));
end;
@@ -3614,6 +3667,7 @@ end;
function TfrmMain.GetSelectedRect: TRect;
begin
Result := Rect(-1, -1, -1, -1);
if CurrentTile <> nil then
begin
if SelectedTile <> nil then
+23 -5
View File
@@ -110,18 +110,27 @@ var
begin
RegisterPacketHandler($0D, nil);
if FRadarDependencies <> nil then FreeAndNil(FRadarDependencies);
if FRadar <> nil then
begin
SetLength(radarMap, FRadar.Width * FRadar.Height);
if Length(radarMap) > 0 then
begin
for x := 0 to FRadar.Width - 1 do
for y := 0 to FRadar.Height - 1 do
radarMap[x * FRadar.Height + y] := EncodeUOColor(PInteger(FRadar.PixelPointer[x, y])^);
radarMapFile := TFileStream.Create(GetAppConfigDir(False) + 'RadarMap.cache',
fmCreate);
try
radarMapFile.Write(radarMap[0], Length(radarMap) * SizeOf(Word));
finally
radarMapFile.Free;
if FRadarDependencies <> nil then FreeAndNil(FRadarDependencies);
if FRadar <> nil then FreeAndNil(FRadar);
end;
end;
FreeAndNil(FRadar);
end;
end;
procedure TfrmRadarMap.FormResize(Sender: TObject);
@@ -183,12 +192,17 @@ begin
if FileExists(radarMapFileName) then
begin
radarMapFile := TFileStream.Create(radarMapFileName, fmOpenRead);
try
SetLength(radarMap, radarMapFile.Size div SizeOf(Word));
if Length(radarMap) > 0 then
begin
radarMapFile.Read(radarMap[0], radarMapFile.Size);
radarMapFile.Free;
realChecksum := crc32(realChecksum, @radarMap[0], Length(radarMap) * SizeOf(Word));
end;
finally
radarMapFile.Free;
end;
end;
if checksum <> realChecksum then
begin
@@ -203,6 +217,7 @@ begin
$02: //radar map
begin
SetLength(radarMap, (ABuffer.Size - ABuffer.Position) div SizeOf(Word));
if Length(radarMap) > 0 then
ABuffer.Read(radarMap[0], Length(radarMap) * SizeOf(Word));
RefreshRadar(radarMap);
//frmMain.Enabled := True;
@@ -213,11 +228,14 @@ begin
begin
x := ABuffer.ReadWord;
y := ABuffer.ReadWord;
if (x < FRadar.Width) and (y < FRadar.Height) then
begin
PInteger(FRadar.PixelPointer[x, y])^ := DecodeUOColor(ABuffer.ReadWord);
RepaintRadar;
end;
end;
end;
end;
procedure TfrmRadarMap.RefreshRadar(ARadarMap: TRadarColorMap);
var
+10 -2
View File
@@ -105,6 +105,7 @@ type
FLastY: Integer;
FAreaMove: TAreaMove;
FTempRegionNode: PVirtualNode;
FEditedRegionNode: PVirtualNode;
FOnRegionModified: TRegionModifiedEvent;
FOnRegionDeleted: TRegionDeletedEvent;
FOnRegionList: TRegionListEvent;
@@ -162,7 +163,7 @@ begin
inherited Create($03, 0); //Admin Packet
FStream.WriteByte($08); //Admin PacketID
FStream.WriteStringNull(ARegionInfo.Name);
count := Min(ARegionInfo.Areas.Count, 256);
count := Min(ARegionInfo.Areas.Count, 255);
FStream.WriteByte(count);
for i := 0 to count - 1 do
begin
@@ -220,6 +221,7 @@ end;
procedure TfrmRegionControl.FormDestroy(Sender: TObject);
begin
frmRadarMap.Dependencies.Remove(pbArea);
frmMain.UnregisterAccessChangedListener(@OnAccessChanged);
FreeAndNil(AdminPacketHandlers[$08]);
FreeAndNil(AdminPacketHandlers[$09]);
FreeAndNil(AdminPacketHandlers[$0A]);
@@ -244,7 +246,7 @@ begin
if FTempRegionNode <> nil then
regionNode := FTempRegionNode
else
regionNode := vstRegions.GetFirstSelected;
regionNode := FEditedRegionNode;
if regionNode <> nil then
begin
regionInfo := vstRegions.GetNodeData(regionNode);
@@ -286,6 +288,7 @@ begin
regionInfo^.Areas := TRectList.Create;
vstRegions.ClearSelection;
vstRegions.Selected[FTempRegionNode] := True;
FEditedRegionNode := FTempRegionNode;
btnSave.Enabled := True;
end else
begin
@@ -401,6 +404,7 @@ begin
areaInfo^.Bottom := p.y;
pbArea.Repaint;
FAreaMove := [amRight, amBottom];
btnSave.Enabled := True;
end;
vstArea.ClearSelection;
vstArea.Selected[match] := True;
@@ -565,6 +569,7 @@ begin
vstArea.EndUpdate;
pbArea.Repaint;
FEditedRegionNode := selected;
btnSave.Enabled := False; //no changes to be saved
end;
@@ -696,6 +701,9 @@ var
regionInfo: PRegionInfo;
begin
vstRegions.BeginUpdate;
FTempRegionNode := nil;
FEditedRegionNode := nil;
btnSave.Enabled := False;
vstRegions.Clear;
regionCount := ABuffer.ReadByte;
for i := 0 to regionCount - 1 do
+24
View File
@@ -352,6 +352,8 @@ uses
GLib2, GDK2, GTK2, GTK2Def, GTK2Proc,
{$ELSEIF Defined(LCLqt5)}
Qt5, qtobjects,
{$ELSEIF Defined(LCLqt6)}
Qt6, qtobjects,
{$ELSEIF Defined(LCLcocoa)}
CocoaGDIObjects, CocoaUtils,
{$IFEND}
@@ -916,6 +918,28 @@ begin
end;
end;
end;
{$ELSEIF Defined(LCLqt6)}
var
QImage: TQtImage;
Context: TQtDeviceContext;
begin
if TestImage(ImageData) then
begin
if not (ImageData.Format in [ifA8R8G8B8, ifX8R8G8B8]) then
raise EImagingError.Create(SBadFormatDisplay);
Context := TQtDeviceContext(DstCanvas.Handle);
// QImage directly uses the image memory, there is no copy done
QImage := TQtImage.Create(ImageData.Bits, ImageData.Width, ImageData.Height,
ImageData.Width * 4, QImageFormat_ARGB32, False);
try
QPainter_drawImage(Context.Widget, PRect(@DstRect), QImage.Handle, @SrcRect, QtAutoColor);
finally
QImage.Free;
end;
end;
end;
{$ELSEIF Defined(LCLcocoa)}
var
CocoaBmp: TCocoaBitmap;
+6
View File
@@ -93,6 +93,8 @@ end;
function TAnimDataProvider.GetData(AID, AOffset: Integer): TAnimData;
begin
if (AID < 0) or (AID >= Length(FAnimData)) then
raise Exception.CreateFmt('Invalid animdata ID %d', [AID]);
Result := FAnimData[AID];
end;
@@ -114,6 +116,8 @@ end;
procedure TAnimDataProvider.SetData(AID, AOffset: Integer; ABlock: TMulBlock);
begin
if (AID < 0) or (AID >= Length(FAnimData)) then
raise Exception.CreateFmt('Invalid animdata ID %d', [AID]);
FreeAndNil(FAnimData[AID]);
FAnimData[AID] := TAnimData(ABlock.Clone);
@@ -126,6 +130,8 @@ end;
function TAnimDataProvider.GetBlock(AID: Integer): TAnimData;
begin
if (AID < 0) or (AID >= Length(FAnimData)) then
raise Exception.CreateFmt('Invalid animdata ID %d', [AID]);
Result := FAnimData[AID].Clone;
end;
+4 -1
View File
@@ -91,7 +91,10 @@ var
begin
FIndex.Position := CalculateIndexOffset(AID);
genericIndex := TGenericIndex.Create(FIndex);
Result := TArt.Create(FData, genericIndex, atLandFlat);
if (genericIndex.Lookup > -1) and (genericIndex.Size > 0) then
Result := TArt.Create(FData, genericIndex, atLandFlat)
else
Result := TArt.Create(nil, nil, atLandFlat);
genericIndex.Free;
Result.OnChanged := @OnChanged;
Result.OnFinished := @OnFinished;
+1 -1
View File
@@ -45,7 +45,7 @@ implementation
function TGumpProvider.GetData(AID: Integer; AIndex: TGenericIndex): TMulBlock;
begin
if AIndex.Lookup <> LongInt($FFFFFFFF) then
if (AIndex.Lookup > -1) and (AIndex.Size > 0) then
Result := TGump.Create(FData, TGumpIndex(AIndex))
else
Result := TGump.Create(0, 0);
+4
View File
@@ -92,6 +92,8 @@ function THueProvider.GetData(AID, AOffset: Integer): TMulBlock;
var
group, entry: Integer;
begin
if (AID < 0) or (AID >= FHueGroups.Count * 8) then
raise Exception.CreateFmt('Invalid hue ID %d', [AID]);
group := (AID div 8) mod FHueGroups.Count;
entry := AID mod 8;
Result := TMulBlock(THueGroup(FHueGroups.Items[group]).HueEntries[entry].Clone);
@@ -104,6 +106,8 @@ function THueProvider.GetHue(AIndex: Integer): THue;
var
group, entry: Integer;
begin
if (AIndex < 0) or (AIndex >= FHueGroups.Count * 8) then
raise Exception.CreateFmt('Invalid hue ID %d', [AIndex]);
group := (AIndex div 8) mod FHueGroups.Count;
entry := AIndex mod 8;
Result := THue(THueGroup(FHueGroups.Items[group]).HueEntries[entry]);
+1
View File
@@ -72,6 +72,7 @@ begin
RegisterGumpProvider(nil);
RegisterTexmapProvider(nil);
RegisterTileDataProvider(nil);
RegisterAnimDataProvider(nil);
RegisterHueProvider(nil);
RegisterRadarProvider(nil);
inherited Destroy;
+16 -9
View File
@@ -46,6 +46,7 @@ type
FLandTiles: TLandTileDataArray;
FStaticTiles: TStaticTileDataArray;
FStaticCount: Cardinal;
FVersion: TTileDataVersion;
procedure InitArray;
function CalculateOffset(AID: Integer): Integer; override;
function GetData(AID, AOffset: Integer): TMulBlock; override;
@@ -68,7 +69,7 @@ uses
function TTiledataProvider.CalculateOffset(AID: Integer): Integer;
begin
Result := GetTileDataOffset(AID);
Result := GetTileDataOffset(AID, FVersion);
end;
constructor TTiledataProvider.Create(AData: TStream; AReadOnly: Boolean = False);
@@ -114,13 +115,17 @@ end;
procedure TTiledataProvider.InitArray;
var
i: Integer;
version: TTileDataVersion;
staticGroupSize: Integer;
begin
//Guess the version by looking at the filesize.
if FData.Size >= 3188736 then
version := tdvHighSeas
FVersion := tdvHighSeas
else
version := tdvLegacy;
FVersion := tdvLegacy;
if FVersion >= tdvHighSeas then
staticGroupSize := StaticTileGroupSizeHS
else
staticGroupSize := StaticTileGroupSize;
FData.Position := 0;
Logger.Send([lcInfo], 'Loading $4000 LandTiledata Entries');
@@ -128,13 +133,13 @@ begin
begin
//In High Seas, the first header comes AFTER the unknown tile (for whatever
//reason). Therefore special handling is required.
if ((version = tdvLegacy) and (i mod 32 = 0)) or
((version >= tdvHighSeas) and ((i = 1) or ((i > 1) and (i mod 32 = 0)))) then
if ((FVersion = tdvLegacy) and (i mod 32 = 0)) or
((FVersion >= tdvHighSeas) and ((i = 1) or ((i > 1) and (i mod 32 = 0)))) then
FData.Seek(4, soFromCurrent);
FLandTiles[i] := TLandTileData.Create(FData, version);
FLandTiles[i] := TLandTileData.Create(FData, FVersion);
end;
FStaticCount := ((FData.Size - FData.Position) div StaticTileGroupSize) * 32;
FStaticCount := ((FData.Size - FData.Position) div staticGroupSize) * 32;
Logger.Send([lcInfo], 'Loading $%x StaticTiledata Entries', [FStaticCount]);
SetLength(FStaticTiles, FStaticCount);
@@ -142,7 +147,7 @@ begin
begin
if i mod 32 = 0 then
FData.Seek(4, soFromCurrent);
FStaticTiles[i] := TStaticTileData.Create(FData, version);
FStaticTiles[i] := TStaticTileData.Create(FData, FVersion);
end;
end;
@@ -171,6 +176,8 @@ end;
function TTiledataProvider.GetTileData(AID: Integer): TTiledata;
begin
if (AID < 0) or (AID >= $4000 + Integer(FStaticCount)) then
raise Exception.CreateFmt('Invalid tiledata ID %d', [AID]);
if AID < $4000 then
Result := FLandTiles[AID]
else
+8 -4
View File
@@ -98,7 +98,8 @@ begin
while CEDServerInstance.TCPServer.IterNext do
begin
netState := TNetState(CEDServerInstance.TCPServer.Iterator.UserData);
if (netState <> nil) and (netState.Account.AccessLevel >= AAccessLevel) then
if (netState <> nil) and (netState.Account <> nil) and
(netState.Account.AccessLevel >= AAccessLevel) then
CEDServerInstance.SendPacket(netState, APacket, False);
end;
APacket.Free;
@@ -278,7 +279,7 @@ begin
while CEDServerInstance.TCPServer.IterNext do
begin
netState := TNetState(CEDServerInstance.TCPServer.Iterator.UserData);
if netState <> nil then
if (netState <> nil) and (netState.Account <> nil) then
begin
account := netState.Account;
i := 0;
@@ -342,8 +343,11 @@ begin
inherited Create($03, 0);
FStream.WriteByte($05);
FStream.WriteByte(Byte(AStatus));
FStream.WriteStringNull(AAccount.Name);
if (AStatus = muAdded) or (AStatus = muModified) then
if AAccount <> nil then
FStream.WriteStringNull(AAccount.Name)
else
FStream.WriteStringNull('');
if ((AStatus = muAdded) or (AStatus = muModified)) and (AAccount <> nil) then
begin
FStream.WriteByte(Byte(AAccount.AccessLevel));
FStream.WriteByte(AAccount.Regions.Count);
+32 -3
View File
@@ -48,6 +48,7 @@ type
FTCPServer: TLTcp;
FQuit: Boolean;
FLastFlush: TDateTime;
FLastNetCheck: TDateTime;
FValid: Boolean;
procedure OnAccept(ASocket: TLSocket);
procedure OnCanSend(ASocket: TLSocket);
@@ -121,6 +122,7 @@ begin
FTCPServer.OnError := @OnError;
FQuit := False;
FLastFlush := Now;
FLastNetCheck := Now;
end;
destructor TCEDServer.Destroy;
@@ -228,18 +230,37 @@ begin
size := packetHandler.PacketLength;
if size = 0 then
begin
if buffer.Size > 5 then
if buffer.Size >= 5 then
size := buffer.ReadCardinal
else
Break; //wait for more data
end;
if buffer.Size >= size then
if (size < 5) or (size > 32 * 1024 * 1024) then
begin
Writeln(TimeStamp, 'Dropping client due to invalid packet size: ', ANetState.Socket.PeerAddress);
Disconnect(ANetState.Socket);
buffer.Clear;
end else if buffer.Size >= size then
begin
buffer.Lock(buffer.Position, size - buffer.Position); //prevent handler from reading too much
try
packetHandler.Process(buffer, ANetState);
except
on E: Exception do
begin
Logger.SendException([lcServer], 'Error in packet handler', E);
Writeln(TimeStamp, 'Error processing packet of client: ', ANetState.Socket.PeerAddress);
buffer.Unlock;
Disconnect(ANetState.Socket);
buffer.Clear;
end;
end;
if ANetState.Socket.ConnectionStatus = scConnected then
begin
buffer.Unlock;
buffer.Dequeue(size);
end;
end else
Break; //wait for more data
end else
@@ -255,6 +276,9 @@ begin
begin
Logger.SendException([lcServer], 'Error processing buffer', E);
Writeln(TimeStamp, 'Error processing buffer of client: ', ANetState.Socket.PeerAddress);
buffer.Unlock;
Disconnect(ANetState.Socket);
buffer.Clear;
end;
end;
end;
@@ -299,7 +323,11 @@ begin
begin
repeat
FTCPServer.CallAction;
if SecondsBetween(FLastNetCheck, Now) >= 1 then
begin
CheckNetStates;
FLastNetCheck := Now;
end;
if SecondsBetween(FLastFlush, Now) >= 60 then
begin
FLandscape.Flush;
@@ -327,7 +355,8 @@ begin
while FTCPServer.IterNext do
begin
netState := TNetState(FTCPServer.Iterator.UserData);
if (netState <> nil) and (FTCPServer.Iterator.ConnectionStatus = scConnected) then
if (netState <> nil) and (netState.Account <> nil) and
(FTCPServer.Iterator.ConnectionStatus = scConnected) then
begin
netState.SendQueue.Seek(0, soFromEnd);
netState.SendQueue.CopyFrom(APacket.Stream, 0);
+4 -2
View File
@@ -203,6 +203,7 @@ begin
inherited Create;
FFilename := AFilename;
ReadXMLFile(xmlDoc, AFilename);
try
version := 0;
if not ((xmlDoc.DocumentElement.NodeName = 'CEDConfig') and
TryStrToInt(xmlDoc.DocumentElement.AttribStrings['Version'], version) and
@@ -236,9 +237,10 @@ begin
else
FMapStates := TMapStates.Create(Self);
xmlDoc.Free;
FChanged := False;
finally
xmlDoc.Free;
end;
end;
constructor TConfig.Init(AFilename: string);
+18 -4
View File
@@ -373,7 +373,7 @@ end;
function TLandscape.GetBlockSubscriptions(AX, AY: Word): TLinkedList;
begin
if (AX >= 0) and (AX <= FWidth) and (AY >= 0) and (AY <= FHeight) then
if (AX < FWidth) and (AY < FHeight) then
Result := FBlockSubscriptions[(AY * FWidth) + AX]
else
Result := nil;
@@ -384,7 +384,7 @@ var
block: TMapBlock;
begin
Result := nil;
if (AX >= 0) and (AX <= FCellWidth) and (AY >= 0) and (AY <= FCellHeight) then
if (AX < FCellWidth) and (AY < FCellHeight) then
begin
block := GetMapBlock(AX div 8, AY div 8);
if block <> nil then
@@ -405,7 +405,7 @@ var
block: TSeperatedStaticBlock;
begin
Result := nil;
if (AX >= 0) and (AX <= FCellWidth) and (AY >= 0) and (AY <= FCellHeight) then
if (AX < FCellWidth) and (AY < FCellHeight) then
begin
block := GetStaticBlock(AX div 8, AY div 8);
if block <> nil then
@@ -538,6 +538,10 @@ var
index: TGenericIndex;
begin
FMap.Position := ((AX * FHeight) + AY) * 196;
map := nil;
statics := nil;
index := nil;
try
map := TMapBlock.Create(FMap, AX, AY);
FStaIdx.Position := ((AX * FHeight) + AY) * 12;
@@ -547,6 +551,12 @@ begin
index.Free;
Result := TBlock.Create(map, statics);
except
map.Free;
statics.Free;
index.Free;
raise;
end;
FBlockCache.StoreID(GetID(AX, AY), Result);
end;
@@ -952,6 +962,7 @@ begin
CEDServerInstance.SendPacket(nil, TServerStatePacket.Create(ssOther,
Format('%s is performing large scale operations ...', [ANetState.Account.Name])));
try
//Bitmask
emptyBits := TBits.Create(64);
SetLength(bitMask, FWidth * FHeight);
@@ -1136,6 +1147,7 @@ begin
end;
//clean up
finally
for i := Low(bitMask) to High(bitMask) do
bitMask[i].Free;
emptyBits.Free;
@@ -1145,8 +1157,10 @@ begin
TLargeScaleOperation(operations.Items[i]).Free;
operations.Free;
//Update clients
FRadarMap.EndUpdate;
end;
//Update clients
for i := Low(clients) to High(clients) do
begin
if Length(clients[i].Blocks) > 0 then
+11 -2
View File
@@ -255,6 +255,7 @@ begin
inherited Init(AData, ALandscape);
count := AData.ReadWord;
SetLength(FTileIDs, count);
if count > 0 then
AData.Read(FTileIDs[0], count * SizeOf(Word));
end;
@@ -275,6 +276,7 @@ begin
inherited Init(AData, ALandscape);
count := AData.ReadWord;
SetLength(FTileIDs, count);
if count > 0 then
AData.Read(FTileIDs[0], count * SizeOf(Word));
FMinZ := AData.ReadShortInt;
FMaxZ := AData.ReadShortInt;
@@ -325,6 +327,7 @@ begin
inherited Init(AData, ALandscape);
count := AData.ReadWord;
SetLength(FTileIDs, count);
if count > 0 then
AData.Read(FTileIDs[0], count * SizeOf(Word));
FProbability := AData.ReadByte;
FPlacementType := TStaticsPlacement(AData.ReadByte);
@@ -337,14 +340,17 @@ procedure TLSInsertStatics.Apply(AMapCell: TMapCell; AStatics: TStaticItemList;
var
staticItem, static: TStaticItem;
topZ, staticTop: ShortInt;
i: Integer;
i, tileID: Integer;
begin
if (Length(FTileIDs) = 0) or (Random(100) >= FProbability) then Exit;
tileID := FTileIDs[Random(Length(FTileIDs))];
if tileID < $4000 then Exit;
staticItem := TStaticItem.Create(nil, nil, 0, 0);
staticItem.X := AMapCell.X;
staticItem.Y := AMapCell.Y;
staticItem.TileID := FTileIDs[Random(Length(FTileIDs))] - $4000;
staticItem.TileID := tileID - $4000;
staticItem.Hue := 0;
case FPlacementType of
@@ -358,12 +364,15 @@ begin
for i := 0 to AStatics.Count - 1 do
begin
static := AStatics[i];
if static.TileID < Integer(CEDServerInstance.Landscape.TiledataProvider.StaticCount) then
begin
staticTop := EnsureRange(static.Z +
CEDServerInstance.Landscape.TiledataProvider.StaticTiles[static.TileID].Height,
-128, 127);
if staticTop > topZ then topZ := staticTop;
end;
end;
end;
spFix:
begin
staticItem.Z := FFixZ;
+18 -2
View File
@@ -133,19 +133,34 @@ var
uncompStream: TEnhancedMemoryStream;
uncompBuffer: TDecompressionStream;
targetSize: Cardinal;
innerSize: Cardinal;
packetID: Byte;
begin
targetSize := ABuffer.ReadCardinal;
if (targetSize < 5) or (targetSize > 64 * 1024 * 1024) then
begin
Writeln(TimeStamp, 'Dropping client due to invalid compressed packet size: ', ANetState.Socket.PeerAddress);
ANetState.ReceiveQueue.Clear;
CEDServerInstance.Disconnect(ANetState.Socket);
Exit;
end;
uncompBuffer := TDecompressionStream.Create(ABuffer);
uncompStream := TEnhancedMemoryStream.Create;
try
uncompStream.CopyFrom(uncompBuffer, targetSize);
uncompStream.Position := 0;
packetID := uncompStream.ReadByte;
if PacketHandlers[packetID] <> nil then
if (packetID <> $01) and (PacketHandlers[packetID] <> nil) then
begin
if PacketHandlers[PacketID].PacketLength = 0 then
uncompStream.Position := uncompStream.Position + 4;
begin
innerSize := uncompStream.ReadCardinal;
if (innerSize < 5) or
(uncompStream.Size - uncompStream.Position < innerSize - 5) then
Exit;
end else if uncompStream.Size - uncompStream.Position <
PacketHandlers[PacketID].PacketLength - 1 then
Exit;
uncompStream.Lock(uncompStream.Position, uncompStream.Size - uncompStream.Position);
PacketHandlers[PacketID].Process(uncompStream, ANetState);
uncompStream.Unlock;
@@ -167,6 +182,7 @@ var
begin
if not ValidateAccess(ANetState, alView) then Exit;
SetLength(coords, (ABuffer.Size - ABuffer.Position) div SizeOf(TBlockCoords));
if Length(coords) = 0 then Exit;
ABuffer.Read(coords[0], Length(coords) * SizeOf(TBlockCoords));
CEDServerInstance.SendPacket(ANetState, TCompressedPacket.Create(TBlockPacket.Create(coords, ANetState)));
end;
+6
View File
@@ -102,12 +102,18 @@ begin
inherited Create($01, 0);
sourceStream := APacket.Stream;
compBuffer := TEnhancedMemoryStream.Create;
try
compStream := TCompressionStream.Create(clMax, compBuffer);
try
compStream.CopyFrom(sourceStream, 0);
finally
compStream.Free;
end;
FStream.WriteCardinal(sourceStream.Size);
FStream.CopyFrom(compBuffer, 0);
finally
compBuffer.Free;
end;
APacket.Free;
end;
+10 -3
View File
@@ -142,9 +142,13 @@ var
index: TMulIndex;
begin
radarcol := TFileStream.Create(ARadarCol, fmOpenRead);
try
SetLength(FRadarColors, radarcol.Size div SizeOf(Word));
radarcol.Read(FRadarColors[0], radarcol.Size);
if Length(FRadarColors) > 0 then
radarcol.Read(FRadarColors[0], Length(FRadarColors) * SizeOf(Word));
finally
radarcol.Free;
end;
FWidth := AWidth;
FHeight := AHeight;
@@ -159,13 +163,14 @@ begin
begin
AMap.Read(mapCell, SizeOf(TMapCell));
AMap.Seek(193, soFromCurrent);
if mapCell.TileID < Length(FRadarColors) then
FRadarMap[i] := FRadarColors[mapCell.TileID];
AStaIdx.Read(index, SizeOf(TMulIndex));
if (index.Position < $FFFFFFFF) and (index.Size > 0) then
if (index.Position < $FFFFFFFF) and (index.Size >= 7) then
begin
AStatics.Position := index.Position;
SetLength(staticsItems, index.Size div 7);
AStatics.Read(staticsItems[0], index.Size);
AStatics.Read(staticsItems[0], Length(staticsItems) * SizeOf(TStaticItem));
highestZ := mapCell.Altitude;
for item := Low(staticsItems) to High(staticsItems) do
begin
@@ -173,6 +178,7 @@ begin
(staticsItems[item].Z >= highestZ) then
begin
highestZ := staticsItems[item].Z;
if staticsItems[item].TileID + $4000 < Length(FRadarColors) then
FRadarMap[i] := FRadarColors[staticsItems[item].TileID + $4000];
end;
end;
@@ -221,6 +227,7 @@ var
packet: TPacket;
begin
block := AX * FHeight + AY;
if ATileID >= Length(FRadarColors) then Exit;
color := FRadarColors[ATileID];
if FRadarMap[block] <> color then
begin
+4 -1
View File
@@ -5,6 +5,9 @@
<General>
<Flags>
<MainUnitHasUsesSectionForAllUnits Value="False"/>
<MainUnitHasCreateFormStatements Value="False"/>
<MainUnitHasTitleStatement Value="False"/>
<MainUnitHasScaledStatement Value="False"/>
<LRSInOutputDirectory Value="False"/>
<CompatibilityMode Value="True"/>
</Flags>
@@ -366,7 +369,7 @@
</Target>
<SearchPaths>
<IncludeFiles Value="..;../Imaging"/>
<OtherUnitFiles Value="..;../UOLib;../MulProvider;../Imaging/ZLib"/>
<OtherUnitFiles Value="..;../UOLib;../MulProvider;../Imaging/ZLib;../Imaging"/>
<UnitOutputDirectory Value="../obj/$(TargetCPU)-$(TargetOS)"/>
</SearchPaths>
<Parsing>
+13 -3
View File
@@ -57,6 +57,7 @@ type
function Read(var Buffer; Count: Longint): Longint; override;
function Seek(Offset: Longint; Origin: Word): Longint; override;
procedure Refresh; override;
procedure Flush; override;
end;
implementation
@@ -80,10 +81,14 @@ begin
end;
procedure TBufferedStream.Flush;
var
memorySize: Int64;
begin
FBaseStream.Size := Size;
memorySize := inherited GetSize;
Position := 0;
FBaseStream.Size := memorySize;
FBaseStream.Position := 0;
FBaseStream.CopyFrom(Self, 0);
FBaseStream.CopyFrom(Self, memorySize);
end;
function TBufferedStream.GetSize: Int64;
@@ -136,9 +141,14 @@ end;
function TBufferedReader.Write(const Buffer; Count: Integer): Longint;
begin
FBaseStream.Position := FReadBuffer.Position;
FBaseStream.Write(Buffer, Count);
Result := FBaseStream.Write(Buffer, Count);
if Result < Count then Exit;
Result := FReadBuffer.Write(Buffer, Count);
end;
procedure TBufferedReader.Flush;
begin
end;
end.
+25 -7
View File
@@ -60,6 +60,7 @@ type
FLast: PCacheEntry;
FOnRemoveObject: TRemoveObjectEvent;
procedure DoRemoveObject(var AObject: T; ANotify: Boolean = True);
procedure UpdateLast;
public
constructor Create(ASize: Integer);
destructor Destroy; override;
@@ -103,6 +104,8 @@ var
i: Integer;
current: PCacheEntry;
begin
if ASize < 2 then
raise Exception.Create('TCacheManager requires a size of at least 2');
FOnRemoveObject := nil;
FSize := ASize;
if FSize > 0 then
@@ -219,29 +222,43 @@ begin
Result := ACacheEntry <> nil;
end;
procedure TCacheManager.UpdateLast;
begin
if FFirst = nil then
begin
FLast := nil;
Exit;
end;
FLast := FFirst;
if FLast^.Next = nil then Exit;
while FLast^.Next^.Next <> nil do
FLast := FLast^.Next;
end;
function TCacheManager.QueryID(const AID: Integer;
out AObj: T): Boolean;
var
current: PCacheEntry;
current, prev: PCacheEntry;
begin
current := FFirst;
FLast := current;
prev := nil;
Result := False;
while (current <> nil) and (not Result) do
while current <> nil do
begin
if (current^.ID = AID) then
if current^.ID = AID then
begin
Result := True;
AObj := current^.Obj;
if current <> FFirst then
begin
FLast^.Next := current^.Next;
prev^.Next := current^.Next;
current^.Next := FFirst;
FFirst := current;
UpdateLast;
end;
Break;
end;
if (current^.Next <> nil) then
FLast := current;
prev := current;
current := current^.Next;
end;
end;
@@ -281,6 +298,7 @@ begin
end;
FFirst^.ID := AID;
FFirst^.Obj := AObj;
UpdateLast;
end;
end.
+82 -34
View File
@@ -115,61 +115,105 @@ end;
function TEnhancedMemoryStream.ReadStringBigUniNull: WideString;
var
buffer: PWideChar;
length: Integer;
i, j, maxChars: Integer;
begin
Result := '';
buffer := Pointer(PtrInt(Memory) + Position);
length := 0;
while (buffer[length] <> #0) and (length < (Size - Position)) do
buffer := Pointer(PtrInt(FMemory) + FPosition);
maxChars := (FSize - (FPosition - FLockOffset)) div 2;
if maxChars <= 0 then Exit;
SetLength(Result, maxChars * 2);
i := 0;
j := 0;
while (i < maxChars) and (buffer[i] <> #0) do
begin
if (SwapWideChar(buffer[length]) = #10) and (SwapWideChar(buffer[length - 1]) <> #13) then
Result := Result + #13;
Result := Result + SwapWideChar(buffer[length]);
if (SwapWideChar(buffer[length]) = #13) and (SwapWideChar(buffer[length + 1]) <> #10) then
Result := Result + #10;
inc(length);
if (SwapWideChar(buffer[i]) = #10) and ((i = 0) or (SwapWideChar(buffer[i - 1]) <> #13)) then
begin
Inc(j);
Result[j] := #13;
end;
Position := Position + (Length + 1) * 2;
Inc(j);
Result[j] := SwapWideChar(buffer[i]);
if (SwapWideChar(buffer[i]) = #13) and ((i + 1 >= maxChars) or (SwapWideChar(buffer[i + 1]) <> #10)) then
begin
Inc(j);
Result[j] := #10;
end;
Inc(i);
end;
SetLength(Result, j);
if i < maxChars then
FPosition := FPosition + (i + 1) * 2
else
FPosition := FPosition + i * 2;
end;
function TEnhancedMemoryStream.ReadStringFixed(ALength: Integer): string;
var
buffer: PChar;
length: Integer;
i, j: Integer;
begin
Result := '';
buffer := Pointer(PtrInt(FMemory) + FPosition);
length := 0;
while (length < ALength) and (length < (FSize - (FPosition - FLockOffset))) do
if ALength <= 0 then Exit;
if ALength > (FSize - (FPosition - FLockOffset)) then
ALength := FSize - (FPosition - FLockOffset);
if ALength <= 0 then Exit;
SetLength(Result, ALength * 2);
i := 0;
j := 0;
while i < ALength do
begin
if (buffer[length] = #10) and (buffer[length - 1] <> #13) then
Result := Result + #13;
Result := Result + buffer[length];
if (buffer[length] = #13) and (buffer[length + 1] <> #10) then
Result := Result + #10;
inc(length);
if (buffer[i] = #10) and ((i = 0) or (buffer[i - 1] <> #13)) then
begin
Inc(j);
Result[j] := #13;
end;
FPosition := FPosition + length + 1;
Inc(j);
Result[j] := buffer[i];
if (buffer[i] = #13) and ((i + 1 >= ALength) or (buffer[i + 1] <> #10)) then
begin
Inc(j);
Result[j] := #10;
end;
Inc(i);
end;
SetLength(Result, j);
FPosition := FPosition + i;
end;
function TEnhancedMemoryStream.ReadStringNull: string;
var
buffer: PByteArray;
length: Integer;
i, j, maxLen: Integer;
begin
Result := '';
buffer := Pointer(PtrInt(FMemory) + FPosition);
length := 0;
while (buffer^[length] <> 0) and (length < (FSize - (FPosition - FLockOffset))) do
maxLen := FSize - (FPosition - FLockOffset);
if maxLen <= 0 then Exit;
SetLength(Result, maxLen * 2);
i := 0;
j := 0;
while (i < maxLen) and (buffer^[i] <> 0) do
begin
if (buffer^[length] = 10) and (buffer^[length - 1] <> 13) then
Result := Result + #13;
Result := Result + Char(buffer^[length]);
if (buffer^[length] = 13) and (buffer^[length + 1] <> 10) then
Result := Result + #10;
inc(length);
if (buffer^[i] = 10) and ((i = 0) or (buffer^[i - 1] <> 13)) then
begin
Inc(j);
Result[j] := #13;
end;
FPosition := FPosition + length + 1;
Inc(j);
Result[j] := Char(buffer^[i]);
if (buffer^[i] = 13) and ((i + 1 >= maxLen) or (buffer^[i + 1] <> 10)) then
begin
Inc(j);
Result[j] := #10;
end;
Inc(i);
end;
SetLength(Result, j);
if i < maxLen then
FPosition := FPosition + i + 1
else
FPosition := FPosition + i;
end;
function TEnhancedMemoryStream.ReadWord: Word;
@@ -224,10 +268,14 @@ end;
procedure TEnhancedMemoryStream.WriteStringFixed(AValue: string;
ALength: Integer);
var
i: Integer;
oldLength: Integer;
begin
for i := Length(AValue) to ALength do
AValue := AValue + #0;
oldLength := Length(AValue);
if oldLength < ALength then
begin
SetLength(AValue, ALength);
FillChar((PChar(AValue) + oldLength)^, ALength - oldLength, 0);
end;
Write(PChar(AValue)^, ALength);
end;
+8 -10
View File
@@ -95,7 +95,7 @@ end;
procedure TLinkedList.Delete(AData: Pointer);
var
currentItem, lastItem, nextItem: PLinkedItem;
currentItem, lastItem: PLinkedItem;
begin
lastItem := nil;
currentItem := FFirst;
@@ -107,17 +107,16 @@ begin
if FLast = currentItem then FLast := lastItem;
if lastItem <> nil then lastItem^.Next := currentItem^.Next;
Dispose(currentItem);
nextItem := nil;
end else
nextItem := currentItem^.Next;
Exit;
end;
lastItem := currentItem;
currentItem := nextItem;
currentItem := currentItem^.Next;
end;
end;
procedure TLinkedList.Delete(AID: Integer);
var
currentItem, lastItem, nextItem: PLinkedItem;
currentItem, lastItem: PLinkedItem;
begin
lastItem := nil;
currentItem := FFirst;
@@ -129,11 +128,10 @@ begin
if FLast = currentItem then FLast := lastItem;
if lastItem <> nil then lastItem^.Next := currentItem^.Next;
Dispose(currentItem);
nextItem := nil;
end else
nextItem := currentItem^.Next;
Exit;
end;
lastItem := currentItem;
currentItem := nextItem;
currentItem := currentItem^.Next;
end;
end;
+1
View File
@@ -144,6 +144,7 @@ var
begin
for i := 0 to 7 do
AnimData[i].Free;
inherited Destroy;
end;
procedure TAnimDataGroup.Write(AData: TStream);
+18 -10
View File
@@ -91,6 +91,7 @@ begin
begin
AData.Position := AIndex.Lookup;
block := TMemoryStream.Create;
try
block.CopyFrom(AData, AIndex.Size);
block.Position := 0;
@@ -195,7 +196,9 @@ begin
PWordArray(FGraphic.Bits)^[i] := PWordArray(FGraphic.Bits)^[i] xor $8000; //invert alpha bit
end else
FGraphic:= TSingleImage.Create;
if Assigned(block) then block.Free;
finally
block.Free;
end;
end else
begin
FHeader := 1;
@@ -233,7 +236,7 @@ end;
procedure TArt.RefreshBuffer;
var
argbGraphic: TSingleImage;
i, x, y, lineWidth, start: Integer;
i, y, lineWidth, start: Integer;
iCurrentHeight, iCurrentWidth: Integer;
width, height: SmallInt;
color, run, offset: Word;
@@ -246,27 +249,32 @@ begin
FBuffer.Size := 0;
if FArtType = atLand then
begin
if (argbGraphic.Height <> 44) or (argbGraphic.Width <> 44) then Exit;
x := 21;
if (argbGraphic.Height <> 44) or (argbGraphic.Width <> 44) then
begin
argbGraphic.Free;
Exit;
end;
y := 0;
lineWidth := 2;
for i := 1 to 22 do
begin
Dec(x);
FBuffer.Write(PWordArray(argbGraphic.Bits + y * 44 * 2)^[x + i], lineWidth);
FBuffer.Write(PWordArray(argbGraphic.Bits + y * 44 * 2)^[22 - i], lineWidth * 2);
Inc(y);
Inc(lineWidth, 2);
end;
for i := 1 to 22 do
begin
Dec(lineWidth, 2);
FBuffer.Write(PWordArray(argbGraphic.Bits + y * 44 * 2)^[x + i], lineWidth);
Inc(x);
FBuffer.Write(PWordArray(argbGraphic.Bits + y * 44 * 2)^[i - 1], lineWidth * 2);
Inc(y);
end;
end else if FArtType = atStatic then
begin
if (argbGraphic.Height = 0) or (argbGraphic.Width = 0) then Exit;
if (argbGraphic.Height = 0) or (argbGraphic.Width = 0) then
begin
argbGraphic.Free;
Exit;
end;
width := argbGraphic.Width;
height := argbGraphic.Height;
FBuffer.Write(FHeader, SizeOf(LongInt));
@@ -283,7 +291,7 @@ begin
run := 0;
for iCurrentWidth := 0 to width - 1 do //process every pixel on the current line
begin
color := PWordArray(FGraphic.Bits + iCurrentHeight * width * 2)^[iCurrentWidth];
color := PWordArray(argbGraphic.Bits + iCurrentHeight * width * 2)^[iCurrentWidth];
if (color and $8000 = 0) and (run = 0) then //new visible pixel found
begin
FBuffer.Write(offset, SizeOf(Word));
+9 -2
View File
@@ -122,6 +122,7 @@ begin
begin
AData.Position := AIndex.Lookup;
block := TMemoryStream.Create;
try
block.CopyFrom(AData, AIndex.Size);
block.Position := 0;
for i := 0 to AIndex.Height - 1 do
@@ -135,16 +136,22 @@ begin
iCurrentWidth := 0;
while iCurrentWidth < AIndex.Width do
begin
block.Read(Value, SizeOf(Word));
block.Read(Run, SizeOf(Word));
if (block.Read(Value, SizeOf(Word)) < SizeOf(Word)) or
(block.Read(Run, SizeOf(Word)) < SizeOf(Word)) or (Run = 0) then
Break;
if Value > 0 then Value := Value or $8000; //Set alpha bit of non-black colors
for i := 0 to Run - 1 do
begin
if iCurrentWidth + i >= AIndex.Width then Break;
PWordArray(FGraphic.Bits + iCurrentHeight * AIndex.Width * 2)^[iCurrentWidth + i] := Value;
end;
inc(iCurrentWidth, Run);
end;
end;
finally
block.Free;
end;
end;
FGraphic.Format := ifA8R8G8B8;
end;
+3
View File
@@ -103,6 +103,7 @@ begin
if AData <> nil then
begin
buffer := TMemoryStream.Create;
try
buffer.CopyFrom(AData, 88);
buffer.Position := 0;
for i := 0 to 31 do
@@ -113,9 +114,11 @@ begin
buffer.Read(FTableStart, SizeOf(Word));
buffer.Read(FTableEnd, SizeOf(Word));
buffer.Read(PChar(FName)^, 20);
finally
buffer.Free;
end;
end;
end;
function THue.GetName: string;
begin
+6 -5
View File
@@ -73,19 +73,20 @@ end;
procedure TLocalizationEntry.Serialize(Data: TStream);
var
iLength: SmallInt;
text: string;
encodedText: string;
begin
Data.Write(FNumber, SizeOf(Integer));
Data.Write(FUnknown, SizeOf(Byte));
text := UTF8Encode(FText);
iLength := Length(text);
encodedText := UTF8Encode(FText);
iLength := Length(encodedText);
Data.Write(iLength, SizeOf(SmallInt));
Data.Write(PChar(text)^, iLength);
Data.Write(PChar(encodedText)^, iLength);
end;
function TLocalizationEntry.GetSize: Integer;
begin
Result := SizeOf(Integer) + SizeOf(Byte) + SizeOf(SmallInt) + Length(FText);
Result := SizeOf(Integer) + SizeOf(Byte) + SizeOf(SmallInt)
+ Length(UTF8Encode(FText));
end;
end.
+4
View File
@@ -199,9 +199,13 @@ begin
Result := TMapBlock.Create(nil);
Result.FX := FX;
Result.FY := FY;
Result.FHeader := FHeader;
for i := 0 to 63 do
begin
Result.Cells[i].Free;
Result.Cells[i] := Cells[i].Clone;
end;
end;
procedure TMapBlock.Write(AData: TStream);
var
+1 -1
View File
@@ -101,7 +101,7 @@ procedure TMulBlockEventHandler.RegisterEvent(AEvent: TMulBlockChanged);
var
eventInfo: PMethod;
begin
//UnregisterEvent(AEvent);
UnregisterEvent(AEvent);
New(eventInfo);
eventInfo^.Code := TMethod(AEvent).Code;
eventInfo^.Data := TMethod(AEvent).Data;
+13 -3
View File
@@ -69,7 +69,13 @@ begin
begin
while (x < width) and (y < height) do
begin
Data.Read(pixelData, SizeOf(Byte));
if (Data.Read(pixelData, SizeOf(Byte)) < SizeOf(Byte)) or
(pixelData and $7F = 0) then
begin
x := width;
y := height;
Break;
end;
if (pixelData and $80) = $80 then color := clBlack else color := clWhite;
for run := 1 to (pixelData and $7F) do
begin
@@ -114,6 +120,7 @@ var
height, width, x, y: Integer;
run: Byte;
state, newState: Boolean;
row: PByte;
procedure DoWrite;
var
@@ -130,13 +137,16 @@ begin
Data.Write(width, SizeOf(Integer));
Data.Write(height, SizeOf(Integer));
run := 0;
state := not (FGraphic.Canvas.Pixels[0,0] = clWhite);
state := True;
if (width > 0) and (height > 0) then
state := (PByte(FGraphic.ScanLine[0])[0] and $80) = 0;
if Assigned(FOnProgress) then FOnProgress(0, 0);
for y := 0 to height - 1 do
begin
row := FGraphic.ScanLine[y];
for x := 0 to width - 1 do
begin
newState := not (FGraphic.Canvas.Pixels[x,y] = clWhite);
newState := (row[x shr 3] and ($80 shr (x and 7))) = 0;
if (state = newState) and (run < $7F) then
begin
inc(run);
+4 -1
View File
@@ -179,16 +179,19 @@ begin
FY := AY;
FItems := TStaticItemList.Create(True);
if (AData <> nil) and (AIndex.Lookup > 0) and (AIndex.Size > 0) then
if (AData <> nil) and (AIndex.Lookup > -1) and (AIndex.Size > 0) then
begin
AData.Position := AIndex.Lookup;
block := TMemoryStream.Create;
try
block.CopyFrom(AData, AIndex.Size);
block.Position := 0;
for i := 1 to (AIndex.Size div 7) do
FItems.Add(TStaticItem.Create(Self, block, AX, AY));
finally
block.Free;
end;
end;
FChanged := False;
end;
+1
View File
@@ -63,6 +63,7 @@ begin
else
size := 128;
FGraphic := TSingleImage.CreateFromParams(size, size, ifX1R5G5B5);
FBuffer := TMemoryStream.Create;
if assigned(AData) then
begin
AData.Position := AIndex.Lookup;
+38 -2
View File
@@ -37,6 +37,10 @@ const
LandTileGroupSize = 4 + 32 * LandTileDataSize;
StaticTileDataSize = 37;
StaticTileGroupSize = 4 + 32 * StaticTileDataSize;
LandTileDataSizeHS = LandTileDataSize + 4;
LandTileGroupSizeHS = 4 + 32 * LandTileDataSizeHS;
StaticTileDataSizeHS = StaticTileDataSize + 4;
StaticTileGroupSizeHS = 4 + 32 * StaticTileDataSizeHS;
type
TTileDataFlag = (tdfBackground, tdfWeapon, tdfTransparent, tdfTranslucent,
@@ -125,6 +129,7 @@ type
procedure Write(AData: TStream); override;
protected
FUnknown: LongInt;
FVersion: TTileDataVersion;
public
LandTileData: array[0..31] of TLandTiledata;
property Unknown: LongInt read FUnknown write FUnknown;
@@ -140,16 +145,18 @@ type
procedure Write(AData: TStream); override;
protected
FUnknown: LongInt;
FVersion: TTileDataVersion;
public
StaticTileData: array[0..31] of TStaticTiledata;
property Unknown: LongInt read FUnknown write FUnknown;
end;
function GetTileDataOffset(ABlock: Integer): Integer;
function GetTileDataOffset(ABlock: Integer; AVersion: TTileDataVersion = tdvLegacy): Integer;
implementation
function GetTileDataOffset(ABlock: Integer): Integer;
function GetTileDataOffset(ABlock: Integer; AVersion: TTileDataVersion): Integer;
var
group, tile: Integer;
begin
@@ -159,6 +166,10 @@ begin
group := ABlock div 32;
tile := ABlock mod 32;
if AVersion >= tdvHighSeas then
Result := 512 * LandTileGroupSizeHS + group * StaticTileGroupSizeHS + 4
+ tile * StaticTileDataSizeHS
else
Result := 512 * LandTileGroupSize + group * StaticTileGroupSize + 4
+ tile * StaticTileDataSize;
end else
@@ -166,6 +177,13 @@ begin
group := ABlock div 32;
tile := ABlock mod 32;
if AVersion >= tdvHighSeas then
begin
if ABlock = 0 then
Result := 0
else
Result := ABlock * LandTileDataSizeHS + (group + 1) * 4;
end else
Result := group * LandTileGroupSize + 4 + tile * LandTileDataSize;
end;
end;
@@ -246,6 +264,9 @@ end;
function TLandTiledata.GetSize: Integer;
begin
if FVersion >= tdvHighSeas then
GetSize := LandTileDataSizeHS
else
GetSize := LandTileDataSize;
end;
@@ -325,6 +346,9 @@ end;
function TStaticTiledata.GetSize: Integer;
begin
if FVersion >= tdvHighSeas then
GetSize := StaticTileDataSizeHS
else
GetSize := StaticTileDataSize;
end;
@@ -335,6 +359,7 @@ constructor TLandTileGroup.Create(AData: TStream;
var
i: Integer;
begin
FVersion := AVersion;
if assigned(AData) then
begin
AData.Read(FUnknown, SizeOf(LongInt));
@@ -358,6 +383,7 @@ var
begin
Result := TLandTileGroup.Create(nil);
Result.FUnknown := FUnknown;
Result.FVersion := FVersion;
for i := 0 to 31 do
Result.LandTileData[i] := LandTileData[i].Clone;
end;
@@ -373,16 +399,22 @@ end;
function TLandTileGroup.GetSize: Integer;
begin
if FVersion >= tdvHighSeas then
GetSize := LandTileGroupSizeHS
else
GetSize := LandTileGroupSize;
end;
{ TStaticTileGroup }
constructor TStaticTileGroup.Create(AData: TStream;
AVersion: TTileDataVersion = tdvLegacy);
var
i: Integer;
begin
FVersion := AVersion;
if assigned(AData) then
begin
AData.Read(FUnknown, SizeOf(LongInt));
@@ -406,6 +438,7 @@ var
begin
Result := TStaticTileGroup.Create(nil);
Result.FUnknown := FUnknown;
Result.FVersion := FVersion;
for i := 0 to 31 do
Result.StaticTileData[i] := StaticTileData[i].Clone;
end;
@@ -421,6 +454,9 @@ end;
function TStaticTileGroup.GetSize: Integer;
begin
if FVersion >= tdvHighSeas then
GetSize := StaticTileGroupSizeHS
else
GetSize := StaticTileGroupSize;
end;
+19 -5
View File
@@ -229,6 +229,8 @@ end;
function TFifoStream.Read(var Buffer; ACount: Longint): Longint;
begin
if ACount < 0 then
raise EStreamError.Create('Invalid read count');
Result := 0;
If (FSize > 0) and (FPosition - FLockOffset < FSize) then
begin
@@ -243,7 +245,10 @@ function TFifoStream.Write(const Buffer; ACount: Longint): Longint;
var
NewPos: Longint;
begin
Unlock;
if ACount < 0 then
raise EStreamError.Create('Invalid write count');
if (FLockOffset <> 0) or (FRealSize <> 0) then
raise EStreamError.Create('Cannot write to a locked fifo stream');
if ACount = 0 then
Exit(0);
NewPos := FPosition + ACount;
@@ -265,6 +270,8 @@ begin
soFromEnd : FPosition := FSize + AOffset + FLockOffset;
soFromCurrent : FPosition := FPosition + AOffset;
end;
if (FPosition < FLockOffset) or (FPosition > FSize + FLockOffset) then
raise EStreamError.Create('Invalid seek position');
Result := FPosition - FLockOffset;
end;
@@ -328,6 +335,8 @@ var
newCapacity, newSize: Longint;
queue, newMemory: Pointer;
begin
if ACount < 0 then
raise EStreamError.Create('Invalid dequeue count');
Unlock;
if ACount >= FSize then
begin
@@ -343,8 +352,6 @@ begin
begin
newMemory := GetMem(newCapacity);
System.Move(queue^, newMemory^, newSize);
if (newMemory = nil) and (newCapacity > 0) then
raise EStreamError.Create(SMemoryStreamError);
FreeMem(FMemory);
FMemory := newMemory;
FCapacity := newCapacity;
@@ -362,6 +369,8 @@ procedure TFifoStream.Enqueue(const Buffer; ACount: Longint);
var
oldPos: Int64;
begin
if ACount < 0 then
raise EStreamError.Create('Invalid enqueue count');
Unlock;
oldPos := FPosition;
FPosition := FSize;
@@ -459,10 +468,15 @@ begin
end;
function TStreamWrapper.ReadStringFixed(ALength: Integer): string;
var
bytesRead: Integer;
begin
if not Assigned(FStream) then Exit('');
if (not Assigned(FStream)) or (ALength <= 0) then Exit('');
SetLength(Result, ALength);
FStream.Read(PChar(Result)^, ALength);
FillChar(PChar(Result)^, ALength, 0);
bytesRead := FStream.Read(PChar(Result)^, ALength);
if bytesRead < ALength then
SetLength(Result, bytesRead);
end;
procedure TStreamWrapper.WriteBoolean(AValue: Boolean);
+12 -2
View File
@@ -125,7 +125,15 @@ var
begin
element := AssureElement(AParent, AName);
if assigned(element.FirstChild) then
begin
if element.FirstChild.NodeType = TEXT_NODE then
TDOMText(element.FirstChild).NodeValue := AValue
else
begin
element.RemoveChild(element.FirstChild).Free;
element.AppendChild(AParent.OwnerDocument.CreateTextNode(AValue));
end;
end
else
element.AppendChild(AParent.OwnerDocument.CreateTextNode(AValue));
end;
@@ -135,7 +143,8 @@ var
element: TDOMElement;
begin
element := FindChild(AParent, AName);
if assigned(element) and assigned(element.FirstChild) then
if assigned(element) and assigned(element.FirstChild)
and (element.FirstChild.NodeType = TEXT_NODE) then
Result := TDOMText(element.FirstChild).Data
else
Result := ADefault;
@@ -163,7 +172,8 @@ end;
class function TXmlHelper.ReadBoolean(AParent: TDOMElement; AName: string;
ADefault: Boolean): Boolean;
begin
Result := StrToBool(ReadString(AParent, AName, BoolToStr(ADefault)));
if not TryStrToBool(ReadString(AParent, AName, ''), Result) then
Result := ADefault;
end;
class procedure TXmlHelper.WriteCoords(AParent: TDOMElement; AName: string; AX,
+192
View File
@@ -0,0 +1,192 @@
unit UTestAccount;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, DOM, XMLRead, XMLWrite, fpcunit, testregistry,
UEnums, UInterfaces, UAccount, UConfig, UTestConfig;
type
TTestAccounts = class(TTestCase)
private
function BuildAccount: TAccount;
function AccountToXML(AAccount: TAccount): string;
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure CreateAndCheckPassword;
procedure UpdatePasswordInvalidatesOldPassword;
procedure HashDoesNotContainPassword;
procedure FindInList;
procedure SerializeDeserializeRoundtrip;
end;
implementation
uses
MD5;
type
TDummyOwner = class(TObject, IInvalidate)
procedure Invalidate;
end;
procedure TDummyOwner.Invalidate;
begin
//notify chain ends here in tests
end;
var
configPath: string;
dummyOwner: TDummyOwner;
procedure TTestAccounts.SetUp;
begin
//account serialization validates regions against the global config
configPath := WriteTestConfigFile;
Config := TConfig.Create(configPath);
dummyOwner := TDummyOwner.Create;
end;
procedure TTestAccounts.TearDown;
begin
FreeAndNil(Config);
dummyOwner.Free;
DeleteFile(configPath);
end;
function TTestAccounts.BuildAccount: TAccount;
var
regions: TStringList;
begin
regions := TStringList.Create;
regions.Add('britain');
regions.Add('yew');
Result := TAccount.Create(dummyOwner, 'alice', 'secret', alNormal, regions);
end;
function TTestAccounts.AccountToXML(AAccount: TAccount): string;
var
doc: TXMLDocument;
root: TDOMElement;
stream: TStringStream;
begin
doc := TXMLDocument.Create;
try
root := doc.CreateElement('accounts');
doc.AppendChild(root);
AAccount.Serialize(root);
stream := TStringStream.Create('');
try
WriteXMLFile(doc, stream);
Result := stream.DataString;
finally
stream.Free;
end;
finally
doc.Free;
end;
end;
procedure TTestAccounts.CreateAndCheckPassword;
var
account: TAccount;
begin
account := BuildAccount;
try
AssertEquals('name', 'alice', account.Name);
AssertTrue('correct password accepted', account.CheckPassword('secret'));
AssertFalse('wrong password rejected', account.CheckPassword('wrong'));
finally
account.Free;
end;
end;
procedure TTestAccounts.UpdatePasswordInvalidatesOldPassword;
var
account: TAccount;
begin
account := BuildAccount;
try
account.UpdatePassword('newpass');
AssertFalse('old password must stop working', account.CheckPassword('secret'));
AssertTrue('new password accepted', account.CheckPassword('newpass'));
finally
account.Free;
end;
end;
procedure TTestAccounts.HashDoesNotContainPassword;
var
account: TAccount;
begin
account := BuildAccount;
try
AssertTrue('stored hash must not contain the plain password',
Pos('secret', account.PasswordHash) = 0);
finally
account.Free;
end;
end;
procedure TTestAccounts.FindInList;
var
list: TAccountList;
account: TAccount;
begin
list := TAccountList.Create(dummyOwner);
try
account := BuildAccount;
list.Add(account);
AssertSame('find existing', account, list.Find('alice'));
AssertEquals('index', 0, list.IndexOf('alice'));
AssertTrue('missing is nil', list.Find('bob') = nil);
finally
list.Free;
end;
end;
procedure TTestAccounts.SerializeDeserializeRoundtrip;
var
account, loaded: TAccount;
xml: string;
stream: TStringStream;
doc: TXMLDocument;
begin
account := BuildAccount;
try
xml := AccountToXML(account);
stream := TStringStream.Create(xml);
try
ReadXMLFile(doc, stream);
try
loaded := TAccount.Deserialize(nil, doc.DocumentElement);
try
AssertEquals('name survives', 'alice', loaded.Name);
AssertTrue('password hash survives',
loaded.CheckPassword('secret'));
AssertEquals('access level survives', Ord(alNormal),
Ord(loaded.AccessLevel));
AssertEquals('regions survive', 2, loaded.Regions.Count);
AssertEquals('region name', 'britain', loaded.Regions[0]);
finally
loaded.Free;
end;
finally
doc.Free;
end;
finally
stream.Free;
end;
finally
account.Free;
end;
end;
initialization
RegisterTests([TTestAccounts]);
end.
+264
View File
@@ -0,0 +1,264 @@
unit UTestArt;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, fpcunit, testregistry,
UEnhancedMemoryStream, UGenericIndex, UMulBlock, UArt;
type
TTestArt = class(TTestCase)
private
function BuildLandBlock: TMemoryStream;
function BuildStaticBlock: TMemoryStream;
function LandBlockSize: Integer;
published
procedure LandRoundtripIsByteIdentical;
procedure StaticRoundtripIsByteIdentical;
procedure LandRejectsWrongDimensions;
procedure StaticRejectsEmptyDimensions;
end;
implementation
function TTestArt.LandBlockSize: Integer;
begin
//22 rows of 2,4,...,44 words plus 22 rows of 44,42,...,2 words
Result := (2 + 44) * 22 * 2;
end;
function TTestArt.BuildLandBlock: TMemoryStream;
var
x, y: Integer;
startCol, words, i: Integer;
color: Word;
begin
Result := TMemoryStream.Create;
for y := 0 to 43 do
begin
if y < 22 then
begin
startCol := 21 - y;
words := (y + 1) * 2;
end else
begin
startCol := y - 22;
words := (44 - y) * 2;
end;
for i := 0 to words - 1 do
begin
x := startCol + i;
//deterministic pattern, alpha bit set like real land tiles; channel
//values are 0 or 31 so they survive the 16 to 32 to 16 bit conversion
case (x + y) mod 4 of
0: color := $8000;
1: color := $8000 or $7C00;
2: color := $8000 or $03E0;
3: color := $8000 or $001F;
end;
Result.Write(color, SizeOf(Word));
end;
end;
end;
function TTestArt.BuildStaticBlock: TMemoryStream;
var
row, i: Integer;
color: Word;
offset, runLen: Word;
lookup: array[0..3] of Word;
begin
Result := TMemoryStream.Create;
Result.WriteDWord(1); //header
Result.WriteWord(8); //width
Result.WriteWord(4); //height
//row offsets in words, relative to the start of the pixel data
//row length: offset + run + 3 colors + end marker = 14 bytes = 7 words
//last row: offset + run + 2 colors + end marker = 12 bytes
lookup[0] := 0;
lookup[1] := 7;
lookup[2] := 14;
lookup[3] := 21;
for i := 0 to 3 do
Result.WriteWord(lookup[i]);
for row := 0 to 3 do
begin
if row < 3 then
begin
offset := 0;
runLen := 3;
end else
begin
offset := 1;
runLen := 2;
end;
Result.Write(offset, SizeOf(Word));
Result.Write(runLen, SizeOf(Word));
for i := 0 to runLen - 1 do
begin
//channels 0 or 31 survive the 16 to 32 to 16 bit conversion
case (row + i) mod 4 of
0: color := $0000;
1: color := $7C00;
2: color := $03E0;
3: color := $001F;
end;
Result.Write(color, SizeOf(Word));
end;
offset := 0;
runLen := 0;
Result.Write(offset, SizeOf(Word));
Result.Write(runLen, SizeOf(Word));
end;
end;
procedure TTestArt.LandRoundtripIsByteIdentical;
var
block, output: TMemoryStream;
index: TGenericIndex;
art: TArt;
decoded, encoded: PByteArray;
i: Integer;
begin
block := BuildLandBlock;
try
index := TGenericIndex.Create(nil);
try
index.Lookup := 0;
index.Size := block.Size;
block.Position := 0;
art := TArt.Create(block, index, atLand);
try
AssertEquals('decoded size matches block', Int64(LandBlockSize),
Int64(art.GetSize));
output := TMemoryStream.Create;
try
art.Write(output);
AssertEquals('re-encoded size', Int64(LandBlockSize),
Int64(output.Size));
decoded := block.Memory;
encoded := output.Memory;
for i := 0 to LandBlockSize - 1 do
if decoded^[i] <> encoded^[i] then
begin
AssertEquals('pixel data at byte ' + IntToStr(i),
decoded^[i], encoded^[i]);
Break;
end;
AssertTrue('roundtrip must be byte identical', True);
finally
output.Free;
end;
finally
art.Free;
end;
finally
index.Free;
end;
finally
block.Free;
end;
end;
procedure TTestArt.StaticRoundtripIsByteIdentical;
var
block, output: TMemoryStream;
index: TGenericIndex;
art: TArt;
decoded, encoded: PByteArray;
i: Integer;
begin
block := BuildStaticBlock;
try
index := TGenericIndex.Create(nil);
try
index.Lookup := 0;
index.Size := block.Size;
block.Position := 0;
art := TArt.Create(block, index, atStatic);
try
AssertEquals('decoded size matches block', Int64(block.Size),
Int64(art.GetSize));
output := TMemoryStream.Create;
try
art.Write(output);
AssertEquals('re-encoded size', Int64(block.Size),
Int64(output.Size));
decoded := block.Memory;
encoded := output.Memory;
for i := 0 to block.Size - 1 do
if decoded^[i] <> encoded^[i] then
begin
AssertEquals('pixel data at byte ' + IntToStr(i),
decoded^[i], encoded^[i]);
Break;
end;
AssertTrue('roundtrip must be byte identical', True);
finally
output.Free;
end;
finally
art.Free;
end;
finally
index.Free;
end;
finally
block.Free;
end;
end;
procedure TTestArt.LandRejectsWrongDimensions;
var
block: TMemoryStream;
index: TGenericIndex;
art: TArt;
begin
block := TMemoryStream.Create; //not 44x44 worth of data
try
index := TGenericIndex.Create(nil);
try
index.Lookup := 0;
index.Size := 0;
art := TArt.Create(nil, index, atLand);
try
AssertEquals('empty output for invalid dimensions', Int64(0),
Int64(art.GetSize));
finally
art.Free;
end;
finally
index.Free;
end;
finally
block.Free;
end;
end;
procedure TTestArt.StaticRejectsEmptyDimensions;
var
index: TGenericIndex;
art: TArt;
begin
index := TGenericIndex.Create(nil);
try
index.Lookup := 0;
index.Size := 0;
art := TArt.Create(nil, index, atStatic);
try
AssertEquals('empty output for empty dimensions', Int64(0),
Int64(art.GetSize));
finally
art.Free;
end;
finally
index.Free;
end;
end;
initialization
RegisterTests([TTestArt]);
end.
+116
View File
@@ -0,0 +1,116 @@
unit UTestBufferedStreams;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, fpcunit, testregistry,
UEnhancedMemoryStream, UBufferedStreams;
type
TTestBufferedStream = class(TTestCase)
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure RefreshLoadsBaseContent;
procedure FlushWritesAppendedData;
procedure FlushWritesShrunkenData;
procedure ReaderWriteGoesThroughToBase;
procedure ReaderFlushIsHarmless;
procedure ReaderReadReturnsBaseContent;
end;
implementation
var
base: TMemoryStream;
buffered: TBufferedStream;
reader: TBufferedReader;
procedure TTestBufferedStream.SetUp;
begin
base := TMemoryStream.Create;
buffered := nil;
reader := nil;
end;
procedure TTestBufferedStream.TearDown;
begin
FreeAndNil(buffered);
FreeAndNil(reader);
FreeAndNil(base);
end;
procedure TTestBufferedStream.RefreshLoadsBaseContent;
var
buffer: array[0..4] of Byte;
begin
base.Write(PChar('hello')^, 5);
buffered := TBufferedStream.Create(base, False);
AssertEquals('size mirrors base', Int64(5), buffered.Size);
buffered.Position := 0;
buffered.Read(buffer, 5);
AssertEquals('h', Char(buffer[0]));
AssertEquals('e', Char(buffer[1]));
AssertEquals('l', Char(buffer[2]));
AssertEquals('l', Char(buffer[3]));
AssertEquals('o', Char(buffer[4]));
end;
procedure TTestBufferedStream.FlushWritesAppendedData;
begin
base.Write(PChar('hello')^, 5);
buffered := TBufferedStream.Create(base, False);
buffered.Seek(0, soFromEnd);
buffered.Write(PChar(' world')^, 6);
buffered.Flush;
AssertEquals('base received appended data', Int64(11), base.Size);
end;
procedure TTestBufferedStream.FlushWritesShrunkenData;
begin
base.Write(PChar('hello')^, 5);
buffered := TBufferedStream.Create(base, False);
buffered.Size := 3;
buffered.Flush;
AssertEquals('base follows shrink', Int64(3), base.Size);
end;
procedure TTestBufferedStream.ReaderWriteGoesThroughToBase;
begin
reader := TBufferedReader.Create(base, False);
reader.Seek(0, soFromEnd);
reader.Write(PChar('data')^, 4);
AssertEquals('base has the written bytes', Int64(4), base.Size);
AssertEquals('reader agrees on size', Int64(4), reader.Size);
end;
procedure TTestBufferedStream.ReaderFlushIsHarmless;
begin
base.Write(PChar('data')^, 4);
reader := TBufferedReader.Create(base, False);
reader.Flush; //must not truncate or raise
AssertEquals('base intact after flush', Int64(4), base.Size);
end;
procedure TTestBufferedStream.ReaderReadReturnsBaseContent;
var
buffer: array[0..3] of Byte;
begin
base.Write(PChar('abcd')^, 4);
reader := TBufferedReader.Create(base, False);
AssertEquals('reader sees base size', Int64(4), reader.Size);
reader.Position := 0;
reader.Read(buffer, 4);
AssertEquals('a', Char(buffer[0]));
AssertEquals('b', Char(buffer[1]));
AssertEquals('c', Char(buffer[2]));
AssertEquals('d', Char(buffer[3]));
end;
initialization
RegisterTests([TTestBufferedStream]);
end.
+230
View File
@@ -0,0 +1,230 @@
unit UTestCacheManager;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, fpcunit, testregistry, UCacheManager;
type
TIntegerCache = specialize TCacheManager<TObject>;
TTestCacheManager = class(TTestCase)
published
procedure RejectsSizeBelowTwo;
procedure StoreAfterMissKeepsInvariant;
procedure StoreTwiceKeepsInvariant;
procedure HitReordersWithoutBreakingStore;
procedure RemoveIDKeepsInvariant;
procedure ClearRemovesAllObjects;
procedure DiscardIDKeepsEntryUsable;
procedure DestroyFreesAllEntries;
end;
implementation
procedure TTestCacheManager.RejectsSizeBelowTwo;
var
raised: Boolean;
begin
raised := False;
try
TIntegerCache.Create(1).Free;
except
on E: Exception do
raised := True;
end;
AssertTrue('size 1 must be rejected', raised);
raised := False;
try
TIntegerCache.Create(0).Free;
except
on E: Exception do
raised := True;
end;
AssertTrue('size 0 must be rejected', raised);
end;
procedure TTestCacheManager.StoreAfterMissKeepsInvariant;
var
cache: TIntegerCache;
objects: array[0..15] of TObject;
resultObj: TObject;
i: Integer;
begin
for i := 0 to High(objects) do
objects[i] := TObject.Create;
cache := TIntegerCache.Create(8);
try
for i := 0 to High(objects) do
begin
AssertFalse('query must miss', cache.QueryID(i, resultObj));
cache.StoreID(i, objects[i]);
end;
//entries 0..7 were evicted (and freed by the cache), 8..15 must hit
AssertTrue('most recent entry must hit', cache.QueryID(15, resultObj));
AssertSame('hit must return the stored object', objects[15], resultObj);
AssertTrue('oldest surviving entry must hit', cache.QueryID(8, resultObj));
AssertFalse('evicted entry must miss', cache.QueryID(7, resultObj));
finally
cache.Free; //frees the remaining owned objects
end;
end;
procedure TTestCacheManager.StoreTwiceKeepsInvariant;
var
cache: TIntegerCache;
objA, objB, resultObj: TObject;
begin
objA := TObject.Create;
objB := TObject.Create;
cache := TIntegerCache.Create(4);
try
AssertFalse(cache.QueryID(1, resultObj));
cache.StoreID(1, objA);
cache.StoreID(2, objB); //used to nil-deref via a stale tail pointer
AssertTrue(cache.QueryID(2, resultObj));
AssertSame(objB, resultObj);
AssertTrue(cache.QueryID(1, resultObj));
AssertSame(objA, resultObj);
finally
cache.Free; //frees objA and objB
end;
end;
procedure TTestCacheManager.HitReordersWithoutBreakingStore;
var
cache: TIntegerCache;
objects: array[0..6] of TObject;
resultObj: TObject;
i: Integer;
begin
for i := 0 to High(objects) do
objects[i] := TObject.Create;
cache := TIntegerCache.Create(8);
try
for i := 0 to High(objects) do
begin
AssertFalse(cache.QueryID(i, resultObj));
cache.StoreID(i, objects[i]);
end;
//hit an entry that is not at the front, then store again
AssertTrue(cache.QueryID(2, resultObj));
AssertSame(objects[2], resultObj);
AssertFalse(cache.QueryID(7, resultObj));
cache.StoreID(7, TObject.Create); //entry 7 becomes front
AssertTrue(cache.QueryID(2, resultObj));
AssertSame(objects[2], resultObj);
AssertTrue(cache.QueryID(5, resultObj));
AssertSame(objects[5], resultObj);
finally
cache.Free;
end;
end;
procedure TTestCacheManager.RemoveIDKeepsInvariant;
var
cache: TIntegerCache;
objects: array[0..3] of TObject;
obj5, resultObj: TObject;
i: Integer;
begin
for i := 0 to High(objects) do
objects[i] := TObject.Create;
obj5 := TObject.Create;
cache := TIntegerCache.Create(4);
try
for i := 0 to High(objects) do
begin
AssertFalse(cache.QueryID(i, resultObj));
cache.StoreID(i, objects[i]);
end;
cache.RemoveID(3); //frees objects[3]
cache.RemoveID(0); //frees objects[0]
AssertFalse('removed entry must miss', cache.QueryID(3, resultObj));
AssertFalse('removed entry must miss', cache.QueryID(0, resultObj));
cache.StoreID(5, obj5); //store right after removals
AssertTrue(cache.QueryID(5, resultObj));
AssertSame(obj5, resultObj);
AssertTrue(cache.QueryID(2, resultObj));
AssertTrue(cache.QueryID(1, resultObj));
finally
cache.Free; //frees objects[1], objects[2], obj5
end;
end;
procedure TTestCacheManager.ClearRemovesAllObjects;
var
cache: TIntegerCache;
objects: array[0..2] of TObject;
replacement, resultObj: TObject;
i: Integer;
begin
for i := 0 to High(objects) do
objects[i] := TObject.Create;
cache := TIntegerCache.Create(4);
try
for i := 0 to High(objects) do
begin
AssertFalse(cache.QueryID(i, resultObj));
cache.StoreID(i, objects[i]);
end;
cache.Clear; //frees the objects
for i := 0 to High(objects) do
AssertFalse('cleared entry must miss', cache.QueryID(i, resultObj));
replacement := TObject.Create;
cache.StoreID(9, replacement); //entries must be reusable afterwards
AssertTrue(cache.QueryID(9, resultObj));
AssertSame(replacement, resultObj);
finally
cache.Free;
end;
end;
procedure TTestCacheManager.DiscardIDKeepsEntryUsable;
var
cache: TIntegerCache;
objA, objB, resultObj: TObject;
begin
objA := TObject.Create;
objB := TObject.Create;
cache := TIntegerCache.Create(4);
try
AssertFalse(cache.QueryID(1, resultObj));
cache.StoreID(1, objA);
cache.DiscardID(1); //entry detached, ownership back to the caller
AssertFalse('discarded entry must miss', cache.QueryID(1, resultObj));
cache.StoreID(2, objB);
AssertTrue(cache.QueryID(2, resultObj));
AssertSame(objB, resultObj);
finally
cache.Free; //frees objB only
objA.Free; //discarded object is ours again
end;
end;
procedure TTestCacheManager.DestroyFreesAllEntries;
var
cache: TIntegerCache;
objects: array[0..3] of TObject;
resultObj: TObject;
i: Integer;
begin
for i := 0 to High(objects) do
objects[i] := TObject.Create;
cache := TIntegerCache.Create(4);
for i := 0 to High(objects) do
begin
AssertFalse(cache.QueryID(i, resultObj));
cache.StoreID(i, objects[i]);
end;
AssertTrue(cache.QueryID(3, resultObj)); //move-to-front before destroy
cache.Free; //must not crash, must free all entries
end;
initialization
RegisterTests([TTestCacheManager]);
end.
+143
View File
@@ -0,0 +1,143 @@
unit UTestConfig;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, fpcunit, testregistry, UConfig;
function BuildTestConfigXML: string;
function WriteTestConfigFile: string;
type
TTestConfig = class(TTestCase)
protected
procedure SetUp; override;
procedure TearDown; override;
private
FConfigPath: string;
procedure ExpectLoadFailure(const AXML, ATag: string);
published
procedure ValidConfigLoads;
procedure InvalidVersionRaises;
procedure MissingAccountsRaise;
procedure MissingMapRaises;
end;
implementation
function BuildTestConfigXML: string;
begin
Result :=
'<CEDConfig Version="3">' +
'<Port>2597</Port>' +
'<Map>' +
'<Map>map0.mul</Map>' +
'<StaIdx>staidx0.mul</StaIdx>' +
'<Statics>statics0.mul</Statics>' +
'<Width>10</Width>' +
'<Height>20</Height>' +
'</Map>' +
'<Tiledata>tiledata.mul</Tiledata>' +
'<Radarcol>radarcol.mul</Radarcol>' +
'<Regions>' +
'<Region><Name>britain</Name><Area><Rect x1="0" y1="0" x2="10" y2="10"/></Area></Region>' +
'<Region><Name>yew</Name><Area><Rect x1="5" y1="5" x2="15" y2="15"/></Area></Region>' +
'</Regions>' +
'<Accounts/>' +
'</CEDConfig>';
end;
function WriteTestConfigFile: string;
var
path: string;
stream: TStringStream;
begin
path := GetTempDir + 'centred-test-config.xml';
stream := TStringStream.Create(BuildTestConfigXML);
try
stream.SaveToFile(path);
finally
stream.Free;
end;
Result := path;
end;
procedure TTestConfig.SetUp;
begin
FConfigPath := '';
end;
procedure TTestConfig.TearDown;
begin
if FConfigPath <> '' then
DeleteFile(FConfigPath);
end;
procedure TTestConfig.ExpectLoadFailure(const AXML, ATag: string);
var
raised: Boolean;
begin
FConfigPath := GetTempDir + 'centred-test-config-' + ATag + '.xml';
with TStringStream.Create(AXML) do
try
SaveToFile(FConfigPath);
finally
Free;
end;
raised := False;
try
TConfig.Create(FConfigPath).Free;
except
on E: Exception do
raised := True;
end;
AssertTrue('loading must fail (' + ATag + ')', raised);
end;
procedure TTestConfig.ValidConfigLoads;
var
config: TConfig;
begin
FConfigPath := WriteTestConfigFile;
config := TConfig.Create(FConfigPath);
try
AssertEquals('port', 2597, config.Port);
AssertEquals('map file', 'map0.mul', config.Map.MapFile);
AssertEquals('width', 10, config.Map.Width);
AssertEquals('height', 20, config.Map.Height);
AssertEquals('tiledata', 'tiledata.mul', config.Tiledata);
AssertEquals('radarcol', 'radarcol.mul', config.Radarcol);
AssertEquals('regions', 2, config.Regions.Count);
AssertTrue('region by name', config.Regions.Find('britain') <> nil);
finally
config.Free;
end;
end;
procedure TTestConfig.InvalidVersionRaises;
var
xml: string;
begin
xml := StringReplace(BuildTestConfigXML, 'Version="3"', 'Version="2"', []);
ExpectLoadFailure(xml, 'badversion');
end;
procedure TTestConfig.MissingAccountsRaise;
begin
ExpectLoadFailure(StringReplace(BuildTestConfigXML, '<Accounts/>', '', []),
'noaccounts');
end;
procedure TTestConfig.MissingMapRaises;
begin
ExpectLoadFailure(StringReplace(BuildTestConfigXML,
'<Map><Map>map0.mul</Map><StaIdx>staidx0.mul</StaIdx><Statics>statics0.mul</Statics><Width>10</Width><Height>20</Height></Map>',
'', []), 'nomap');
end;
initialization
RegisterTests([TTestConfig]);
end.
+168
View File
@@ -0,0 +1,168 @@
unit UTestEnhancedMemoryStream;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, fpcunit, testregistry,
UStreamHelper, UEnhancedMemoryStream;
type
TTestEnhancedMemoryStream = class(TTestCase)
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure ReadWriteIntegers;
procedure ReadStringNullBasic;
procedure ReadStringNullStopsAtEndWithoutTerminator;
procedure ReadStringNullEmptyWindow;
procedure ReadStringNullNormalizesLineEnds;
procedure ReadStringNullDoesNotReadPastWindow;
procedure ReadStringBigUniNullBasic;
procedure ReadStringBigUniNullStopsAtEnd;
procedure ReadStringFixedConsumesExactlyLength;
procedure WriteStringFixedPadsWithZeros;
procedure WriteStringFixedKeepsLongValues;
end;
implementation
var
stream: TEnhancedMemoryStream;
procedure TTestEnhancedMemoryStream.SetUp;
begin
stream := TEnhancedMemoryStream.Create;
end;
procedure TTestEnhancedMemoryStream.TearDown;
begin
stream.Free;
end;
procedure TTestEnhancedMemoryStream.ReadWriteIntegers;
begin
stream.WriteCardinal($AABBCCDD);
stream.WriteWord($BEEF);
stream.WriteByte($42);
stream.WriteShortInt(-5);
stream.Position := 0;
AssertEquals('cardinal', Cardinal($AABBCCDD), stream.ReadCardinal);
AssertEquals('word', Word($BEEF), stream.ReadWord);
AssertEquals('byte', Byte($42), stream.ReadByte);
AssertEquals('shortint', ShortInt(-5), stream.ReadShortInt);
end;
procedure TTestEnhancedMemoryStream.ReadStringNullBasic;
begin
stream.WriteStringNull('alice');
stream.Position := 0;
AssertEquals('alice', stream.ReadStringNull);
AssertEquals('position after terminator', Int64(6), stream.Position);
end;
procedure TTestEnhancedMemoryStream.ReadStringNullStopsAtEndWithoutTerminator;
begin
stream.WriteByte(Ord('a'));
stream.WriteByte(Ord('b'));
stream.Position := 0;
AssertEquals('ab', stream.ReadStringNull);
AssertEquals('no overshoot on missing terminator', Int64(2), stream.Position);
end;
procedure TTestEnhancedMemoryStream.ReadStringNullEmptyWindow;
begin
stream.Lock(0, 0);
try
AssertEquals('', stream.ReadStringNull);
finally
stream.Unlock;
end;
end;
procedure TTestEnhancedMemoryStream.ReadStringNullNormalizesLineEnds;
begin
stream.WriteStringNull('a' + #10 + 'b' + #13 + 'c' + #13#10 + 'd');
stream.Position := 0;
AssertEquals('a' + #13#10 + 'b' + #13#10 + 'c' + #13#10 + 'd',
stream.ReadStringNull);
end;
procedure TTestEnhancedMemoryStream.ReadStringNullDoesNotReadPastWindow;
var
nextByte: Byte;
begin
stream.WriteStringNull('ab');
stream.WriteByte($99); //must not be consumed by the locked read
stream.Position := 0;
stream.Lock(0, 3); //only the null-terminated string
try
AssertEquals('ab', stream.ReadStringNull);
finally
stream.Unlock;
end;
nextByte := stream.ReadByte;
AssertEquals('window boundary must be respected', Byte($99), nextByte);
end;
procedure TTestEnhancedMemoryStream.ReadStringBigUniNullBasic;
begin
//big endian UTF-16
stream.WriteWord(Word(Ord('A')) shl 8);
stream.WriteWord(Word(Ord('B')) shl 8);
stream.WriteWord(0);
stream.Position := 0;
AssertEquals('AB', string(stream.ReadStringBigUniNull));
AssertEquals('position after terminator', Int64(6), stream.Position);
end;
procedure TTestEnhancedMemoryStream.ReadStringBigUniNullStopsAtEnd;
begin
stream.WriteWord(Word(Ord('A')) shl 8);
stream.Position := 0;
AssertEquals('A', string(stream.ReadStringBigUniNull));
AssertEquals('no overshoot', Int64(2), stream.Position);
end;
procedure TTestEnhancedMemoryStream.ReadStringFixedConsumesExactlyLength;
begin
stream.WriteStringNull('abcde');
stream.Position := 0;
AssertEquals('abc', stream.ReadStringFixed(3));
AssertEquals('consumed exactly the requested bytes', Int64(3), stream.Position);
end;
procedure TTestEnhancedMemoryStream.WriteStringFixedPadsWithZeros;
var
i: Integer;
buffer: array[0..4] of Byte;
begin
stream.WriteStringFixed('ab', 5);
AssertEquals('padded size', Int64(5), stream.Size);
stream.Position := 0;
stream.Read(buffer, 5);
AssertEquals('a', Char(buffer[0]));
AssertEquals('b', Char(buffer[1]));
for i := 2 to 4 do
AssertEquals('padding byte', 0, buffer[i]);
end;
procedure TTestEnhancedMemoryStream.WriteStringFixedKeepsLongValues;
var
buffer: array[0..2] of Byte;
begin
stream.WriteStringFixed('abcd', 3);
AssertEquals('truncated to target length', Int64(3), stream.Size);
stream.Position := 0;
stream.Read(buffer, 3);
AssertEquals('a', Char(buffer[0]));
AssertEquals('b', Char(buffer[1]));
AssertEquals('c', Char(buffer[2]));
end;
initialization
RegisterTests([TTestEnhancedMemoryStream]);
end.
+154
View File
@@ -0,0 +1,154 @@
unit UTestLandscapeBounds;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, fpcunit, testregistry, UMap, UTiledata, ULandscape;
type
TTestLandscapeBounds = class(TTestCase)
private
FMap: TMemoryStream;
FStatics: TMemoryStream;
FStaIdx: TMemoryStream;
FTiledata: TMemoryStream;
FRadarColPath: string;
FLandscape: TLandscape;
procedure BuildStreams;
procedure BuildLandscape;
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure ValidStreamSizesValidate;
procedure BlockSubscriptionAtOrigin;
procedure BlockSubscriptionOutsideIsNil;
procedure MapCellInsideBlock;
procedure MapCellOutsideIsNil;
end;
implementation
uses
UEnhancedMemoryStream;
procedure TTestLandscapeBounds.SetUp;
begin
FMap := nil;
FStatics := nil;
FStaIdx := nil;
FTiledata := nil;
FLandscape := nil;
end;
procedure TTestLandscapeBounds.TearDown;
begin
FreeAndNil(FLandscape);
FreeAndNil(FMap);
FreeAndNil(FStatics);
FreeAndNil(FStaIdx);
FreeAndNil(FTiledata);
if FRadarColPath <> '' then
DeleteFile(FRadarColPath);
end;
procedure TTestLandscapeBounds.BuildStreams;
var
i: Integer;
begin
//one map block: header + 64 cells (tile id word + altitude byte)
FMap := TMemoryStream.Create;
FMap.WriteDWord(0);
for i := 0 to 63 do
begin
FMap.WriteWord(0);
FMap.WriteByte(5);
end;
//one empty static index entry
FStaIdx := TMemoryStream.Create;
FStaIdx.WriteDWord(Cardinal($FFFFFFFF));
FStaIdx.WriteDWord(0);
FStaIdx.WriteDWord(0);
FStatics := TMemoryStream.Create;
//legacy tiledata: 512 land groups worth of zeroed entries
FTiledata := TMemoryStream.Create;
for i := 0 to 512 * LandTileGroupSize - 1 do
FTiledata.WriteByte(0);
//radarcol: one color, must live on disk
FRadarColPath := GetTempDir + 'centred-test-radarcol.mul';
with TFileStream.Create(FRadarColPath, fmCreate) do
try
WriteWord(Word($3173));
finally
Free;
end;
end;
procedure TTestLandscapeBounds.BuildLandscape;
var
valid: Boolean;
begin
FLandscape := TLandscape.Create(FMap, FStatics, FStaIdx, FTiledata,
FRadarColPath, 1, 1, valid);
AssertTrue('fixture landscape must validate', valid);
end;
procedure TTestLandscapeBounds.ValidStreamSizesValidate;
begin
BuildStreams;
BuildLandscape;
end;
procedure TTestLandscapeBounds.BlockSubscriptionAtOrigin;
begin
BuildStreams;
BuildLandscape;
AssertTrue('subscription list exists for block 0,0',
FLandscape.BlockSubscriptions[0, 0] <> nil);
end;
procedure TTestLandscapeBounds.BlockSubscriptionOutsideIsNil;
begin
BuildStreams;
BuildLandscape;
//x = width must be rejected (used to read past the array)
AssertTrue('x outside must be nil', FLandscape.BlockSubscriptions[1, 0] = nil);
//y = height must be rejected
AssertTrue('y outside must be nil', FLandscape.BlockSubscriptions[0, 1] = nil);
AssertTrue('both outside must be nil',
FLandscape.BlockSubscriptions[1, 1] = nil);
end;
procedure TTestLandscapeBounds.MapCellInsideBlock;
var
cell: TMapCell;
begin
BuildStreams;
BuildLandscape;
cell := FLandscape.MapCell[0, 0];
AssertTrue('cell 0,0 exists', cell <> nil);
AssertEquals('altitude from the fixture', 5, cell.Altitude);
cell := FLandscape.MapCell[7, 7];
AssertTrue('cell 7,7 exists', cell <> nil);
end;
procedure TTestLandscapeBounds.MapCellOutsideIsNil;
begin
BuildStreams;
BuildLandscape;
AssertTrue('x = cell width is outside',
FLandscape.MapCell[8, 0] = nil);
AssertTrue('y = cell height is outside',
FLandscape.MapCell[0, 8] = nil);
end;
initialization
RegisterTests([TTestLandscapeBounds]);
end.
+173
View File
@@ -0,0 +1,173 @@
unit UTestLinkedList;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, fpcunit, testregistry, ULinkedList;
type
TTestLinkedList = class(TTestCase)
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure AddAndIterate;
procedure DeleteOnlyRemovesFirstMatch;
procedure DeleteHead;
procedure DeleteTail;
procedure DeleteMiddle;
procedure DeleteByID;
procedure DeleteMissingIsHarmless;
procedure ClearEmptiesList;
end;
implementation
var
items: array[0..2] of Pointer;
list: TLinkedList;
procedure TTestLinkedList.SetUp;
var
i: Integer;
begin
for i := 0 to High(items) do
items[i] := Pointer(PtrInt(100 + i));
list := TLinkedList.Create;
end;
procedure TTestLinkedList.TearDown;
begin
list.Free;
end;
procedure TTestLinkedList.AddAndIterate;
var
item: PLinkedItem;
count: Integer;
begin
list.Add(0, items[0]);
list.Add(0, items[1]);
list.Add(0, items[2]);
count := 0;
item := nil;
while list.Iterate(item) do
begin
case count of
0: AssertSame('order 1', items[0], item^.Data);
1: AssertSame('order 2', items[1], item^.Data);
2: AssertSame('order 3', items[2], item^.Data);
end;
Inc(count);
end;
AssertEquals(3, count);
end;
procedure TTestLinkedList.DeleteOnlyRemovesFirstMatch;
var
item: PLinkedItem;
count, firstMatches: Integer;
begin
list.Add(0, items[0]);
list.Add(0, items[0]); //duplicate
list.Add(0, items[1]);
list.Delete(items[0]);
count := 0;
firstMatches := 0;
item := nil;
while list.Iterate(item) do
begin
if item^.Data = items[0] then Inc(firstMatches);
Inc(count);
end;
AssertEquals('duplicate survives', 1, firstMatches);
AssertEquals('two entries remain', 2, count);
end;
procedure TTestLinkedList.DeleteHead;
var
item: PLinkedItem;
begin
list.Add(0, items[0]);
list.Add(0, items[1]);
list.Delete(items[0]);
item := nil;
AssertTrue(list.Iterate(item));
AssertSame('second item becomes head', items[1], item^.Data);
AssertFalse('no third entry', list.Iterate(item));
end;
procedure TTestLinkedList.DeleteTail;
var
item: PLinkedItem;
begin
list.Add(0, items[0]);
list.Add(0, items[1]);
list.Delete(items[1]);
list.Add(0, items[2]); //append after tail deletion
item := nil;
AssertTrue(list.Iterate(item));
AssertSame(items[0], item^.Data);
AssertTrue(list.Iterate(item));
AssertSame('append after tail delete stays intact', items[2], item^.Data);
AssertFalse(list.Iterate(item));
end;
procedure TTestLinkedList.DeleteMiddle;
var
item: PLinkedItem;
begin
list.Add(0, items[0]);
list.Add(0, items[1]);
list.Add(0, items[2]);
list.Delete(items[1]);
item := nil;
AssertTrue(list.Iterate(item));
AssertSame(items[0], item^.Data);
AssertTrue(list.Iterate(item));
AssertSame('chain must stay linked', items[2], item^.Data);
AssertFalse(list.Iterate(item));
end;
procedure TTestLinkedList.DeleteByID;
var
item: PLinkedItem;
begin
list.Add(42, items[0]);
list.Add(43, items[1]);
list.Delete(42);
item := nil;
AssertTrue(list.Iterate(item));
AssertSame(items[1], item^.Data);
AssertFalse(list.Iterate(item));
end;
procedure TTestLinkedList.DeleteMissingIsHarmless;
var
item: PLinkedItem;
begin
list.Add(0, items[0]);
list.Delete(Pointer(PtrInt(999))); //no match, no crash
item := nil;
AssertTrue('entry untouched', list.Iterate(item));
AssertSame(items[0], item^.Data);
AssertFalse('no extra entries', list.Iterate(item));
end;
procedure TTestLinkedList.ClearEmptiesList;
var
item: PLinkedItem;
begin
list.Add(0, items[0]);
list.Add(0, items[1]);
list.Clear;
item := nil;
AssertFalse('empty after clear', list.Iterate(item));
end;
initialization
RegisterTests([TTestLinkedList]);
end.
+126
View File
@@ -0,0 +1,126 @@
unit UTestLocalization;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, fpcunit, testregistry,
UEnhancedMemoryStream, ULocalization;
type
TTestLocalizationEntry = class(TTestCase)
published
procedure SerializeDeserializeRoundtrip;
procedure SizeMatchesSerializedBytes;
procedure SizeCountsEncodedBytesForNonASCII;
procedure NonASCIISurvivesRoundtrip;
end;
implementation
procedure TTestLocalizationEntry.SerializeDeserializeRoundtrip;
var
entry, loaded: TLocalizationEntry;
stream: TEnhancedMemoryStream;
begin
entry := TLocalizationEntry.Create;
try
entry.Number := 4711;
entry.Unknown := 7;
entry.Text := 'hello world';
stream := TEnhancedMemoryStream.Create;
try
entry.Serialize(stream);
stream.Position := 0;
loaded := TLocalizationEntry.Deserialize(stream);
try
AssertEquals('number survives', 4711, loaded.Number);
AssertEquals('unknown survives', 7, loaded.Unknown);
AssertEquals('text survives', 'hello world', loaded.Text);
finally
loaded.Free;
end;
finally
stream.Free;
end;
finally
entry.Free;
end;
end;
procedure TTestLocalizationEntry.SizeMatchesSerializedBytes;
var
entry: TLocalizationEntry;
stream: TEnhancedMemoryStream;
begin
entry := TLocalizationEntry.Create;
try
entry.Text := 'sample text';
stream := TEnhancedMemoryStream.Create;
try
entry.Serialize(stream);
AssertEquals('GetSize must match the serialized byte count',
Int64(entry.GetSize), stream.Size);
finally
stream.Free;
end;
finally
entry.Free;
end;
end;
procedure TTestLocalizationEntry.SizeCountsEncodedBytesForNonASCII;
var
entry: TLocalizationEntry;
stream: TEnhancedMemoryStream;
begin
entry := TLocalizationEntry.Create;
try
//'Grüße' is 5 characters but 7 bytes in UTF-8
entry.Text := 'Grüße';
stream := TEnhancedMemoryStream.Create;
try
entry.Serialize(stream);
AssertEquals('size must count encoded bytes, not characters',
Int64(entry.GetSize), stream.Size);
AssertTrue('utf-8 encoding of Grüße exceeds the character count',
entry.GetSize > 7 + 5);
finally
stream.Free;
end;
finally
entry.Free;
end;
end;
procedure TTestLocalizationEntry.NonASCIISurvivesRoundtrip;
var
entry, loaded: TLocalizationEntry;
stream: TEnhancedMemoryStream;
begin
entry := TLocalizationEntry.Create;
try
entry.Text := 'Grüße aus München';
stream := TEnhancedMemoryStream.Create;
try
entry.Serialize(stream);
stream.Position := 0;
loaded := TLocalizationEntry.Deserialize(stream);
try
AssertEquals('utf-8 text survives', 'Grüße aus München', loaded.Text);
finally
loaded.Free;
end;
finally
stream.Free;
end;
finally
entry.Free;
end;
end;
initialization
RegisterTests([TTestLocalizationEntry]);
end.
+190
View File
@@ -0,0 +1,190 @@
unit UTestMap;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, fpcunit, testregistry, UEnhancedMemoryStream, UGenericIndex, UMap;
type
TTestMapBlock = class(TTestCase)
published
procedure WriteReadRoundtrip;
procedure ClonePreservesAllCells;
procedure ClonePreservesHeader;
procedure CloneIsIndependent;
procedure GetSizeMatchesSerialization;
end;
TTestMapCell = class(TTestCase)
published
procedure ClonePreservesValues;
end;
implementation
function BuildPopulatedBlock: TMapBlock;
var
i: Integer;
begin
Result := TMapBlock.Create(nil);
Result.Header := 12345;
for i := 0 to 63 do
begin
Result.Cells[i].X := i mod 8;
Result.Cells[i].Y := i div 8;
Result.Cells[i].Z := (i * 3) mod 128 - 64;
Result.Cells[i].TileID := (i * 7) mod 1000;
end;
end;
procedure TTestMapBlock.WriteReadRoundtrip;
var
source, loaded: TMapBlock;
stream: TEnhancedMemoryStream;
i: Integer;
index: TGenericIndex;
begin
source := BuildPopulatedBlock;
try
stream := TEnhancedMemoryStream.Create;
try
source.Write(stream);
AssertEquals('serialized block size', Int64(MapBlockSize), stream.Size);
stream.Position := 0;
index := TGenericIndex.Create(nil);
try
index.Lookup := 0;
index.Size := MapBlockSize;
loaded := TMapBlock.Create(stream, 1, 1);
try
AssertEquals('header preserved', source.Header, loaded.Header);
for i := 0 to 63 do
begin
AssertEquals('cell z ' + IntToStr(i), source.Cells[i].Z,
loaded.Cells[i].Z);
AssertEquals('cell tile ' + IntToStr(i), source.Cells[i].TileID,
loaded.Cells[i].TileID);
end;
finally
loaded.Free;
end;
finally
index.Free;
end;
finally
stream.Free;
end;
finally
source.Free;
end;
end;
procedure TTestMapBlock.ClonePreservesAllCells;
var
source, clone: TMapBlock;
i: Integer;
begin
source := BuildPopulatedBlock;
try
clone := source.Clone;
try
for i := 0 to 63 do
begin
AssertEquals('clone z ' + IntToStr(i), source.Cells[i].Z,
clone.Cells[i].Z);
AssertEquals('clone tile ' + IntToStr(i), source.Cells[i].TileID,
clone.Cells[i].TileID);
AssertEquals('clone x ' + IntToStr(i), source.Cells[i].X,
clone.Cells[i].X);
AssertEquals('clone y ' + IntToStr(i), source.Cells[i].Y,
clone.Cells[i].Y);
end;
finally
clone.Free;
end;
finally
source.Free;
end;
end;
procedure TTestMapBlock.ClonePreservesHeader;
var
source, clone: TMapBlock;
begin
source := BuildPopulatedBlock;
try
clone := source.Clone;
try
AssertEquals('header must be cloned', source.Header, clone.Header);
finally
clone.Free;
end;
finally
source.Free;
end;
end;
procedure TTestMapBlock.CloneIsIndependent;
var
source, clone: TMapBlock;
begin
source := BuildPopulatedBlock;
try
clone := source.Clone;
try
clone.Cells[5].Z := source.Cells[5].Z + 10;
clone.Header := source.Header + 1;
AssertEquals('source untouched by clone edits', source.Cells[5].Z,
source.Cells[5].Z);
AssertEquals('original z unchanged', source.Cells[5].Z,
source.Cells[5].Z);
AssertTrue('clone z differs', clone.Cells[5].Z <> source.Cells[5].Z);
AssertTrue('clone header differs', clone.Header <> source.Header);
finally
clone.Free;
end;
finally
source.Free;
end;
end;
procedure TTestMapBlock.GetSizeMatchesSerialization;
var
block: TMapBlock;
begin
block := TMapBlock.Create(nil);
try
AssertEquals(MapBlockSize, block.GetSize);
finally
block.Free;
end;
end;
procedure TTestMapCell.ClonePreservesValues;
var
cell, clone: TMapCell;
begin
cell := TMapCell.Create(nil, nil, 3, 4);
try
cell.Z := 42;
cell.TileID := 1234;
clone := cell.Clone;
try
AssertEquals(3, clone.X);
AssertEquals(4, clone.Y);
AssertEquals(42, clone.Z);
AssertEquals(1234, clone.TileID);
finally
clone.Free;
end;
finally
cell.Free;
end;
end;
initialization
RegisterTests([TTestMapBlock, TTestMapCell]);
end.
+103
View File
@@ -0,0 +1,103 @@
unit UTestPacket;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, fpcunit, testregistry, UEnhancedMemoryStream, UPacket;
type
TTestPacket = class(TTestCase)
published
procedure FixedLengthPacketLayout;
procedure DynamicLengthIsPatchedUp;
procedure DynamicLengthPatchIsIdempotent;
procedure EmptyDynamicPacket;
end;
implementation
procedure TTestPacket.FixedLengthPacketLayout;
var
packet: TPacket;
stream: TEnhancedMemoryStream;
begin
packet := TPacket.Create($05, 5);
try
AssertEquals('declared length', Cardinal(5), packet.PacketLength);
stream := packet.Stream;
//fixed length packets carry only the id byte; the length lives in the
//handler table on the receiving side
AssertEquals('stream holds only the id byte', Int64(1), stream.Size);
stream.Position := 0;
AssertEquals('id byte', Byte($05), stream.ReadByte);
finally
packet.Free;
end;
end;
procedure TTestPacket.DynamicLengthIsPatchedUp;
var
packet: TPacket;
stream: TEnhancedMemoryStream;
begin
packet := TPacket.Create($04, 0);
try
stream := packet.Stream; //one getter call: patches length, resets position
stream.Position := stream.Size;
stream.WriteWord($1234);
stream.WriteWord($5678);
AssertEquals('id + length + payload', Int64(9), stream.Size);
stream := packet.Stream; //property access patches the length field
stream.Position := 1;
AssertEquals('length covers the whole packet', Cardinal(9),
stream.ReadCardinal);
finally
packet.Free;
end;
end;
procedure TTestPacket.DynamicLengthPatchIsIdempotent;
var
packet: TPacket;
stream: TEnhancedMemoryStream;
begin
packet := TPacket.Create($04, 0);
try
stream := packet.Stream;
stream.Position := stream.Size;
stream.WriteByte($42);
stream := packet.Stream; //property access patches the length field
stream.Position := 1;
AssertEquals('first access patches', Cardinal(6), stream.ReadCardinal);
stream.Position := 1;
AssertEquals('second access keeps the length', Cardinal(6),
stream.ReadCardinal);
finally
packet.Free;
end;
end;
procedure TTestPacket.EmptyDynamicPacket;
var
packet: TPacket;
stream: TEnhancedMemoryStream;
begin
packet := TPacket.Create($04, 0);
try
stream := packet.Stream;
AssertEquals('header only', Int64(5), stream.Size);
stream.Position := 0;
stream.ReadByte;
AssertEquals('length is the header size', Cardinal(5),
stream.ReadCardinal);
finally
packet.Free;
end;
end;
initialization
RegisterTests([TTestPacket]);
end.
+253
View File
@@ -0,0 +1,253 @@
unit UTestPackets;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, fpcunit, testregistry,
UEnhancedMemoryStream, UPacket, UStatics, UPackets;
type
TTestClientPackets = class(TTestCase)
published
procedure LoginRequestLayout;
procedure RequestBlocksWithoutCoords;
procedure RequestBlocksWithCoords;
procedure ElevateStaticPacketSize;
procedure ElevateStaticSignedZ;
procedure DrawMapPacketSize;
procedure MoveStaticPacketSize;
procedure DeleteStaticPacketSize;
procedure HueStaticPacketSize;
procedure InsertStaticPacketSize;
procedure CompressedPacketWireFormat;
procedure FreeBlockPacketSize;
end;
implementation
procedure TTestClientPackets.LoginRequestLayout;
var
packet: TLoginRequestPacket;
stream: TEnhancedMemoryStream;
begin
packet := TLoginRequestPacket.Create('alice', 'secret');
try
stream := packet.Stream;
AssertEquals('id + length + payload', Int64(19), stream.Size);
stream.Position := 0;
AssertEquals('admin id', Byte($02), stream.ReadByte);
AssertEquals('packet length', Cardinal(19), stream.ReadCardinal);
AssertEquals('connection sub id', Byte($03), stream.ReadByte);
AssertEquals('username', 'alice', stream.ReadStringNull);
AssertEquals('password', 'secret', stream.ReadStringNull);
finally
packet.Free;
end;
end;
procedure TTestClientPackets.RequestBlocksWithoutCoords;
var
packet: TRequestBlocksPacket;
stream: TEnhancedMemoryStream;
coords: TBlockCoordsArray;
begin
SetLength(coords, 0);
packet := TRequestBlocksPacket.Create(coords);
try
stream := packet.Stream;
AssertEquals('header only', Int64(5), stream.Size);
stream.Position := 0;
stream.ReadByte;
AssertEquals('declared length', Cardinal(5), stream.ReadCardinal);
finally
packet.Free;
end;
end;
procedure TTestClientPackets.RequestBlocksWithCoords;
var
packet: TRequestBlocksPacket;
stream: TEnhancedMemoryStream;
coords: TBlockCoordsArray;
begin
SetLength(coords, 2);
coords[0].X := 1;
coords[0].Y := 2;
coords[1].X := 3;
coords[1].Y := 4;
packet := TRequestBlocksPacket.Create(coords);
try
stream := packet.Stream;
AssertEquals('header + two coords', Int64(5 + 2 * 4), stream.Size);
stream.Position := 0;
stream.ReadByte;
AssertEquals('declared length matches', Cardinal(13),
stream.ReadCardinal);
finally
packet.Free;
end;
end;
procedure TTestClientPackets.ElevateStaticPacketSize;
var
packet: TElevateStaticPacket;
stream: TEnhancedMemoryStream;
begin
packet := TElevateStaticPacket.Create(1, 2, 3, 4, 5, 6);
try
stream := packet.Stream;
AssertEquals('declared length equals stream size',
Int64(packet.PacketLength), stream.Size);
finally
packet.Free;
end;
end;
procedure TTestClientPackets.ElevateStaticSignedZ;
var
packet: TElevateStaticPacket;
stream: TEnhancedMemoryStream;
z: ShortInt;
begin
packet := TElevateStaticPacket.Create(1, 2, 3, 4, 5, -6);
try
stream := packet.Stream;
stream.Position := stream.Size - 1;
z := stream.ReadShortInt;
AssertEquals('negative z must survive the writer', ShortInt(-6), z);
finally
packet.Free;
end;
end;
procedure TTestClientPackets.DrawMapPacketSize;
var
packet: TDrawMapPacket;
stream: TEnhancedMemoryStream;
begin
packet := TDrawMapPacket.Create(1, 2, 3, 4);
try
stream := packet.Stream;
AssertEquals(Int64(packet.PacketLength), stream.Size);
finally
packet.Free;
end;
end;
procedure TTestClientPackets.MoveStaticPacketSize;
var
packet: TMoveStaticPacket;
stream: TEnhancedMemoryStream;
begin
packet := TMoveStaticPacket.Create(1, 2, 3, 4, 5, 6, 7);
try
stream := packet.Stream;
AssertEquals(Int64(packet.PacketLength), stream.Size);
finally
packet.Free;
end;
end;
procedure TTestClientPackets.DeleteStaticPacketSize;
var
item: TStaticItem;
packet: TDeleteStaticPacket;
stream: TEnhancedMemoryStream;
begin
item := TStaticItem.Create(nil, nil, 1, 2);
try
packet := TDeleteStaticPacket.Create(item);
try
stream := packet.Stream;
AssertEquals(Int64(packet.PacketLength), stream.Size);
finally
packet.Free;
end;
finally
item.Free;
end;
end;
procedure TTestClientPackets.HueStaticPacketSize;
var
packet: THueStaticPacket;
stream: TEnhancedMemoryStream;
begin
packet := THueStaticPacket.Create(1, 2, 3, 4, 5, 6);
try
stream := packet.Stream;
AssertEquals(Int64(packet.PacketLength), stream.Size);
finally
packet.Free;
end;
end;
procedure TTestClientPackets.InsertStaticPacketSize;
var
packet: TInsertStaticPacket;
stream: TEnhancedMemoryStream;
begin
packet := TInsertStaticPacket.Create(1, 2, 3, 4, 5);
try
stream := packet.Stream;
AssertEquals(Int64(packet.PacketLength), stream.Size);
finally
packet.Free;
end;
end;
procedure TTestClientPackets.CompressedPacketWireFormat;
var
source: TPacket;
compressed: TCompressedPacket;
stream: TEnhancedMemoryStream;
innerSize: Cardinal;
i: Integer;
begin
source := TPacket.Create($06, 8);
try
stream := source.Stream;
stream.Position := stream.Size;
for i := 1 to 8 do
stream.WriteByte(Byte(i * 11));
compressed := TCompressedPacket.Create(source); //takes ownership
try
AssertEquals('wrapper id', Byte($01), compressed.PacketID);
stream := compressed.Stream;
stream.Position := 0;
AssertEquals('wrapper id byte', Byte($01), stream.ReadByte);
AssertEquals('wrapper length covers everything', Int64(stream.Size),
Int64(stream.ReadCardinal));
stream.Position := 5;
innerSize := stream.ReadCardinal;
AssertEquals('announced inner stream size', Cardinal(9), innerSize);
AssertTrue('deflate payload present', stream.Size > 9);
finally
compressed.Free;
end;
except
source.Free; //only reached if compression failed before taking ownership
raise;
end;
end;
procedure TTestClientPackets.FreeBlockPacketSize;
var
packet: TFreeBlockPacket;
stream: TEnhancedMemoryStream;
begin
packet := TFreeBlockPacket.Create(3, 4);
try
stream := packet.Stream;
AssertEquals(Int64(packet.PacketLength), stream.Size);
finally
packet.Free;
end;
end;
initialization
RegisterTests([TTestClientPackets]);
end.
+131
View File
@@ -0,0 +1,131 @@
unit UTestRegions;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, DOM, XMLRead, XMLWrite, fpcunit, testregistry, URegions;
type
TTestRegions = class(TTestCase)
private
function RegionsToXML(AList: TRegionList): string;
function ListFromXML(const AXML: string): TRegionList;
published
procedure CreateAndFind;
procedure SerializeDeserializeRoundtrip;
procedure FindMissingReturnsNil;
end;
implementation
function TTestRegions.RegionsToXML(AList: TRegionList): string;
var
doc: TXMLDocument;
root: TDOMElement;
stream: TStringStream;
begin
doc := TXMLDocument.Create;
try
root := doc.CreateElement('regions');
doc.AppendChild(root);
AList.Serialize(root);
stream := TStringStream.Create('');
try
WriteXMLFile(doc, stream);
Result := stream.DataString;
finally
stream.Free;
end;
finally
doc.Free;
end;
end;
function TTestRegions.ListFromXML(const AXML: string): TRegionList;
var
doc: TXMLDocument;
stream: TStringStream;
begin
stream := TStringStream.Create(AXML);
try
ReadXMLFile(doc, stream);
try
Result := TRegionList.Deserialize(nil, doc.DocumentElement);
finally
doc.Free;
end;
finally
stream.Free;
end;
end;
procedure TTestRegions.CreateAndFind;
var
list: TRegionList;
region: TRegion;
begin
list := TRegionList.Create(nil);
try
region := TRegion.Create(list, 'britain');
list.Add(region);
region.Areas.Add(1, 2, 3, 4);
AssertEquals('count', 1, list.Count);
AssertSame('find by name', region, list.Find('britain'));
AssertEquals('index by name', 0, list.IndexOf('britain'));
finally
list.Free;
end;
end;
procedure TTestRegions.SerializeDeserializeRoundtrip;
var
list: TRegionList;
region: TRegion;
xml: string;
loaded: TRegionList;
found: TRegion;
begin
list := TRegionList.Create(nil);
try
region := TRegion.Create(list, 'yew');
list.Add(region);
region.Areas.Add(10, 20, 30, 40);
region.Areas.Add(50, 60, 70, 80);
xml := RegionsToXML(list);
loaded := ListFromXML(xml);
try
AssertEquals('region count survives', 1, loaded.Count);
found := loaded.Find('yew');
AssertTrue('region found', found <> nil);
AssertEquals('area count survives', 2, found.Areas.Count);
AssertEquals('area 0 left', 10, found.Areas.Rects[0].Left);
AssertEquals('area 0 top', 20, found.Areas.Rects[0].Top);
AssertEquals('area 0 right', 30, found.Areas.Rects[0].Right);
AssertEquals('area 0 bottom', 40, found.Areas.Rects[0].Bottom);
AssertEquals('area 1 left', 50, found.Areas.Rects[1].Left);
finally
loaded.Free;
end;
finally
list.Free;
end;
end;
procedure TTestRegions.FindMissingReturnsNil;
var
list: TRegionList;
begin
list := TRegionList.Create(nil);
try
AssertTrue('missing region is nil', list.Find('nowhere') = nil);
finally
list.Free;
end;
end;
initialization
RegisterTests([TTestRegions]);
end.
+191
View File
@@ -0,0 +1,191 @@
unit UTestStatics;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, fpcunit, testregistry,
UEnhancedMemoryStream, UGenericIndex, UStatics;
type
TTestStaticBlock = class(TTestCase)
published
procedure WriteReadRoundtrip;
procedure LoadsBlockAtOffsetZero;
procedure EmptyLookupLoadsNothing;
procedure ClonePreservesItems;
procedure SortOrdersByPriority;
end;
implementation
procedure PopulateBlock(ABlock: TStaticBlock);
var
item: TStaticItem;
begin
item := TStaticItem.Create(nil, nil, 0, 0);
item.X := 2;
item.Y := 3;
item.Z := 10;
item.TileID := 100;
item.Hue := 5;
ABlock.Items.Add(item);
item := TStaticItem.Create(nil, nil, 0, 0);
item.X := 2;
item.Y := 3;
item.Z := -20;
item.TileID := 200;
item.Hue := 0;
ABlock.Items.Add(item);
end;
procedure TTestStaticBlock.WriteReadRoundtrip;
var
source, loaded: TStaticBlock;
stream: TEnhancedMemoryStream;
index: TGenericIndex;
begin
source := TStaticBlock.Create(nil, nil, 1, 2);
try
PopulateBlock(source);
stream := TEnhancedMemoryStream.Create;
try
source.Write(stream);
AssertEquals('two items serialized', Int64(2 * 7), stream.Size);
stream.Position := 0;
index := TGenericIndex.Create(nil);
try
index.Lookup := 0;
index.Size := stream.Size;
loaded := TStaticBlock.Create(stream, index, 1, 2);
try
AssertEquals('item count', 2, loaded.Items.Count);
AssertEquals('item 0 tile', 100, loaded.Items[0].TileID);
AssertEquals('item 0 z', 10, loaded.Items[0].Z);
AssertEquals('item 0 hue', 5, loaded.Items[0].Hue);
AssertEquals('item 1 tile', 200, loaded.Items[1].TileID);
AssertEquals('item 1 z', -20, loaded.Items[1].Z);
finally
loaded.Free;
end;
finally
index.Free;
end;
finally
stream.Free;
end;
finally
source.Free;
end;
end;
procedure TTestStaticBlock.LoadsBlockAtOffsetZero;
var
source, loaded: TStaticBlock;
stream: TEnhancedMemoryStream;
index: TGenericIndex;
begin
source := TStaticBlock.Create(nil, nil, 0, 0);
try
PopulateBlock(source);
stream := TEnhancedMemoryStream.Create;
try
source.Write(stream);
stream.Position := 0;
index := TGenericIndex.Create(nil);
try
index.Lookup := 0; //offset zero is valid, especially in fresh files
index.Size := stream.Size;
loaded := TStaticBlock.Create(stream, index, 0, 0);
try
AssertEquals('block at offset zero must load', 2, loaded.Items.Count);
finally
loaded.Free;
end;
finally
index.Free;
end;
finally
stream.Free;
end;
finally
source.Free;
end;
end;
procedure TTestStaticBlock.EmptyLookupLoadsNothing;
var
stream: TEnhancedMemoryStream;
index: TGenericIndex;
loaded: TStaticBlock;
begin
stream := TEnhancedMemoryStream.Create;
try
index := TGenericIndex.Create(nil);
try
index.Lookup := -1;
index.Size := 0;
loaded := TStaticBlock.Create(stream, index, 0, 0);
try
AssertEquals('no items for empty lookup', 0, loaded.Items.Count);
finally
loaded.Free;
end;
finally
index.Free;
end;
finally
stream.Free;
end;
end;
procedure TTestStaticBlock.ClonePreservesItems;
var
source, clone: TStaticBlock;
i: Integer;
begin
source := TStaticBlock.Create(nil, nil, 0, 0);
try
PopulateBlock(source);
clone := source.Clone;
try
AssertEquals('item count cloned', source.Items.Count, clone.Items.Count);
for i := 0 to source.Items.Count - 1 do
begin
AssertEquals('tile ' + IntToStr(i), source.Items[i].TileID,
clone.Items[i].TileID);
AssertEquals('z ' + IntToStr(i), source.Items[i].Z, clone.Items[i].Z);
AssertEquals('hue ' + IntToStr(i), source.Items[i].Hue,
clone.Items[i].Hue);
end;
finally
clone.Free;
end;
finally
source.Free;
end;
end;
procedure TTestStaticBlock.SortOrdersByPriority;
var
block: TStaticBlock;
begin
block := TStaticBlock.Create(nil, nil, 0, 0);
try
PopulateBlock(block);
block.Items[0].Priority := 2;
block.Items[1].Priority := 1;
block.Sort;
AssertEquals('lower priority first', 1, block.Items[0].Priority);
AssertEquals('higher priority second', 2, block.Items[1].Priority);
finally
block.Free;
end;
end;
initialization
RegisterTests([TTestStaticBlock]);
end.
+262
View File
@@ -0,0 +1,262 @@
unit UTestStreamHelper;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, fpcunit, testregistry, UStreamHelper;
type
TTestFifoStream = class(TTestCase)
private
procedure DoSeekBeforeStart;
procedure DoSeekPastEnd;
procedure DoNegativeRead;
procedure DoNegativeWrite;
procedure DoNegativeDequeue;
procedure DoWriteWhileLocked;
procedure DoDequeueThenSeek;
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure EnqueueDequeueOrder;
procedure DequeueRemovesFront;
procedure LockRestrictsWindow;
procedure UnlockRestoresFullSize;
procedure SeekBeforeStartRaises;
procedure SeekPastEndRaises;
procedure NegativeReadRaises;
procedure NegativeWriteRaises;
procedure NegativeDequeueRaises;
procedure WriteWhileLockedRaises;
procedure ClearEmptiesStream;
procedure DequeueThenSeekStaysInBounds;
procedure SaveLoadRoundtrip;
end;
implementation
var
fifo: TFifoStream;
procedure TTestFifoStream.SetUp;
begin
fifo := TFifoStream.Create;
end;
procedure TTestFifoStream.TearDown;
begin
fifo.Free;
end;
procedure TTestFifoStream.DoSeekBeforeStart;
begin
fifo.Seek(-1, soFromBeginning);
end;
procedure TTestFifoStream.DoSeekPastEnd;
begin
fifo.Seek(11, soFromBeginning);
end;
procedure TTestFifoStream.DoNegativeRead;
var
buffer: Byte;
begin
fifo.Read(buffer, -1);
end;
procedure TTestFifoStream.DoNegativeWrite;
var
buffer: Byte;
begin
fifo.Write(buffer, -1);
end;
procedure TTestFifoStream.DoNegativeDequeue;
begin
fifo.Dequeue(-1);
end;
procedure TTestFifoStream.DoWriteWhileLocked;
var
buffer: Byte;
begin
fifo.Write(buffer, 1);
end;
procedure TTestFifoStream.DoDequeueThenSeek;
begin
fifo.Dequeue(2);
fifo.Seek(2, soFromBeginning); //within the shrunken queue
end;
procedure TTestFifoStream.EnqueueDequeueOrder;
var
buffer: array[0..2] of Byte;
i: Integer;
value: Byte;
begin
for i := 1 to 3 do
begin
value := i;
fifo.Enqueue(value, 1);
end;
AssertEquals('size after enqueues', Int64(3), fifo.Size);
fifo.Position := 0;
fifo.Read(buffer, 3);
for i := 1 to 3 do
AssertEquals('byte order', i, buffer[i - 1]);
end;
procedure TTestFifoStream.DequeueRemovesFront;
var
buffer: array[0..0] of Byte;
i: Integer;
value: Byte;
begin
for i := 1 to 3 do
begin
value := i;
fifo.Enqueue(value, 1);
end;
fifo.Dequeue(2);
AssertEquals('size after dequeue', Int64(1), fifo.Size);
fifo.Position := 0;
fifo.Read(buffer, 1);
AssertEquals('remaining byte', 3, buffer[0]);
end;
procedure TTestFifoStream.LockRestrictsWindow;
var
buffer: array[0..4] of Byte;
i: Integer;
value: Byte;
begin
for i := 0 to 9 do
begin
value := i;
fifo.Enqueue(value, 1);
end;
fifo.Lock(2, 5);
try
AssertEquals('locked size', Int64(5), fifo.Size);
fifo.Position := 0;
fifo.Read(buffer, 5);
for i := 0 to 4 do
AssertEquals('window content', 2 + i, buffer[i]);
finally
fifo.Unlock;
end;
end;
procedure TTestFifoStream.UnlockRestoresFullSize;
var
i: Integer;
value: Byte;
begin
for i := 0 to 9 do
begin
value := i;
fifo.Enqueue(value, 1);
end;
fifo.Lock(2, 5);
fifo.Unlock;
AssertEquals('full size after unlock', Int64(10), fifo.Size);
end;
procedure TTestFifoStream.SeekBeforeStartRaises;
begin
AssertException('seek before start must raise', EStreamError, @DoSeekBeforeStart);
end;
procedure TTestFifoStream.SeekPastEndRaises;
begin
AssertException('seek past end must raise', EStreamError, @DoSeekPastEnd);
end;
procedure TTestFifoStream.NegativeReadRaises;
begin
AssertException('negative read count must raise', EStreamError, @DoNegativeRead);
end;
procedure TTestFifoStream.NegativeWriteRaises;
begin
AssertException('negative write count must raise', EStreamError, @DoNegativeWrite);
end;
procedure TTestFifoStream.NegativeDequeueRaises;
begin
AssertException('negative dequeue must raise', EStreamError, @DoNegativeDequeue);
end;
procedure TTestFifoStream.WriteWhileLockedRaises;
var
value: Byte;
begin
value := 1;
fifo.Enqueue(value, 1);
fifo.Lock(0, 1);
try
AssertException('write to locked stream must raise', EStreamError,
@DoWriteWhileLocked);
finally
fifo.Unlock;
end;
end;
procedure TTestFifoStream.ClearEmptiesStream;
var
value: Byte;
begin
value := 1;
fifo.Enqueue(value, 1);
value := 2;
fifo.Enqueue(value, 1);
fifo.Clear;
AssertEquals('empty after clear', Int64(0), fifo.Size);
value := 3;
fifo.Enqueue(value, 1); //must be usable afterwards
AssertEquals('usable after clear', Int64(1), fifo.Size);
end;
procedure TTestFifoStream.DequeueThenSeekStaysInBounds;
var
value: Byte;
begin
value := 1;
fifo.Enqueue(value, 1);
value := 2;
fifo.Enqueue(value, 1);
value := 3;
fifo.Enqueue(value, 1);
AssertException('seek must respect the shrunken queue', EStreamError,
@DoDequeueThenSeek);
end;
procedure TTestFifoStream.SaveLoadRoundtrip;
var
source: TMemoryStream;
buffer: array[0..2] of Byte;
begin
source := TMemoryStream.Create;
try
source.WriteAnsiString('abc');
fifo.LoadFromStream(source);
AssertEquals('loaded size', Int64(7), fifo.Size); //length prefix + 'abc'
fifo.Position := 4;
fifo.Read(buffer, 3);
AssertEquals('a', Char(buffer[0]));
AssertEquals('b', Char(buffer[1]));
AssertEquals('c', Char(buffer[2]));
finally
source.Free;
end;
end;
initialization
RegisterTests([TTestFifoStream]);
end.
+261
View File
@@ -0,0 +1,261 @@
unit UTestTiledata;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, fpcunit, testregistry,
UEnhancedMemoryStream, UTiledata;
type
TTestTileDataOffset = class(TTestCase)
published
procedure LegacyLandOffsets;
procedure LegacyStaticOffsets;
procedure HighSeasLandOffsets;
procedure HighSeasStaticOffsets;
end;
TTestTileDataSizes = class(TTestCase)
published
procedure LegacyLandTileSize;
procedure HighSeasLandTileSize;
procedure LegacyStaticTileSize;
procedure HighSeasStaticTileSize;
procedure LegacyLandFlagsSize;
procedure HighSeasFlagsSize;
end;
TTestTileDataRoundtrip = class(TTestCase)
published
procedure LandTileLegacyRoundtrip;
procedure LandTileHighSeasRoundtrip;
procedure StaticTileHighSeasRoundtrip;
end;
implementation
procedure TTestTileDataOffset.LegacyLandOffsets;
begin
AssertEquals('tile 0 (after group header)', 4,
GetTileDataOffset(0, tdvLegacy));
AssertEquals('tile 1', 4 + LandTileDataSize,
GetTileDataOffset(1, tdvLegacy));
AssertEquals('tile 32 starts after group header', 836 + 4,
GetTileDataOffset(32, tdvLegacy));
AssertEquals('last land tile',
511 * LandTileGroupSize + 4 + 31 * LandTileDataSize,
GetTileDataOffset($3FFF, tdvLegacy));
end;
procedure TTestTileDataOffset.LegacyStaticOffsets;
begin
AssertEquals('first static tile',
512 * LandTileGroupSize + 4,
GetTileDataOffset($4000, tdvLegacy));
AssertEquals('second static tile',
512 * LandTileGroupSize + 4 + StaticTileDataSize,
GetTileDataOffset($4001, tdvLegacy));
end;
procedure TTestTileDataOffset.HighSeasLandOffsets;
begin
//High Seas quirk: the first group header comes AFTER the unknown tile
AssertEquals('HS tile 0 sits at file start', 0,
GetTileDataOffset(0, tdvHighSeas));
AssertEquals('HS tile 1 after tile 0 and its header',
LandTileDataSizeHS + 4,
GetTileDataOffset(1, tdvHighSeas));
AssertEquals('HS tile 32 after second group header',
32 * LandTileDataSizeHS + 2 * 4,
GetTileDataOffset(32, tdvHighSeas));
end;
procedure TTestTileDataOffset.HighSeasStaticOffsets;
begin
AssertEquals('HS first static tile',
512 * LandTileGroupSizeHS + 4,
GetTileDataOffset($4000, tdvHighSeas));
AssertEquals('HS second static tile',
512 * LandTileGroupSizeHS + 4 + StaticTileDataSizeHS,
GetTileDataOffset($4001, tdvHighSeas));
end;
procedure TTestTileDataSizes.LegacyLandTileSize;
var
tile: TLandTiledata;
begin
tile := TLandTiledata.Create(nil);
try
AssertEquals(LandTileDataSize, tile.GetSize);
finally
tile.Free;
end;
end;
procedure TTestTileDataSizes.HighSeasLandTileSize;
var
tile: TLandTiledata;
begin
tile := TLandTiledata.Create(nil, tdvHighSeas);
try
AssertEquals(LandTileDataSizeHS, tile.GetSize);
finally
tile.Free;
end;
end;
procedure TTestTileDataSizes.LegacyStaticTileSize;
var
tile: TStaticTiledata;
begin
tile := TStaticTiledata.Create(nil);
try
AssertEquals(StaticTileDataSize, tile.GetSize);
finally
tile.Free;
end;
end;
procedure TTestTileDataSizes.HighSeasStaticTileSize;
var
tile: TStaticTiledata;
begin
tile := TStaticTiledata.Create(nil, tdvHighSeas);
try
AssertEquals(StaticTileDataSizeHS, tile.GetSize);
finally
tile.Free;
end;
end;
procedure TTestTileDataSizes.LegacyLandFlagsSize;
var
tile: TLandTiledata;
begin
tile := TLandTiledata.Create(nil);
try
tile.Flags := [tdfSurface, tdfBridge];
AssertEquals('legacy writes one flag dword', LandTileDataSize,
tile.GetSize);
finally
tile.Free;
end;
end;
procedure TTestTileDataSizes.HighSeasFlagsSize;
var
tile: TLandTiledata;
begin
tile := TLandTiledata.Create(nil, tdvHighSeas);
try
tile.Flags := [tdfSurface];
AssertEquals('HighSeas writes two flag dwords', LandTileDataSizeHS,
tile.GetSize);
finally
tile.Free;
end;
end;
procedure TTestTileDataRoundtrip.LandTileLegacyRoundtrip;
var
tile, loaded: TLandTiledata;
stream: TEnhancedMemoryStream;
begin
tile := TLandTiledata.Create(nil);
try
tile.Flags := [tdfWall, tdfImpassable];
tile.TextureID := 1234;
tile.TileName := 'stone';
stream := TEnhancedMemoryStream.Create;
try
tile.Write(stream);
AssertEquals('serialized size', Int64(LandTileDataSize), stream.Size);
stream.Position := 0;
loaded := TLandTiledata.Create(stream);
try
AssertTrue('flags survive', [tdfWall, tdfImpassable] = loaded.Flags);
AssertEquals('texture survives', 1234, loaded.TextureID);
AssertEquals('name survives', 'stone', Trim(loaded.TileName));
finally
loaded.Free;
end;
finally
stream.Free;
end;
finally
tile.Free;
end;
end;
procedure TTestTileDataRoundtrip.LandTileHighSeasRoundtrip;
var
tile, loaded: TLandTiledata;
stream: TEnhancedMemoryStream;
begin
tile := TLandTiledata.Create(nil, tdvHighSeas);
try
tile.Flags := [tdfSurface];
tile.TextureID := 42;
tile.TileName := 'grass';
stream := TEnhancedMemoryStream.Create;
try
tile.Write(stream);
AssertEquals('HighSeas serialized size', Int64(LandTileDataSizeHS),
stream.Size);
stream.Position := 0;
loaded := TLandTiledata.Create(stream, tdvHighSeas);
try
AssertTrue('flags survive', [tdfSurface] = loaded.Flags);
AssertEquals('texture survives', 42, loaded.TextureID);
AssertEquals('name survives', 'grass', Trim(loaded.TileName));
finally
loaded.Free;
end;
finally
stream.Free;
end;
finally
tile.Free;
end;
end;
procedure TTestTileDataRoundtrip.StaticTileHighSeasRoundtrip;
var
tile, loaded: TStaticTiledata;
stream: TEnhancedMemoryStream;
begin
tile := TStaticTiledata.Create(nil, tdvHighSeas);
try
tile.Flags := [tdfContainer];
tile.Weight := 10;
tile.Height := 7;
tile.TileName := 'chest';
stream := TEnhancedMemoryStream.Create;
try
tile.Write(stream);
AssertEquals('HighSeas serialized size', Int64(StaticTileDataSizeHS),
stream.Size);
stream.Position := 0;
loaded := TStaticTiledata.Create(stream, tdvHighSeas);
try
AssertTrue('flags survive', [tdfContainer] = loaded.Flags);
AssertEquals('weight survives', 10, loaded.Weight);
AssertEquals('height survives', 7, loaded.Height);
AssertEquals('name survives', 'chest', Trim(loaded.TileName));
finally
loaded.Free;
end;
finally
stream.Free;
end;
finally
tile.Free;
end;
end;
initialization
RegisterTests([TTestTileDataOffset, TTestTileDataSizes, TTestTileDataRoundtrip]);
end.
+124
View File
@@ -0,0 +1,124 @@
unit UTestXmlHelper;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, DOM, XMLRead, XMLWrite, fpcunit, testregistry, UXmlHelper;
type
TTestXmlHelper = class(TTestCase)
private
FDoc: TXMLDocument;
function Root: TDOMElement;
procedure LoadXML(const AXML: string);
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure WriteReadStringRoundtrip;
procedure ReadStringReturnsDefaultWhenMissing;
procedure WriteReadIntegerRoundtrip;
procedure ReadIntegerReturnsDefaultWhenMissing;
procedure ReadBooleanParsesValidValues;
procedure ReadBooleanFallsBackToDefaultOnGarbage;
procedure ReadBooleanFallsBackToDefaultWhenMissing;
procedure ReadStringToleratesCommentChild;
end;
implementation
procedure TTestXmlHelper.SetUp;
begin
FDoc := TXMLDocument.Create;
FDoc.AppendChild(FDoc.CreateElement('root'));
end;
procedure TTestXmlHelper.TearDown;
begin
FreeAndNil(FDoc);
end;
function TTestXmlHelper.Root: TDOMElement;
begin
Result := FDoc.DocumentElement;
end;
procedure TTestXmlHelper.LoadXML(const AXML: string);
var
stream: TStringStream;
begin
FreeAndNil(FDoc);
stream := TStringStream.Create(AXML);
try
ReadXMLFile(FDoc, stream);
finally
stream.Free;
end;
end;
procedure TTestXmlHelper.WriteReadStringRoundtrip;
begin
TXmlHelper.WriteString(Root, 'name', 'alice');
AssertEquals('alice', TXmlHelper.ReadString(Root, 'name', 'default'));
end;
procedure TTestXmlHelper.ReadStringReturnsDefaultWhenMissing;
begin
AssertEquals('default', TXmlHelper.ReadString(Root, 'missing', 'default'));
end;
procedure TTestXmlHelper.WriteReadIntegerRoundtrip;
begin
TXmlHelper.WriteInteger(Root, 'port', 2597);
AssertEquals(2597, TXmlHelper.ReadInteger(Root, 'port', 0));
end;
procedure TTestXmlHelper.ReadIntegerReturnsDefaultWhenMissing;
begin
AssertEquals(1234, TXmlHelper.ReadInteger(Root, 'missing', 1234));
end;
procedure TTestXmlHelper.ReadBooleanParsesValidValues;
begin
TXmlHelper.WriteBoolean(Root, 'yes', True);
TXmlHelper.WriteBoolean(Root, 'no', False);
AssertTrue(TXmlHelper.ReadBoolean(Root, 'yes', False));
AssertFalse(TXmlHelper.ReadBoolean(Root, 'no', True));
end;
procedure TTestXmlHelper.ReadBooleanFallsBackToDefaultOnGarbage;
begin
LoadXML('<root><flag>garbage</flag></root>');
AssertFalse('garbage must yield default False',
TXmlHelper.ReadBoolean(Root, 'flag', False));
AssertTrue('garbage must yield default True',
TXmlHelper.ReadBoolean(Root, 'flag', True));
end;
procedure TTestXmlHelper.ReadBooleanFallsBackToDefaultWhenMissing;
begin
AssertTrue(TXmlHelper.ReadBoolean(Root, 'missing', True));
AssertFalse(TXmlHelper.ReadBoolean(Root, 'missing', False));
end;
procedure TTestXmlHelper.ReadStringToleratesCommentChild;
var
element, text: TDOMElement;
comment: TDOMComment;
begin
element := FDoc.CreateElement('entry');
Root.AppendChild(element);
comment := FDoc.CreateComment('metadata');
element.AppendChild(comment); //comment must not be treated as the value
text := FDoc.CreateElement('value');
element.AppendChild(text);
TXmlHelper.WriteString(element, 'value', 'real');
AssertEquals('real', TXmlHelper.ReadString(element, 'value', 'default'));
end;
initialization
RegisterTests([TTestXmlHelper]);
end.
+92
View File
@@ -0,0 +1,92 @@
<?xml version="1.0" encoding="UTF-8"?>
<CONFIG>
<ProjectOptions>
<Version Value="12"/>
<General>
<Flags>
<MainUnitHasUsesSectionForAllUnits Value="False"/>
<MainUnitHasCreateFormStatements Value="False"/>
<MainUnitHasTitleStatement Value="False"/>
<MainUnitHasScaledStatement Value="False"/>
<LRSInOutputDirectory Value="False"/>
<CompatibilityMode Value="True"/>
</Flags>
<SessionStorage Value="InProjectDir"/>
</General>
<VersionInfo>
<UseVersionInfo Value="False"/>
</VersionInfo>
<BuildModes Count="1">
<Item1 Name="default" Default="True"/>
</BuildModes>
<PublishOptions>
<Version Value="2"/>
</PublishOptions>
<RunParams>
<FormatVersion Value="2"/>
<Modes Count="1">
<Mode0 Name="default"/>
</Modes>
</RunParams>
<RequiredPackages Count="2">
<Item1>
<PackageName Value="multiloglaz"/>
</Item1>
<Item2>
<PackageName Value="lnetbase"/>
</Item2>
</RequiredPackages>
<Units Count="5">
<Unit0>
<Filename Value="unittests-server.lpr"/>
<IsPartOfProject Value="True"/>
</Unit0>
<Unit1>
<Filename Value="UTestRegions.pas"/>
<IsPartOfProject Value="True"/>
</Unit1>
<Unit2>
<Filename Value="UTestAccount.pas"/>
<IsPartOfProject Value="True"/>
</Unit2>
<Unit3>
<Filename Value="UTestConfig.pas"/>
<IsPartOfProject Value="True"/>
</Unit3>
<Unit4>
<Filename Value="UTestLandscapeBounds.pas"/>
<IsPartOfProject Value="True"/>
</Unit4>
</Units>
</ProjectOptions>
<CompilerOptions>
<Version Value="11"/>
<Target>
<Filename Value="bin/unittests-server"/>
</Target>
<SearchPaths>
<IncludeFiles Value="..;../Imaging"/>
<OtherUnitFiles Value="..;../Server;../UOLib;../MulProvider;../Imaging;../Imaging/ZLib"/>
<UnitOutputDirectory Value="obj-tests/$(TargetCPU)-$(TargetOS)"/>
<SrcPath Value="..;../Server;../UOLib;../MulProvider;../Imaging;../Imaging/ZLib"/>
</SearchPaths>
<Parsing>
<SyntaxOptions>
<CStyleOperator Value="False"/>
</SyntaxOptions>
</Parsing>
<CodeGeneration>
<Checks>
<IOChecks Value="True"/>
<RangeChecks Value="True"/>
<OverflowChecks Value="True"/>
<StackChecks Value="True"/>
</Checks>
</CodeGeneration>
<Linking>
<Debugging>
<DebugInfoType Value="dsDwarf3"/>
</Debugging>
</Linking>
</CompilerOptions>
</CONFIG>
+20
View File
@@ -0,0 +1,20 @@
program unittestsserver;
{$mode objfpc}{$H+}
uses
simpletestrunner,
UTestRegions,
UTestAccount,
UTestConfig,
UTestLandscapeBounds;
begin
with TTestRunner.Create(nil) do
try
Initialize;
Run;
finally
Free;
end;
end.
+126
View File
@@ -0,0 +1,126 @@
<?xml version="1.0" encoding="UTF-8"?>
<CONFIG>
<ProjectOptions>
<Version Value="12"/>
<General>
<Flags>
<MainUnitHasUsesSectionForAllUnits Value="False"/>
<MainUnitHasCreateFormStatements Value="False"/>
<MainUnitHasTitleStatement Value="False"/>
<MainUnitHasScaledStatement Value="False"/>
<LRSInOutputDirectory Value="False"/>
<CompatibilityMode Value="True"/>
</Flags>
<SessionStorage Value="InProjectDir"/>
</General>
<VersionInfo>
<UseVersionInfo Value="False"/>
</VersionInfo>
<BuildModes Count="1">
<Item1 Name="default" Default="True"/>
</BuildModes>
<PublishOptions>
<Version Value="2"/>
</PublishOptions>
<RunParams>
<FormatVersion Value="2"/>
<Modes Count="1">
<Mode0 Name="default"/>
</Modes>
</RunParams>
<RequiredPackages Count="1">
<Item1>
<PackageName Value="multiloglaz"/>
</Item1>
</RequiredPackages>
<Units Count="14">
<Unit0>
<Filename Value="unittests.lpr"/>
<IsPartOfProject Value="True"/>
</Unit0>
<Unit1>
<Filename Value="UTestCacheManager.pas"/>
<IsPartOfProject Value="True"/>
</Unit1>
<Unit2>
<Filename Value="UTestEnhancedMemoryStream.pas"/>
<IsPartOfProject Value="True"/>
</Unit2>
<Unit3>
<Filename Value="UTestStreamHelper.pas"/>
<IsPartOfProject Value="True"/>
</Unit3>
<Unit4>
<Filename Value="UTestBufferedStreams.pas"/>
<IsPartOfProject Value="True"/>
</Unit4>
<Unit5>
<Filename Value="UTestXmlHelper.pas"/>
<IsPartOfProject Value="True"/>
</Unit5>
<Unit6>
<Filename Value="UTestLinkedList.pas"/>
<IsPartOfProject Value="True"/>
</Unit6>
<Unit7>
<Filename Value="UTestPacket.pas"/>
<IsPartOfProject Value="True"/>
</Unit7>
<Unit8>
<Filename Value="UTestArt.pas"/>
<IsPartOfProject Value="True"/>
</Unit8>
<Unit9>
<Filename Value="UTestMap.pas"/>
<IsPartOfProject Value="True"/>
</Unit9>
<Unit10>
<Filename Value="UTestStatics.pas"/>
<IsPartOfProject Value="True"/>
</Unit10>
<Unit11>
<Filename Value="UTestTiledata.pas"/>
<IsPartOfProject Value="True"/>
</Unit11>
<Unit12>
<Filename Value="UTestLocalization.pas"/>
<IsPartOfProject Value="True"/>
</Unit12>
<Unit13>
<Filename Value="UTestPackets.pas"/>
<IsPartOfProject Value="True"/>
</Unit13>
</Units>
</ProjectOptions>
<CompilerOptions>
<Version Value="11"/>
<Target>
<Filename Value="bin/unittests"/>
</Target>
<SearchPaths>
<IncludeFiles Value="..;../Imaging"/>
<OtherUnitFiles Value="..;../UOLib;../MulProvider;../Imaging;../Imaging/ZLib;../Client"/>
<UnitOutputDirectory Value="obj-tests/$(TargetCPU)-$(TargetOS)"/>
<SrcPath Value="..;../UOLib;../MulProvider;../Imaging;../Imaging/ZLib"/>
</SearchPaths>
<Parsing>
<SyntaxOptions>
<CStyleOperator Value="False"/>
</SyntaxOptions>
</Parsing>
<CodeGeneration>
<Checks>
<IOChecks Value="True"/>
<RangeChecks Value="True"/>
<OverflowChecks Value="True"/>
<StackChecks Value="True"/>
</Checks>
</CodeGeneration>
<Linking>
<Debugging>
<DebugInfoType Value="dsDwarf3"/>
<UseHeaptrc Value="True"/>
</Debugging>
</Linking>
</CompilerOptions>
</CONFIG>
+29
View File
@@ -0,0 +1,29 @@
program unittests;
{$mode objfpc}{$H+}
uses
simpletestrunner,
UTestCacheManager,
UTestEnhancedMemoryStream,
UTestStreamHelper,
UTestBufferedStreams,
UTestXmlHelper,
UTestLinkedList,
UTestPacket,
UTestArt,
UTestMap,
UTestStatics,
UTestTiledata,
UTestLocalization,
UTestPackets;
begin
with TTestRunner.Create(nil) do
try
Initialize;
Run;
finally
Free;
end;
end.