Compare commits

..

184 Commits

Author SHA1 Message Date
Nut.andor
120ed02a69 Merge branch 'pulls/1195352/10' workspace + project as json 2025-08-04 21:05:23 +02:00
Nut.andor
f308580deb Json project files 2025-08-04 20:47:39 +02:00
Nut.andor
fd41013ade Merge branch 'pulls/1195352/9' 2025-08-04 20:47:18 +02:00
Nut.andor
114e09597e Pull Request #10: Json project files 2025-08-04 13:39:00 +02:00
Nut.andor
3ceee2e9e6 decrease version to avoid swing issue 2025-07-17 20:49:36 +02:00
OMGeeky
83cc57515d Add .workspace.json and .project.json to .gitignore in createProject.bat 2025-07-17 20:36:56 +02:00
OMGeeky
06d4131582 Add toJsonString method for JsonSerializable objects 2025-07-17 20:33:56 +02:00
OMGeeky
60205d54de Remove AndorsTrainer references and related functionality 2025-07-17 20:33:56 +02:00
OMGeeky
f6fbb0f5a3 Remove unused SavedGame references and related functionality
it didn't really work for a long time anyway and was extremely outdated
2025-07-17 20:33:56 +02:00
OMGeeky
af48341439 fix json project & workspace file paths when migrating from binary 2025-07-17 20:33:56 +02:00
OMGeeky
7b7218ad4e Add error handling for update check timeouts and HTTP status exceptions 2025-07-17 19:45:29 +02:00
OMGeeky
1ddf1c5051 Add notification for error when opening SpritesheetEditor 2025-07-17 18:20:16 +02:00
OMGeeky
f9a9ab97de Sort spritesheets by ID in the Project-Tree 2025-07-17 18:19:31 +02:00
Nut.andor
b37d32b5c2 Deduplicating a lot of stuff 2025-07-16 21:22:01 +02:00
OMGeeky
3c5ed1d6f6 Merge branch 'dedup-1' into json-project-files 2025-07-15 12:54:32 +02:00
Nut.andor
32ff1b57fa Pull Request #9: Deduplicating a lot of stuff 2025-07-13 02:28:01 +02:00
OMGeeky
090584dbcc add warning about icon 2025-07-13 02:25:01 +02:00
OMGeeky
e858e436c6 Merge remote-tracking branch 'origin/master' into dedup-1
# Conflicts:
#	src/com/gpl/rpg/atcontentstudio/ATContentStudio.java
#	src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java
2025-07-13 02:21:49 +02:00
OMGeeky
4b2aa77cb6 refactor to keep compatibility with old java version (openjdk-11 tested) 2025-07-03 20:16:36 +02:00
OMGeeky
24e1e526ce refactor to keep compatibility with old java version (openjdk-11 tested) 2025-07-03 20:05:00 +02:00
Nut.andor
861c4c3bb1 Merge branch 'pulls/1195352/8' 2025-06-28 21:23:39 +02:00
Nut.andor
c18fcfc667 Auto-Package on release 2025-06-28 20:46:50 +02:00
Nut.andor
9b1ac0d3e1 new item sprite (map objects) 2025-06-28 20:45:16 +02:00
OMGeeky
782d436681 Revert "remove saves (temporarily?) since they don't really work"
This reverts commit 7929ffe2a7.
2025-06-25 01:27:34 +02:00
OMGeeky
397d1ded8c make project file to json
same as with .workspace the .project file now saves as .project.json and falls back to .project
2025-06-25 01:24:41 +02:00
OMGeeky
aef6429dbc code style 2025-06-24 23:27:54 +02:00
OMGeeky
c43b8464a2 save .workspace as json
(under .workspace.json)

falls back on old .workspace implementation
2025-06-24 23:27:38 +02:00
OMGeeky
7929ffe2a7 remove saves (temporarily?) since they don't really work 2025-06-24 21:51:41 +02:00
OMGeeky
a3ffecfd23 improve json saving to file 2025-06-24 21:50:52 +02:00
OMGeeky
1cbcd5b661 remove finished todo list 2025-06-24 20:36:59 +02:00
OMGeeky
0eddd25292 delete inspectionProfile 2025-06-24 20:29:43 +02:00
OMGeeky
1c83eedd80 format 2025-06-24 20:10:18 +02:00
OMGeeky
6c296868c0 add null check 2025-06-24 19:50:35 +02:00
OMGeeky
8f5452b487 add myself to Contributor list 2025-06-24 19:11:56 +02:00
OMGeeky
f9f1caafc6 extract some code 2025-06-24 18:57:53 +02:00
OMGeeky
c0e24b4cf5 fix bug, where condition buttons are enabled in readonly mode 2025-06-24 18:45:15 +02:00
OMGeeky
cd36813050 move some things around and make the code sturdier 2025-06-24 18:40:54 +02:00
OMGeeky
358d855eec fix number comparison bugs 2025-06-24 18:11:24 +02:00
OMGeeky
281e314815 extract ConditionEffectEditorPane 2025-06-24 18:00:47 +02:00
OMGeeky
3f19ca959b improve code a bit 2025-06-24 16:51:29 +02:00
OMGeeky
6b74ad5cbe fix bug, where some values were not being updated when switching category to a different action type 2025-06-24 16:40:42 +02:00
OMGeeky
93e44a2b50 improve *EffectPane initialisation 2025-06-24 16:39:46 +02:00
OMGeeky
652da07cc8 change warning message when no action type can be determined for an item when writing 2025-06-24 16:30:49 +02:00
OMGeeky
2dbe881dd7 change ItemEditor to use *EffectPane classes 2025-06-24 16:25:13 +02:00
OMGeeky
b7e9bf0582 move ListModels to CommonEditor for re-use 2025-06-24 16:07:50 +02:00
OMGeeky
6dcd8599b3 reformat CommonEditor 2025-06-24 15:38:55 +02:00
OMGeeky
62ed795fed add codeStyle to git 2025-06-24 15:38:41 +02:00
OMGeeky
ec04b810d9 fix bug 2025-06-24 15:23:44 +02:00
OMGeeky
18b92a3921 add valueChanged override for HitRecievedEffectPane 2025-06-24 15:16:36 +02:00
OMGeeky
127ed76006 improve isNull check 2025-06-24 14:53:59 +02:00
OMGeeky
56242e85f2 check TODOs 2025-06-24 14:44:45 +02:00
OMGeeky
de2b47821b add TODOs that need to be done before finishing. 2025-06-23 22:12:16 +02:00
OMGeeky
7eb60117c4 fix bug in writeMinMaxToMap 2025-06-23 22:09:45 +02:00
OMGeeky
0c69438a33 move the hitReceivedEffect fields to the correct position 2025-06-23 21:55:08 +02:00
OMGeeky
380bb1de17 improve DeathEffectPane generics & inheritance 2025-06-23 21:47:36 +02:00
OMGeeky
9ae9914dde cleanup 2025-06-23 21:29:09 +02:00
OMGeeky
c78fcde633 extract hitReceivedEffect stuff into HitReceivedEffectPane 2025-06-23 21:29:02 +02:00
OMGeeky
270c613f66 add applyToTargetHint to HitEffectPanel 2025-06-23 21:17:44 +02:00
OMGeeky
ebafae7503 extract some valueChanged stuff for DeathEffectPane & HitEffectPane 2025-06-23 21:03:04 +02:00
OMGeeky
572c658b43 change some constructor stuff for it and switch the deathEffectPane to the new DeathEffectPane class 2025-06-23 20:41:40 +02:00
OMGeeky
5031fa3c72 rename some stuff 2025-06-23 19:58:22 +02:00
OMGeeky
7f0b55a71c add possibility for hint where the effect is applied to 2025-06-23 18:57:59 +02:00
OMGeeky
ab91d330bd extract parts of HitEffectPane into DeathEffectPane for better usage 2025-06-23 18:51:04 +02:00
OMGeeky
27a86ee654 continue to extract HitEffectPane 2025-06-23 18:43:54 +02:00
OMGeeky
ad15063dcc start to extract HitEffectPane 2025-06-23 18:23:54 +02:00
OMGeeky
2ea425dda6 use isImmunity & isClear & isInfinite more 2025-06-23 18:20:52 +02:00
OMGeeky
f22052525c change wrong ConditionsCellRenderer to TimedConditionsCellRenderer 2025-06-23 17:37:13 +02:00
OMGeeky
63e381a804 move ConditionsCellRenderer to CommonEditor 2025-06-23 17:35:46 +02:00
OMGeeky
488dd92893 extract actorConditionElementChanged + some parse stuff 2025-06-23 17:25:39 +02:00
OMGeeky
f04f062723 extract some more toJson stuff to reduce duplication 2025-06-23 16:24:47 +02:00
OMGeeky
e91f770975 extract some toJson stuff to reduce duplication 2025-06-23 16:08:21 +02:00
OMGeeky
7018703ba6 extract linkIcon 2025-06-23 15:15:16 +02:00
OMGeeky
93f0a902ba extract linkEffects 2025-06-23 15:09:52 +02:00
OMGeeky
1ca2b9068e extract isImmunity & isClear & isInfinite 2025-06-23 15:09:41 +02:00
OMGeeky
a7f214a1cb extract TimedConditionsCellRenderer into CommonEditor 2025-06-23 14:35:27 +02:00
OMGeeky
b2c05037e5 use BasicEffect for HitReceivedEffect values to reuse logic 2025-06-23 14:31:50 +02:00
OMGeeky
517a798b6f extract BasicEffect and rename TimedConditionEffect to TimedActorConditionEffect 2025-06-23 14:31:06 +02:00
OMGeeky
e9fecee876 extract some code into updateConditionEffect (ITEM & NPC) 2025-06-23 14:03:13 +02:00
OMGeeky
967bbf918b extract some more CollapsibleItemLists (in ItemEditor) 2025-06-23 13:21:07 +02:00
OMGeeky
5ce84dc1b1 extract some CollapsibleItemLists (in ItemEditor) 2025-06-23 13:02:03 +02:00
OMGeeky
0a18309bfe remove some leftover code 2025-06-23 12:36:54 +02:00
OMGeeky
edc4634cbe extract some CollapsibleItemLists (in QUEST & NPC) 2025-06-22 20:03:18 +02:00
OMGeeky
1e25eabb50 fix deprecated warnings 2025-06-22 19:13:58 +02:00
OMGeeky
1c7de2b97f misc 2025-06-22 18:57:44 +02:00
OMGeeky
e40fe058dd fix oversight, where changes would call the wrong event 2025-06-22 18:57:37 +02:00
OMGeeky
919e65187f improve addNumberField 2025-06-22 18:55:05 +02:00
OMGeeky
7b780462ea handle wrong values passed to addNumberField better 2025-06-22 17:48:12 +02:00
OMGeeky
00147c2708 extract one CollapsibleItemList defs in ItemEditor 2025-06-21 21:07:45 +02:00
OMGeeky
70cc945010 misc 2025-06-21 20:24:33 +02:00
OMGeeky
21005f1ba6 improve bounds check in getElementAt 2025-06-21 20:16:57 +02:00
OMGeeky
b5a6aa6706 rename some stuff and be more specific on some usages 2025-06-21 20:16:05 +02:00
OMGeeky
3cc6eb9edb enable buttons to move up and down on all (extracted) list panels 2025-06-21 20:01:01 +02:00
OMGeeky
d166e49f4d extract common stuff of addIntegerField & addDoubleField 2025-06-21 19:25:44 +02:00
OMGeeky
d1568cd2ed extract common stuff of addTextField & addTextArea 2025-06-21 19:10:03 +02:00
OMGeeky
685ce223da extract refresh button creation 2025-06-21 19:09:35 +02:00
OMGeeky
18cb73385f remove Unnecessary semicolons 2025-06-21 18:37:54 +02:00
OMGeeky
90359bf285 reformat all code 2025-06-21 18:36:37 +02:00
OMGeeky
bb187621b7 remove a bunch of unused assignments 2025-06-21 18:19:25 +02:00
OMGeeky
a4b431efdd remove some commented out code from earlier 2025-06-21 17:59:59 +02:00
OMGeeky
cffbf973e1 change more ListModel implementations to more specific implementations
like ListenerListModel, ListenerCollectionModel or OrderedListenerListModel
2025-06-21 17:59:59 +02:00
OMGeeky
979a7bc43f add interface ListenerCollectionModel and use it in the OrderedListenerListModel 2025-06-21 17:59:59 +02:00
OMGeeky
6b049d3b7b rename CustomListModel to OrderedListenerListModel 2025-06-21 17:59:59 +02:00
OMGeeky
edd0160c9d extract some code into ListenerListModel interface 2025-06-21 17:59:59 +02:00
OMGeeky
fdcc4fab55 extract some code 2025-06-21 17:59:59 +02:00
OMGeeky
d030e11019 change more ListModel implementations to CustomListModel 2025-06-21 17:59:59 +02:00
OMGeeky
333100b19b add more ListModel to CustomListModel changes 2025-06-21 17:59:59 +02:00
OMGeeky
cfb906736d extract into sub-methods 2025-06-21 17:59:59 +02:00
OMGeeky
cf8c0497bc add navigation to getCollapsibleItemList 2025-06-21 17:59:59 +02:00
OMGeeky
355bb2bc54 extract collapsibleItemList with buttons into method
this is currently done for
- items in a droplist
- replies
- rewards

others should follow
2025-06-21 17:59:59 +02:00
OMGeeky
e1e85d7a90 extract into CustomListModel 2025-06-01 20:26:18 +02:00
OMGeeky
9ed9393b16 extract wordWrap to TextUtils helper-class 2025-06-01 19:24:24 +02:00
OMGeeky
8c42b498b0 rename needsToBeLinked to linkCheck and continue dedupe 2025-06-01 19:16:59 +02:00
OMGeeky
8561415574 dedup link check 2025-06-01 19:01:35 +02:00
OMGeeky
185f168b19 misc 2025-06-01 18:52:12 +02:00
OMGeeky
70055be6d2 improve usings 2025-05-03 20:16:57 +02:00
OMGeeky
286d95d83d improve imports 2025-05-03 20:14:45 +02:00
OMGeeky
04b704daf0 more de-duplication 2025-05-03 20:10:36 +02:00
OMGeeky
3f1f988808 fix missed null check 2025-05-03 20:07:28 +02:00
OMGeeky
e232c33339 more de-duplication 2025-05-03 20:07:28 +02:00
OMGeeky
4239beb825 de-dupe code 2025-05-03 20:07:28 +02:00
Nut.andor
eb6377a983 Adding better error message in TMX input 2025-03-16 20:17:57 +01:00
Nut.andor
2fb16c9213 missing JDK in misc.xml 2025-03-16 20:17:32 +01:00
Nut.andor
6741100a4f Pull Request #8: Auto-Package on release 2025-02-18 23:52:51 +01:00
OMGeeky
dbff7fb571 Refactor version handling to read APP_VERSION from ATCS_latest file
(cherry picked from commit c9cccf9eb2)
2025-02-18 23:34:08 +01:00
OMGeeky
dfb3e31a7a Update package.sh to copy version file from VERSION_FILE variable
(cherry picked from commit 5ff45746d8)
2025-02-18 23:33:48 +01:00
OMGeeky
022c9ad229 Update release workflow to read version from the correct file path
(cherry picked from commit f14d21e322)
2025-02-18 23:33:27 +01:00
OMGeeky
38a3d4082b Update package.sh to reference ATCS_latest from the source directory and copy it to the temporary packaging directory
(cherry picked from commit 5191f56a01)
2025-02-18 23:31:20 +01:00
OMGeeky
cd78ee3ad0 Add .gitattributes to normalize line endings and enforce LF for bash scripts
(cherry picked from commit a71e8fe0a4)
2025-02-18 23:29:00 +01:00
OMGeeky
7b30cc6355 Remove unnecessary exit command from ATCS.sh
(cherry picked from commit a76d425ab7)
2025-02-18 23:29:00 +01:00
OMGeeky
9a6c5ecf6e delete obsolete Linux folder 2025-02-18 22:34:29 +01:00
OMGeeky
ed81c2382f Fix some issues with the linux ATCS.sh when the current path has spaces etc. 2025-02-18 22:33:08 +01:00
OMGeeky
ed2ad56b76 cleanup some packaging stuff 2025-02-18 18:08:02 +01:00
OMGeeky
becf45f249 Refactor release workflow to consolidate asset uploads 2025-02-16 01:19:20 +01:00
OMGeeky
c950324cd9 Reorder NSIS installation step in release workflow 2025-02-16 01:10:25 +01:00
OMGeeky
b58d080f4d Update installer script and release workflow to improve version handling 2025-02-16 01:07:44 +01:00
OMGeeky
a2640c2da0 Update installer script and release workflow to use dynamic versioning 2025-02-16 00:57:27 +01:00
OMGeeky
4fe7e71a43 Refactor GitHub Actions workflow to streamline version retrieval process 2025-02-16 00:39:10 +01:00
OMGeeky
9a162ac58d Refactor release workflow to improve directory navigation and version handling 2025-02-16 00:36:02 +01:00
OMGeeky
93718230a5 Merge pull request #1 from OMGeeky/package-improvements
Package improvements
2025-02-16 00:27:35 +01:00
OMGeeky
4fbf7de85a Merge remote-tracking branch 'omgeeky/package-improvements' into package-improvements
# Conflicts:
#	packaging/Windows/ATCS_Installer.nsi
2025-02-16 00:26:03 +01:00
OMGeeky
f0be1a8135 Add GitHub Actions workflow for automated release builds 2025-02-16 00:24:50 +01:00
OMGeeky
104d3db5ad Update ATCS_Installer.nsi to change ATCS_SOURCE_DIR path for improved directory structure and allow github actions 2025-02-16 00:24:47 +01:00
OMGeeky
f154efcecc Update ATCS_Installer.nsi to dynamically set VERSION from ATCS_latest file 2025-02-16 00:24:05 +01:00
OMGeeky
00e9e3b2a7 Enhance package.sh to support platform-specific archive creation using PowerShell on Windows 2025-02-16 00:23:52 +01:00
OMGeeky
92436d3ce9 Update package.sh to switch from tar.gz to zip for archive creation 2025-02-16 00:23:52 +01:00
OMGeeky
b6cfe349c0 Add GitHub Actions workflow for automated release builds 2025-02-16 00:21:42 +01:00
OMGeeky
1e2daa56a4 Update ATCS_Installer.nsi to change ATCS_SOURCE_DIR path for improved directory structure and allow github actions 2025-02-16 00:21:05 +01:00
OMGeeky
2caaaeb474 Update ATCS_Installer.nsi to dynamically set VERSION from ATCS_latest file 2025-02-16 00:20:21 +01:00
OMGeeky
0e8ed1a25d Enhance package.sh to support platform-specific archive creation using PowerShell on Windows 2025-02-16 00:01:27 +01:00
Nut.andor
e2fdf08fec new spritesheets index 2025-02-15 23:48:39 +01:00
OMGeeky
b5dceb9fd1 Update package.sh to switch from tar.gz to zip for archive creation 2025-02-15 23:32:36 +01:00
Nut.andor
1555bd63db Version with actor condition description is 21 2025-02-15 17:04:23 +01:00
Nut.andor
56fff8a730 nsi 2025-02-15 16:53:27 +01:00
Nut.andor
dd7b3d5300 version nbr 2025-02-15 16:44:40 +01:00
Nut.andor
68affdde8c misc 2025-02-15 16:44:13 +01:00
Nut.andor
6cec8b835e nsi 2025-02-15 16:36:45 +01:00
Nut.andor
aa43382296 Merge branch 'pulls/1195352/7' 2025-02-15 16:34:58 +01:00
Nut.andor
ec346e9c98 command parameters 2025-02-15 16:33:12 +01:00
Nut.andor
61d5af822c Build scripts 2025-02-15 16:12:38 +01:00
Nut.andor
c2d05b2bff Pull Request #7: Build scripts 2025-02-15 16:03:43 +01:00
OMGeeky
e60378ab64 Refactor package.sh to simplify JAR creation and improve directory structure 2025-02-15 16:03:36 +01:00
Nut.andor
6578236775 Merge branch 'pulls/1195352/6' 2025-02-15 14:38:30 +01:00
OMGeeky
4fa2409c24 Update .gitignore to include /out and ATCS.jar, and adjust patterns for ATCS_v*.tar.gz 2025-02-15 02:03:22 +01:00
OMGeeky
b5aa453fd6 cleanup package.sh 2025-02-15 02:03:08 +01:00
OMGeeky
42f1c87278 re-enable XML validation in TMXMapReader and update package script to copy resources recursively 2025-02-15 01:47:11 +01:00
OMGeeky
9097b97316 Disable XML validation and external DTD loading in TMXMapReader
This is because of a weird error, that only happens, when the jar is built manually somehow...
2025-02-15 01:17:59 +01:00
OMGeeky
7965ecb4f1 Update ATContentStudio_jar.xml to replace library elements with extracted-dir elements for JAR files and modify misc.xml to set default project JDK 2025-02-15 01:11:51 +01:00
OMGeeky
01963517ba Update .gitignore to exclude ATCS_v*.tar.gz and old.sh files 2025-02-15 00:31:47 +01:00
OMGeeky
30bef443d5 Refactor package script to extract library files directly to TEMP_DIR and simplify classpath 2025-02-15 00:28:16 +01:00
OMGeeky
8d01716d93 Refactor package script to simplify JAR creation and archive process 2025-02-15 00:09:21 +01:00
OMGeeky
fce5cd71ff Fix package script to construct source path and compile all Java files from specified directories 2025-02-14 23:49:00 +01:00
OMGeeky
0cddbb04e9 Enhance build script to include additional source code folders for compilation 2025-02-14 23:44:39 +01:00
OMGeeky
00ec5fe49f Update build script to include all Java files in the compilation process 2025-02-14 23:25:39 +01:00
OMGeeky
5cdb42ae07 clean up script 2025-02-14 20:30:57 +01:00
OMGeeky
c98f51744b Add initial project configuration files and setup for ATContentStudio 2025-02-14 20:04:44 +01:00
Nut.andor
5550b257ca add description field to actor conditions 2024-12-28 14:53:02 +01:00
Nut.andor
619aa1075f Pull Request #6: add description field to actor conditions 2024-12-27 13:05:53 +01:00
OMGeeky
38a3ad85c8 add description field to actor conditions 2024-12-27 10:12:48 +01:00
OMGeeky
89f764b62b Merge branch 'AndorsTrailRelease:master' into master 2024-12-27 10:10:35 +01:00
Nut.andor
d81233d470 createProject 2024-08-26 23:23:14 +02:00
Nut.andor
e1685aa625 createProject 2024-08-26 23:23:06 +02:00
OMGeeky
ae3ca5d50a fix typo & improve path safety (space in path should now be allowed) 2024-06-16 17:17:07 +02:00
OMGeeky
a00b8fbc66 fix typo 2024-06-16 17:00:32 +02:00
OMGeeky
4d03c15e08 Improve some error messages 2024-02-08 18:38:11 +00:00
160 changed files with 30591 additions and 34070 deletions

6
.gitattributes vendored Normal file
View File

@@ -0,0 +1,6 @@
# Set default behavior to automatically normalize line endings.
* text=auto
# Force bash scripts to always use LF line endings so that if a repo is accessed
# in Unix via a file share from Windows, the scripts will work.
*.sh text eol=lf

56
.github/workflows/release.yml vendored Normal file
View File

@@ -0,0 +1,56 @@
name: Release Build
on:
release:
types: [created]
jobs:
build:
runs-on: windows-latest
steps:
- uses: actions/checkout@v2
- name: Get Version
id: get_version
shell: bash
run: |
echo "Reading version from file:"
cat res/ATCS_latest
echo ""
VERSION=$(tr -d '[:space:]' < "res/ATCS_latest")
echo "Processed version: $VERSION"
echo "VERSION=$VERSION" >> $GITHUB_ENV
echo "Environment variable set to: $VERSION"
- name: Set up JDK
uses: actions/setup-java@v2
with:
java-version: '11'
distribution: 'temurin'
- name: Build JAR
shell: bash
run: |
cd packaging
chmod +x package.sh
echo "Building JAR and ZIP for version: ${{ env.VERSION }}"
./package.sh -windows
echo "Created artifacts:"
ls -la common/ATCS.jar
ls -la ATCS_${{ env.VERSION }}.zip
- name: Install NSIS
uses: joncloud/makensis-action@v4
with:
script-file: packaging/Windows/ATCS_Installer.nsi
arguments: /DVERSION="${{ env.VERSION }}"
- name: Upload Release Assets
uses: softprops/action-gh-release@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
files: |
./packaging/ATCS_${{ env.VERSION }}.zip
./packaging/ATCS_${{ env.VERSION }}_Setup.exe

6
.gitignore vendored
View File

@@ -2,6 +2,12 @@
/Project /Project
/bin /bin
/packaging/tmp/ /packaging/tmp/
/out
packaging/common/lib packaging/common/lib
packaging/common/ATCS.jar packaging/common/ATCS.jar
packaging/ATCS_*.zip packaging/ATCS_*.zip
ATCS_v*.tar.gz
ATCS.jar
/packaging/common/ATCS.env.bat
/packaging/common/ATCS.env
/packaging/common/ATCS_v*.zip

8
.idea/.gitignore generated vendored Normal file
View File

@@ -0,0 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

17
.idea/artifacts/ATContentStudio_jar.xml generated Normal file
View File

@@ -0,0 +1,17 @@
<component name="ArtifactManager">
<artifact name="ATContentStudio:jar">
<output-path>$PROJECT_DIR$/out/artifacts/ATContentStudio_jar</output-path>
<root id="root">
<element id="archive" name="ATContentStudio.jar">
<element id="module-output" name="ATContentStudio" />
<element id="extracted-dir" path="$PROJECT_DIR$/lib/bsh-2.0b4.jar" path-in-jar="/" />
<element id="extracted-dir" path="$PROJECT_DIR$/lib/rsyntaxtextarea.jar" path-in-jar="/" />
<element id="extracted-dir" path="$PROJECT_DIR$/lib/prefuse.jar" path-in-jar="/" />
<element id="extracted-dir" path="$PROJECT_DIR$/lib/jsoup-1.10.2.jar" path-in-jar="/" />
<element id="extracted-dir" path="$PROJECT_DIR$/lib/json_simple-1.1.jar" path-in-jar="/" />
<element id="extracted-dir" path="$PROJECT_DIR$/lib/ui.jar" path-in-jar="/" />
<element id="extracted-dir" path="$PROJECT_DIR$/lib/jide-oss.jar" path-in-jar="/" />
</element>
</root>
</artifact>
</component>

19
.idea/codeStyles/Project.xml generated Normal file
View File

@@ -0,0 +1,19 @@
<component name="ProjectCodeStyleConfiguration">
<code_scheme name="Project" version="173">
<JavaCodeStyleSettings>
<option name="JD_P_AT_EMPTY_LINES" value="false" />
</JavaCodeStyleSettings>
<codeStyleSettings language="JAVA">
<option name="RIGHT_MARGIN" value="200" />
<option name="ALIGN_MULTILINE_PARAMETERS_IN_CALLS" value="true" />
<option name="CALL_PARAMETERS_WRAP" value="1" />
<option name="BINARY_OPERATION_WRAP" value="5" />
<option name="SOFT_MARGINS" value="120" />
</codeStyleSettings>
<codeStyleSettings language="JSON">
<indentOptions>
<option name="INDENT_SIZE" value="4" />
</indentOptions>
</codeStyleSettings>
</code_scheme>
</component>

5
.idea/codeStyles/codeStyleConfig.xml generated Normal file
View File

@@ -0,0 +1,5 @@
<component name="ProjectCodeStyleConfiguration">
<state>
<option name="USE_PER_PROJECT_SETTINGS" value="true" />
</state>
</component>

4
.idea/misc.xml generated Normal file
View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" languageLevel="JDK_11" default="true" project-jdk-name="temurin-11" project-jdk-type="JavaSDK" />
</project>

8
.idea/modules.xml generated Normal file
View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/ATContentStudio.iml" filepath="$PROJECT_DIR$/ATContentStudio.iml" />
</modules>
</component>
</project>

6
.idea/vcs.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>

117
ATContentStudio.iml Normal file
View File

@@ -0,0 +1,117 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="EclipseModuleManager">
<libelement value="jar://$MODULE_DIR$/lib/jide-oss.jar!/" />
<libelement value="jar://$MODULE_DIR$/lib/json_simple-1.1.jar!/" />
<libelement value="jar://$MODULE_DIR$/lib/junit-4.10.jar!/" />
<libelement value="jar://$MODULE_DIR$/lib/prefuse.jar!/" />
<libelement value="jar://$MODULE_DIR$/lib/rsyntaxtextarea.jar!/" />
<libelement value="jar://$MODULE_DIR$/lib/ui.jar!/" />
<libelement value="jar://$MODULE_DIR$/lib/bsh-2.0b4.jar!/" />
<libelement value="jar://$MODULE_DIR$/lib/jsoup-1.10.2.jar!/" />
<libelement value="jar://$MODULE_DIR$/lib/AndorsTrainer_v0.1.5.jar!/" />
<src_description expected_position="0">
<src_folder value="file://$MODULE_DIR$/src" expected_position="0" />
<src_folder value="file://$MODULE_DIR$/res" expected_position="1" />
<src_folder value="file://$MODULE_DIR$/hacked-libtiled" expected_position="2" />
<src_folder value="file://$MODULE_DIR$/siphash-zackehh/src/main/java" expected_position="3" />
<src_folder value="file://$MODULE_DIR$/minify" expected_position="4" />
</src_description>
</component>
<component name="NewModuleRootManager">
<output url="file://$MODULE_DIR$/bin" />
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/hacked-libtiled" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/minify" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/res" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/siphash-zackehh/src/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="inheritedJdk" />
<orderEntry type="module-library">
<library name="jide-oss.jar">
<CLASSES>
<root url="jar://$MODULE_DIR$/lib/jide-oss.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library name="json_simple-1.1.jar">
<CLASSES>
<root url="jar://$MODULE_DIR$/lib/json_simple-1.1.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library name="junit-4.10.jar">
<CLASSES>
<root url="jar://$MODULE_DIR$/lib/junit-4.10.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library name="prefuse.jar">
<CLASSES>
<root url="jar://$MODULE_DIR$/lib/prefuse.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library name="rsyntaxtextarea.jar">
<CLASSES>
<root url="jar://$MODULE_DIR$/lib/rsyntaxtextarea.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library name="ui.jar">
<CLASSES>
<root url="jar://$MODULE_DIR$/lib/ui.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library name="bsh-2.0b4.jar">
<CLASSES>
<root url="jar://$MODULE_DIR$/lib/bsh-2.0b4.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
<orderEntry type="module-library">
<library name="jsoup-1.10.2.jar">
<CLASSES>
<root url="jar://$MODULE_DIR$/lib/jsoup-1.10.2.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="jar://$MODULE_DIR$/lib/jsoup-1.10.2-sources.jar!/" />
</SOURCES>
</library>
</orderEntry>
<orderEntry type="module-library">
<library name="AndorsTrainer_v0.1.5.jar">
<CLASSES>
<root url="jar://$MODULE_DIR$/lib/AndorsTrainer_v0.1.5.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
</component>
</module>

View File

@@ -1,4 +0,0 @@
export MAIN_CLASS=com.gpl.rpg.atcontentstudio.ATContentStudio
export CP="lib/*:src:res:hacked-libtiled:siphash-zackehh/src/main/java/:."
javac -cp $CP ./src/com/gpl/rpg/atcontentstudio/ATContentStudio.java
java -cp $CP $MAIN_CLASS

129
createProject.bat Normal file
View File

@@ -0,0 +1,129 @@
@echo off
echo.
echo ***
echo *** createProject v1.0 (2024-08-24)
echo ***
echo *** This script will help to setup an ATCS project
echo *** and connect it to a repo on Github
echo ***
echo.
rem Save this script anywhere on your PC (e.g. C:\AT\createProject.bat)
rem Then open a command shell: CMD
rem and call the script in the shell.
if "%1"=="" goto :noParamError
echo You have entered:
echo.
echo ATCS-project: %1
echo in Directory: %2
echo Github user: %3
echo.
pause
if "%3"=="" goto :help
if not "%4"=="" goto :help
if not exist %2 md %2
rem --- Create ATCS project (if not already done)
:atcs
if not exist %2\%1\created\drawable\char_hero.png (
echo.
echo Do the following steps:
echo.
echo 1. Start ATCS
echo 2. Create your ATCS workspace in %2
echo 3. Add the new project %1
echo 4. Exit ATCS
echo.
pause
goto :atcs
) else (
echo ATCS Project exists
)
rem --- Create git repository
rem This is the really important part :)
rem -- go into project dir (even if we do not need to create the git repo)
echo cd %2\%1
cd %2\%1
if not exist %2\%1\readme.md (
echo creating readme
echo # %1 > readme.md
) else (
echo readme already exists
)
if not exist %2\%1\.gitignore (
echo creating gitignore
echo .workspace > .gitignore
echo .project >> .gitignore
echo .workspace.json >> .gitignore
echo .project.json >> .gitignore
echo altered/drawable >> .gitignore
echo altered/drawable/* >> .gitignore
echo created/drawable >> .gitignore
echo created/drawable/* >> .gitignore
echo tmp/res/values/loadresources.xml >> .gitignore
) else (
echo gitignore already existed
)
:git
if not exist %2\%1\.git (
echo Initializing git
git init -b main || (
echo "failed to init git. Please make sure it is installed"
pause
goto :git
)
:git_commit
git add readme.md
git add .gitignore
git commit -m "Init project" || (
echo "failed to create the initial commit."
pause
goto :git_commit
)
echo Done initializing git
) else (
echo git was already initialized
)
echo.
echo Now create your repo %1 on https://github.com/%3 (if not already done)
echo.
pause
echo pushing to git repo https://github.com/%3/%1.git
git remote add origin https://github.com/%3/%1.git
git push -u origin main
echo.
echo At last you have to find the repo in your git client:
echo - In Smartgit: Menu option: Repository / Search for repository
echo.
goto :end
:noParamError
echo.
echo You have given no parameter.
echo Maybe you have just double clicked it? That won't work.
echo I have opened a CMD shell for you. Enter the command in that shell.
start cmd
echo Please switch to the CMD shell
:help
echo.
echo Enter the command with 3 parameters:
echo %0 project path git-user
echo.
echo Example: %0 feygard_1 c:\AT\ATCS NutAndor
echo.
:end
echo.
echo *** End ***
pause

View File

@@ -43,7 +43,7 @@ public class MapObject implements Cloneable
{ {
private Properties properties = new Properties(); private Properties properties = new Properties();
private ObjectGroup objectGroup; private ObjectGroup objectGroup;
private Rectangle bounds = new Rectangle(); private Rectangle bounds;
private String name = "Object"; private String name = "Object";
private String type = ""; private String type = "";
private String imageSource = ""; private String imageSource = "";

View File

@@ -57,7 +57,7 @@ public class Sprite
private String name = null; private String name = null;
private int id = -1; private int id = -1;
private int flags = KEY_LOOP; private int flags;
private float frameRate = 1.0f; //one fps private float frameRate = 1.0f; //one fps
private Tile[] frames; private Tile[] frames;

View File

@@ -98,7 +98,11 @@ public class TileSet implements Iterable<Tile>
File f = new File(imgFilename); File f = new File(imgFilename);
BufferedImage image = ImageIO.read(f.getCanonicalFile()); BufferedImage image;
try {
image = ImageIO.read(f.getCanonicalFile());
} catch (IOException e) { throw new IOException("Failed to load " + imgFilename);
}
if (image == null) { if (image == null) {
throw new IOException("Failed to load " + imgFilename); throw new IOException("Failed to load " + imgFilename);
} }

View File

@@ -588,7 +588,7 @@ public class TMXMapWriter
} }
// Iterate while parents are the same // Iterate while parents are the same
int shared = 0; int shared;
int maxShared = Math.min(fromParents.size(), toParents.size()); int maxShared = Math.min(fromParents.size(), toParents.size());
for (shared = 0; shared < maxShared; shared++) { for (shared = 0; shared < maxShared; shared++) {
String fromParent = fromParents.get(shared); String fromParent = fromParents.get(shared);

Binary file not shown.

View File

@@ -1 +0,0 @@
v0.6.19

View File

@@ -1,2 +0,0 @@
/ATCS_v*.zip
/ATCS_v*.zip.rename

View File

@@ -1,20 +0,0 @@
@echo off
set "ATCS_DIR=%~dp0"
set "MAX_MEM=512M"
set "CP=%ATCS_DIR%lib\*"
set "JAVA=javaw.exe"
set "JAVA_OPTS=-DFONT_SCALE=1.0 -Dswing.aatext=true"
set "ENV_FILE=%ATCS_DIR%ATCS.env.bat"
set "MAIN_CLASS=com.gpl.rpg.atcontentstudio.ATContentStudio"
if exist "%ENV_FILE%" (
call "%ENV_FILE%"
) else (
echo REM set "MAX_MEM=%MAX_MEM%">"%ENV_FILE%"
echo REM set "JAVA=%JAVA%">>"%ENV_FILE%"
echo REM set "JAVA_OPTS=%JAVA_OPTS%">>"%ENV_FILE%"
echo.>>"%ENV_FILE%"
)
start "" "%JAVA%" %JAVA_OPTS% -Xmx%MAX_MEM% -cp "%CP%" %MAIN_CLASS%

Binary file not shown.

Before

Width:  |  Height:  |  Size: 24 KiB

View File

@@ -1,22 +0,0 @@
#!/bin/bash
ATCS_DIR=$(dirname $(readlink -f "$0" || greadlink -f "$0" || stat -f "$0"))
MAX_MEM=512M
CP=$(find ${ATCS_DIR}/lib/ -name '*.jar' | paste -sd: -)
JAVA=java
JAVA_OPTS='-DFONT_SCALE=1.0 -Dswing.aatext=true'
ENV_FILE=${ATCS_DIR}/ATCS.env
MAIN_CLASS=com.gpl.rpg.atcontentstudio.ATContentStudio
if [ -f ${ENV_FILE} ]
then
source ${ENV_FILE}
else
echo "#MAX_MEM=${MAX_MEM}" > ${ENV_FILE}
echo "#JAVA=${JAVA}" >> ${ENV_FILE}
echo "#JAVA_OPTS=${JAVA_OPTS}" >> ${ENV_FILE}
echo "" >> ${ENV_FILE}
fi
export ENV_FILE
$JAVA ${JAVA_OPTS} -Xmx${MAX_MEM} -cp ${CP} ${MAIN_CLASS}

View File

@@ -1 +0,0 @@
/*.jar

View File

@@ -1,11 +1,12 @@
!include MUI2.nsh !include MUI2.nsh
!define VERSION "0.6.20" ; Version will be passed as /DVERSION=vx.x.x
!define TRAINER_VERSION "0.1.5" !define TRAINER_VERSION "0.1.5"
!define JAVA_BIN "java" !define JAVA_BIN "java"
!define ATCS_SOURCE_DIR "..\..\"
Name "Andor's Trail Content Studio v${VERSION}" Name "Andor's Trail Content Studio ${VERSION}"
OutFile "ATCS_v${VERSION}_Setup.exe" OutFile "..\ATCS_${VERSION}_Setup.exe"
InstallDir "$PROGRAMFILES\ATCS\" InstallDir "$PROGRAMFILES\ATCS\"
;SetCompressor /SOLID /FINAL lzma ;SetCompressor /SOLID /FINAL lzma
@@ -13,10 +14,10 @@ InstallDir "$PROGRAMFILES\ATCS\"
Var StartMenuFolder Var StartMenuFolder
!define MUI_WELCOMEPAGE_TITLE "Welcome to Andor's Trail Content Studio installer" !define MUI_WELCOMEPAGE_TITLE "Welcome to Andor's Trail Content Studio installer"
!define MUI_WELCOMEPAGE_TEXT "This will install Andor's Trail Content Studio v${VERSION} installer" !define MUI_WELCOMEPAGE_TEXT "This will install Andor's Trail Content Studio ${VERSION}"
!define MUI_FINISHPAGE_TEXT "Andor's Trail Content Studio v${VERSION} install completed !" !define MUI_FINISHPAGE_TEXT "Andor's Trail Content Studio ${VERSION} - Install completed !"
!define MUI_STARTMENUPAGE_DEFAULTFOLDER "Andor's Trail Content Studio" !define MUI_STARTMENUPAGE_DEFAULTFOLDER "Andor's Trail Content Studio"
!define MUI_PAGE_HEADER_TEXT "Installing Andor's Trail Content Studio v${VERSION}" !define MUI_PAGE_HEADER_TEXT "Installing Andor's Trail Content Studio ${VERSION}"
;Start Menu Folder Page Configuration ;Start Menu Folder Page Configuration
@@ -46,24 +47,26 @@ Var StartMenuFolder
!insertmacro MUI_UNPAGE_CONFIRM !insertmacro MUI_UNPAGE_CONFIRM
!insertmacro MUI_UNPAGE_INSTFILES !insertmacro MUI_UNPAGE_INSTFILES
!insertmacro MUI_LANGUAGE "English" !insertmacro MUI_LANGUAGE "English"
;------------------------------------------------------------------------------------
Section install Section install
;--- Create in ...\packaging\common\ ATCS.cmd ATCT.ico ATCS.jar
SetOutPath $INSTDIR SetOutPath $INSTDIR
file "ATCS.ico" file "ATCS.ico"
file "${ATCS_SOURCE_DIR}\packaging\common\ATCS.jar"
Delete "$INSTDIR\lib\*"
Call GetJRE Call GetJRE
Pop $R0 Pop $R0
; file "${ATCS_SOURCE_DIR}\packaging\common\ATCS.cmd"
; !insertmacro _ReplaceInFile "ATCS.cmd" "java.exe" "$R0" (It was too much work this way)
FileOpen $9 "ATCS.cmd" w FileOpen $9 "ATCS.cmd" w
FileWrite $9 '@echo off$\r$\n' FileWrite $9 '@echo off$\r$\n'
FileWrite $9 '$\r$\n' FileWrite $9 '$\r$\n'
FileWrite $9 'set "ATCS_DIR=%~dp0"$\r$\n' FileWrite $9 'set "ATCS_DIR=%~dp0"$\r$\n'
FileWrite $9 'set "MAX_MEM=512M"$\r$\n' FileWrite $9 'set "MAX_MEM=1024M"$\r$\n'
FileWrite $9 'set "CP=%ATCS_DIR%lib\*"$\r$\n' FileWrite $9 'set "CP=%ATCS_DIR%lib\*"$\r$\n'
FileWrite $9 'set "JAVA=$R0"$\r$\n' FileWrite $9 'set "JAVA=$R0"$\r$\n'
FileWrite $9 'set "JAVA_OPTS="$\r$\n' FileWrite $9 'set "JAVA_OPTS="$\r$\n'
@@ -79,29 +82,15 @@ Section install
FileWrite $9 ' echo.>>"%ENV_FILE%"$\r$\n' FileWrite $9 ' echo.>>"%ENV_FILE%"$\r$\n'
FileWrite $9 ')$\r$\n' FileWrite $9 ')$\r$\n'
FileWrite $9 '$\r$\n' FileWrite $9 '$\r$\n'
FileWrite $9 'start "" "%JAVA%" %JAVA_OPTS% -Xmx%MAX_MEM% -cp "%CP%" %MAIN_CLASS%$\r$\n' FileWrite $9 'start "" "%JAVA%" %JAVA_OPTS% -Xmx%MAX_MEM% -jar ATCS.jar$\r$\n'
FileClose $9 FileClose $9
SetOutPath "$INSTDIR\lib\"
file "C:\AT\ATCS_source\lib\jide-oss.jar"
file "C:\AT\ATCS_source\lib\ui.jar"
file "C:\AT\ATCS_source\lib\AndorsTrainer_v${TRAINER_VERSION}.jar"
file "C:\AT\ATCS_source\lib\junit-4.10.jar"
file "C:\AT\ATCS_source\lib\json_simple-1.1.jar"
file "C:\AT\temp\ATCS_v0.6.20\ATCS_v${VERSION}.jar"
file "C:\AT\ATCS_source\lib\rsyntaxtextarea.jar"
file "C:\AT\ATCS_source\lib\prefuse.jar"
file "C:\AT\ATCS_source\lib\bsh-2.0b4.jar"
file "C:\AT\ATCS_source\lib\jsoup-1.10.2.jar"
SetOutPath $INSTDIR
WriteUninstaller "$INSTDIR\Uninstall.exe" WriteUninstaller "$INSTDIR\Uninstall.exe"
!insertmacro MUI_STARTMENU_WRITE_BEGIN "ATCS" !insertmacro MUI_STARTMENU_WRITE_BEGIN "ATCS"
;Create shortcuts ;--- Create shortcuts
CreateDirectory "$SMPROGRAMS\$StartMenuFolder" CreateDirectory "$SMPROGRAMS\$StartMenuFolder"
CreateShortcut "$SMPROGRAMS\$StartMenuFolder\Andor's Trail Content Studio.lnk" "$INSTDIR\ATCS.cmd" "" "$INSTDIR\ATCS.ico" CreateShortcut "$SMPROGRAMS\$StartMenuFolder\Andor's Trail Content Studio.lnk" "$INSTDIR\ATCS.cmd" "" "$INSTDIR\ATCS.ico"
CreateShortcut "$SMPROGRAMS\$StartMenuFolder\Uninstall.lnk" "$INSTDIR\Uninstall.exe" CreateShortcut "$SMPROGRAMS\$StartMenuFolder\Uninstall.lnk" "$INSTDIR\Uninstall.exe"
@@ -110,6 +99,8 @@ Section install
SectionEnd SectionEnd
;------------------------------------------------------------------------------------
Section uninstall Section uninstall
Delete "$INSTDIR\lib\jide-oss.jar" Delete "$INSTDIR\lib\jide-oss.jar"
@@ -117,18 +108,17 @@ Section uninstall
Delete "$INSTDIR\lib\junit-4.10.jar" Delete "$INSTDIR\lib\junit-4.10.jar"
Delete "$INSTDIR\lib\json_simple-1.1.jar" Delete "$INSTDIR\lib\json_simple-1.1.jar"
Delete "$INSTDIR\lib\AndorsTrainer_v${TRAINER_VERSION}.jar" Delete "$INSTDIR\lib\AndorsTrainer_v${TRAINER_VERSION}.jar"
Delete "$INSTDIR\lib\ATCS_v${VERSION}.jar"
Delete "$INSTDIR\lib\rsyntaxtextarea.jar" Delete "$INSTDIR\lib\rsyntaxtextarea.jar"
Delete "$INSTDIR\lib\prefuse.jar" Delete "$INSTDIR\lib\prefuse.jar"
Delete "$INSTDIR\lib\bsh-2.0b4.jar" Delete "$INSTDIR\lib\bsh-2.0b4.jar"
Delete "$INSTDIR\lib\jsoup-1.10.2.jar" Delete "$INSTDIR\lib\jsoup-1.10.2.jar"
RMDir "$INSTDIR\lib\" RMDir "$INSTDIR\lib\"
Delete "$INSTDIR\ATCS.ico" Delete "$INSTDIR\ATCS.ico"
Delete "$INSTDIR\ATCS.cmd" Delete "$INSTDIR\ATCS.cmd"
Delete "$INSTDIR\ATCS.env.bat" Delete "$INSTDIR\ATCS.env.bat"
Delete "$INSTDIR\ATCS.jar"
Delete "$INSTDIR\Uninstall.exe" Delete "$INSTDIR\Uninstall.exe"
RMDir "$INSTDIR" RMDir "$INSTDIR"
!insertmacro MUI_STARTMENU_GETFOLDER "ATCS" $StartMenuFolder !insertmacro MUI_STARTMENU_GETFOLDER "ATCS" $StartMenuFolder
@@ -140,19 +130,20 @@ Section uninstall
SectionEnd SectionEnd
;------------------------------------------------------------------------------------
Function GetJRE Function GetJRE
; ;
; Find JRE (javaw.exe) ; Find JRE (java.exe)
; DISABLED 1 - in .\jre directory (JRE Installed with application) ; DISABLED 1 - in .\jre directory (JRE Installed with application)
; 2 - in JAVA_HOME environment variable ; 2 - in JAVA_HOME environment variable
; 3 - in the registry ; 3 - in the registry
; 4 - assume javaw.exe in current dir or PATH ; 4 - assume java.exe in current dir or PATH
Push $R0 Push $R0
Push $R1 Push $R1
;ClearErrors ;ClearErrors
;StrCpy $R0 "$EXEDIR\jre\bin\javaw.exe" ;StrCpy $R0 "$EXEDIR\jre\bin\java.exe"
;IfFileExists $R0 JreFound ;IfFileExists $R0 JreFound
;StrCpy $R0 "" ;StrCpy $R0 ""

View File

@@ -1,8 +1,8 @@
@echo off @echo off
set "ATCS_DIR=%~dp0" set "ATCS_DIR=%~dp0"
set "MAX_MEM=512M" set "MAX_MEM=1024M"
set "JAVA=javaw.exe" set "JAVA=java.exe"
set "JAVA_OPTS=-DFONT_SCALE=1.0 -Dswing.aatext=true" set "JAVA_OPTS=-DFONT_SCALE=1.0 -Dswing.aatext=true"
set "ENV_FILE=%ATCS_DIR%ATCS.env.bat" set "ENV_FILE=%ATCS_DIR%ATCS.env.bat"

View File

@@ -1,4 +0,0 @@
#MAX_MEM=512M
#JAVA=java
#JAVA_OPTS=-DFONT_SCALE=1.0 -Dswing.aatext=true

View File

@@ -1,21 +1,26 @@
#!/bin/bash #!/bin/bash
ATCS_DIR=$(dirname $(readlink -f "$0" || greadlink -f "$0" || stat -f "$0")) ATCS_DIR="$(dirname "$(readlink -f "$0" || greadlink -f "$0" || stat -f "$0")")"
echo "ATCS_DIR: '${ATCS_DIR}'"
MAX_MEM=512M MAX_MEM="512M"
JAVA="java"
JAVA=java
JAVA_OPTS='-DFONT_SCALE=1.0 -Dswing.aatext=true' JAVA_OPTS='-DFONT_SCALE=1.0 -Dswing.aatext=true'
ENV_FILE=${ATCS_DIR}/ATCS.env
if [ -f ${ENV_FILE} ]; then ENV_FILE="${ATCS_DIR}/ATCS.env"
source ${ENV_FILE}
if [ -f "${ENV_FILE}" ]; then
source "${ENV_FILE}"
else else
echo "#MAX_MEM=${MAX_MEM}" >${ENV_FILE} {
echo "#JAVA=${JAVA}" >>${ENV_FILE} echo "#MAX_MEM=\"${MAX_MEM}\""
echo "#JAVA_OPTS=${JAVA_OPTS}" >>${ENV_FILE} echo "#JAVA=\"${JAVA}\""
echo "" >>${ENV_FILE} echo "#JAVA_OPTS=\"${JAVA_OPTS}\""
echo ""
}>"${ENV_FILE}"
fi fi
export ENV_FILE export ENV_FILE
$JAVA ${JAVA_OPTS} -Xmx${MAX_MEM} -jar ${ATCS_DIR}/ATCS.jar # shellcheck disable=SC2086
# (spellchecker is disabled for this line, because we want it to be split into multiple arguments)
$JAVA ${JAVA_OPTS} -Xmx${MAX_MEM} -jar "${ATCS_DIR}/ATCS.jar"

View File

@@ -1,84 +1,125 @@
#windows or linux #!/bin/bash
if [ "$1" = "-windows" ] ; then
# Script to build ATCS.jar, replicating IntelliJ artifact definition
# Linux and Windows compatible
# --- Platform Detection ---
if [ "$1" = "-windows" ]; then
echo "Got '-windows' flag. Running Windows version" echo "Got '-windows' flag. Running Windows version"
LINUX=false PLATFORM="WINDOWS"
else else
echo "No '-windows' flag. Running linux version" echo "No '-windows' flag. Running Linux version"
LINUX=true PLATFORM="LINUX"
fi fi
#read the folder this script should be in (should be the packaging folder inside the ATCS source) # --- Configuration ---
PACKAGING_DIR=$(dirname $(readlink -f "$0" || greadlink -f "$0" || stat -f "$0")) PACKAGING_DIR=$(dirname "$(readlink -f "$0" || greadlink -f "$0" || stat -f "$0")")
ATCS_SOURCE_DIR=$(dirname "${PACKAGING_DIR}") ATCS_SOURCE_DIR=$(dirname "${PACKAGING_DIR}")
TEMP_DIR=${PACKAGING_DIR}/tmp TEMP_DIR="${PACKAGING_DIR}/tmp"
echo "Packaging dir: ${PACKAGING_DIR}" JAR_LOCATION="${PACKAGING_DIR}/ATCS.jar" # Output JAR location as per script
echo "ATCS_SOURCE_DIR: ${ATCS_SOURCE_DIR}" MANIFEST_LOCATION="${PACKAGING_DIR}/Manifest.txt"
#ATContentStudio VERSION_FILE="${ATCS_SOURCE_DIR}/res/ATCS_latest"
JAR_LOCATION="${PACKAGING_DIR}/common/ATCS.jar" SOURCE_BASE_DIR="${ATCS_SOURCE_DIR}/src" # Base directory for standard source code
MANIFEST_LOCATION=${PACKAGING_DIR}/Manifest.txt LIB_BASE_DIR="${ATCS_SOURCE_DIR}/lib" # Base directory for libraries
echo ""
# --- **ADDITIONAL SOURCE CODE FOLDERS** ---
EXTRA_SOURCE_DIRS=(
"hacked-libtiled"
"minify"
"siphash-zackehh/src/main/java"
)
# --- Libraries to include ---
LIBRARIES=(
"bsh-2.0b4.jar"
"jide-oss.jar"
"json_simple-1.1.jar"
"jsoup-1.10.2.jar"
"junit-4.10.jar"
"prefuse.jar"
"rsyntaxtextarea.jar"
"ui.jar"
)
# --- Get version ---
echo "Getting version" echo "Getting version"
VERSION=$(cat ${PACKAGING_DIR}/ATCS_latest) VERSION=$(tr -d '[:space:]' < "${VERSION_FILE}")
echo "Got version ${VERSION}" echo "Got version ${VERSION}"
# --- Prepare temporary directory ---
echo "Removing tmp folder" echo "Removing tmp folder"
rm -rf ${PACKAGING_DIR}/tmp/ rm -rf "${TEMP_DIR}"
echo "recreating tmp folder" echo "Recreating tmp folder"
mkdir ${PACKAGING_DIR}/tmp/ mkdir -p "${TEMP_DIR}"
#ATCS_SOURCE_DIR="${PACKAGING_DIR}/.."
# --- **EXTRACT lib files directly to TEMP_DIR** ---
echo 'Extracting lib files to TEMP_DIR'
for LIB in "${LIBRARIES[@]}"; do
echo "Extracting library: ${LIB}"
unzip -qo "${LIB_BASE_DIR}/${LIB}" -d "${TEMP_DIR}" # Extract JAR contents to TEMP_DIR root
done
# --- Set ClassPath ---
echo "Getting source files"
# Find all java files in source directories
SOURCE_FILES=$(find "${SOURCE_BASE_DIR}" "${EXTRA_SOURCE_DIRS[@]/#/${ATCS_SOURCE_DIR}/}" -name "*.java" -print)
#echo "SourceFiles: ${SOURCE_FILES}"
echo "" echo ""
#copy manifest to temp folder for editing
cp ${MANIFEST_LOCATION} ${TEMP_DIR}
MANIFEST_LOCATION=${TEMP_DIR}/Manifest.txt
#copy lib files to packaged folder? # --- Build Java classes ---
echo 'copying lib files' echo 'Building java classes'
mkdir -p ${PACKAGING_DIR}/common/lib/
cp ${ATCS_SOURCE_DIR}/lib/* ${PACKAGING_DIR}/common/lib/
cd $ATCS_SOURCE_DIR # shellcheck disable=SC2086
#set ClassPath variable to use in the building etc. # (we need word splitting here to pass multiple files)
echo 'setting class path' javac -cp "${TEMP_DIR}" -d "${TEMP_DIR}" ${SOURCE_FILES}
#linux needs a : as seperator while windows needs ; if [ $? -ne 0 ]; then
if [ "$LINUX" = true ] ; then echo "Compilation failed. Please check errors above."
CP="lib/*:src:hacked-libtiled:siphash-zackehh/src/main/java" exit 1
else
CP="lib/*;src;hacked-libtiled;siphash-zackehh/src/main/java"
fi fi
echo "ClassPath: " echo "Compilation successful"
echo ${CP}
echo ""
#set build the classes # --- Copy res stuff to temp folder ---
echo 'building java classes' echo "Copying some stuff to temp folder"
#javac -cp $CP *.java cp -r "${ATCS_SOURCE_DIR}"/res/* "${TEMP_DIR}/"
javac -cp $CP ${ATCS_SOURCE_DIR}/src/com/gpl/rpg/atcontentstudio/*.java -d ${TEMP_DIR} mkdir -p "${TEMP_DIR}/com/gpl/rpg/atcontentstudio/img"
echo javac -cp $CP ${ATCS_SOURCE_DIR}/src/com/gpl/rpg/atcontentstudio/*.java -d ${TEMP_DIR} mkdir -p "${TEMP_DIR}/tiled/io/resources/"
echo "" cp -r "${ATCS_SOURCE_DIR}"/src/com/gpl/rpg/atcontentstudio/img/* "${TEMP_DIR}/com/gpl/rpg/atcontentstudio/img/" # some icons
LIB_PATHS=$(find lib -name '*.jar' | paste -sd' ') cp -r "${ATCS_SOURCE_DIR}"/hacked-libtiled/tiled/io/resources/* "${TEMP_DIR}/tiled/io/resources/" # dtd file for tmx maps
echo "LIB_PATHS: ${LIB_PATHS}" cp "${VERSION_FILE}" "${TEMP_DIR}/" # Copy version file
# add all lib files to the class path in the temp Manifest
echo "Class-Path: . lib/* ${LIB_PATHS}" >>${MANIFEST_LOCATION}
# --- Create JAR file ---
echo "" echo ""
echo "creating jar at location: ${JAR_LOCATION}" echo "Creating jar at location: ${JAR_LOCATION}"
# create the jar file cd "${TEMP_DIR}" || exit # Change to temp dir for JAR command
# the command with those parameters requires this format:
# jar vmfc <Manifest file> <Jar file (target location)> <all things to add to the jar file> # JAR command WITHOUT lib directory
# the things to add always use the whole relative path from the current dir, jar cfm "${JAR_LOCATION}" "${MANIFEST_LOCATION}" -C . .
# so when that is not wanted, the -C <location> thing will change to that dir if [ $? -ne 0 ]; then
jar mfc ${MANIFEST_LOCATION} ${JAR_LOCATION} -C ${PACKAGING_DIR}/tmp/ com/gpl/rpg/atcontentstudio/ -C res . -C ${ATCS_SOURCE_DIR}/src . echo "JAR creation failed."
exit 1
fi
cd "${PACKAGING_DIR}" || exit # Go back to packaging dir
echo '' echo ''
echo "Done creating jar" echo "Done creating jar at ${JAR_LOCATION}"
cp -f "${JAR_LOCATION}" "${PACKAGING_DIR}/common/ATCS.jar" # Copy JAR to versioned name
if [ "$LINUX" = true ] ; then # --- Create archive ---
cd ${PACKAGING_DIR} cd "${PACKAGING_DIR}" || exit
echo "Creating archive" echo "Creating archive"
tar caf "ATCS_${VERSION}.tar.gz" "common" if [ "$PLATFORM" = "WINDOWS" ]; then
echo "Created archive at ${PACKAGING_DIR}/ATCS_${VERSION}.tar.gz" # Use PowerShell's Compress-Archive which is available by default on Windows
powershell.exe -Command "Compress-Archive -Path './common/*' -DestinationPath './ATCS_${VERSION}.zip' -Force"
else else
echo "Can't create zip files on windows yet. Please pack the content of the '${PACKAGING_DIR}/common/' folder yourself" # Use zip command on Linux
zip -r "ATCS_${VERSION}.zip" common/* # archive the 'common' folder which now contains the JAR and libs
fi fi
if [ $? -ne 0 ]; then
echo "Archive creation failed."
exit 1
fi
echo "Created archive at ${PACKAGING_DIR}/ATCS_${VERSION}.zip"
echo "Script finished."

1
res/ATCS_latest Normal file
View File

@@ -0,0 +1 @@
v0.6.21

View File

@@ -1,6 +1,7 @@
atcs.spritesheet.actorconditions_1.category=actorcondition atcs.spritesheet.actorconditions_1.category=actorcondition
atcs.spritesheet.actorconditions_2.category=actorcondition atcs.spritesheet.actorconditions_2.category=actorcondition
atcs.spritesheet.actorconditions_japozero.category=actorcondition atcs.spritesheet.actorconditions_japozero.category=actorcondition
atcs.spritesheet.actorconditions_newb.category=actorcondition
atcs.spritesheet.actorconditions_omi1.category=actorcondition atcs.spritesheet.actorconditions_omi1.category=actorcondition
atcs.spritesheet.actorconditions_omi2.category=actorcondition atcs.spritesheet.actorconditions_omi2.category=actorcondition
@@ -60,6 +61,7 @@ atcs.spritesheet.monsters_gisons.category=monster
atcs.spritesheet.monsters_guynmart.category=monster atcs.spritesheet.monsters_guynmart.category=monster
atcs.spritesheet.monsters_insects.category=monster atcs.spritesheet.monsters_insects.category=monster
atcs.spritesheet.monsters_johny.category=monster
atcs.spritesheet.monsters_karvis1.category=monster atcs.spritesheet.monsters_karvis1.category=monster
atcs.spritesheet.monsters_karvis2.category=monster atcs.spritesheet.monsters_karvis2.category=monster
atcs.spritesheet.monsters_ld1.category=monster atcs.spritesheet.monsters_ld1.category=monster

6
src/META-INF/MANIFEST.MF Normal file
View File

@@ -0,0 +1,6 @@
Manifest-Version: 1.0
Main-Class: com.gpl.rpg.atcontentstudio.ATContentStudio
Class-Path: jide-oss.jar jsoup-1.10.2.jar ui.jar junit-4.10.jar AndorsTr
ainer_v0.1.5.jar prefuse.jar rsyntaxtextarea.jar bsh-2.0b4.jar json_sim
ple-1.1.jar

View File

@@ -1,10 +1,16 @@
package com.gpl.rpg.atcontentstudio; package com.gpl.rpg.atcontentstudio;
import java.awt.Color; import com.gpl.rpg.atcontentstudio.model.Workspace;
import java.awt.Desktop; import com.gpl.rpg.atcontentstudio.ui.StudioFrame;
import java.awt.Dimension; import com.gpl.rpg.atcontentstudio.ui.WorkerDialog;
import java.awt.Font; import com.gpl.rpg.atcontentstudio.ui.WorkspaceSelector;
import java.awt.Toolkit; import prefuse.data.expression.parser.ExpressionParser;
import javax.swing.*;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import javax.swing.plaf.FontUIResource;
import java.awt.*;
import java.awt.event.WindowAdapter; import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent; import java.awt.event.WindowEvent;
import java.io.BufferedReader; import java.io.BufferedReader;
@@ -14,35 +20,19 @@ import java.io.InputStreamReader;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.net.URL; import java.net.URL;
import java.net.http.HttpTimeoutException;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.HashMap; import java.util.HashMap;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.*;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import javax.swing.JEditorPane;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.UIDefaults;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import javax.swing.plaf.FontUIResource;
import prefuse.data.expression.parser.ExpressionParser;
import com.gpl.rpg.atcontentstudio.model.Workspace;
import com.gpl.rpg.atcontentstudio.ui.StudioFrame;
import com.gpl.rpg.atcontentstudio.ui.WorkerDialog;
import com.gpl.rpg.atcontentstudio.ui.WorkspaceSelector;
public class ATContentStudio { public class ATContentStudio {
public static final String APP_NAME = "Andor's Trail Content Studio"; public static final String APP_NAME = "Andor's Trail Content Studio";
public static final String APP_VERSION = "v0.6.20"; public static final String APP_VERSION = readVersionFromFile();
public static final String CHECK_UPDATE_URL = "https://andorstrail.com/static/ATCS_latest"; public static final String CHECK_UPDATE_URL = "https://andorstrail.com/static/ATCS_latest";
public static final String DOWNLOAD_URL = "https://andorstrail.com/viewtopic.php?f=6&t=4806"; public static final String DOWNLOAD_URL = "https://andorstrail.com/viewtopic.php?f=6&t=4806";
@@ -62,7 +52,7 @@ public class ATContentStudio {
*/ */
public static void main(String[] args) { public static void main(String[] args) {
String fontScaling = System.getProperty(FONT_SCALE_ENV_VAR_NAME); String fontScaling = System.getProperty(FONT_SCALE_ENV_VAR_NAME);
Float fontScale = null; Float fontScale;
if (fontScaling != null) { if (fontScaling != null) {
try { try {
fontScale = Float.parseFloat(fontScaling); fontScale = Float.parseFloat(fontScaling);
@@ -125,7 +115,8 @@ public class ATContentStudio {
frame = new StudioFrame(APP_NAME + " " + APP_VERSION); frame = new StudioFrame(APP_NAME + " " + APP_VERSION);
frame.setVisible(true); frame.setVisible(true);
frame.setDefaultCloseOperation(StudioFrame.DO_NOTHING_ON_CLOSE); frame.setDefaultCloseOperation(StudioFrame.DO_NOTHING_ON_CLOSE);
}; }
}); });
for (File f : ConfigCache.getKnownWorkspaces()) { for (File f : ConfigCache.getKnownWorkspaces()) {
if (workspaceRoot.equals(f)) { if (workspaceRoot.equals(f)) {
@@ -196,8 +187,14 @@ public class ATContentStudio {
} }
} catch (MalformedURLException e) { } catch (MalformedURLException e) {
e.printStackTrace(); e.printStackTrace();
} catch (HttpTimeoutException e) {
System.out.println("Could not connect to url to check for updates (timeout): " + CHECK_UPDATE_URL);
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); if (e.getMessage() != null && e.getMessage().startsWith("Server returned HTTP response code:")) {
System.out.println("Could not fetch current version from server to check for updates (non-success-status): " + e.getMessage());
} else {
System.out.println("Could not check for updates: '" + CHECK_UPDATE_URL + "' - " + e.getMessage());
}
} finally { } finally {
try { try {
if (in != null) if (in != null)
@@ -213,7 +210,7 @@ public class ATContentStudio {
System.out.println("Scaling fonts to " + SCALING); System.out.println("Scaling fonts to " + SCALING);
UIDefaults defaults = UIManager.getLookAndFeelDefaults(); UIDefaults defaults = UIManager.getLookAndFeelDefaults();
Map<Object, Object> newDefaults = new HashMap<Object, Object>(); Map<Object, Object> newDefaults = new HashMap<Object, Object>();
for (Enumeration<Object> e = defaults.keys(); e.hasMoreElements();) { for (Enumeration<Object> e = defaults.keys(); e.hasMoreElements(); ) {
Object key = e.nextElement(); Object key = e.nextElement();
Object value = defaults.get(key); Object value = defaults.get(key);
if (value instanceof Font) { if (value instanceof Font) {
@@ -231,4 +228,14 @@ public class ATContentStudio {
} }
} }
} }
private static String readVersionFromFile() {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(
Objects.requireNonNull(ATContentStudio.class.getResourceAsStream("/ATCS_latest"))))) {
return reader.readLine();
} catch (IOException e) {
e.printStackTrace();
return "unknown";
}
}
} }

View File

@@ -1,12 +1,12 @@
package com.gpl.rpg.atcontentstudio; package com.gpl.rpg.atcontentstudio;
import com.gpl.rpg.atcontentstudio.io.SettingsSave;
import java.io.File; import java.io.File;
import java.io.Serializable; import java.io.Serializable;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import com.gpl.rpg.atcontentstudio.io.SettingsSave;
public class ConfigCache implements Serializable { public class ConfigCache implements Serializable {
private static final long serialVersionUID = 4584324644282843961L; private static final long serialVersionUID = 4584324644282843961L;
@@ -18,9 +18,9 @@ public class ConfigCache implements Serializable {
static { static {
if (System.getenv("APPDATA") != null) { if (System.getenv("APPDATA") != null) {
CONFIG_CACHE_STORAGE = new File(System.getenv("APPDATA")+File.separator+ATContentStudio.APP_NAME+File.separator+"configCache" ); CONFIG_CACHE_STORAGE = new File(System.getenv("APPDATA") + File.separator + ATContentStudio.APP_NAME + File.separator + "configCache");
} else { } else {
CONFIG_CACHE_STORAGE = new File(System.getenv("HOME")+File.separator+"."+ATContentStudio.APP_NAME+File.separator+"configCache" ); CONFIG_CACHE_STORAGE = new File(System.getenv("HOME") + File.separator + "." + ATContentStudio.APP_NAME + File.separator + "configCache");
} }
CONFIG_CACHE_STORAGE.getParentFile().mkdirs(); CONFIG_CACHE_STORAGE.getParentFile().mkdirs();
if (CONFIG_CACHE_STORAGE.exists()) { if (CONFIG_CACHE_STORAGE.exists()) {
@@ -77,7 +77,7 @@ public class ConfigCache implements Serializable {
} }
public static void putNotifViewConfig(boolean[] view) { public static void putNotifViewConfig(boolean[] view) {
for (int i=instance.notifConfig.length; i<0; --i) { for (int i = instance.notifConfig.length; i < 0; --i) {
instance.notifConfig[i] = view[i]; instance.notifConfig[i] = view[i];
} }
instance.save(); instance.save();
@@ -91,7 +91,8 @@ public class ConfigCache implements Serializable {
return instance.notifConfig; return instance.notifConfig;
} }
public static void init() {} public static void init() {
}
public static void clear() { public static void clear() {
instance.knownWorkspaces.clear(); instance.knownWorkspaces.clear();

View File

@@ -8,7 +8,7 @@ public class Notification {
public static List<Notification> notifs = new ArrayList<Notification>(); public static List<Notification> notifs = new ArrayList<Notification>();
private static List<NotificationListener> listeners = new CopyOnWriteArrayList<NotificationListener>(); private static List<NotificationListener> listeners = new CopyOnWriteArrayList<NotificationListener>();
public static boolean showS = true, showI = true, showW = true, showE = true; public static boolean showS, showI, showW, showE;
static { static {
boolean[] config = ConfigCache.getNotifViewConfig(); boolean[] config = ConfigCache.getNotifViewConfig();
@@ -34,7 +34,7 @@ public class Notification {
} }
public String toString() { public String toString() {
return "["+type.toString()+"] "+text; return "[" + type.toString() + "] " + text;
} }
public static void clear() { public static void clear() {

View File

@@ -3,6 +3,7 @@ package com.gpl.rpg.atcontentstudio;
public interface NotificationListener { public interface NotificationListener {
public void onNewNotification(Notification n); public void onNewNotification(Notification n);
public void onListCleared(int i); public void onListCleared(int i);
} }

View File

@@ -0,0 +1,8 @@
package com.gpl.rpg.atcontentstudio.io;
import java.util.Map;
public interface JsonSerializable {
Map toMap();
void fromMap(Map map);
}

View File

@@ -1,15 +1,9 @@
package com.gpl.rpg.atcontentstudio.io; package com.gpl.rpg.atcontentstudio.io;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import com.gpl.rpg.atcontentstudio.Notification; import com.gpl.rpg.atcontentstudio.Notification;
import java.io.*;
public class SettingsSave { public class SettingsSave {
public static void saveInstance(Object obj, File f, String type) { public static void saveInstance(Object obj, File f, String type) {
@@ -20,21 +14,21 @@ public class SettingsSave {
oos.writeObject(obj); oos.writeObject(obj);
oos.flush(); oos.flush();
oos.close(); oos.close();
Notification.addSuccess(type+" successfully saved."); Notification.addSuccess(type + " successfully saved.");
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
Notification.addError(type+" saving error: "+e.getMessage()); Notification.addError(type + " saving error: " + e.getMessage());
} finally { } finally {
try { try {
fos.close(); fos.close();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
Notification.addError(type+" saving error: "+e.getMessage()); Notification.addError(type + " saving error: " + e.getMessage());
} }
} }
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
e.printStackTrace(); e.printStackTrace();
Notification.addError(type+" saving error: "+e.getMessage()); Notification.addError(type + " saving error: " + e.getMessage());
} }
} }
@@ -48,27 +42,27 @@ public class SettingsSave {
ois = new ObjectInputStream(fis); ois = new ObjectInputStream(fis);
try { try {
result = ois.readObject(); result = ois.readObject();
Notification.addSuccess(type+" successfully loaded."); Notification.addSuccess(type + " successfully loaded.");
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
e.printStackTrace(); e.printStackTrace();
Notification.addError(type+" loading error: "+e.getMessage()); Notification.addError(type + " loading error: " + e.getMessage());
} finally { } finally {
ois.close(); ois.close();
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
Notification.addError(type+" loading error: "+e.getMessage()); Notification.addError(type + " loading error: " + e.getMessage());
} finally { } finally {
try { try {
fis.close(); fis.close();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
Notification.addError(type+" loading error: "+e.getMessage()); Notification.addError(type + " loading error: " + e.getMessage());
} }
} }
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
e.printStackTrace(); e.printStackTrace();
Notification.addError(type+" loading error: "+e.getMessage()); Notification.addError(type + " loading error: " + e.getMessage());
} }
return result; return result;
} }

View File

@@ -1,16 +1,15 @@
package com.gpl.rpg.atcontentstudio.model; package com.gpl.rpg.atcontentstudio.model;
import java.awt.Image;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import javax.swing.tree.TreeNode;
import com.gpl.rpg.atcontentstudio.model.GameSource.Type; import com.gpl.rpg.atcontentstudio.model.GameSource.Type;
import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet; import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet;
import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons;
import javax.swing.tree.TreeNode;
import java.awt.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
public class ClosedProject implements ProjectTreeNode { public class ClosedProject implements ProjectTreeNode {
String name; String name;
@@ -25,26 +24,32 @@ public class ClosedProject implements ProjectTreeNode {
public TreeNode getChildAt(int childIndex) { public TreeNode getChildAt(int childIndex) {
return null; return null;
} }
@Override @Override
public int getChildCount() { public int getChildCount() {
return 0; return 0;
} }
@Override @Override
public TreeNode getParent() { public TreeNode getParent() {
return parent; return parent;
} }
@Override @Override
public int getIndex(TreeNode node) { public int getIndex(TreeNode node) {
return 0; return 0;
} }
@Override @Override
public boolean getAllowsChildren() { public boolean getAllowsChildren() {
return false; return false;
} }
@Override @Override
public boolean isLeaf() { public boolean isLeaf() {
return true; return true;
} }
@Override @Override
public Enumeration<ProjectTreeNode> children() { public Enumeration<ProjectTreeNode> children() {
return null; return null;
@@ -52,19 +57,22 @@ public class ClosedProject implements ProjectTreeNode {
@Override @Override
public void childrenAdded(List<ProjectTreeNode> path) { public void childrenAdded(List<ProjectTreeNode> path) {
path.add(0,this); path.add(0, this);
parent.childrenAdded(path); parent.childrenAdded(path);
} }
@Override @Override
public void childrenChanged(List<ProjectTreeNode> path) { public void childrenChanged(List<ProjectTreeNode> path) {
path.add(0,this); path.add(0, this);
parent.childrenChanged(path); parent.childrenChanged(path);
} }
@Override @Override
public void childrenRemoved(List<ProjectTreeNode> path) { public void childrenRemoved(List<ProjectTreeNode> path) {
path.add(0,this); path.add(0, this);
parent.childrenRemoved(path); parent.childrenRemoved(path);
} }
@Override @Override
public void notifyCreated() { public void notifyCreated() {
childrenAdded(new ArrayList<ProjectTreeNode>()); childrenAdded(new ArrayList<ProjectTreeNode>());
@@ -72,7 +80,7 @@ public class ClosedProject implements ProjectTreeNode {
@Override @Override
public String getDesc() { public String getDesc() {
return name+" [closed]"; return name + " [closed]";
} }
@Override @Override
@@ -85,16 +93,19 @@ public class ClosedProject implements ProjectTreeNode {
public Image getIcon() { public Image getIcon() {
return getOpenIcon(); return getOpenIcon();
} }
@Override @Override
public Image getClosedIcon() { public Image getClosedIcon() {
//TODO Create a cool Project icon. //TODO Create a cool Project icon.
return DefaultIcons.getStdClosedIcon(); return DefaultIcons.getStdClosedIcon();
} }
@Override @Override
public Image getLeafIcon() { public Image getLeafIcon() {
//TODO Create a cool Project icon. //TODO Create a cool Project icon.
return DefaultIcons.getStdClosedIcon(); return DefaultIcons.getStdClosedIcon();
} }
@Override @Override
public Image getOpenIcon() { public Image getOpenIcon() {
//TODO Create a cool Project icon. //TODO Create a cool Project icon.

View File

@@ -1,17 +1,13 @@
package com.gpl.rpg.atcontentstudio.model; package com.gpl.rpg.atcontentstudio.model;
import java.awt.Image; import com.gpl.rpg.atcontentstudio.model.bookmarks.BookmarkEntry;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import javax.swing.tree.TreeNode; import javax.swing.tree.TreeNode;
import java.awt.*;
import com.gpl.rpg.atcontentstudio.model.bookmarks.BookmarkEntry; import java.io.Serializable;
import java.util.List;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
public abstract class GameDataElement implements ProjectTreeNode, Serializable { public abstract class GameDataElement implements ProjectTreeNode, Serializable {
@@ -44,51 +40,60 @@ public abstract class GameDataElement implements ProjectTreeNode, Serializable {
public Enumeration<ProjectTreeNode> children() { public Enumeration<ProjectTreeNode> children() {
return null; return null;
} }
@Override @Override
public boolean getAllowsChildren() { public boolean getAllowsChildren() {
return false; return false;
} }
@Override @Override
public TreeNode getChildAt(int arg0) { public TreeNode getChildAt(int arg0) {
return null; return null;
} }
@Override @Override
public int getChildCount() { public int getChildCount() {
return 0; return 0;
} }
@Override @Override
public int getIndex(TreeNode arg0) { public int getIndex(TreeNode arg0) {
return 0; return 0;
} }
@Override @Override
public TreeNode getParent() { public TreeNode getParent() {
return parent; return parent;
} }
@Override @Override
public boolean isLeaf() { public boolean isLeaf() {
return true; return true;
} }
@Override @Override
public void childrenAdded(List<ProjectTreeNode> path) { public void childrenAdded(List<ProjectTreeNode> path) {
path.add(0,this); path.add(0, this);
parent.childrenAdded(path); parent.childrenAdded(path);
} }
@Override @Override
public void childrenChanged(List<ProjectTreeNode> path) { public void childrenChanged(List<ProjectTreeNode> path) {
path.add(0,this); path.add(0, this);
parent.childrenChanged(path); parent.childrenChanged(path);
} }
@Override @Override
public void childrenRemoved(List<ProjectTreeNode> path) { public void childrenRemoved(List<ProjectTreeNode> path) {
path.add(0,this); path.add(0, this);
parent.childrenRemoved(path); parent.childrenRemoved(path);
} }
@Override @Override
public void notifyCreated() { public void notifyCreated() {
childrenAdded(new ArrayList<ProjectTreeNode>()); childrenAdded(new ArrayList<ProjectTreeNode>());
} }
@Override @Override
public abstract String getDesc(); public abstract String getDesc();
@@ -97,8 +102,8 @@ public abstract class GameDataElement implements ProjectTreeNode, Serializable {
} }
public abstract void parse(); public abstract void parse();
public abstract void link();
public abstract void link();
@Override @Override
@@ -110,10 +115,17 @@ public abstract class GameDataElement implements ProjectTreeNode, Serializable {
public Image getIcon() { public Image getIcon() {
return null; return null;
} }
@Override @Override
public Image getClosedIcon() {return null;} public Image getClosedIcon() {
return null;
}
@Override @Override
public Image getOpenIcon() {return null;} public Image getOpenIcon() {
return null;
}
@Override @Override
public Image getLeafIcon() { public Image getLeafIcon() {
return getIcon(); return getIcon();
@@ -172,6 +184,7 @@ public abstract class GameDataElement implements ProjectTreeNode, Serializable {
public static interface BacklinksListener { public static interface BacklinksListener {
public void backlinkAdded(GameDataElement gde); public void backlinkAdded(GameDataElement gde);
public void backlinkRemoved(GameDataElement gde); public void backlinkRemoved(GameDataElement gde);
} }
@@ -190,4 +203,35 @@ public abstract class GameDataElement implements ProjectTreeNode, Serializable {
public abstract List<SaveEvent> attemptSave(); public abstract List<SaveEvent> attemptSave();
/**
* Checks if the current state indicates that parsing/linking should be skipped.
*
* @return true if the operation should be skipped, false otherwise
*/
protected boolean shouldSkipParseOrLink() {
if (shouldSkipParse()) return true;
if (this.state == State.linked) {
//Already linked.
return true;
}
return false;
}
protected boolean shouldSkipParse() {
if (this.state == State.created || this.state == State.modified || this.state == State.saved) {
//This type of state is unrelated to parsing/linking.
return true;
}
return false;
}
/**
* Ensures the element is parsed if needed based on its current state.
*/
protected void ensureParseIfNeeded() {
if (this.state == State.init) {
//Not parsed yet.
this.parse();
}
}
} }

View File

@@ -1,28 +1,6 @@
package com.gpl.rpg.atcontentstudio.model; package com.gpl.rpg.atcontentstudio.model;
import java.awt.Image; import com.gpl.rpg.atcontentstudio.io.JsonSerializable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.swing.tree.TreeNode;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import com.gpl.rpg.atcontentstudio.model.Project.ResourceSet; import com.gpl.rpg.atcontentstudio.model.Project.ResourceSet;
import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet; import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet;
import com.gpl.rpg.atcontentstudio.model.maps.TMXMapSet; import com.gpl.rpg.atcontentstudio.model.maps.TMXMapSet;
@@ -32,13 +10,27 @@ import com.gpl.rpg.atcontentstudio.model.sprites.SpriteSheetSet;
import com.gpl.rpg.atcontentstudio.model.sprites.Spritesheet; import com.gpl.rpg.atcontentstudio.model.sprites.Spritesheet;
import com.gpl.rpg.atcontentstudio.model.tools.writermode.WriterModeDataSet; import com.gpl.rpg.atcontentstudio.model.tools.writermode.WriterModeDataSet;
import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class GameSource implements ProjectTreeNode, Serializable { import javax.swing.tree.TreeNode;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.awt.*;
import java.io.*;
import java.util.List;
import java.util.*;
public class GameSource implements ProjectTreeNode, Serializable, JsonSerializable {
private static final long serialVersionUID = -1512979360971918158L; private static final long serialVersionUID = -1512979360971918158L;
public static final String DEFAULT_REL_PATH_FOR_GAME_RESOURCE = "res"+File.separator+"values"+File.separator+"loadresources.xml"; public static final String DEFAULT_REL_PATH_FOR_GAME_RESOURCE = "res" + File.separator + "values" + File.separator + "loadresources.xml";
public static final String DEFAULT_REL_PATH_FOR_DEBUG_RESOURCE = "res"+File.separator+"values"+File.separator+"loadresources_debug.xml"; public static final String DEFAULT_REL_PATH_FOR_DEBUG_RESOURCE = "res" + File.separator + "values" + File.separator + "loadresources_debug.xml";
public transient GameDataSet gameData; public transient GameDataSet gameData;
public transient TMXMapSet gameMaps; public transient TMXMapSet gameMaps;
@@ -47,6 +39,22 @@ public class GameSource implements ProjectTreeNode, Serializable {
public transient WriterModeDataSet writerModeDataSet; public transient WriterModeDataSet writerModeDataSet;
private transient SavedSlotCollection v; private transient SavedSlotCollection v;
@Override
public Map toMap() {
Map map = new HashMap();
map.put("type", type.toString());
map.put("baseFolder", baseFolder.getPath());
return map;
}
@Override
public void fromMap(Map map) {
if(map==null)return;
type = Enum.valueOf(Type.class, (String)map.get("type"));
baseFolder = new File((String) map.get("baseFolder"));
}
public static enum Type { public static enum Type {
source, source,
referenced, referenced,
@@ -57,10 +65,14 @@ public class GameSource implements ProjectTreeNode, Serializable {
public File baseFolder; public File baseFolder;
public Type type; public Type type;
public transient Project parent = null; public transient Project parent;
public transient Map<String, List<String>> referencedSourceFiles = null; public transient Map<String, List<String>> referencedSourceFiles = null;
public GameSource(Map json, Project parent) {
fromMap(json);
refreshTransients(parent);
}
public GameSource(File folder, Project parent) { public GameSource(File folder, Project parent) {
this.parent = parent; this.parent = parent;
this.baseFolder = folder; this.baseFolder = folder;
@@ -105,7 +117,7 @@ public class GameSource implements ProjectTreeNode, Serializable {
} }
public void readResourceList() { public void readResourceList() {
File xmlFile = null; File xmlFile;
if (parent.sourceSetToUse == ResourceSet.gameData) { if (parent.sourceSetToUse == ResourceSet.gameData) {
xmlFile = new File(baseFolder, DEFAULT_REL_PATH_FOR_GAME_RESOURCE); xmlFile = new File(baseFolder, DEFAULT_REL_PATH_FOR_GAME_RESOURCE);
} else if (parent.sourceSetToUse == ResourceSet.debugData) { } else if (parent.sourceSetToUse == ResourceSet.debugData) {
@@ -138,7 +150,7 @@ public class GameSource implements ProjectTreeNode, Serializable {
NodeList arrayItems = arrayNode.getElementsByTagName("item"); NodeList arrayItems = arrayNode.getElementsByTagName("item");
if (arrayItems != null) { if (arrayItems != null) {
for (int j = 0; j < arrayItems.getLength(); j++) { for (int j = 0; j < arrayItems.getLength(); j++) {
arrayContents.add(((Element)arrayItems.item(j)).getTextContent()); arrayContents.add(((Element) arrayItems.item(j)).getTextContent());
} }
referencedSourceFiles.put(name, arrayContents); referencedSourceFiles.put(name, arrayContents);
} }
@@ -160,40 +172,49 @@ public class GameSource implements ProjectTreeNode, Serializable {
public Enumeration<ProjectTreeNode> children() { public Enumeration<ProjectTreeNode> children() {
return v.getNonEmptyElements(); return v.getNonEmptyElements();
} }
@Override @Override
public boolean getAllowsChildren() { public boolean getAllowsChildren() {
return true; return true;
} }
@Override @Override
public TreeNode getChildAt(int arg0) { public TreeNode getChildAt(int arg0) {
return v.getNonEmptyElementAt(arg0); return v.getNonEmptyElementAt(arg0);
} }
@Override @Override
public int getChildCount() { public int getChildCount() {
return v.getNonEmptySize(); return v.getNonEmptySize();
} }
@Override @Override
public int getIndex(TreeNode arg0) { public int getIndex(TreeNode arg0) {
return v.getNonEmptyIndexOf((ProjectTreeNode) arg0); return v.getNonEmptyIndexOf((ProjectTreeNode) arg0);
} }
@Override @Override
public TreeNode getParent() { public TreeNode getParent() {
return parent; return parent;
} }
@Override @Override
public boolean isLeaf() { public boolean isLeaf() {
return false; return false;
} }
@Override @Override
public void childrenAdded(List<ProjectTreeNode> path) { public void childrenAdded(List<ProjectTreeNode> path) {
path.add(0, this); path.add(0, this);
parent.childrenAdded(path); parent.childrenAdded(path);
} }
@Override @Override
public void childrenChanged(List<ProjectTreeNode> path) { public void childrenChanged(List<ProjectTreeNode> path) {
path.add(0, this); path.add(0, this);
parent.childrenChanged(path); parent.childrenChanged(path);
} }
@Override @Override
public void childrenRemoved(List<ProjectTreeNode> path) { public void childrenRemoved(List<ProjectTreeNode> path) {
if (path.size() == 1 && this.v.getNonEmptySize() == 1) { if (path.size() == 1 && this.v.getNonEmptySize() == 1) {
@@ -203,6 +224,7 @@ public class GameSource implements ProjectTreeNode, Serializable {
parent.childrenRemoved(path); parent.childrenRemoved(path);
} }
} }
@Override @Override
public void notifyCreated() { public void notifyCreated() {
childrenAdded(new ArrayList<ProjectTreeNode>()); childrenAdded(new ArrayList<ProjectTreeNode>());
@@ -210,14 +232,20 @@ public class GameSource implements ProjectTreeNode, Serializable {
node.notifyCreated(); node.notifyCreated();
} }
} }
@Override @Override
public String getDesc() { public String getDesc() {
switch(type) { switch (type) {
case altered: return (needsSaving() ? "*" : "")+"Altered data"; case altered:
case created: return (needsSaving() ? "*" : "")+"Created data"; return (needsSaving() ? "*" : "") + "Altered data";
case referenced: return (needsSaving() ? "*" : "")+"Referenced data"; case created:
case source: return (needsSaving() ? "*" : "")+"AT Source"; //The fact that it is from "source" is already mentionned by its parent. return (needsSaving() ? "*" : "") + "Created data";
default: return (needsSaving() ? "*" : "")+"Game data"; case referenced:
return (needsSaving() ? "*" : "") + "Referenced data";
case source:
return (needsSaving() ? "*" : "") + "AT Source"; //The fact that it is from "source" is already mentionned by its parent.
default:
return (needsSaving() ? "*" : "") + "Game data";
} }
} }
@@ -252,18 +280,22 @@ public class GameSource implements ProjectTreeNode, Serializable {
public Image getIcon() { public Image getIcon() {
return getOpenIcon(); return getOpenIcon();
} }
@Override @Override
public Image getClosedIcon() { public Image getClosedIcon() {
return DefaultIcons.getATClosedIcon(); return DefaultIcons.getATClosedIcon();
} }
@Override @Override
public Image getLeafIcon() { public Image getLeafIcon() {
return DefaultIcons.getATClosedIcon(); return DefaultIcons.getATClosedIcon();
} }
@Override @Override
public Image getOpenIcon() { public Image getOpenIcon() {
return DefaultIcons.getATOpenIcon(); return DefaultIcons.getATOpenIcon();
} }
@Override @Override
public GameDataSet getDataSet() { public GameDataSet getDataSet() {
return null; return null;

View File

@@ -1,19 +1,53 @@
package com.gpl.rpg.atcontentstudio.model; package com.gpl.rpg.atcontentstudio.model;
import java.awt.Dimension; import com.gpl.rpg.atcontentstudio.io.JsonSerializable;
import java.awt.*;
import java.io.Serializable; import java.io.Serializable;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
public class Preferences implements Serializable { public class Preferences implements Serializable, JsonSerializable {
private static final long serialVersionUID = 2455802658424031276L; private static final long serialVersionUID = 2455802658424031276L;
public Dimension windowSize = null; public Dimension windowSize = null;
public Map<String, Integer> splittersPositions = new HashMap<String, Integer>(); public Map<String, Integer> splittersPositions = new HashMap<>();
public Preferences() { public Preferences() {
} }
@Override
public Map toMap() {
Map map = new HashMap();
if(windowSize!= null){
Map windowSizeMap = new HashMap<>();
windowSizeMap.put("width", windowSize.width);
windowSizeMap.put("height", windowSize.height);
map.put("windowSize", windowSizeMap);
}
map.put("splittersPositions", splittersPositions);
return map;
}
@Override
public void fromMap(Map map) {
if(map == null) return;
Map windowSize1 = (Map) map.get("windowSize");
if(windowSize1 != null){
windowSize = new Dimension(((Number) windowSize1.get("width")).intValue(), ((Number) windowSize1.get("height")).intValue());
}
Map<String, Number> splitters = (Map<String, Number>) map.get("splittersPositions");
Map<String, Integer> splittersInt = new HashMap<>(splitters.size());
for (Map.Entry<String, Number> entry : splitters. entrySet()){
splittersInt.put(entry.getKey(), entry.getValue().intValue());
}
splittersPositions = splittersInt;
}
} }

View File

@@ -1,45 +1,21 @@
package com.gpl.rpg.atcontentstudio.model; package com.gpl.rpg.atcontentstudio.model;
import java.awt.Image; import com.gpl.rpg.atcontentstudio.ATContentStudio;
import java.io.ByteArrayInputStream; import com.gpl.rpg.atcontentstudio.Notification;
import java.io.File; import com.gpl.rpg.atcontentstudio.io.JsonSerializable;
import java.io.FileInputStream; import com.gpl.rpg.atcontentstudio.io.SettingsSave;
import java.io.FileNotFoundException; import com.gpl.rpg.atcontentstudio.model.GameSource.Type;
import java.io.FileOutputStream; import com.gpl.rpg.atcontentstudio.model.bookmarks.BookmarksRoot;
import java.io.FileWriter; import com.gpl.rpg.atcontentstudio.model.gamedata.*;
import java.io.IOException; import com.gpl.rpg.atcontentstudio.model.maps.TMXMap;
import java.io.Serializable; import com.gpl.rpg.atcontentstudio.model.maps.TMXMapSet;
import java.io.StringReader; import com.gpl.rpg.atcontentstudio.model.maps.Worldmap;
import java.io.StringWriter; import com.gpl.rpg.atcontentstudio.model.maps.WorldmapSegment;
import java.nio.charset.StandardCharsets; import com.gpl.rpg.atcontentstudio.model.sprites.Spritesheet;
import java.nio.file.Files; import com.gpl.rpg.atcontentstudio.model.tools.writermode.WriterModeData;
import java.nio.file.Path; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons;
import java.nio.file.Paths; import com.gpl.rpg.atcontentstudio.ui.WorkerDialog;
import java.util.ArrayList; import com.gpl.rpg.atcontentstudio.utils.FileUtils;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.swing.tree.TreeNode;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.json.simple.JSONArray;
import org.w3c.dom.Comment; import org.w3c.dom.Comment;
import org.w3c.dom.Document; import org.w3c.dom.Document;
import org.w3c.dom.Element; import org.w3c.dom.Element;
@@ -47,35 +23,24 @@ import org.w3c.dom.NodeList;
import org.xml.sax.InputSource; import org.xml.sax.InputSource;
import org.xml.sax.SAXException; import org.xml.sax.SAXException;
import com.gpl.rpg.atcontentstudio.ATContentStudio; import javax.swing.tree.TreeNode;
import com.gpl.rpg.atcontentstudio.Notification; import javax.xml.parsers.DocumentBuilder;
import com.gpl.rpg.atcontentstudio.io.JsonPrettyWriter; import javax.xml.parsers.DocumentBuilderFactory;
import com.gpl.rpg.atcontentstudio.io.SettingsSave; import javax.xml.parsers.ParserConfigurationException;
import com.gpl.rpg.atcontentstudio.model.GameSource.Type; import javax.xml.transform.*;
import com.gpl.rpg.atcontentstudio.model.bookmarks.BookmarksRoot; import javax.xml.transform.dom.DOMSource;
import com.gpl.rpg.atcontentstudio.model.gamedata.ActorCondition; import javax.xml.transform.stream.StreamResult;
import com.gpl.rpg.atcontentstudio.model.gamedata.Dialogue; import javax.xml.transform.stream.StreamSource;
import com.gpl.rpg.atcontentstudio.model.gamedata.Droplist; import java.awt.*;
import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataCategory; import java.io.*;
import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet; import java.nio.charset.StandardCharsets;
import com.gpl.rpg.atcontentstudio.model.gamedata.Item; import java.nio.file.Files;
import com.gpl.rpg.atcontentstudio.model.gamedata.ItemCategory; import java.nio.file.Path;
import com.gpl.rpg.atcontentstudio.model.gamedata.JSONElement; import java.nio.file.Paths;
import com.gpl.rpg.atcontentstudio.model.gamedata.NPC; import java.util.List;
import com.gpl.rpg.atcontentstudio.model.gamedata.Quest; import java.util.*;
import com.gpl.rpg.atcontentstudio.model.gamedata.QuestStage;
import com.gpl.rpg.atcontentstudio.model.maps.TMXMap;
import com.gpl.rpg.atcontentstudio.model.maps.TMXMapSet;
import com.gpl.rpg.atcontentstudio.model.maps.Worldmap;
import com.gpl.rpg.atcontentstudio.model.maps.WorldmapSegment;
import com.gpl.rpg.atcontentstudio.model.saves.SavedGamesSet;
import com.gpl.rpg.atcontentstudio.model.sprites.Spritesheet;
import com.gpl.rpg.atcontentstudio.model.tools.writermode.WriterModeData;
import com.gpl.rpg.atcontentstudio.ui.DefaultIcons;
import com.gpl.rpg.atcontentstudio.ui.WorkerDialog;
import com.gpl.rpg.atcontentstudio.utils.FileUtils;
public class Project implements ProjectTreeNode, Serializable { public class Project implements ProjectTreeNode, Serializable, JsonSerializable {
private static final long serialVersionUID = 4807454973303366758L; private static final long serialVersionUID = 4807454973303366758L;
private static final String drawablePath = TMXMapSet.DEFAULT_REL_PATH_TO_DRAWABLE.replace("\\", "/"); private static final String drawablePath = TMXMapSet.DEFAULT_REL_PATH_TO_DRAWABLE.replace("\\", "/");
@@ -83,6 +48,7 @@ public class Project implements ProjectTreeNode, Serializable {
//Every instance field that is not transient will be saved in this file. //Every instance field that is not transient will be saved in this file.
public static final String SETTINGS_FILE = ".project"; public static final String SETTINGS_FILE = ".project";
public static final String SETTINGS_FILE_JSON = ".project.json";
public String name; public String name;
@@ -91,19 +57,39 @@ public class Project implements ProjectTreeNode, Serializable {
public GameSource baseContent; //A.k.a library public GameSource baseContent; //A.k.a library
public GameSource referencedContent; //Pointers to base content
public transient GameSource alteredContent; //Copied from base content (does not overwrite yet) public transient GameSource alteredContent; //Copied from base content (does not overwrite yet)
public transient GameSource createdContent; //Stand-alone. public transient GameSource createdContent; //Stand-alone.
public transient BookmarksRoot bookmarks; public transient BookmarksRoot bookmarks;
public SavedGamesSet saves; //For simulations.
public transient SavedSlotCollection v; public transient SavedSlotCollection v;
public transient Workspace parent; public transient Workspace parent;
public Properties knownSpritesheetsProperties = null; public Properties knownSpritesheetsProperties;
@Override
public Map toMap() {
Map map = new HashMap();
map.put("name", name.toString());
map.put("baseFolder", baseFolder.getPath());
map.put("open", open);
map.put("baseContent", baseContent.toMap());
map.put("sourceSetToUse", sourceSetToUse.toString());
return map;
}
@Override
public void fromMap(Map map) {
if(map==null)return;
name = (String) map.get("name");
baseFolder = new File((String) map.get("baseFolder"));
open = (boolean) map.get("open");
baseContent = new GameSource((Map) map.get("baseContent"), this);
sourceSetToUse = Enum.valueOf(ResourceSet.class, (String)map.get("sourceSetToUse"));
}
public static enum ResourceSet { public static enum ResourceSet {
gameData, gameData,
@@ -111,53 +97,53 @@ public class Project implements ProjectTreeNode, Serializable {
allFiles allFiles
} }
public ResourceSet sourceSetToUse = ResourceSet.allFiles; public ResourceSet sourceSetToUse;
public Project(Workspace w, String name, File source, ResourceSet sourceSet) { public Project(Workspace w, File projectFile) {
this.parent = w;
loadSpritesheetProperties();
Map json = FileUtils.mapFromJsonFile(projectFile);
this.fromMap(json);
initializeData();
linkAll();
save();
}
public Project(Workspace w, String name, File source, ResourceSet sourceSet){
this.parent = w; this.parent = w;
this.name = name; this.name = name;
this.sourceSetToUse = sourceSet; this.sourceSetToUse = sourceSet;
//CREATE PROJECT //CREATE PROJECT
baseFolder = new File(w.baseFolder, name+File.separator); baseFolder = new File(w.baseFolder, name + File.separator);
try { try {
baseFolder.mkdir(); baseFolder.mkdir();
} catch (SecurityException e) { } catch (SecurityException e) {
Notification.addError("Eror creating project root folder: "+e.getMessage()); Notification.addError("Eror creating project root folder: " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
} }
loadSpritesheetProperties();
baseContent = new GameSource(source, this);
open = true; open = true;
initializeData();
linkAll();
save();
}
private void initializeData() {
v = new SavedSlotCollection(); v = new SavedSlotCollection();
knownSpritesheetsProperties = new Properties(); alteredContent = new GameSource(this, Type.altered);
try { createdContent = new GameSource(this, Type.created);
knownSpritesheetsProperties.load(Project.class.getResourceAsStream("/spritesheets.properties"));
} catch (IOException e) {
Notification.addWarn("Unable to load default spritesheets properties.");
e.printStackTrace();
}
baseContent = new GameSource(source, this);
// referencedContent = new GameSource(this, GameSource.Type.referenced);
alteredContent = new GameSource(this, GameSource.Type.altered);
createdContent = new GameSource(this, GameSource.Type.created);
bookmarks = new BookmarksRoot(this); bookmarks = new BookmarksRoot(this);
saves = new SavedGamesSet(this);
v.add(createdContent); v.add(createdContent);
v.add(alteredContent); v.add(alteredContent);
// v.add(referencedContent); // v.add(referencedContent);
v.add(baseContent); v.add(baseContent);
v.add(saves);
v.add(bookmarks); v.add(bookmarks);
linkAll();
save();
} }
@@ -198,21 +184,22 @@ public class Project implements ProjectTreeNode, Serializable {
@Override @Override
public void childrenAdded(List<ProjectTreeNode> path) { public void childrenAdded(List<ProjectTreeNode> path) {
path.add(0,this); path.add(0, this);
parent.childrenAdded(path); parent.childrenAdded(path);
} }
@Override @Override
public void childrenChanged(List<ProjectTreeNode> path) { public void childrenChanged(List<ProjectTreeNode> path) {
path.add(0,this); path.add(0, this);
parent.childrenChanged(path); parent.childrenChanged(path);
} }
@Override @Override
public void childrenRemoved(List<ProjectTreeNode> path) { public void childrenRemoved(List<ProjectTreeNode> path) {
path.add(0,this); path.add(0, this);
parent.childrenRemoved(path); parent.childrenRemoved(path);
} }
@Override @Override
public void notifyCreated() { public void notifyCreated() {
childrenAdded(new ArrayList<ProjectTreeNode>()); childrenAdded(new ArrayList<ProjectTreeNode>());
@@ -220,9 +207,10 @@ public class Project implements ProjectTreeNode, Serializable {
node.notifyCreated(); node.notifyCreated();
} }
} }
@Override @Override
public String getDesc() { public String getDesc() {
return (needsSaving() ? "*" : "")+name; return (needsSaving() ? "*" : "") + name;
} }
@@ -237,13 +225,21 @@ public class Project implements ProjectTreeNode, Serializable {
public static Project fromFolder(Workspace w, File projRoot) { public static Project fromFolder(Workspace w, File projRoot) {
Project p = null; Project p;
File fJson = new File(projRoot, Project.SETTINGS_FILE_JSON);
if (fJson.exists()) {
p = new Project(w, fJson);
} else {
File f = new File(projRoot, Project.SETTINGS_FILE); File f = new File(projRoot, Project.SETTINGS_FILE);
if (!f.exists()) { if (!f.exists()) {
Notification.addError("Unable to find "+SETTINGS_FILE+" for project "+projRoot.getName()); Notification.addError("Unable to find " + SETTINGS_FILE + " for project " + projRoot.getName());
return null; return null;
} else { } else {
p = (Project) SettingsSave.loadInstance(f, "Project"); p = (Project) SettingsSave.loadInstance(f, "Project");
p.baseFolder = projRoot;
}
p.save();
} }
p.refreshTransients(w); p.refreshTransients(w);
return p; return p;
@@ -254,13 +250,7 @@ public class Project implements ProjectTreeNode, Serializable {
projectElementListeners = new HashMap<Class<? extends GameDataElement>, List<ProjectElementListener>>(); projectElementListeners = new HashMap<Class<? extends GameDataElement>, List<ProjectElementListener>>();
try { loadSpritesheetProperties();
knownSpritesheetsProperties = new Properties();
knownSpritesheetsProperties.load(Project.class.getResourceAsStream("/spritesheets.properties"));
} catch (IOException e) {
Notification.addWarn("Unable to load default spritesheets properties.");
e.printStackTrace();
}
if (sourceSetToUse == null) { if (sourceSetToUse == null) {
sourceSetToUse = ResourceSet.allFiles; sourceSetToUse = ResourceSet.allFiles;
@@ -275,14 +265,11 @@ public class Project implements ProjectTreeNode, Serializable {
createdContent = new GameSource(this, GameSource.Type.created); createdContent = new GameSource(this, GameSource.Type.created);
bookmarks = new BookmarksRoot(this); bookmarks = new BookmarksRoot(this);
saves.refreshTransients();
v = new SavedSlotCollection(); v = new SavedSlotCollection();
v.add(createdContent); v.add(createdContent);
v.add(alteredContent); v.add(alteredContent);
// v.add(referencedContent); // v.add(referencedContent);
v.add(baseContent); v.add(baseContent);
v.add(saves);
v.add(bookmarks); v.add(bookmarks);
@@ -290,6 +277,16 @@ public class Project implements ProjectTreeNode, Serializable {
} }
private void loadSpritesheetProperties() {
knownSpritesheetsProperties = new Properties();
try {
knownSpritesheetsProperties.load(Project.class.getResourceAsStream("/spritesheets.properties"));
} catch (IOException e) {
Notification.addWarn("Unable to load default spritesheets properties.");
e.printStackTrace();
}
}
public void linkAll() { public void linkAll() {
for (ProjectTreeNode node : baseContent.gameData.v.getNonEmptyIterable()) { for (ProjectTreeNode node : baseContent.gameData.v.getNonEmptyIterable()) {
if (node instanceof GameDataCategory<?>) { if (node instanceof GameDataCategory<?>) {
@@ -299,7 +296,7 @@ public class Project implements ProjectTreeNode, Serializable {
} }
} }
for (ProjectTreeNode node : baseContent.gameMaps.tmxMaps) { for (ProjectTreeNode node : baseContent.gameMaps.tmxMaps) {
((TMXMap)node).link(); ((TMXMap) node).link();
} }
for (ProjectTreeNode node : alteredContent.gameData.v.getNonEmptyIterable()) { for (ProjectTreeNode node : alteredContent.gameData.v.getNonEmptyIterable()) {
if (node instanceof GameDataCategory<?>) { if (node instanceof GameDataCategory<?>) {
@@ -309,7 +306,7 @@ public class Project implements ProjectTreeNode, Serializable {
} }
} }
for (ProjectTreeNode node : alteredContent.gameMaps.tmxMaps) { for (ProjectTreeNode node : alteredContent.gameMaps.tmxMaps) {
((TMXMap)node).link(); ((TMXMap) node).link();
} }
for (ProjectTreeNode node : createdContent.gameData.v.getNonEmptyIterable()) { for (ProjectTreeNode node : createdContent.gameData.v.getNonEmptyIterable()) {
if (node instanceof GameDataCategory<?>) { if (node instanceof GameDataCategory<?>) {
@@ -319,7 +316,7 @@ public class Project implements ProjectTreeNode, Serializable {
} }
} }
for (ProjectTreeNode node : createdContent.gameMaps.tmxMaps) { for (ProjectTreeNode node : createdContent.gameMaps.tmxMaps) {
((TMXMap)node).link(); ((TMXMap) node).link();
} }
for (WorldmapSegment node : createdContent.worldmap) { for (WorldmapSegment node : createdContent.worldmap) {
@@ -334,7 +331,7 @@ public class Project implements ProjectTreeNode, Serializable {
} }
public void save() { public void save() {
SettingsSave.saveInstance(this, new File(baseFolder, Project.SETTINGS_FILE), "Project "+this.name); FileUtils.writeStringToFile(FileUtils.toJsonString(toMap()),new File(baseFolder, Project.SETTINGS_FILE_JSON), "Project " + this.name);
} }
@@ -428,7 +425,7 @@ public class Project implements ProjectTreeNode, Serializable {
public ActorCondition getActorCondition(int index) { public ActorCondition getActorCondition(int index) {
if (index < createdContent.gameData.actorConditions.size()) { if (index < createdContent.gameData.actorConditions.size()) {
return createdContent.gameData.actorConditions.get(index); return createdContent.gameData.actorConditions.get(index);
} else if (index < getActorConditionCount()){ } else if (index < getActorConditionCount()) {
return getActorCondition(baseContent.gameData.actorConditions.get(index - createdContent.gameData.actorConditions.size()).id); return getActorCondition(baseContent.gameData.actorConditions.get(index - createdContent.gameData.actorConditions.size()).id);
} }
return null; return null;
@@ -457,7 +454,7 @@ public class Project implements ProjectTreeNode, Serializable {
public Dialogue getDialogue(int index) { public Dialogue getDialogue(int index) {
if (index < createdContent.gameData.dialogues.size()) { if (index < createdContent.gameData.dialogues.size()) {
return createdContent.gameData.dialogues.get(index); return createdContent.gameData.dialogues.get(index);
} else if (index < getDialogueCount()){ } else if (index < getDialogueCount()) {
return getDialogue(baseContent.gameData.dialogues.get(index - createdContent.gameData.dialogues.size()).id); return getDialogue(baseContent.gameData.dialogues.get(index - createdContent.gameData.dialogues.size()).id);
} }
return null; return null;
@@ -486,7 +483,7 @@ public class Project implements ProjectTreeNode, Serializable {
public Droplist getDroplist(int index) { public Droplist getDroplist(int index) {
if (index < createdContent.gameData.droplists.size()) { if (index < createdContent.gameData.droplists.size()) {
return createdContent.gameData.droplists.get(index); return createdContent.gameData.droplists.get(index);
} else if (index < getDroplistCount()){ } else if (index < getDroplistCount()) {
return getDroplist(baseContent.gameData.droplists.get(index - createdContent.gameData.droplists.size()).id); return getDroplist(baseContent.gameData.droplists.get(index - createdContent.gameData.droplists.size()).id);
} }
return null; return null;
@@ -515,7 +512,7 @@ public class Project implements ProjectTreeNode, Serializable {
public Item getItem(int index) { public Item getItem(int index) {
if (index < createdContent.gameData.items.size()) { if (index < createdContent.gameData.items.size()) {
return createdContent.gameData.items.get(index); return createdContent.gameData.items.get(index);
} else if (index < getItemCount()){ } else if (index < getItemCount()) {
return getItem(baseContent.gameData.items.get(index - createdContent.gameData.items.size()).id); return getItem(baseContent.gameData.items.get(index - createdContent.gameData.items.size()).id);
} }
return null; return null;
@@ -528,7 +525,7 @@ public class Project implements ProjectTreeNode, Serializable {
public Item getItemIncludingAltered(int index) { public Item getItemIncludingAltered(int index) {
if (index < createdContent.gameData.items.size()) { if (index < createdContent.gameData.items.size()) {
return createdContent.gameData.items.get(index); return createdContent.gameData.items.get(index);
} else if (index < createdContent.gameData.items.size() + alteredContent.gameData.items.size()){ } else if (index < createdContent.gameData.items.size() + alteredContent.gameData.items.size()) {
return alteredContent.gameData.items.get(index - createdContent.gameData.items.size()); return alteredContent.gameData.items.get(index - createdContent.gameData.items.size());
} else if (index < getItemCountIncludingAltered()) { } else if (index < getItemCountIncludingAltered()) {
return baseContent.gameData.items.get(index - (createdContent.gameData.items.size() + alteredContent.gameData.items.size())); return baseContent.gameData.items.get(index - (createdContent.gameData.items.size() + alteredContent.gameData.items.size()));
@@ -559,7 +556,7 @@ public class Project implements ProjectTreeNode, Serializable {
public ItemCategory getItemCategory(int index) { public ItemCategory getItemCategory(int index) {
if (index < createdContent.gameData.itemCategories.size()) { if (index < createdContent.gameData.itemCategories.size()) {
return createdContent.gameData.itemCategories.get(index); return createdContent.gameData.itemCategories.get(index);
} else if (index < getItemCategoryCount()){ } else if (index < getItemCategoryCount()) {
return getItemCategory(baseContent.gameData.itemCategories.get(index - createdContent.gameData.itemCategories.size()).id); return getItemCategory(baseContent.gameData.itemCategories.get(index - createdContent.gameData.itemCategories.size()).id);
} }
return null; return null;
@@ -595,7 +592,7 @@ public class Project implements ProjectTreeNode, Serializable {
public NPC getNPC(int index) { public NPC getNPC(int index) {
if (index < createdContent.gameData.npcs.size()) { if (index < createdContent.gameData.npcs.size()) {
return createdContent.gameData.npcs.get(index); return createdContent.gameData.npcs.get(index);
} else if (index < getNPCCount()){ } else if (index < getNPCCount()) {
return getNPC(baseContent.gameData.npcs.get(index - createdContent.gameData.npcs.size()).id); return getNPC(baseContent.gameData.npcs.get(index - createdContent.gameData.npcs.size()).id);
} }
return null; return null;
@@ -608,7 +605,7 @@ public class Project implements ProjectTreeNode, Serializable {
public NPC getNPCIncludingAltered(int index) { public NPC getNPCIncludingAltered(int index) {
if (index < createdContent.gameData.npcs.size()) { if (index < createdContent.gameData.npcs.size()) {
return createdContent.gameData.npcs.get(index); return createdContent.gameData.npcs.get(index);
} else if (index < createdContent.gameData.npcs.size() + alteredContent.gameData.npcs.size()){ } else if (index < createdContent.gameData.npcs.size() + alteredContent.gameData.npcs.size()) {
return alteredContent.gameData.npcs.get(index - createdContent.gameData.npcs.size()); return alteredContent.gameData.npcs.get(index - createdContent.gameData.npcs.size());
} else if (index < getNPCCountIncludingAltered()) { } else if (index < getNPCCountIncludingAltered()) {
return baseContent.gameData.npcs.get(index - (createdContent.gameData.npcs.size() + alteredContent.gameData.npcs.size())); return baseContent.gameData.npcs.get(index - (createdContent.gameData.npcs.size() + alteredContent.gameData.npcs.size()));
@@ -639,7 +636,7 @@ public class Project implements ProjectTreeNode, Serializable {
public Quest getQuest(int index) { public Quest getQuest(int index) {
if (index < createdContent.gameData.quests.size()) { if (index < createdContent.gameData.quests.size()) {
return createdContent.gameData.quests.get(index); return createdContent.gameData.quests.get(index);
} else if (index < getQuestCount()){ } else if (index < getQuestCount()) {
return getQuest(baseContent.gameData.quests.get(index - createdContent.gameData.quests.size()).id); return getQuest(baseContent.gameData.quests.get(index - createdContent.gameData.quests.size()).id);
} }
return null; return null;
@@ -667,7 +664,7 @@ public class Project implements ProjectTreeNode, Serializable {
public WorldmapSegment getWorldmapSegment(int index) { public WorldmapSegment getWorldmapSegment(int index) {
if (index < createdContent.worldmap.size()) { if (index < createdContent.worldmap.size()) {
return createdContent.worldmap.get(index); return createdContent.worldmap.get(index);
} else if (index < getWorldmapSegmentCount()){ } else if (index < getWorldmapSegmentCount()) {
return getWorldmapSegment(baseContent.worldmap.get(index - createdContent.worldmap.size()).id); return getWorldmapSegment(baseContent.worldmap.get(index - createdContent.worldmap.size()).id);
} }
return null; return null;
@@ -703,7 +700,7 @@ public class Project implements ProjectTreeNode, Serializable {
public Spritesheet getSpritesheet(int index) { public Spritesheet getSpritesheet(int index) {
if (index < createdContent.gameSprites.spritesheets.size()) { if (index < createdContent.gameSprites.spritesheets.size()) {
return createdContent.gameSprites.spritesheets.get(index); return createdContent.gameSprites.spritesheets.get(index);
} else if (index < getSpritesheetCount()){ } else if (index < getSpritesheetCount()) {
return getSpritesheet(baseContent.gameSprites.spritesheets.get(index - createdContent.gameSprites.spritesheets.size()).id); return getSpritesheet(baseContent.gameSprites.spritesheets.get(index - createdContent.gameSprites.spritesheets.size()).id);
} }
return null; return null;
@@ -731,7 +728,7 @@ public class Project implements ProjectTreeNode, Serializable {
public TMXMap getMap(int index) { public TMXMap getMap(int index) {
if (index < createdContent.gameMaps.getChildCount()) { if (index < createdContent.gameMaps.getChildCount()) {
return createdContent.gameMaps.get(index); return createdContent.gameMaps.get(index);
} else if (index < getMapCount()){ } else if (index < getMapCount()) {
return getMap(baseContent.gameMaps.get(index - createdContent.gameMaps.getChildCount()).id); return getMap(baseContent.gameMaps.get(index - createdContent.gameMaps.getChildCount()).id);
} }
return null; return null;
@@ -769,16 +766,19 @@ public class Project implements ProjectTreeNode, Serializable {
public Image getIcon() { public Image getIcon() {
return getOpenIcon(); return getOpenIcon();
} }
@Override @Override
public Image getClosedIcon() { public Image getClosedIcon() {
//TODO Create a cool Project icon. //TODO Create a cool Project icon.
return DefaultIcons.getStdClosedIcon(); return DefaultIcons.getStdClosedIcon();
} }
@Override @Override
public Image getLeafIcon() { public Image getLeafIcon() {
//TODO Create a cool Project icon. //TODO Create a cool Project icon.
return DefaultIcons.getStdClosedIcon(); return DefaultIcons.getStdClosedIcon();
} }
@Override @Override
public Image getOpenIcon() { public Image getOpenIcon() {
//TODO Create a cool Project icon. //TODO Create a cool Project icon.
@@ -788,7 +788,7 @@ public class Project implements ProjectTreeNode, Serializable {
public void makeWritable(JSONElement node) { public void makeWritable(JSONElement node) {
GameSource.Type type = node.getDataType(); GameSource.Type type = node.getDataType();
if (type == null) { if (type == null) {
Notification.addError("Unable to make "+node.getDesc()+" writable. No owning GameDataSet found."); Notification.addError("Unable to make " + node.getDesc() + " writable. No owning GameDataSet found.");
} else { } else {
if (type == GameSource.Type.source) { if (type == GameSource.Type.source) {
JSONElement clone = (JSONElement) node.clone(); JSONElement clone = (JSONElement) node.clone();
@@ -809,17 +809,16 @@ public class Project implements ProjectTreeNode, Serializable {
clone.state = GameDataElement.State.created; clone.state = GameDataElement.State.created;
alteredContent.gameData.addElement(clone); alteredContent.gameData.addElement(clone);
} else { } else {
Notification.addError("Unable to make "+node.getDesc()+" writable. It does not originate from game source material."); Notification.addError("Unable to make " + node.getDesc() + " writable. It does not originate from game source material.");
} }
} }
} }
public void makeWritable(TMXMap node) { public void makeWritable(TMXMap node) {
GameSource.Type type = node.getDataType(); GameSource.Type type = node.getDataType();
if (type == null) { if (type == null) {
Notification.addError("Unable to make "+node.getDesc()+" writable. No owning GameDataSet found."); Notification.addError("Unable to make " + node.getDesc() + " writable. No owning GameDataSet found.");
} else { } else {
if (type == GameSource.Type.source) { if (type == GameSource.Type.source) {
TMXMap clone = node.clone(); TMXMap clone = node.clone();
@@ -831,7 +830,7 @@ public class Project implements ProjectTreeNode, Serializable {
clone.state = GameDataElement.State.created; clone.state = GameDataElement.State.created;
alteredContent.gameMaps.addMap(clone); alteredContent.gameMaps.addMap(clone);
} else { } else {
Notification.addError("Unable to make "+node.getDesc()+" writable. It does not originate from game source material."); Notification.addError("Unable to make " + node.getDesc() + " writable. It does not originate from game source material.");
} }
} }
} }
@@ -839,7 +838,7 @@ public class Project implements ProjectTreeNode, Serializable {
public void makeWritable(WorldmapSegment node) { public void makeWritable(WorldmapSegment node) {
GameSource.Type type = node.getDataType(); GameSource.Type type = node.getDataType();
if (type == null) { if (type == null) {
Notification.addError("Unable to make "+node.getDesc()+" writable. No owning GameDataSet found."); Notification.addError("Unable to make " + node.getDesc() + " writable. No owning GameDataSet found.");
} else { } else {
if (type == GameSource.Type.source) { if (type == GameSource.Type.source) {
WorldmapSegment clone = node.clone(); WorldmapSegment clone = node.clone();
@@ -853,13 +852,12 @@ public class Project implements ProjectTreeNode, Serializable {
clone.state = GameDataElement.State.created; clone.state = GameDataElement.State.created;
alteredContent.worldmap.addSegment(clone); alteredContent.worldmap.addSegment(clone);
} else { } else {
Notification.addError("Unable to make "+node.getDesc()+" writable. It does not originate from game source material."); Notification.addError("Unable to make " + node.getDesc() + " writable. It does not originate from game source material.");
} }
} }
} }
/** /**
*
* @param node. Before calling this method, make sure that no other node with the same class and id exist in either created or altered. * @param node. Before calling this method, make sure that no other node with the same class and id exist in either created or altered.
*/ */
public void createElement(JSONElement node) { public void createElement(JSONElement node) {
@@ -883,7 +881,6 @@ public class Project implements ProjectTreeNode, Serializable {
} }
/** /**
*
* @param node. Before calling this method, make sure that no other node with the same class and id exist in either created or altered. * @param node. Before calling this method, make sure that no other node with the same class and id exist in either created or altered.
*/ */
public void createElements(List<? extends JSONElement> nodes) { public void createElements(List<? extends JSONElement> nodes) {
@@ -911,7 +908,6 @@ public class Project implements ProjectTreeNode, Serializable {
} }
/** /**
*
* @param node. Before calling this method, make sure that no other map with the same id exist in either created or altered. * @param node. Before calling this method, make sure that no other map with the same id exist in either created or altered.
*/ */
public void createElement(TMXMap node) { public void createElement(TMXMap node) {
@@ -941,16 +937,16 @@ public class Project implements ProjectTreeNode, Serializable {
public void moveToCreated(JSONElement target) { public void moveToCreated(JSONElement target) {
target.childrenRemoved(new ArrayList<ProjectTreeNode>()); target.childrenRemoved(new ArrayList<ProjectTreeNode>());
((GameDataCategory<?>)target.getParent()).remove(target); ((GameDataCategory<?>) target.getParent()).remove(target);
target.state = GameDataElement.State.created; target.state = GameDataElement.State.created;
createdContent.gameData.addElement(target); createdContent.gameData.addElement(target);
} }
public void moveToAltered(JSONElement target) { public void moveToAltered(JSONElement target) {
target.childrenRemoved(new ArrayList<ProjectTreeNode>()); target.childrenRemoved(new ArrayList<ProjectTreeNode>());
((GameDataCategory<?>)target.getParent()).remove(target); ((GameDataCategory<?>) target.getParent()).remove(target);
target.state = GameDataElement.State.created; target.state = GameDataElement.State.created;
((JSONElement) target).jsonFile = new File(baseContent.gameData.getGameDataElement(((JSONElement)target).getClass(), target.id).jsonFile.getAbsolutePath()); ((JSONElement) target).jsonFile = new File(baseContent.gameData.getGameDataElement(((JSONElement) target).getClass(), target.id).jsonFile.getAbsolutePath());
alteredContent.gameData.addElement((JSONElement) target); alteredContent.gameData.addElement((JSONElement) target);
} }
@@ -975,7 +971,6 @@ public class Project implements ProjectTreeNode, Serializable {
} }
public void createWriterSketch(WriterModeData node) { public void createWriterSketch(WriterModeData node) {
node.writable = true; node.writable = true;
createdContent.writerModeDataSet.add(node); createdContent.writerModeDataSet.add(node);
@@ -1014,11 +1009,6 @@ public class Project implements ProjectTreeNode, Serializable {
} }
public void addSave(File selectedFile) {
saves.addSave(selectedFile);
}
public List<NPC> getSpawnGroup(String spawngroup_id) { public List<NPC> getSpawnGroup(String spawngroup_id) {
List<NPC> result = new ArrayList<NPC>(); List<NPC> result = new ArrayList<NPC>();
int i = getNPCCount(); int i = getNPCCount();
@@ -1060,7 +1050,8 @@ public class Project implements ProjectTreeNode, Serializable {
} }
public void removeElementListener(Class<? extends GameDataElement> interestingType, ProjectElementListener listener) { public void removeElementListener(Class<? extends GameDataElement> interestingType, ProjectElementListener listener) {
if (projectElementListeners.get(interestingType) != null) projectElementListeners.get(interestingType).remove(listener); if (projectElementListeners.get(interestingType) != null)
projectElementListeners.get(interestingType).remove(listener);
} }
public void fireElementAdded(GameDataElement element, int index) { public void fireElementAdded(GameDataElement element, int index) {
@@ -1080,10 +1071,10 @@ public class Project implements ProjectTreeNode, Serializable {
} }
public void exportProjectAsZipPackage(final File target) { public void exportProjectAsZipPackage(final File target) {
WorkerDialog.showTaskMessage("Exporting project "+name+"...", ATContentStudio.frame, true, new Runnable() { WorkerDialog.showTaskMessage("Exporting project " + name + "...", ATContentStudio.frame, true, new Runnable() {
@Override @Override
public void run() { public void run() {
Notification.addInfo("Exporting project \""+name+"\" as "+target.getAbsolutePath()); Notification.addInfo("Exporting project \"" + name + "\" as " + target.getAbsolutePath());
File tmpDir; File tmpDir;
try { try {
@@ -1095,7 +1086,7 @@ public class Project implements ProjectTreeNode, Serializable {
e.printStackTrace(); e.printStackTrace();
} }
Notification.addSuccess("Project \""+name+"\" exported as "+target.getAbsolutePath()); Notification.addSuccess("Project \"" + name + "\" exported as " + target.getAbsolutePath());
} }
@@ -1103,10 +1094,10 @@ public class Project implements ProjectTreeNode, Serializable {
} }
public void exportProjectOverGameSource(final File target) { public void exportProjectOverGameSource(final File target) {
WorkerDialog.showTaskMessage("Exporting project "+name+"...", ATContentStudio.frame, true, new Runnable() { WorkerDialog.showTaskMessage("Exporting project " + name + "...", ATContentStudio.frame, true, new Runnable() {
@Override @Override
public void run() { public void run() {
Notification.addInfo("Exporting project \""+name+"\" into "+target.getAbsolutePath()); Notification.addInfo("Exporting project \"" + name + "\" into " + target.getAbsolutePath());
File tmpDir; File tmpDir;
try { try {
@@ -1118,7 +1109,7 @@ public class Project implements ProjectTreeNode, Serializable {
e.printStackTrace(); e.printStackTrace();
} }
Notification.addSuccess("Project \""+name+"\" exported into "+target.getAbsolutePath()); Notification.addSuccess("Project \"" + name + "\" exported into " + target.getAbsolutePath());
} }
@@ -1137,13 +1128,15 @@ public class Project implements ProjectTreeNode, Serializable {
// } // }
Map<Class<? extends GameDataElement>, List<String>> writtenFilesPerDataType = new LinkedHashMap<Class<? extends GameDataElement>, List<String>>(); Map<Class<? extends GameDataElement>, List<String>> writtenFilesPerDataType = new LinkedHashMap<Class<? extends GameDataElement>, List<String>>();
List<String> writtenFiles; List<String> writtenFiles;
writtenFiles = writeDataDeltaForDataType(createdContent.gameData.actorConditions, alteredContent.gameData.actorConditions, baseContent.gameData.actorConditions, ActorCondition.class, tmpJsonDataDir); writtenFiles = writeDataDeltaForDataType(createdContent.gameData.actorConditions, alteredContent.gameData.actorConditions, baseContent.gameData.actorConditions, ActorCondition.class,
tmpJsonDataDir);
writtenFilesPerDataType.put(ActorCondition.class, writtenFiles); writtenFilesPerDataType.put(ActorCondition.class, writtenFiles);
writtenFiles = writeDataDeltaForDataType(createdContent.gameData.dialogues, alteredContent.gameData.dialogues, baseContent.gameData.dialogues, Dialogue.class, tmpJsonDataDir); writtenFiles = writeDataDeltaForDataType(createdContent.gameData.dialogues, alteredContent.gameData.dialogues, baseContent.gameData.dialogues, Dialogue.class, tmpJsonDataDir);
writtenFilesPerDataType.put(Dialogue.class, writtenFiles); writtenFilesPerDataType.put(Dialogue.class, writtenFiles);
writtenFiles = writeDataDeltaForDataType(createdContent.gameData.droplists, alteredContent.gameData.droplists, baseContent.gameData.droplists, Droplist.class, tmpJsonDataDir); writtenFiles = writeDataDeltaForDataType(createdContent.gameData.droplists, alteredContent.gameData.droplists, baseContent.gameData.droplists, Droplist.class, tmpJsonDataDir);
writtenFilesPerDataType.put(Droplist.class, writtenFiles); writtenFilesPerDataType.put(Droplist.class, writtenFiles);
writtenFiles = writeDataDeltaForDataType(createdContent.gameData.itemCategories, alteredContent.gameData.itemCategories, baseContent.gameData.itemCategories, ItemCategory.class, tmpJsonDataDir); writtenFiles = writeDataDeltaForDataType(createdContent.gameData.itemCategories, alteredContent.gameData.itemCategories, baseContent.gameData.itemCategories, ItemCategory.class,
tmpJsonDataDir);
writtenFilesPerDataType.put(ItemCategory.class, writtenFiles); writtenFilesPerDataType.put(ItemCategory.class, writtenFiles);
writtenFiles = writeDataDeltaForDataType(createdContent.gameData.items, alteredContent.gameData.items, baseContent.gameData.items, Item.class, tmpJsonDataDir); writtenFiles = writeDataDeltaForDataType(createdContent.gameData.items, alteredContent.gameData.items, baseContent.gameData.items, Item.class, tmpJsonDataDir);
writtenFilesPerDataType.put(Item.class, writtenFiles); writtenFilesPerDataType.put(Item.class, writtenFiles);
@@ -1241,22 +1234,9 @@ public class Project implements ProjectTreeNode, Serializable {
} }
for (String fName : dataToWritePerFilename.keySet()) { for (String fName : dataToWritePerFilename.keySet()) {
File jsonFile = new File(targetFolder, fName); File jsonFile = new File(targetFolder, fName);
StringWriter writer = new JsonPrettyWriter();
try { String textToWrite = FileUtils.toJsonString(dataToWritePerFilename.get(fName));
JSONArray.writeJSONString(dataToWritePerFilename.get(fName), writer); FileUtils.writeStringToFile(textToWrite, jsonFile, "JSON file '"+jsonFile.getAbsolutePath()+"'", false);
} catch (IOException e) {
//Impossible with a StringWriter
}
String textToWrite = writer.toString();
try {
FileWriter w = new FileWriter(jsonFile);
w.write(textToWrite);
w.close();
// Notification.addSuccess("Json file "+jsonFile.getAbsolutePath()+" saved.");
} catch (IOException e) {
Notification.addError("Error while writing json file "+jsonFile.getAbsolutePath()+" : "+e.getMessage());
e.printStackTrace();
}
} }
return filenamesToWrite; return filenamesToWrite;
} }
@@ -1319,19 +1299,19 @@ public class Project implements ProjectTreeNode, Serializable {
NodeList arrayItems = arrayNode.getElementsByTagName("item"); NodeList arrayItems = arrayNode.getElementsByTagName("item");
if (arrayItems != null) { if (arrayItems != null) {
for (int j = 0; j < arrayItems.getLength(); j++) { for (int j = 0; j < arrayItems.getLength(); j++) {
resName = ((Element)arrayItems.item(j)).getTextContent(); resName = ((Element) arrayItems.item(j)).getTextContent();
if (resName == null) continue; if (resName == null) continue;
resToFile = resName.replaceFirst("\\A"+resPrefix, "")+fileSuffix; resToFile = resName.replaceFirst("\\A" + resPrefix, "") + fileSuffix;
writtenFiles.remove(resToFile); writtenFiles.remove(resToFile);
} }
} }
if (!writtenFiles.isEmpty()) { if (!writtenFiles.isEmpty()) {
Comment com = doc.createComment("Added by ATCS "+ATContentStudio.APP_VERSION+" for project "+getProject().name); Comment com = doc.createComment("Added by ATCS " + ATContentStudio.APP_VERSION + " for project " + getProject().name);
arrayNode.appendChild(com); arrayNode.appendChild(com);
Collections.sort(writtenFiles); Collections.sort(writtenFiles);
for (String missingRes : writtenFiles) { for (String missingRes : writtenFiles) {
Element item = doc.createElement("item"); Element item = doc.createElement("item");
fileToRes = resPrefix+missingRes.replaceFirst(fileSuffix+"\\z", ""); fileToRes = resPrefix + missingRes.replaceFirst(fileSuffix + "\\z", "");
item.setTextContent(fileToRes); item.setTextContent(fileToRes);
arrayNode.appendChild(item); arrayNode.appendChild(item);
} }
@@ -1400,7 +1380,4 @@ public class Project implements ProjectTreeNode, Serializable {
} }
} }

View File

@@ -1,23 +1,26 @@
package com.gpl.rpg.atcontentstudio.model; package com.gpl.rpg.atcontentstudio.model;
import java.awt.Image; import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet;
import java.util.List;
import javax.swing.tree.TreeNode; import javax.swing.tree.TreeNode;
import java.awt.*;
import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet; import java.util.List;
public interface ProjectTreeNode extends TreeNode { public interface ProjectTreeNode extends TreeNode {
public void childrenAdded(List<ProjectTreeNode> path); public void childrenAdded(List<ProjectTreeNode> path);
public void childrenChanged(List<ProjectTreeNode> path); public void childrenChanged(List<ProjectTreeNode> path);
public void childrenRemoved(List<ProjectTreeNode> path); public void childrenRemoved(List<ProjectTreeNode> path);
public void notifyCreated(); public void notifyCreated();
public String getDesc(); public String getDesc();
/** /**
* Unnecessary for anything not below a Project. Can return null. * Unnecessary for anything not below a Project. Can return null.
*
* @return the parent Project or null. * @return the parent Project or null.
*/ */
public Project getProject(); public Project getProject();
@@ -25,29 +28,31 @@ public interface ProjectTreeNode extends TreeNode {
/** /**
* Unnecessary for anything not below a GameDataSet. Can return null. * Unnecessary for anything not below a GameDataSet. Can return null.
*
* @return the parent GameDataSet or null. * @return the parent GameDataSet or null.
*/ */
public GameDataSet getDataSet(); public GameDataSet getDataSet();
public Image getIcon(); public Image getIcon();
/** /**
*
* @return The icon depicting this node when it is an open folder. Can be null for leaves. * @return The icon depicting this node when it is an open folder. Can be null for leaves.
*/ */
public Image getOpenIcon(); public Image getOpenIcon();
/** /**
*
* @return The icon depicting this node when it is a closed folder. Can be null for leaves. * @return The icon depicting this node when it is a closed folder. Can be null for leaves.
*/ */
public Image getClosedIcon(); public Image getClosedIcon();
/** /**
*
* @return The icon depicting this node when it is a leaf. Should return the closed one for empty folders. * @return The icon depicting this node when it is a leaf. Should return the closed one for empty folders.
*/ */
public Image getLeafIcon(); public Image getLeafIcon();
/** /**
* Unnecessary for anything not below a GameSource. Can return null. * Unnecessary for anything not below a GameSource. Can return null.
*
* @return the parent GameSource or null. * @return the parent GameSource or null.
*/ */
public GameSource.Type getDataType(); public GameSource.Type getDataType();

View File

@@ -29,7 +29,7 @@ public class SaveEvent {
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (!(obj instanceof SaveEvent)) return false; if (!(obj instanceof SaveEvent)) return false;
else return (((SaveEvent)obj).type == this.type) && (((SaveEvent)obj).target == this.target); else return (((SaveEvent) obj).type == this.type) && (((SaveEvent) obj).target == this.target);
} }
} }

View File

@@ -1,35 +1,30 @@
package com.gpl.rpg.atcontentstudio.model; package com.gpl.rpg.atcontentstudio.model;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import com.gpl.rpg.atcontentstudio.ATContentStudio; import com.gpl.rpg.atcontentstudio.ATContentStudio;
import com.gpl.rpg.atcontentstudio.Notification; import com.gpl.rpg.atcontentstudio.Notification;
import com.gpl.rpg.atcontentstudio.io.JsonSerializable;
import com.gpl.rpg.atcontentstudio.io.SettingsSave; import com.gpl.rpg.atcontentstudio.io.SettingsSave;
import com.gpl.rpg.atcontentstudio.model.GameSource.Type; import com.gpl.rpg.atcontentstudio.model.GameSource.Type;
import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet; import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet;
import com.gpl.rpg.atcontentstudio.ui.ProjectsTree.ProjectsTreeModel; import com.gpl.rpg.atcontentstudio.ui.ProjectsTree.ProjectsTreeModel;
import com.gpl.rpg.atcontentstudio.ui.WorkerDialog; import com.gpl.rpg.atcontentstudio.ui.WorkerDialog;
import com.gpl.rpg.atcontentstudio.utils.FileUtils;
import org.jsoup.SerializationException;
public class Workspace implements ProjectTreeNode, Serializable { import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.io.*;
import java.nio.file.Files;
import java.util.List;
import java.util.*;
public class Workspace implements ProjectTreeNode, Serializable, JsonSerializable {
private static final long serialVersionUID = 7938633033601384956L; private static final long serialVersionUID = 7938633033601384956L;
public static final String WS_SETTINGS_FILE = ".workspace"; public static final String WS_SETTINGS_FILE = ".workspace";
public static final String WS_SETTINGS_FILE_JSON = ".workspace.json";
public static Workspace activeWorkspace; public static Workspace activeWorkspace;
@@ -45,6 +40,7 @@ public class Workspace implements ProjectTreeNode, Serializable {
public transient ProjectsTreeModel projectsTreeModel = null; public transient ProjectsTreeModel projectsTreeModel = null;
public Workspace(File workspaceRoot) { public Workspace(File workspaceRoot) {
boolean freshWorkspace = false;
baseFolder = workspaceRoot; baseFolder = workspaceRoot;
if (!workspaceRoot.exists()) { if (!workspaceRoot.exists()) {
try { try {
@@ -56,23 +52,70 @@ public class Workspace implements ProjectTreeNode, Serializable {
} }
} }
settings = new WorkspaceSettings(this); settings = new WorkspaceSettings(this);
settingsFile = new File(workspaceRoot, WS_SETTINGS_FILE); settingsFile = new File(workspaceRoot, WS_SETTINGS_FILE_JSON);
if (!settingsFile.exists()) { if (!settingsFile.exists()) {
try { try {
settingsFile.createNewFile(); settingsFile.createNewFile();
freshWorkspace = true;
} catch (IOException e) { } catch (IOException e) {
Notification.addError("Error creating workspace datafile: " Notification.addError("Error creating workspace datafile: "
+ e.getMessage()); + e.getMessage());
e.printStackTrace(); e.printStackTrace();
} }
}
Notification.addSuccess("New workspace created: " Notification.addSuccess("New workspace created: "
+ workspaceRoot.getAbsolutePath()); + workspaceRoot.getAbsolutePath());
}
if (freshWorkspace)
save(); save();
} }
@Override
public Map toMap() {
Map map = new HashMap();
map.put("serialVersionUID", serialVersionUID);
map.put("preferences", preferences.toMap());
map.put("projectsName", (new ArrayList<String>(projectsName)));
map.put("projectsOpenByName", projectsOpenByName);
List<String> l = new ArrayList<>(knownMapSourcesFolders.size());
for (File f: knownMapSourcesFolders){
l.add(f.getPath());
}
map.put("knownMapSourcesFolders", l);
return map;
}
@Override
public void fromMap(Map map) {
if(serialVersionUID != (long) map.get("serialVersionUID")){
throw new SerializationException("wrong seriaVersionUID");
}
preferences.fromMap((Map) map.get("preferences"));
projectsName = new HashSet<>((List<String>) map.getOrDefault("projectsName", new HashSet<String>()));
projectsOpenByName = (Map<String, Boolean>) map.getOrDefault("projectsOpenByName", new HashMap<String, Boolean>() );
List<String> knownMapSourcesFolders1 = (List<String>) map.getOrDefault("knownMapSourcesFolders", new ArrayList<String>());
knownMapSourcesFolders = new HashSet<>();
if (knownMapSourcesFolders1 != null){
int size = knownMapSourcesFolders1.size();
for (String path: knownMapSourcesFolders1) {
//TODO: catch invalid paths...?
knownMapSourcesFolders.add(new File(path));
}
}
}
public static void setActive(File workspaceRoot) { public static void setActive(File workspaceRoot) {
Workspace w = null; Workspace w;
File f2 = new File(workspaceRoot, WS_SETTINGS_FILE_JSON);
if (f2.exists()) {
w = loadWorkspaceFromJson(workspaceRoot, f2);
w.refreshTransients();
} else {
Notification.addInfo("Could not find json workspace file. Checking for binary file");
File f = new File(workspaceRoot, WS_SETTINGS_FILE); File f = new File(workspaceRoot, WS_SETTINGS_FILE);
if (!workspaceRoot.exists() || !f.exists()) { if (!workspaceRoot.exists() || !f.exists()) {
w = new Workspace(workspaceRoot); w = new Workspace(workspaceRoot);
@@ -81,19 +124,33 @@ public class Workspace implements ProjectTreeNode, Serializable {
if (w == null) { if (w == null) {
w = new Workspace(workspaceRoot); w = new Workspace(workspaceRoot);
} else { } else {
w.settingsFile = f2;
w.baseFolder = workspaceRoot;
Notification.addInfo("Switched workspace to json format.");
w.refreshTransients(); w.refreshTransients();
} }
w.save();
}
} }
activeWorkspace = w; activeWorkspace = w;
} }
private static Workspace loadWorkspaceFromJson(File workspaceRoot, File settingsFile) {
Workspace w = w = new Workspace(workspaceRoot);
Map json = FileUtils.mapFromJsonFile(settingsFile);
if (json!= null) {
w.fromMap(json);
}
return w;
}
public static void saveActive() { public static void saveActive() {
activeWorkspace.save(); activeWorkspace.save();
} }
public void save() { public void save() {
settings.save(); settings.save();
SettingsSave.saveInstance(this, settingsFile, "Workspace"); FileUtils.writeStringToFile(FileUtils.toJsonString(this), settingsFile, "Workspace");
} }
@Override @Override
@@ -145,7 +202,7 @@ public class Workspace implements ProjectTreeNode, Serializable {
if (projectsTreeModel != null) { if (projectsTreeModel != null) {
while (path.size() > 1) { while (path.size() > 1) {
projectsTreeModel.changeNode(new TreePath(path.toArray())); projectsTreeModel.changeNode(new TreePath(path.toArray()));
path.remove(path.size()-1); path.remove(path.size() - 1);
} }
} }
@@ -311,7 +368,6 @@ public class Workspace implements ProjectTreeNode, Serializable {
Notification.addError("Error while deleting closed project " Notification.addError("Error while deleting closed project "
+ cp.name + ". Files may remain in the workspace."); + cp.name + ". Files may remain in the workspace.");
} }
cp = null;
saveActive(); saveActive();
} }
@@ -327,7 +383,6 @@ public class Workspace implements ProjectTreeNode, Serializable {
Notification.addError("Error while deleting project " + p.name Notification.addError("Error while deleting project " + p.name
+ ". Files may remain in the workspace."); + ". Files may remain in the workspace.");
} }
p = null;
saveActive(); saveActive();
} }
@@ -339,7 +394,7 @@ public class Workspace implements ProjectTreeNode, Serializable {
for (File c : f.listFiles()) for (File c : f.listFiles())
b &= delete(c); b &= delete(c);
} }
return b &= f.delete(); return b & f.delete();
} }
@Override @Override
@@ -365,5 +420,4 @@ public class Workspace implements ProjectTreeNode, Serializable {
} }
return false; return false;
} }
} }

View File

@@ -1,21 +1,15 @@
package com.gpl.rpg.atcontentstudio.model; package com.gpl.rpg.atcontentstudio.model;
import java.io.File; import com.gpl.rpg.atcontentstudio.Notification;
import java.io.FileReader; import com.gpl.rpg.atcontentstudio.utils.FileUtils;
import java.io.FileWriter; import org.json.simple.parser.JSONParser;
import java.io.IOException;
import java.io.StringWriter; import java.io.*;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import com.gpl.rpg.atcontentstudio.Notification;
import com.gpl.rpg.atcontentstudio.io.JsonPrettyWriter;
public class WorkspaceSettings { public class WorkspaceSettings {
public static final String VERSION_KEY = "ATCS_Version"; public static final String VERSION_KEY = "ATCS_Version";
@@ -38,7 +32,7 @@ public class WorkspaceSettings {
public static String DEFAULT_IMG_EDITOR_COMMAND = "gimp"; public static String DEFAULT_IMG_EDITOR_COMMAND = "gimp";
public Setting<String> imageEditorCommand = new PrimitiveSetting<String>("imageEditorCommand", DEFAULT_IMG_EDITOR_COMMAND); public Setting<String> imageEditorCommand = new PrimitiveSetting<String>("imageEditorCommand", DEFAULT_IMG_EDITOR_COMMAND);
public static String[] LANGUAGE_LIST = new String[]{null, "de", "ru", "pl", "fr", "it", "es", "nl", "uk", "ca", "sv", "pt", "pt_BR", "zh_Hant", "zh_Hans", "ja", "cs", "tr", "ko", "hu", "sl", "bg", "id", "fi", "th", "gl", "ms" ,"pa", "az", "nb"}; public static String[] LANGUAGE_LIST = new String[]{null, "de", "ru", "pl", "fr", "it", "es", "nl", "uk", "ca", "sv", "pt", "pt_BR", "zh_Hant", "zh_Hans", "ja", "cs", "tr", "ko", "hu", "sl", "bg", "id", "fi", "th", "gl", "ms", "pa", "az", "nb"};
public Setting<String> translatorLanguage = new NullDefaultPrimitiveSetting<String>("translatorLanguage"); public Setting<String> translatorLanguage = new NullDefaultPrimitiveSetting<String>("translatorLanguage");
public static Boolean DEFAULT_ALLOW_INTERNET = true; public static Boolean DEFAULT_ALLOW_INTERNET = true;
public Setting<Boolean> useInternet = new PrimitiveSetting<Boolean>("useInternet", DEFAULT_ALLOW_INTERNET); public Setting<Boolean> useInternet = new PrimitiveSetting<Boolean>("useInternet", DEFAULT_ALLOW_INTERNET);
@@ -79,7 +73,7 @@ public class WorkspaceSettings {
} }
} catch (Exception e) { } catch (Exception e) {
Notification.addError("Error while parsing workspace settings: "+e.getMessage()); Notification.addError("Error while parsing workspace settings: " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
if (reader != null) if (reader != null)
@@ -113,22 +107,8 @@ public class WorkspaceSettings {
} }
json.put(VERSION_KEY, SETTINGS_VERSION); json.put(VERSION_KEY, SETTINGS_VERSION);
StringWriter writer = new JsonPrettyWriter(); String toWrite = FileUtils.toJsonString(json);
try { FileUtils.writeStringToFile(toWrite, file, "Workspace settings");
JSONObject.writeJSONString(json, writer);
} catch (IOException e) {
//Impossible with a StringWriter
}
String toWrite = writer.toString();
try {
FileWriter w = new FileWriter(file);
w.write(toWrite);
w.close();
Notification.addSuccess("Workspace settings saved.");
} catch (IOException e) {
Notification.addError("Error while saving workspace settings : "+e.getMessage());
e.printStackTrace();
}
} }
public void resetDefault() { public void resetDefault() {
@@ -160,7 +140,7 @@ public class WorkspaceSettings {
public abstract void readFromJson(@SuppressWarnings("rawtypes") Map json); public abstract void readFromJson(@SuppressWarnings("rawtypes") Map json);
@SuppressWarnings({ "rawtypes", "unchecked" }) @SuppressWarnings({"rawtypes", "unchecked"})
public void saveToJson(Map json) { public void saveToJson(Map json) {
if (!defaultValue.equals(value)) json.put(id, value); if (!defaultValue.equals(value)) json.put(id, value);
} }
@@ -174,9 +154,9 @@ public class WorkspaceSettings {
this.value = this.defaultValue = defaultValue; this.value = this.defaultValue = defaultValue;
} }
@SuppressWarnings({ "rawtypes", "unchecked" }) @SuppressWarnings({"rawtypes", "unchecked"})
public void readFromJson(Map json) { public void readFromJson(Map json) {
if (json.get(id) != null) value = (X)json.get(id); if (json.get(id) != null) value = (X) json.get(id);
} }
@@ -188,7 +168,7 @@ public class WorkspaceSettings {
super(id, null); super(id, null);
} }
@SuppressWarnings({ "unchecked", "rawtypes" }) @SuppressWarnings({"unchecked", "rawtypes"})
@Override @Override
public void saveToJson(Map json) { public void saveToJson(Map json) {
if (value != null) json.put(id, value); if (value != null) json.put(id, value);
@@ -202,13 +182,13 @@ public class WorkspaceSettings {
this.value = this.defaultValue = defaultValue; this.value = this.defaultValue = defaultValue;
} }
@SuppressWarnings({ "rawtypes", "unchecked" }) @SuppressWarnings({"rawtypes", "unchecked"})
@Override @Override
public void readFromJson(Map json) { public void readFromJson(Map json) {
value = new ArrayList<X>(); value = new ArrayList<X>();
if (json.get(id) != null) { if (json.get(id) != null) {
for (Object o : ((List)json.get(id))) { for (Object o : ((List) json.get(id))) {
value.add((X)o); value.add((X) o);
} }
} }
} }
@@ -216,5 +196,4 @@ public class WorkspaceSettings {
} }
} }

View File

@@ -1,12 +1,5 @@
package com.gpl.rpg.atcontentstudio.model.bookmarks; package com.gpl.rpg.atcontentstudio.model.bookmarks;
import java.awt.Image;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import javax.swing.tree.TreeNode;
import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.GameDataElement;
import com.gpl.rpg.atcontentstudio.model.GameSource.Type; import com.gpl.rpg.atcontentstudio.model.GameSource.Type;
import com.gpl.rpg.atcontentstudio.model.Project; import com.gpl.rpg.atcontentstudio.model.Project;
@@ -15,6 +8,12 @@ import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet;
import com.gpl.rpg.atcontentstudio.model.gamedata.Quest; import com.gpl.rpg.atcontentstudio.model.gamedata.Quest;
import com.gpl.rpg.atcontentstudio.model.gamedata.QuestStage; import com.gpl.rpg.atcontentstudio.model.gamedata.QuestStage;
import javax.swing.tree.TreeNode;
import java.awt.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
public class BookmarkEntry implements BookmarkNode { public class BookmarkEntry implements BookmarkNode {
public GameDataElement bookmarkedElement; public GameDataElement bookmarkedElement;
@@ -64,21 +63,22 @@ public class BookmarkEntry implements BookmarkNode {
@Override @Override
public void childrenAdded(List<ProjectTreeNode> path) { public void childrenAdded(List<ProjectTreeNode> path) {
path.add(0,this); path.add(0, this);
parent.childrenAdded(path); parent.childrenAdded(path);
} }
@Override @Override
public void childrenChanged(List<ProjectTreeNode> path) { public void childrenChanged(List<ProjectTreeNode> path) {
path.add(0,this); path.add(0, this);
parent.childrenChanged(path); parent.childrenChanged(path);
} }
@Override @Override
public void childrenRemoved(List<ProjectTreeNode> path) { public void childrenRemoved(List<ProjectTreeNode> path) {
path.add(0,this); path.add(0, this);
parent.childrenRemoved(path); parent.childrenRemoved(path);
} }
@Override @Override
public void notifyCreated() { public void notifyCreated() {
childrenAdded(new ArrayList<ProjectTreeNode>()); childrenAdded(new ArrayList<ProjectTreeNode>());
@@ -87,13 +87,19 @@ public class BookmarkEntry implements BookmarkNode {
@Override @Override
public String getDesc() { public String getDesc() {
if (bookmarkedElement instanceof QuestStage) { if (bookmarkedElement instanceof QuestStage) {
String text = ((GameDataElement)bookmarkedElement).getDesc(); String text = ((GameDataElement) bookmarkedElement).getDesc();
if (text.length() > 60) { if (text.length() > 60) {
text = text.substring(0, 57)+"..."; text = text.substring(0, 57) + "...";
} }
return ((GameDataElement)bookmarkedElement).getDataType().toString()+"/"+((Quest)((QuestStage)bookmarkedElement).parent).id+"#"+((QuestStage)bookmarkedElement).progress+":"+text; return ((GameDataElement) bookmarkedElement).getDataType().toString() +
"/" +
((Quest) ((QuestStage) bookmarkedElement).parent).id +
"#" +
((QuestStage) bookmarkedElement).progress +
":" +
text;
} else { } else {
return ((GameDataElement)bookmarkedElement).getDataType().toString()+"/"+((GameDataElement)bookmarkedElement).getDesc(); return ((GameDataElement) bookmarkedElement).getDataType().toString() + "/" + ((GameDataElement) bookmarkedElement).getDesc();
} }
} }

View File

@@ -1,20 +1,16 @@
package com.gpl.rpg.atcontentstudio.model.bookmarks; package com.gpl.rpg.atcontentstudio.model.bookmarks;
import java.awt.Image;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;
import javax.swing.tree.TreeNode;
import com.gpl.rpg.atcontentstudio.model.GameSource.Type; import com.gpl.rpg.atcontentstudio.model.GameSource.Type;
import com.gpl.rpg.atcontentstudio.model.Project; import com.gpl.rpg.atcontentstudio.model.Project;
import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode; import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode;
import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet; import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet;
import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons;
import javax.swing.tree.TreeNode;
import java.awt.*;
import java.util.List;
import java.util.*;
public class BookmarkFolder implements BookmarkNode { public class BookmarkFolder implements BookmarkNode {
List<BookmarkNode> contents = new LinkedList<BookmarkNode>(); List<BookmarkNode> contents = new LinkedList<BookmarkNode>();
@@ -70,13 +66,13 @@ public class BookmarkFolder implements BookmarkNode {
@Override @Override
public void childrenAdded(List<ProjectTreeNode> path) { public void childrenAdded(List<ProjectTreeNode> path) {
path.add(0,this); path.add(0, this);
parent.childrenAdded(path); parent.childrenAdded(path);
} }
@Override @Override
public void childrenChanged(List<ProjectTreeNode> path) { public void childrenChanged(List<ProjectTreeNode> path) {
path.add(0,this); path.add(0, this);
parent.childrenChanged(path); parent.childrenChanged(path);
} }
@@ -89,6 +85,7 @@ public class BookmarkFolder implements BookmarkNode {
parent.childrenRemoved(path); parent.childrenRemoved(path);
} }
} }
@Override @Override
public void notifyCreated() { public void notifyCreated() {
childrenAdded(new ArrayList<ProjectTreeNode>()); childrenAdded(new ArrayList<ProjectTreeNode>());

View File

@@ -2,9 +2,10 @@ package com.gpl.rpg.atcontentstudio.model.bookmarks;
import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode; import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode;
public interface BookmarkNode extends ProjectTreeNode{ public interface BookmarkNode extends ProjectTreeNode {
public void save(); public void save();
public void delete(); public void delete();
} }

View File

@@ -1,36 +1,27 @@
package com.gpl.rpg.atcontentstudio.model.bookmarks; package com.gpl.rpg.atcontentstudio.model.bookmarks;
import java.awt.Image;
import java.io.File;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import javax.swing.tree.TreeNode;
import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.GameDataElement;
import com.gpl.rpg.atcontentstudio.model.GameSource.Type; import com.gpl.rpg.atcontentstudio.model.GameSource.Type;
import com.gpl.rpg.atcontentstudio.model.Project; import com.gpl.rpg.atcontentstudio.model.Project;
import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode; import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode;
import com.gpl.rpg.atcontentstudio.model.SavedSlotCollection; import com.gpl.rpg.atcontentstudio.model.SavedSlotCollection;
import com.gpl.rpg.atcontentstudio.model.gamedata.ActorCondition; import com.gpl.rpg.atcontentstudio.model.gamedata.*;
import com.gpl.rpg.atcontentstudio.model.gamedata.Dialogue;
import com.gpl.rpg.atcontentstudio.model.gamedata.Droplist;
import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet;
import com.gpl.rpg.atcontentstudio.model.gamedata.Item;
import com.gpl.rpg.atcontentstudio.model.gamedata.ItemCategory;
import com.gpl.rpg.atcontentstudio.model.gamedata.NPC;
import com.gpl.rpg.atcontentstudio.model.gamedata.Quest;
import com.gpl.rpg.atcontentstudio.model.maps.TMXMap; import com.gpl.rpg.atcontentstudio.model.maps.TMXMap;
import com.gpl.rpg.atcontentstudio.model.maps.WorldmapSegment; import com.gpl.rpg.atcontentstudio.model.maps.WorldmapSegment;
import com.gpl.rpg.atcontentstudio.model.sprites.Spritesheet; import com.gpl.rpg.atcontentstudio.model.sprites.Spritesheet;
import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons;
import javax.swing.tree.TreeNode;
import java.awt.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
public class BookmarksRoot implements BookmarkNode { public class BookmarksRoot implements BookmarkNode {
SavedSlotCollection v = new SavedSlotCollection(); SavedSlotCollection v = new SavedSlotCollection();
public transient Project parent = null; public transient Project parent;
BookmarkFolder ac, diag, dl, it, ic, npc, q, tmx, sp, wm; BookmarkFolder ac, diag, dl, it, ic, npc, q, tmx, sp, wm;
@@ -90,11 +81,13 @@ public class BookmarksRoot implements BookmarkNode {
path.add(0, this); path.add(0, this);
parent.childrenAdded(path); parent.childrenAdded(path);
} }
@Override @Override
public void childrenChanged(List<ProjectTreeNode> path) { public void childrenChanged(List<ProjectTreeNode> path) {
path.add(0, this); path.add(0, this);
parent.childrenChanged(path); parent.childrenChanged(path);
} }
@Override @Override
public void childrenRemoved(List<ProjectTreeNode> path) { public void childrenRemoved(List<ProjectTreeNode> path) {
if (path.size() == 1 && this.v.getNonEmptySize() == 1) { if (path.size() == 1 && this.v.getNonEmptySize() == 1) {
@@ -104,6 +97,7 @@ public class BookmarksRoot implements BookmarkNode {
parent.childrenRemoved(path); parent.childrenRemoved(path);
} }
} }
@Override @Override
public void notifyCreated() { public void notifyCreated() {
childrenAdded(new ArrayList<ProjectTreeNode>()); childrenAdded(new ArrayList<ProjectTreeNode>());
@@ -114,7 +108,7 @@ public class BookmarksRoot implements BookmarkNode {
@Override @Override
public String getDesc() { public String getDesc() {
return (needsSaving() ? "*" : "")+"Bookmarks"; return (needsSaving() ? "*" : "") + "Bookmarks";
} }
@Override @Override
@@ -167,11 +161,12 @@ public class BookmarksRoot implements BookmarkNode {
} }
@Override @Override
public void delete() {} public void delete() {
}
public void addBookmark(GameDataElement target) { public void addBookmark(GameDataElement target) {
BookmarkEntry node; BookmarkEntry node;
BookmarkFolder folder = null; BookmarkFolder folder;
if (target instanceof ActorCondition) { if (target instanceof ActorCondition) {
folder = ac; folder = ac;
} else if (target instanceof Dialogue) { } else if (target instanceof Dialogue) {
@@ -197,7 +192,8 @@ public class BookmarksRoot implements BookmarkNode {
} }
ProjectTreeNode higherEmptyParent = folder; ProjectTreeNode higherEmptyParent = folder;
while (higherEmptyParent != null) { while (higherEmptyParent != null) {
if (higherEmptyParent.getParent() != null && ((ProjectTreeNode)higherEmptyParent.getParent()).isEmpty()) higherEmptyParent = (ProjectTreeNode)higherEmptyParent.getParent(); if (higherEmptyParent.getParent() != null && ((ProjectTreeNode) higherEmptyParent.getParent()).isEmpty())
higherEmptyParent = (ProjectTreeNode) higherEmptyParent.getParent();
else break; else break;
} }
if (higherEmptyParent == this && !this.isEmpty()) higherEmptyParent = null; if (higherEmptyParent == this && !this.isEmpty()) higherEmptyParent = null;

View File

@@ -1,6 +1,12 @@
package com.gpl.rpg.atcontentstudio.model.gamedata; package com.gpl.rpg.atcontentstudio.model.gamedata;
import java.awt.Image; import com.gpl.rpg.atcontentstudio.Notification;
import com.gpl.rpg.atcontentstudio.model.GameDataElement;
import com.gpl.rpg.atcontentstudio.model.GameSource;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.awt.*;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.FileReader; import java.io.FileReader;
@@ -9,26 +15,20 @@ import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import com.gpl.rpg.atcontentstudio.Notification;
import com.gpl.rpg.atcontentstudio.model.GameDataElement;
import com.gpl.rpg.atcontentstudio.model.GameSource;
public class ActorCondition extends JSONElement { public class ActorCondition extends JSONElement {
private static final long serialVersionUID = -3969824899972048507L; private static final long serialVersionUID = -3969824899972048507L;
public static final Integer MAGNITUDE_CLEAR = -99; public static final Integer MAGNITUDE_CLEAR = -99;
public static final Integer DURATION_FOREVER = 999;; public static final Integer DURATION_FOREVER = 999;
public static final Integer DURATION_NONE = 0; public static final Integer DURATION_NONE = 0;
// Available from init state // Available from init state
//public String id; inherited. //public String id; inherited.
public String icon_id; public String icon_id;
public String display_name; public String display_name;
public String description;
// Available from parsed state // Available from parsed state
public ACCategory category = null; public ACCategory category = null;
@@ -46,10 +46,7 @@ public class ActorCondition extends JSONElement {
} }
public static enum VisualEffectID { public static enum VisualEffectID {
redSplash redSplash, blueSwirl, greenSplash, miss
,blueSwirl
,greenSplash
,miss
} }
public static class RoundEffect implements Cloneable { public static class RoundEffect implements Cloneable {
@@ -97,7 +94,7 @@ public class ActorCondition extends JSONElement {
@Override @Override
public String getDesc() { public String getDesc() {
return (needsSaving() ? "*" : "")+display_name+" ("+id+")"; return (needsSaving() ? "*" : "") + display_name + " (" + id + ")";
} }
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
@@ -108,7 +105,7 @@ public class ActorCondition extends JSONElement {
reader = new FileReader(jsonFile); reader = new FileReader(jsonFile);
List actorConditions = (List) parser.parse(reader); List actorConditions = (List) parser.parse(reader);
for (Object obj : actorConditions) { for (Object obj : actorConditions) {
Map aCondJson = (Map)obj; Map aCondJson = (Map) obj;
ActorCondition aCond = fromJson(aCondJson); ActorCondition aCond = fromJson(aCondJson);
aCond.jsonFile = jsonFile; aCond.jsonFile = jsonFile;
aCond.parent = category; aCond.parent = category;
@@ -118,13 +115,13 @@ public class ActorCondition extends JSONElement {
category.add(aCond); category.add(aCond);
} }
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
} catch (IOException e) { } catch (IOException e) {
Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
} catch (ParseException e) { } catch (ParseException e) {
Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
if (reader != null) if (reader != null)
@@ -157,6 +154,7 @@ public class ActorCondition extends JSONElement {
@Override @Override
public void parse(Map aCondJson) { public void parse(Map aCondJson) {
if (aCondJson.get("description") != null) this.description = (String) aCondJson.get("description");
if (aCondJson.get("category") != null) this.category = ACCategory.valueOf((String) aCondJson.get("category")); if (aCondJson.get("category") != null) this.category = ACCategory.valueOf((String) aCondJson.get("category"));
this.positive = JSONElement.getInteger((Number) aCondJson.get("isPositive")); this.positive = JSONElement.getInteger((Number) aCondJson.get("isPositive"));
Map abilityEffect = (Map) aCondJson.get("abilityEffect"); Map abilityEffect = (Map) aCondJson.get("abilityEffect");
@@ -164,8 +162,8 @@ public class ActorCondition extends JSONElement {
this.constant_ability_effect = new AbilityEffect(); this.constant_ability_effect = new AbilityEffect();
this.constant_ability_effect.increase_attack_chance = JSONElement.getInteger((Number) abilityEffect.get("increaseAttackChance")); this.constant_ability_effect.increase_attack_chance = JSONElement.getInteger((Number) abilityEffect.get("increaseAttackChance"));
if (abilityEffect.get("increaseAttackDamage") != null) { if (abilityEffect.get("increaseAttackDamage") != null) {
this.constant_ability_effect.increase_damage_min = JSONElement.getInteger((Number) (((Map)abilityEffect.get("increaseAttackDamage")).get("min"))); this.constant_ability_effect.increase_damage_min = JSONElement.getInteger((Number) (((Map) abilityEffect.get("increaseAttackDamage")).get("min")));
this.constant_ability_effect.increase_damage_max = JSONElement.getInteger((Number) (((Map)abilityEffect.get("increaseAttackDamage")).get("max"))); this.constant_ability_effect.increase_damage_max = JSONElement.getInteger((Number) (((Map) abilityEffect.get("increaseAttackDamage")).get("max")));
} }
this.constant_ability_effect.max_hp_boost = JSONElement.getInteger((Number) abilityEffect.get("increaseMaxHP")); this.constant_ability_effect.max_hp_boost = JSONElement.getInteger((Number) abilityEffect.get("increaseMaxHP"));
this.constant_ability_effect.max_ap_boost = JSONElement.getInteger((Number) abilityEffect.get("increaseMaxAP")); this.constant_ability_effect.max_ap_boost = JSONElement.getInteger((Number) abilityEffect.get("increaseMaxAP"));
@@ -182,38 +180,40 @@ public class ActorCondition extends JSONElement {
if (roundEffect != null) { if (roundEffect != null) {
this.round_effect = new RoundEffect(); this.round_effect = new RoundEffect();
if (roundEffect.get("increaseCurrentHP") != null) { if (roundEffect.get("increaseCurrentHP") != null) {
this.round_effect.hp_boost_max = JSONElement.getInteger((Number) (((Map)roundEffect.get("increaseCurrentHP")).get("max"))); this.round_effect.hp_boost_max = JSONElement.getInteger((Number) (((Map) roundEffect.get("increaseCurrentHP")).get("max")));
this.round_effect.hp_boost_min = JSONElement.getInteger((Number) (((Map)roundEffect.get("increaseCurrentHP")).get("min"))); this.round_effect.hp_boost_min = JSONElement.getInteger((Number) (((Map) roundEffect.get("increaseCurrentHP")).get("min")));
} }
if (roundEffect.get("increaseCurrentAP") != null) { if (roundEffect.get("increaseCurrentAP") != null) {
this.round_effect.ap_boost_max = JSONElement.getInteger((Number) (((Map)roundEffect.get("increaseCurrentAP")).get("max"))); this.round_effect.ap_boost_max = JSONElement.getInteger((Number) (((Map) roundEffect.get("increaseCurrentAP")).get("max")));
this.round_effect.ap_boost_min = JSONElement.getInteger((Number) (((Map)roundEffect.get("increaseCurrentAP")).get("min"))); this.round_effect.ap_boost_min = JSONElement.getInteger((Number) (((Map) roundEffect.get("increaseCurrentAP")).get("min")));
} }
String vfx = (String) roundEffect.get("visualEffectID"); String vfx = (String) roundEffect.get("visualEffectID");
this.round_effect.visual_effect = null; this.round_effect.visual_effect = null;
if (vfx != null) { if (vfx != null) {
try { try {
this.round_effect.visual_effect = VisualEffectID.valueOf(vfx); this.round_effect.visual_effect = VisualEffectID.valueOf(vfx);
} catch(IllegalArgumentException e) {} } catch (IllegalArgumentException e) {
}
} }
} }
Map fullRoundEffect = (Map) aCondJson.get("fullRoundEffect"); Map fullRoundEffect = (Map) aCondJson.get("fullRoundEffect");
if (fullRoundEffect != null) { if (fullRoundEffect != null) {
this.full_round_effect = new RoundEffect(); this.full_round_effect = new RoundEffect();
if (fullRoundEffect.get("increaseCurrentHP") != null) { if (fullRoundEffect.get("increaseCurrentHP") != null) {
this.full_round_effect.hp_boost_max = JSONElement.getInteger((Number) (((Map)fullRoundEffect.get("increaseCurrentHP")).get("max"))); this.full_round_effect.hp_boost_max = JSONElement.getInteger((Number) (((Map) fullRoundEffect.get("increaseCurrentHP")).get("max")));
this.full_round_effect.hp_boost_min = JSONElement.getInteger((Number) (((Map)fullRoundEffect.get("increaseCurrentHP")).get("min"))); this.full_round_effect.hp_boost_min = JSONElement.getInteger((Number) (((Map) fullRoundEffect.get("increaseCurrentHP")).get("min")));
} }
if (fullRoundEffect.get("increaseCurrentAP") != null) { if (fullRoundEffect.get("increaseCurrentAP") != null) {
this.full_round_effect.ap_boost_max = JSONElement.getInteger((Number) (((Map)fullRoundEffect.get("increaseCurrentAP")).get("max"))); this.full_round_effect.ap_boost_max = JSONElement.getInteger((Number) (((Map) fullRoundEffect.get("increaseCurrentAP")).get("max")));
this.full_round_effect.ap_boost_min = JSONElement.getInteger((Number) (((Map)fullRoundEffect.get("increaseCurrentAP")).get("min"))); this.full_round_effect.ap_boost_min = JSONElement.getInteger((Number) (((Map) fullRoundEffect.get("increaseCurrentAP")).get("min")));
} }
String vfx = (String) fullRoundEffect.get("visualEffectID"); String vfx = (String) fullRoundEffect.get("visualEffectID");
this.full_round_effect.visual_effect = null; this.full_round_effect.visual_effect = null;
if (vfx != null) { if (vfx != null) {
try { try {
this.full_round_effect.visual_effect = VisualEffectID.valueOf(vfx); this.full_round_effect.visual_effect = VisualEffectID.valueOf(vfx);
} catch(IllegalArgumentException e) {} } catch (IllegalArgumentException e) {
}
} }
} }
this.state = State.parsed; this.state = State.parsed;
@@ -222,21 +222,19 @@ public class ActorCondition extends JSONElement {
@Override @Override
public void link() { public void link() {
if (this.state == State.created || this.state == State.modified || this.state == State.saved) { if (shouldSkipParseOrLink()) {
//This type of state is unrelated to parsing/linking.
return;
}
if (this.state == State.init) {
//Not parsed yet.
this.parse();
} else if (this.state == State.linked) {
//Already linked.
return; return;
} }
ensureParseIfNeeded();
if (this.icon_id != null) { if (this.icon_id != null) {
String spritesheetId = this.icon_id.split(":")[0]; String spritesheetId = this.icon_id.split(":")[0];
if (getProject().getSpritesheet(spritesheetId) == null) { if (getProject().getSpritesheet(spritesheetId) == null) {
System.out.println("Actor Condition");
System.out.println(this.id); System.out.println(this.id);
System.out.println("failed to load spritesheet:");
System.out.println(spritesheetId);
System.out.println("while creating backlink for icon_id:");
System.out.println(this.icon_id);
} }
getProject().getSpritesheet(spritesheetId).addBacklink(this); getProject().getSpritesheet(spritesheetId).addBacklink(this);
} }
@@ -266,6 +264,7 @@ public class ActorCondition extends JSONElement {
clone.state = this.state; clone.state = this.state;
clone.id = this.id; clone.id = this.id;
clone.display_name = this.display_name; clone.display_name = this.display_name;
clone.description = this.description;
clone.icon_id = this.icon_id; clone.icon_id = this.icon_id;
clone.category = this.category; clone.category = this.category;
clone.positive = this.positive; clone.positive = this.positive;
@@ -287,19 +286,21 @@ public class ActorCondition extends JSONElement {
//Nothing to link to. //Nothing to link to.
} }
@SuppressWarnings({ "rawtypes", "unchecked" }) @SuppressWarnings({"rawtypes", "unchecked"})
@Override @Override
public Map toJson() { public Map toJson() {
Map jsonAC = new LinkedHashMap(); Map jsonAC = new LinkedHashMap();
jsonAC.put("id", this.id); jsonAC.put("id", this.id);
if (this.icon_id != null) jsonAC.put("iconID", this.icon_id); if (this.icon_id != null) jsonAC.put("iconID", this.icon_id);
if (this.display_name != null) jsonAC.put("name", this.display_name); if (this.display_name != null) jsonAC.put("name", this.display_name);
if (this.description != null) jsonAC.put("description", this.description);
if (this.category != null) jsonAC.put("category", this.category.toString()); if (this.category != null) jsonAC.put("category", this.category.toString());
if (this.positive != null && this.positive == 1) jsonAC.put("isPositive", this.positive); if (this.positive != null && this.positive == 1) jsonAC.put("isPositive", this.positive);
if (this.stacking != null && this.stacking == 1) jsonAC.put("isStacking", this.stacking); if (this.stacking != null && this.stacking == 1) jsonAC.put("isStacking", this.stacking);
if (this.round_effect != null) { if (this.round_effect != null) {
Map jsonRound = new LinkedHashMap(); Map jsonRound = new LinkedHashMap();
if (this.round_effect.visual_effect != null) jsonRound.put("visualEffectID", this.round_effect.visual_effect.toString()); if (this.round_effect.visual_effect != null)
jsonRound.put("visualEffectID", this.round_effect.visual_effect.toString());
if (this.round_effect.hp_boost_min != null || this.round_effect.hp_boost_max != null) { if (this.round_effect.hp_boost_min != null || this.round_effect.hp_boost_max != null) {
Map jsonHP = new LinkedHashMap(); Map jsonHP = new LinkedHashMap();
if (this.round_effect.hp_boost_min != null) jsonHP.put("min", this.round_effect.hp_boost_min); if (this.round_effect.hp_boost_min != null) jsonHP.put("min", this.round_effect.hp_boost_min);
@@ -320,7 +321,8 @@ public class ActorCondition extends JSONElement {
} }
if (this.full_round_effect != null) { if (this.full_round_effect != null) {
Map jsonFullRound = new LinkedHashMap(); Map jsonFullRound = new LinkedHashMap();
if (this.full_round_effect.visual_effect != null) jsonFullRound.put("visualEffectID", this.full_round_effect.visual_effect.toString()); if (this.full_round_effect.visual_effect != null)
jsonFullRound.put("visualEffectID", this.full_round_effect.visual_effect.toString());
if (this.full_round_effect.hp_boost_min != null || this.full_round_effect.hp_boost_max != null) { if (this.full_round_effect.hp_boost_min != null || this.full_round_effect.hp_boost_max != null) {
Map jsonHP = new LinkedHashMap(); Map jsonHP = new LinkedHashMap();
if (this.full_round_effect.hp_boost_min != null) jsonHP.put("min", this.full_round_effect.hp_boost_min); if (this.full_round_effect.hp_boost_min != null) jsonHP.put("min", this.full_round_effect.hp_boost_min);
@@ -341,24 +343,36 @@ public class ActorCondition extends JSONElement {
} }
if (this.constant_ability_effect != null) { if (this.constant_ability_effect != null) {
Map jsonAbility = new LinkedHashMap(); Map jsonAbility = new LinkedHashMap();
if (this.constant_ability_effect.increase_attack_chance != null) jsonAbility.put("increaseAttackChance", this.constant_ability_effect.increase_attack_chance); if (this.constant_ability_effect.increase_attack_chance != null)
jsonAbility.put("increaseAttackChance", this.constant_ability_effect.increase_attack_chance);
if (this.constant_ability_effect.increase_damage_min != null || this.constant_ability_effect.increase_damage_max != null) { if (this.constant_ability_effect.increase_damage_min != null || this.constant_ability_effect.increase_damage_max != null) {
Map jsonAD = new LinkedHashMap(); Map jsonAD = new LinkedHashMap();
if (this.constant_ability_effect.increase_damage_min != null) jsonAD.put("min", this.constant_ability_effect.increase_damage_min); if (this.constant_ability_effect.increase_damage_min != null)
jsonAD.put("min", this.constant_ability_effect.increase_damage_min);
else jsonAD.put("min", 0); else jsonAD.put("min", 0);
if (this.constant_ability_effect.increase_damage_max != null) jsonAD.put("max", this.constant_ability_effect.increase_damage_max); if (this.constant_ability_effect.increase_damage_max != null)
jsonAD.put("max", this.constant_ability_effect.increase_damage_max);
else jsonAD.put("max", 0); else jsonAD.put("max", 0);
jsonAbility.put("increaseAttackDamage", jsonAD); jsonAbility.put("increaseAttackDamage", jsonAD);
} }
if (this.constant_ability_effect.max_hp_boost != null) jsonAbility.put("increaseMaxHP", this.constant_ability_effect.max_hp_boost); if (this.constant_ability_effect.max_hp_boost != null)
if (this.constant_ability_effect.max_ap_boost != null) jsonAbility.put("increaseMaxAP", this.constant_ability_effect.max_ap_boost); jsonAbility.put("increaseMaxHP", this.constant_ability_effect.max_hp_boost);
if (this.constant_ability_effect.increase_move_cost != null) jsonAbility.put("increaseMoveCost", this.constant_ability_effect.increase_move_cost); if (this.constant_ability_effect.max_ap_boost != null)
if (this.constant_ability_effect.increase_use_cost != null) jsonAbility.put("increaseUseItemCost", this.constant_ability_effect.increase_use_cost); jsonAbility.put("increaseMaxAP", this.constant_ability_effect.max_ap_boost);
if (this.constant_ability_effect.increase_reequip_cost != null) jsonAbility.put("increaseReequipCost", this.constant_ability_effect.increase_reequip_cost); if (this.constant_ability_effect.increase_move_cost != null)
if (this.constant_ability_effect.increase_attack_cost != null) jsonAbility.put("increaseAttackCost", this.constant_ability_effect.increase_attack_cost); jsonAbility.put("increaseMoveCost", this.constant_ability_effect.increase_move_cost);
if (this.constant_ability_effect.increase_critical_skill != null) jsonAbility.put("increaseCriticalSkill", this.constant_ability_effect.increase_critical_skill); if (this.constant_ability_effect.increase_use_cost != null)
if (this.constant_ability_effect.increase_block_chance != null) jsonAbility.put("increaseBlockChance", this.constant_ability_effect.increase_block_chance); jsonAbility.put("increaseUseItemCost", this.constant_ability_effect.increase_use_cost);
if (this.constant_ability_effect.increase_damage_resistance != null) jsonAbility.put("increaseDamageResistance", this.constant_ability_effect.increase_damage_resistance); if (this.constant_ability_effect.increase_reequip_cost != null)
jsonAbility.put("increaseReequipCost", this.constant_ability_effect.increase_reequip_cost);
if (this.constant_ability_effect.increase_attack_cost != null)
jsonAbility.put("increaseAttackCost", this.constant_ability_effect.increase_attack_cost);
if (this.constant_ability_effect.increase_critical_skill != null)
jsonAbility.put("increaseCriticalSkill", this.constant_ability_effect.increase_critical_skill);
if (this.constant_ability_effect.increase_block_chance != null)
jsonAbility.put("increaseBlockChance", this.constant_ability_effect.increase_block_chance);
if (this.constant_ability_effect.increase_damage_resistance != null)
jsonAbility.put("increaseDamageResistance", this.constant_ability_effect.increase_damage_resistance);
jsonAC.put("abilityEffect", jsonAbility); jsonAC.put("abilityEffect", jsonAbility);
} }
return jsonAC; return jsonAC;
@@ -366,7 +380,7 @@ public class ActorCondition extends JSONElement {
@Override @Override
public String getProjectFilename() { public String getProjectFilename() {
return "actorconditions_"+getProject().name+".json"; return "actorconditions_" + getProject().name + ".json";
} }
} }

View File

@@ -0,0 +1,384 @@
package com.gpl.rpg.atcontentstudio.model.gamedata;
import com.gpl.rpg.atcontentstudio.Notification;
import com.gpl.rpg.atcontentstudio.model.GameDataElement;
import com.gpl.rpg.atcontentstudio.model.Project;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public final class Common {
public static <T extends ActorConditionEffect> void actorConditionElementChanged(List<T> list, GameDataElement oldOne, GameDataElement newOne, GameDataElement backlink) {
if (list != null) {
for (T c : list) {
if (c.condition == oldOne) {
oldOne.removeBacklink(backlink);
c.condition = (ActorCondition) newOne;
if (newOne != null) newOne.addBacklink(backlink);
}
}
}
}
//region link common stuff
public static void linkConditions(List<? extends ActorConditionEffect> conditions, Project proj, GameDataElement backlink) {
if (conditions != null) {
for (ActorConditionEffect ce : conditions) {
if (ce.condition_id != null) ce.condition = proj.getActorCondition(ce.condition_id);
if (ce.condition != null) ce.condition.addBacklink(backlink);
}
}
}
public static void linkEffects(HitEffect effect, Project proj, GameDataElement backlink) {
linkEffects((DeathEffect) effect, proj, backlink);
if (effect != null) {
linkConditions(effect.conditions_target, proj, backlink);
}
}
public static void linkEffects(DeathEffect effect, Project proj, GameDataElement backlink) {
if (effect != null) {
linkConditions(effect.conditions_source, proj, backlink);
}
}
public static void linkIcon(Project proj, String iconId, GameDataElement backlink) {
if (iconId != null) {
String spritesheetId = iconId.split(":")[0];
if (proj.getSpritesheet(spritesheetId) == null) {
Notification.addError("Error Spritesheet " + spritesheetId + ". has no backlink. (" + iconId + ")");
return;
}
proj.getSpritesheet(spritesheetId).addBacklink(backlink);
}
}
//endregion
//region write common stuff
public static void writeMinMaxToMap(Map parent, Integer min, Integer max, int defaultValue) {
if (min != null || max != null) {
if (min != null)
parent.put("min", min);
else parent.put("min", defaultValue);
if (max != null)
parent.put("max", max);
else parent.put("max", defaultValue);
}
}
public static void writeMinMaxToMap(Map parent, String key, Integer min, Integer max, int defaultValue) {
if (min != null || max != null) {
Map minMaxMap = new LinkedHashMap();
parent.put(key, minMaxMap);
writeMinMaxToMap(minMaxMap, min, max, defaultValue);
}
}
public static void writeDescriptionToMap(Map parent, String description) {
if (description != null) parent.put("description", description);
}
public static void writeIconToMap(Map parent, String icon_id) {
if (icon_id != null) parent.put("iconID", icon_id);
}
public static void writeHitReceivedEffectToMap(Map parent, HitReceivedEffect effect) {
if (effect != null) {
writeHitEffectToMap(parent, effect);
writeBasicEffectObjectToMap(effect.target, parent, "increaseAttackerCurrentHP", "increaseAttackerCurrentAP");
}
}
public static void writeHitReceivedEffectToMap(Map parent, HitReceivedEffect effect, String key) {
if (effect != null) {
Map effectJson = new LinkedHashMap();
parent.put(key, effectJson);
writeHitReceivedEffectToMap(effectJson, effect);
}
}
public static void writeHitEffectToMap(Map parent, HitEffect effect) {
if (effect != null) {
writeDeathEffectToMap(parent, effect);
writeTimedActorConditionEffectObjectToMap(effect.conditions_target, parent, "conditionsTarget");
}
}
public static void writeHitEffectToMap(Map parent, HitEffect effect, String key) {
if (effect != null) {
Map effectJson = new LinkedHashMap();
parent.put(key, effectJson);
writeHitEffectToMap(effectJson, effect);
}
}
public static void writeDeathEffectToMap(Map parent, DeathEffect effect) {
writeBasicEffectObjectToMap(effect, parent, "increaseCurrentHP", "increaseCurrentAP");
writeTimedActorConditionEffectObjectToMap(effect.conditions_source, parent, "conditionsSource");
}
public static void writeDeathEffectToMap(Map parent, DeathEffect effect, String key) {
if (effect != null) {
Map effectJson = new LinkedHashMap();
parent.put(key, effectJson);
writeDeathEffectToMap(effectJson, effect);
}
}
public static void writeBasicEffectObjectToMap(BasicEffect effect, Map parent, String keyHP, String keyAP) {
writeMinMaxToMap(parent, keyHP, effect.hp_boost_min, effect.hp_boost_max, 0);
writeMinMaxToMap(parent, keyAP, effect.ap_boost_min, effect.ap_boost_max, 0);
}
public static void writeTimedActorConditionEffectObjectToMap(List<TimedActorConditionEffect> list, Map parent, String key) {
if (list != null) {
List conditionsSourceJson = new ArrayList();
parent.put(key, conditionsSourceJson);
for (TimedActorConditionEffect condition : list) {
Map conditionJson = new LinkedHashMap();
conditionsSourceJson.add(conditionJson);
writeTimedConditionEffectToMap(condition, conditionJson);
}
}
}
public static void writeConditionEffectToMap(ActorConditionEffect condition, Map parent) {
if (condition.condition != null) {
parent.put("condition", condition.condition.id);
} else if (condition.condition_id != null) {
parent.put("condition", condition.condition_id);
}
if (condition.magnitude != null) {
parent.put("magnitude", condition.magnitude);
}
}
public static void writeTimedConditionEffectToMap(TimedActorConditionEffect condition, Map parent) {
writeConditionEffectToMap(condition, parent);
if (condition.duration != null) {
parent.put("duration", condition.duration);
}
if (condition.chance != null) {
parent.put("chance", JSONElement.printJsonChance(condition.chance));
}
}
//endregion
public static class TimedActorConditionEffect extends ActorConditionEffect {
//Available from parsed state
public Integer duration = null;
public Double chance = null;
public TimedActorConditionEffect createClone() {
TimedActorConditionEffect cclone = new TimedActorConditionEffect();
cclone.magnitude = this.magnitude;
cclone.condition_id = this.condition_id;
cclone.condition = this.condition;
cclone.chance = this.chance;
cclone.duration = this.duration;
return cclone;
}
public boolean isInfinite() {
return duration != null && duration.equals(ActorCondition.DURATION_FOREVER);
}
public boolean isImmunity() {
return (super.isClear()) && (duration != null && duration > ActorCondition.DURATION_NONE);
}
@Override
public boolean isClear() {
return (super.isClear()) && (duration == null || duration.equals(ActorCondition.DURATION_NONE));
}
}
public static class ActorConditionEffect {
//Available from parsed state
public Integer magnitude = null;
public String condition_id = null;
//Available from linked state
public ActorCondition condition = null;
public boolean isClear() {
return magnitude == null || magnitude.equals(ActorCondition.MAGNITUDE_CLEAR);
}
}
@SuppressWarnings("rawtypes")
public static ArrayList<TimedActorConditionEffect> parseTimedConditionEffects(List conditionsSourceJson) {
ArrayList<TimedActorConditionEffect> conditions_source;
if (conditionsSourceJson != null && !conditionsSourceJson.isEmpty()) {
conditions_source = new ArrayList<>();
for (Object conditionJsonObj : conditionsSourceJson) {
Map conditionJson = (Map) conditionJsonObj;
TimedActorConditionEffect condition = new TimedActorConditionEffect();
readConditionEffect(condition, conditionJson);
condition.duration = JSONElement.getInteger((Number) conditionJson.get("duration"));
if (conditionJson.get("chance") != null)
condition.chance = JSONElement.parseChance(conditionJson.get("chance").toString());
conditions_source.add(condition);
}
} else {
conditions_source = null;
}
return conditions_source;
}
@SuppressWarnings("rawtypes")
private static void readConditionEffect(ActorConditionEffect condition, Map conditionJson) {
condition.condition_id = (String) conditionJson.get("condition");
condition.magnitude = JSONElement.getInteger((Number) conditionJson.get("magnitude"));
}
@SuppressWarnings("rawtypes")
public static Common.DeathEffect parseDeathEffect(Map killEffect) {
Common.DeathEffect kill_effect = new Common.DeathEffect();
readDeathEffect(killEffect, kill_effect);
return kill_effect;
}
@SuppressWarnings("rawtypes")
public static HitEffect parseHitEffect(Map hitEffect) {
Common.HitEffect hit_effect = new Common.HitEffect();
readHitEffect(hitEffect, hit_effect);
return hit_effect;
}
@SuppressWarnings("rawtypes")
public static HitReceivedEffect parseHitReceivedEffect(Map hitReceivedEffect) {
HitReceivedEffect hit_received_effect = new Common.HitReceivedEffect();
readHitEffect(hitReceivedEffect, hit_received_effect);
if (hitReceivedEffect.get("increaseAttackerCurrentHP") != null) {
hit_received_effect.target.hp_boost_max = JSONElement.getInteger((Number) (((Map) hitReceivedEffect.get("increaseAttackerCurrentHP")).get("max")));
hit_received_effect.target.hp_boost_min = JSONElement.getInteger((Number) (((Map) hitReceivedEffect.get("increaseAttackerCurrentHP")).get("min")));
}
if (hitReceivedEffect.get("increaseAttackerCurrentAP") != null) {
hit_received_effect.target.ap_boost_max = JSONElement.getInteger((Number) (((Map) hitReceivedEffect.get("increaseAttackerCurrentAP")).get("max")));
hit_received_effect.target.ap_boost_min = JSONElement.getInteger((Number) (((Map) hitReceivedEffect.get("increaseAttackerCurrentAP")).get("min")));
}
return hit_received_effect;
}
@SuppressWarnings("rawtypes")
private static void readDeathEffect(Map killEffect, DeathEffect kill_effect) {
if (killEffect.get("increaseCurrentHP") != null) {
kill_effect.hp_boost_min = JSONElement.getInteger((Number) (((Map) killEffect.get("increaseCurrentHP")).get("min")));
kill_effect.hp_boost_max = JSONElement.getInteger((Number) (((Map) killEffect.get("increaseCurrentHP")).get("max")));
}
if (killEffect.get("increaseCurrentAP") != null) {
kill_effect.ap_boost_min = JSONElement.getInteger((Number) (((Map) killEffect.get("increaseCurrentAP")).get("min")));
kill_effect.ap_boost_max = JSONElement.getInteger((Number) (((Map) killEffect.get("increaseCurrentAP")).get("max")));
}
List conditionsSourceJson = (List) killEffect.get("conditionsSource");
kill_effect.conditions_source = parseTimedConditionEffects(conditionsSourceJson);
}
@SuppressWarnings("rawtypes")
private static void readHitEffect(Map hitEffect, HitEffect hit_effect) {
readDeathEffect(hitEffect, hit_effect);
List conditionsTargetJson = (List) hitEffect.get("conditionsTarget");
hit_effect.conditions_target = parseTimedConditionEffects(conditionsTargetJson);
}
public static class BasicEffect {
public Integer hp_boost_min = null;
public Integer hp_boost_max = null;
public Integer ap_boost_min = null;
public Integer ap_boost_max = null;
public boolean isNull() {
if (ap_boost_min != null) return false;
if (ap_boost_max != null) return false;
if (hp_boost_min != null) return false;
if (hp_boost_max != null) return false;
return true;
}
}
public static class DeathEffect extends BasicEffect {
//Available from parsed state
public List<TimedActorConditionEffect> conditions_source = null;
@Override
public boolean isNull() {
if (!super.isNull()) return false;
if (conditions_source != null) return false;
return true;
}
}
public static class HitEffect extends DeathEffect {
//Available from parsed state
public List<TimedActorConditionEffect> conditions_target = null;
@Override
public boolean isNull() {
if (!super.isNull()) return false;
if (conditions_target != null) return false;
return true;
}
}
public static class HitReceivedEffect extends Common.HitEffect {
//Available from parsed state
public BasicEffect target = new BasicEffect();
@Override
public boolean isNull() {
if (!super.isNull()) return false;
if (!target.isNull()) return false;
return true;
}
}
public static void copyDeathEffectValues(Common.DeathEffect target, Common.DeathEffect source, GameDataElement backlink) {
copyEffectValues(target, source);
if (source.conditions_source != null) {
target.conditions_source = new ArrayList<>();
for (TimedActorConditionEffect c : source.conditions_source) {
TimedActorConditionEffect cclone = c.createClone();
if (cclone.condition != null) {
cclone.condition.addBacklink(backlink);
}
target.conditions_source.add(cclone);
}
}
}
private static void copyEffectValues(BasicEffect target, BasicEffect source) {
target.ap_boost_max = source.ap_boost_max;
target.ap_boost_min = source.ap_boost_min;
target.hp_boost_max = source.hp_boost_max;
target.hp_boost_min = source.hp_boost_min;
}
public static void copyHitEffectValues(Common.HitEffect target, Common.HitEffect source, GameDataElement backlink) {
copyDeathEffectValues(target, source, backlink);
if (source.conditions_target != null) {
target.conditions_target = new ArrayList<>();
for (TimedActorConditionEffect c : source.conditions_target) {
TimedActorConditionEffect cclone = c.createClone();
if (cclone.condition != null) {
cclone.condition.addBacklink(backlink);
}
target.conditions_target.add(cclone);
}
}
}
public static void copyHitReceivedEffectValues(Common.HitReceivedEffect target, Common.HitReceivedEffect source, GameDataElement backlink) {
copyHitEffectValues(target, source, backlink);
copyEffectValues(target.target, source.target);
}
}

View File

@@ -1,19 +1,5 @@
package com.gpl.rpg.atcontentstudio.model.gamedata; package com.gpl.rpg.atcontentstudio.model.gamedata;
import java.awt.Image;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import com.gpl.rpg.atcontentstudio.Notification; import com.gpl.rpg.atcontentstudio.Notification;
import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.GameDataElement;
import com.gpl.rpg.atcontentstudio.model.GameSource; import com.gpl.rpg.atcontentstudio.model.GameSource;
@@ -21,6 +7,16 @@ import com.gpl.rpg.atcontentstudio.model.Project;
import com.gpl.rpg.atcontentstudio.model.gamedata.Requirement.RequirementType; import com.gpl.rpg.atcontentstudio.model.gamedata.Requirement.RequirementType;
import com.gpl.rpg.atcontentstudio.model.maps.TMXMap; import com.gpl.rpg.atcontentstudio.model.maps.TMXMap;
import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.awt.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import java.util.*;
public class Dialogue extends JSONElement { public class Dialogue extends JSONElement {
@@ -95,7 +91,7 @@ public class Dialogue extends JSONElement {
@Override @Override
public String getDesc() { public String getDesc() {
return (needsSaving() ? "*" : "")+id; return (needsSaving() ? "*" : "") + id;
} }
public static String getStaticDesc() { public static String getStaticDesc() {
@@ -110,7 +106,7 @@ public class Dialogue extends JSONElement {
reader = new FileReader(jsonFile); reader = new FileReader(jsonFile);
List dialogues = (List) parser.parse(reader); List dialogues = (List) parser.parse(reader);
for (Object obj : dialogues) { for (Object obj : dialogues) {
Map dialogueJson = (Map)obj; Map dialogueJson = (Map) obj;
Dialogue dialogue = fromJson(dialogueJson); Dialogue dialogue = fromJson(dialogueJson);
dialogue.jsonFile = jsonFile; dialogue.jsonFile = jsonFile;
dialogue.parent = category; dialogue.parent = category;
@@ -120,13 +116,13 @@ public class Dialogue extends JSONElement {
category.add(dialogue); category.add(dialogue);
} }
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
} catch (IOException e) { } catch (IOException e) {
Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
} catch (ParseException e) { } catch (ParseException e) {
Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
if (reader != null) if (reader != null)
@@ -162,7 +158,7 @@ public class Dialogue extends JSONElement {
if (repliesJson != null && !repliesJson.isEmpty()) { if (repliesJson != null && !repliesJson.isEmpty()) {
this.replies = new ArrayList<Dialogue.Reply>(); this.replies = new ArrayList<Dialogue.Reply>();
for (Object replyJsonObj : repliesJson) { for (Object replyJsonObj : repliesJson) {
Map replyJson = (Map)replyJsonObj; Map replyJson = (Map) replyJsonObj;
Reply reply = new Reply(); Reply reply = new Reply();
reply.text = (String) replyJson.get("text"); reply.text = (String) replyJson.get("text");
reply.next_phrase_id = (String) replyJson.get("nextPhraseID"); reply.next_phrase_id = (String) replyJson.get("nextPhraseID");
@@ -174,10 +170,13 @@ public class Dialogue extends JSONElement {
Requirement requirement = new Requirement(); Requirement requirement = new Requirement();
requirement.jsonFile = this.jsonFile; requirement.jsonFile = this.jsonFile;
requirement.parent = this; requirement.parent = this;
if (requirementJson.get("requireType") != null) requirement.type = RequirementType.valueOf((String) requirementJson.get("requireType")); if (requirementJson.get("requireType") != null)
requirement.type = RequirementType.valueOf((String) requirementJson.get("requireType"));
requirement.required_obj_id = (String) requirementJson.get("requireID"); requirement.required_obj_id = (String) requirementJson.get("requireID");
if (requirementJson.get("value") != null) requirement.required_value = JSONElement.getInteger(Integer.parseInt(requirementJson.get("value").toString())); if (requirementJson.get("value") != null)
if (requirementJson.get("negate") != null) requirement.negated = (Boolean) requirementJson.get("negate"); requirement.required_value = JSONElement.getInteger(Integer.parseInt(requirementJson.get("value").toString()));
if (requirementJson.get("negate") != null)
requirement.negated = (Boolean) requirementJson.get("negate");
requirement.state = State.parsed; requirement.state = State.parsed;
reply.requirements.add(requirement); reply.requirements.add(requirement);
} }
@@ -189,11 +188,13 @@ public class Dialogue extends JSONElement {
if (rewardsJson != null && !rewardsJson.isEmpty()) { if (rewardsJson != null && !rewardsJson.isEmpty()) {
this.rewards = new ArrayList<Dialogue.Reward>(); this.rewards = new ArrayList<Dialogue.Reward>();
for (Object rewardJsonObj : rewardsJson) { for (Object rewardJsonObj : rewardsJson) {
Map rewardJson = (Map)rewardJsonObj; Map rewardJson = (Map) rewardJsonObj;
Reward reward = new Reward(); Reward reward = new Reward();
if (rewardJson.get("rewardType") != null) reward.type = Reward.RewardType.valueOf((String) rewardJson.get("rewardType")); if (rewardJson.get("rewardType") != null)
reward.type = Reward.RewardType.valueOf((String) rewardJson.get("rewardType"));
if (rewardJson.get("rewardID") != null) reward.reward_obj_id = (String) rewardJson.get("rewardID"); if (rewardJson.get("rewardID") != null) reward.reward_obj_id = (String) rewardJson.get("rewardID");
if (rewardJson.get("value") != null) reward.reward_value = JSONElement.getInteger((Number) rewardJson.get("value")); if (rewardJson.get("value") != null)
reward.reward_value = JSONElement.getInteger((Number) rewardJson.get("value"));
if (rewardJson.get("mapName") != null) reward.map_name = (String) rewardJson.get("mapName"); if (rewardJson.get("mapName") != null) reward.map_name = (String) rewardJson.get("mapName");
this.rewards.add(reward); this.rewards.add(reward);
} }
@@ -202,24 +203,15 @@ public class Dialogue extends JSONElement {
} }
@Override @Override
public void link() { public void link() {
if (this.state == State.created || this.state == State.modified || this.state == State.saved) { if (shouldSkipParseOrLink()) {
//This type of state is unrelated to parsing/linking.
return;
}
if (this.state == State.init) {
//Not parsed yet.
this.parse();
} else if (this.state == State.linked) {
//Already linked.
return; return;
} }
ensureParseIfNeeded();
Project proj = getProject(); Project proj = getProject();
if (proj == null) { if (proj == null) {
Notification.addError("Error linking dialogue "+id+". No parent project found."); Notification.addError("Error linking dialogue " + id + ". No parent project found.");
return; return;
} }
if (this.switch_to_npc_id != null) this.switch_to_npc = proj.getNPC(this.switch_to_npc_id); if (this.switch_to_npc_id != null) this.switch_to_npc = proj.getNPC(this.switch_to_npc_id);
@@ -274,7 +266,7 @@ public class Dialogue extends JSONElement {
case removeQuestProgress: case removeQuestProgress:
reward.reward_obj = proj.getQuest(reward.reward_obj_id); reward.reward_obj = proj.getQuest(reward.reward_obj_id);
if (reward.reward_obj != null && reward.reward_value != null) { if (reward.reward_obj != null && reward.reward_value != null) {
QuestStage stage = ((Quest)reward.reward_obj).getStage(reward.reward_value); QuestStage stage = ((Quest) reward.reward_obj).getStage(reward.reward_value);
if (stage != null) { if (stage != null) {
stage.addBacklink(this); stage.addBacklink(this);
} }
@@ -294,7 +286,6 @@ public class Dialogue extends JSONElement {
} }
@Override @Override
public Image getIcon() { public Image getIcon() {
return DefaultIcons.getDialogueIcon(); return DefaultIcons.getDialogueIcon();
@@ -398,7 +389,7 @@ public class Dialogue extends JSONElement {
} }
} }
@SuppressWarnings({ "rawtypes", "unchecked" }) @SuppressWarnings({"rawtypes", "unchecked"})
@Override @Override
public Map toJson() { public Map toJson() {
Map dialogueJson = new LinkedHashMap(); Map dialogueJson = new LinkedHashMap();
@@ -412,7 +403,7 @@ public class Dialogue extends JSONElement {
if (this.replies != null) { if (this.replies != null) {
List repliesJson = new ArrayList(); List repliesJson = new ArrayList();
dialogueJson.put("replies", repliesJson); dialogueJson.put("replies", repliesJson);
for (Reply reply : this.replies){ for (Reply reply : this.replies) {
Map replyJson = new LinkedHashMap(); Map replyJson = new LinkedHashMap();
repliesJson.add(replyJson); repliesJson.add(replyJson);
if (reply.text != null) replyJson.put("text", reply.text); if (reply.text != null) replyJson.put("text", reply.text);
@@ -464,7 +455,7 @@ public class Dialogue extends JSONElement {
@Override @Override
public String getProjectFilename() { public String getProjectFilename() {
return "conversationlist_"+getProject().name+".json"; return "conversationlist_" + getProject().name + ".json";
} }
} }

View File

@@ -1,6 +1,14 @@
package com.gpl.rpg.atcontentstudio.model.gamedata; package com.gpl.rpg.atcontentstudio.model.gamedata;
import java.awt.Image; import com.gpl.rpg.atcontentstudio.Notification;
import com.gpl.rpg.atcontentstudio.model.GameDataElement;
import com.gpl.rpg.atcontentstudio.model.GameSource;
import com.gpl.rpg.atcontentstudio.model.Project;
import com.gpl.rpg.atcontentstudio.ui.DefaultIcons;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.awt.*;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.FileReader; import java.io.FileReader;
@@ -10,15 +18,6 @@ import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import com.gpl.rpg.atcontentstudio.Notification;
import com.gpl.rpg.atcontentstudio.model.GameDataElement;
import com.gpl.rpg.atcontentstudio.model.GameSource;
import com.gpl.rpg.atcontentstudio.model.Project;
import com.gpl.rpg.atcontentstudio.ui.DefaultIcons;
public class Droplist extends JSONElement { public class Droplist extends JSONElement {
@@ -46,7 +45,7 @@ public class Droplist extends JSONElement {
@Override @Override
public String getDesc() { public String getDesc() {
return (needsSaving() ? "*" : "")+id; return (needsSaving() ? "*" : "") + id;
} }
public static String getStaticDesc() { public static String getStaticDesc() {
@@ -61,7 +60,7 @@ public class Droplist extends JSONElement {
reader = new FileReader(jsonFile); reader = new FileReader(jsonFile);
List droplists = (List) parser.parse(reader); List droplists = (List) parser.parse(reader);
for (Object obj : droplists) { for (Object obj : droplists) {
Map droplistJson = (Map)obj; Map droplistJson = (Map) obj;
Droplist droplist = fromJson(droplistJson); Droplist droplist = fromJson(droplistJson);
droplist.jsonFile = jsonFile; droplist.jsonFile = jsonFile;
droplist.parent = category; droplist.parent = category;
@@ -71,13 +70,13 @@ public class Droplist extends JSONElement {
category.add(droplist); category.add(droplist);
} }
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
} catch (IOException e) { } catch (IOException e) {
Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
} catch (ParseException e) { } catch (ParseException e) {
Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
if (reader != null) if (reader != null)
@@ -111,7 +110,7 @@ public class Droplist extends JSONElement {
if (droppedItemsJson != null && !droppedItemsJson.isEmpty()) { if (droppedItemsJson != null && !droppedItemsJson.isEmpty()) {
this.dropped_items = new ArrayList<DroppedItem>(); this.dropped_items = new ArrayList<DroppedItem>();
for (Object droppedItemJsonObj : droppedItemsJson) { for (Object droppedItemJsonObj : droppedItemsJson) {
Map droppedItemJson = (Map)droppedItemJsonObj; Map droppedItemJson = (Map) droppedItemJsonObj;
DroppedItem droppedItem = new DroppedItem(); DroppedItem droppedItem = new DroppedItem();
droppedItem.item_id = (String) droppedItemJson.get("itemID"); droppedItem.item_id = (String) droppedItemJson.get("itemID");
//if (droppedItemJson.get("chance") != null) droppedItem.chance = JSONElement.parseChance(droppedItemJson.get("chance").toString()); //if (droppedItemJson.get("chance") != null) droppedItem.chance = JSONElement.parseChance(droppedItemJson.get("chance").toString());
@@ -129,20 +128,13 @@ public class Droplist extends JSONElement {
@Override @Override
public void link() { public void link() {
if (this.state == State.created || this.state == State.modified || this.state == State.saved) { if (shouldSkipParseOrLink()) {
//This type of state is unrelated to parsing/linking.
return;
}
if (this.state == State.init) {
//Not parsed yet.
this.parse();
} else if (this.state == State.linked) {
//Already linked.
return; return;
} }
ensureParseIfNeeded();
Project proj = getProject(); Project proj = getProject();
if (proj == null) { if (proj == null) {
Notification.addError("Error linking droplist "+id+". No parent project found."); Notification.addError("Error linking droplist " + id + ". No parent project found.");
return; return;
} }
if (dropped_items != null) { if (dropped_items != null) {
@@ -155,7 +147,6 @@ public class Droplist extends JSONElement {
} }
public static Image getImage() { public static Image getImage() {
return DefaultIcons.getDroplistImage(); return DefaultIcons.getDroplistImage();
} }
@@ -202,7 +193,7 @@ public class Droplist extends JSONElement {
} }
} }
@SuppressWarnings({ "rawtypes", "unchecked" }) @SuppressWarnings({"rawtypes", "unchecked"})
@Override @Override
public Map toJson() { public Map toJson() {
Map droplistJson = new LinkedHashMap(); Map droplistJson = new LinkedHashMap();
@@ -236,7 +227,7 @@ public class Droplist extends JSONElement {
@Override @Override
public String getProjectFilename() { public String getProjectFilename() {
return "droplists_"+getProject().name+".json"; return "droplists_" + getProject().name + ".json";
} }
} }

View File

@@ -1,31 +1,18 @@
package com.gpl.rpg.atcontentstudio.model.gamedata; package com.gpl.rpg.atcontentstudio.model.gamedata;
import java.awt.Image;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Serializable;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.swing.tree.TreeNode;
import org.json.simple.JSONArray;
import com.gpl.rpg.atcontentstudio.Notification; import com.gpl.rpg.atcontentstudio.Notification;
import com.gpl.rpg.atcontentstudio.io.JsonPrettyWriter; import com.gpl.rpg.atcontentstudio.io.JsonPrettyWriter;
import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.*;
import com.gpl.rpg.atcontentstudio.model.GameSource;
import com.gpl.rpg.atcontentstudio.model.GameSource.Type; import com.gpl.rpg.atcontentstudio.model.GameSource.Type;
import com.gpl.rpg.atcontentstudio.model.Project;
import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode;
import com.gpl.rpg.atcontentstudio.model.SaveEvent;
import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons;
import com.gpl.rpg.atcontentstudio.utils.FileUtils;
import org.json.simple.JSONArray;
import javax.swing.tree.TreeNode;
import java.awt.*;
import java.io.*;
import java.util.List;
import java.util.*;
public class GameDataCategory<E extends JSONElement> extends ArrayList<E> implements ProjectTreeNode, Serializable { public class GameDataCategory<E extends JSONElement> extends ArrayList<E> implements ProjectTreeNode, Serializable {
@@ -74,16 +61,19 @@ public class GameDataCategory<E extends JSONElement> extends ArrayList<E> implem
public Enumeration<E> children() { public Enumeration<E> children() {
return Collections.enumeration(this); return Collections.enumeration(this);
} }
@Override @Override
public void childrenAdded(List<ProjectTreeNode> path) { public void childrenAdded(List<ProjectTreeNode> path) {
path.add(0, this); path.add(0, this);
parent.childrenAdded(path); parent.childrenAdded(path);
} }
@Override @Override
public void childrenChanged(List<ProjectTreeNode> path) { public void childrenChanged(List<ProjectTreeNode> path) {
path.add(0, this); path.add(0, this);
parent.childrenChanged(path); parent.childrenChanged(path);
} }
@Override @Override
public void childrenRemoved(List<ProjectTreeNode> path) { public void childrenRemoved(List<ProjectTreeNode> path) {
if (path.size() == 1 && this.getChildCount() == 1) { if (path.size() == 1 && this.getChildCount() == 1) {
@@ -93,6 +83,7 @@ public class GameDataCategory<E extends JSONElement> extends ArrayList<E> implem
parent.childrenRemoved(path); parent.childrenRemoved(path);
} }
} }
@Override @Override
public void notifyCreated() { public void notifyCreated() {
childrenAdded(new ArrayList<ProjectTreeNode>()); childrenAdded(new ArrayList<ProjectTreeNode>());
@@ -100,9 +91,10 @@ public class GameDataCategory<E extends JSONElement> extends ArrayList<E> implem
node.notifyCreated(); node.notifyCreated();
} }
} }
@Override @Override
public String getDesc() { public String getDesc() {
return (needsSaving() ? "*" : "")+this.name; return (needsSaving() ? "*" : "") + this.name;
} }
@Override @Override
@@ -119,14 +111,17 @@ public class GameDataCategory<E extends JSONElement> extends ArrayList<E> implem
public Image getIcon() { public Image getIcon() {
return getOpenIcon(); return getOpenIcon();
} }
@Override @Override
public Image getClosedIcon() { public Image getClosedIcon() {
return DefaultIcons.getJsonClosedIcon(); return DefaultIcons.getJsonClosedIcon();
} }
@Override @Override
public Image getLeafIcon() { public Image getLeafIcon() {
return DefaultIcons.getJsonClosedIcon(); return DefaultIcons.getJsonClosedIcon();
} }
@Override @Override
public Image getOpenIcon() { public Image getOpenIcon() {
return DefaultIcons.getJsonOpenIcon(); return DefaultIcons.getJsonOpenIcon();
@@ -145,7 +140,7 @@ public class GameDataCategory<E extends JSONElement> extends ArrayList<E> implem
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
public void save(File jsonFile) { public void save(File jsonFile) {
if (getDataType() != GameSource.Type.created && getDataType() != GameSource.Type.altered) { if (getDataType() != GameSource.Type.created && getDataType() != GameSource.Type.altered) {
Notification.addError("Error while trying to write json file "+jsonFile.getAbsolutePath()+" : Game Source type "+getDataType().toString()+" should not be saved."); Notification.addError("Error while trying to write json file " + jsonFile.getAbsolutePath() + " : Game Source type " + getDataType().toString() + " should not be saved.");
return; return;
} }
List<Map> dataToSave = new ArrayList<Map>(); List<Map> dataToSave = new ArrayList<Map>();
@@ -156,33 +151,20 @@ public class GameDataCategory<E extends JSONElement> extends ArrayList<E> implem
} }
if (dataToSave.isEmpty() && jsonFile.exists()) { if (dataToSave.isEmpty() && jsonFile.exists()) {
if (jsonFile.delete()) { if (jsonFile.delete()) {
Notification.addSuccess("File "+jsonFile.getAbsolutePath()+" deleted."); Notification.addSuccess("File " + jsonFile.getAbsolutePath() + " deleted.");
} else { } else {
Notification.addError("Error deleting file "+jsonFile.getAbsolutePath()); Notification.addError("Error deleting file " + jsonFile.getAbsolutePath());
} }
return; return;
} }
StringWriter writer = new JsonPrettyWriter();
try { String toWrite = FileUtils.toJsonString(dataToSave);
JSONArray.writeJSONString(dataToSave, writer); if(FileUtils.writeStringToFile(toWrite, jsonFile, "JSON file '"+jsonFile.getAbsolutePath()+"'")){
} catch (IOException e) {
//Impossible with a StringWriter
}
String toWrite = writer.toString();
try {
FileWriter w = new FileWriter(jsonFile);
w.write(toWrite);
w.close();
for (E element : this) { for (E element : this) {
element.state = GameDataElement.State.saved; element.state = GameDataElement.State.saved;
} }
Notification.addSuccess("Json file "+jsonFile.getAbsolutePath()+" saved.");
} catch (IOException e) {
Notification.addError("Error while writing json file "+jsonFile.getAbsolutePath()+" : "+e.getMessage());
e.printStackTrace();
} }
} }
@@ -226,7 +208,8 @@ public class GameDataCategory<E extends JSONElement> extends ArrayList<E> implem
break; break;
} }
} }
events.add(new SaveEvent(SaveEvent.Type.alsoSave, node, true, "There are "+containedIds.get(node.id)+" elements with this ID in this category. Change the conflicting IDs before saving.")); events.add(new SaveEvent(SaveEvent.Type.alsoSave, node, true,
"There are " + containedIds.get(node.id) + " elements with this ID in this category. Change the conflicting IDs before saving."));
} }
} }
if (checkImpactedCategory && impactedCategory != null) { if (checkImpactedCategory && impactedCategory != null) {

View File

@@ -1,14 +1,5 @@
package com.gpl.rpg.atcontentstudio.model.gamedata; package com.gpl.rpg.atcontentstudio.model.gamedata;
import java.awt.Image;
import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import javax.swing.tree.TreeNode;
import com.gpl.rpg.atcontentstudio.Notification; import com.gpl.rpg.atcontentstudio.Notification;
import com.gpl.rpg.atcontentstudio.model.GameSource; import com.gpl.rpg.atcontentstudio.model.GameSource;
import com.gpl.rpg.atcontentstudio.model.GameSource.Type; import com.gpl.rpg.atcontentstudio.model.GameSource.Type;
@@ -18,13 +9,21 @@ import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode;
import com.gpl.rpg.atcontentstudio.model.SavedSlotCollection; import com.gpl.rpg.atcontentstudio.model.SavedSlotCollection;
import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons;
import javax.swing.tree.TreeNode;
import java.awt.*;
import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
public class GameDataSet implements ProjectTreeNode, Serializable { public class GameDataSet implements ProjectTreeNode, Serializable {
private static final long serialVersionUID = -8558067213826970968L; private static final long serialVersionUID = -8558067213826970968L;
public static final String DEFAULT_REL_PATH_IN_SOURCE = "res"+File.separator+"raw"+File.separator; public static final String DEFAULT_REL_PATH_IN_SOURCE = "res" + File.separator + "raw" + File.separator;
public static final String DEFAULT_REL_PATH_IN_PROJECT = "json"+File.separator; public static final String DEFAULT_REL_PATH_IN_PROJECT = "json" + File.separator;
public static final String GAME_AC_ARRAY_NAME = "loadresource_actorconditions"; public static final String GAME_AC_ARRAY_NAME = "loadresource_actorconditions";
public static final String GAME_DIALOGUES_ARRAY_NAME = "loadresource_conversationlists"; public static final String GAME_DIALOGUES_ARRAY_NAME = "loadresource_conversationlists";
@@ -82,79 +81,79 @@ public class GameDataSet implements ProjectTreeNode, Serializable {
if (parent.type == GameSource.Type.source && (parent.parent.sourceSetToUse == ResourceSet.debugData || parent.parent.sourceSetToUse == ResourceSet.gameData)) { if (parent.type == GameSource.Type.source && (parent.parent.sourceSetToUse == ResourceSet.debugData || parent.parent.sourceSetToUse == ResourceSet.gameData)) {
String suffix = (parent.parent.sourceSetToUse == ResourceSet.debugData) ? DEBUG_SUFFIX : ""; String suffix = (parent.parent.sourceSetToUse == ResourceSet.debugData) ? DEBUG_SUFFIX : "";
if (parent.referencedSourceFiles.get(GAME_AC_ARRAY_NAME+suffix) != null) { if (parent.referencedSourceFiles.get(GAME_AC_ARRAY_NAME + suffix) != null) {
for (String resource : parent.referencedSourceFiles.get(GAME_AC_ARRAY_NAME+suffix)) { for (String resource : parent.referencedSourceFiles.get(GAME_AC_ARRAY_NAME + suffix)) {
File f = new File(baseFolder, resource.replaceAll(RESOURCE_PREFIX, "")+FILENAME_SUFFIX); File f = new File(baseFolder, resource.replaceAll(RESOURCE_PREFIX, "") + FILENAME_SUFFIX);
if (f.exists()) { if (f.exists()) {
ActorCondition.fromJson(f, actorConditions); ActorCondition.fromJson(f, actorConditions);
} else { } else {
Notification.addWarn("Unable to locate resource "+resource+" in the game source for project "+getProject().name); Notification.addWarn("Unable to locate resource " + resource + " in the game source for project " + getProject().name);
} }
} }
} }
if (parent.referencedSourceFiles.get(GAME_DIALOGUES_ARRAY_NAME+suffix) != null) { if (parent.referencedSourceFiles.get(GAME_DIALOGUES_ARRAY_NAME + suffix) != null) {
for (String resource : parent.referencedSourceFiles.get(GAME_DIALOGUES_ARRAY_NAME+suffix)) { for (String resource : parent.referencedSourceFiles.get(GAME_DIALOGUES_ARRAY_NAME + suffix)) {
File f = new File(baseFolder, resource.replaceAll(RESOURCE_PREFIX, "")+FILENAME_SUFFIX); File f = new File(baseFolder, resource.replaceAll(RESOURCE_PREFIX, "") + FILENAME_SUFFIX);
if (f.exists()) { if (f.exists()) {
Dialogue.fromJson(f, dialogues); Dialogue.fromJson(f, dialogues);
} else { } else {
Notification.addWarn("Unable to locate resource "+resource+" in the game source for project "+getProject().name); Notification.addWarn("Unable to locate resource " + resource + " in the game source for project " + getProject().name);
} }
} }
} }
if (parent.referencedSourceFiles.get(GAME_DROPLISTS_ARRAY_NAME+suffix) != null) { if (parent.referencedSourceFiles.get(GAME_DROPLISTS_ARRAY_NAME + suffix) != null) {
for (String resource : parent.referencedSourceFiles.get(GAME_DROPLISTS_ARRAY_NAME+suffix)) { for (String resource : parent.referencedSourceFiles.get(GAME_DROPLISTS_ARRAY_NAME + suffix)) {
File f = new File(baseFolder, resource.replaceAll(RESOURCE_PREFIX, "")+FILENAME_SUFFIX); File f = new File(baseFolder, resource.replaceAll(RESOURCE_PREFIX, "") + FILENAME_SUFFIX);
if (f.exists()) { if (f.exists()) {
Droplist.fromJson(f, droplists); Droplist.fromJson(f, droplists);
} else { } else {
Notification.addWarn("Unable to locate resource "+resource+" in the game source for project "+getProject().name); Notification.addWarn("Unable to locate resource " + resource + " in the game source for project " + getProject().name);
} }
} }
} }
if (parent.referencedSourceFiles.get(GAME_ITEMS_ARRAY_NAME+suffix) != null) { if (parent.referencedSourceFiles.get(GAME_ITEMS_ARRAY_NAME + suffix) != null) {
for (String resource : parent.referencedSourceFiles.get(GAME_ITEMS_ARRAY_NAME+suffix)) { for (String resource : parent.referencedSourceFiles.get(GAME_ITEMS_ARRAY_NAME + suffix)) {
File f = new File(baseFolder, resource.replaceAll(RESOURCE_PREFIX, "")+FILENAME_SUFFIX); File f = new File(baseFolder, resource.replaceAll(RESOURCE_PREFIX, "") + FILENAME_SUFFIX);
if (f.exists()) { if (f.exists()) {
Item.fromJson(f, items); Item.fromJson(f, items);
} else { } else {
Notification.addWarn("Unable to locate resource "+resource+" in the game source for project "+getProject().name); Notification.addWarn("Unable to locate resource " + resource + " in the game source for project " + getProject().name);
} }
} }
} }
if (parent.referencedSourceFiles.get(GAME_ITEMCAT_ARRAY_NAME+suffix) != null) { if (parent.referencedSourceFiles.get(GAME_ITEMCAT_ARRAY_NAME + suffix) != null) {
for (String resource : parent.referencedSourceFiles.get(GAME_ITEMCAT_ARRAY_NAME+suffix)) { for (String resource : parent.referencedSourceFiles.get(GAME_ITEMCAT_ARRAY_NAME + suffix)) {
File f = new File(baseFolder, resource.replaceAll(RESOURCE_PREFIX, "")+FILENAME_SUFFIX); File f = new File(baseFolder, resource.replaceAll(RESOURCE_PREFIX, "") + FILENAME_SUFFIX);
if (f.exists()) { if (f.exists()) {
ItemCategory.fromJson(f, itemCategories); ItemCategory.fromJson(f, itemCategories);
} else { } else {
Notification.addWarn("Unable to locate resource "+resource+" in the game source for project "+getProject().name); Notification.addWarn("Unable to locate resource " + resource + " in the game source for project " + getProject().name);
} }
} }
} }
if (parent.referencedSourceFiles.get(GAME_NPC_ARRAY_NAME+suffix) != null) { if (parent.referencedSourceFiles.get(GAME_NPC_ARRAY_NAME + suffix) != null) {
for (String resource : parent.referencedSourceFiles.get(GAME_NPC_ARRAY_NAME+suffix)) { for (String resource : parent.referencedSourceFiles.get(GAME_NPC_ARRAY_NAME + suffix)) {
File f = new File(baseFolder, resource.replaceAll(RESOURCE_PREFIX, "")+FILENAME_SUFFIX); File f = new File(baseFolder, resource.replaceAll(RESOURCE_PREFIX, "") + FILENAME_SUFFIX);
if (f.exists()) { if (f.exists()) {
NPC.fromJson(f, npcs); NPC.fromJson(f, npcs);
} else { } else {
Notification.addWarn("Unable to locate resource "+resource+" in the game source for project "+getProject().name); Notification.addWarn("Unable to locate resource " + resource + " in the game source for project " + getProject().name);
} }
} }
} }
if (parent.referencedSourceFiles.get(GAME_QUESTS_ARRAY_NAME+suffix) != null) { if (parent.referencedSourceFiles.get(GAME_QUESTS_ARRAY_NAME + suffix) != null) {
for (String resource : parent.referencedSourceFiles.get(GAME_QUESTS_ARRAY_NAME+suffix)) { for (String resource : parent.referencedSourceFiles.get(GAME_QUESTS_ARRAY_NAME + suffix)) {
File f = new File(baseFolder, resource.replaceAll(RESOURCE_PREFIX, "")+FILENAME_SUFFIX); File f = new File(baseFolder, resource.replaceAll(RESOURCE_PREFIX, "") + FILENAME_SUFFIX);
if (f.exists()) { if (f.exists()) {
Quest.fromJson(f, quests); Quest.fromJson(f, quests);
} else { } else {
Notification.addWarn("Unable to locate resource "+resource+" in the game source for project "+getProject().name); Notification.addWarn("Unable to locate resource " + resource + " in the game source for project " + getProject().name);
} }
} }
} }
@@ -184,40 +183,49 @@ public class GameDataSet implements ProjectTreeNode, Serializable {
public Enumeration<ProjectTreeNode> children() { public Enumeration<ProjectTreeNode> children() {
return v.getNonEmptyElements(); return v.getNonEmptyElements();
} }
@Override @Override
public boolean getAllowsChildren() { public boolean getAllowsChildren() {
return true; return true;
} }
@Override @Override
public TreeNode getChildAt(int arg0) { public TreeNode getChildAt(int arg0) {
return v.getNonEmptyElementAt(arg0); return v.getNonEmptyElementAt(arg0);
} }
@Override @Override
public int getChildCount() { public int getChildCount() {
return v.getNonEmptySize(); return v.getNonEmptySize();
} }
@Override @Override
public int getIndex(TreeNode arg0) { public int getIndex(TreeNode arg0) {
return v.getNonEmptyIndexOf((ProjectTreeNode) arg0); return v.getNonEmptyIndexOf((ProjectTreeNode) arg0);
} }
@Override @Override
public TreeNode getParent() { public TreeNode getParent() {
return parent; return parent;
} }
@Override @Override
public boolean isLeaf() { public boolean isLeaf() {
return false; return false;
} }
@Override @Override
public void childrenAdded(List<ProjectTreeNode> path) { public void childrenAdded(List<ProjectTreeNode> path) {
path.add(0, this); path.add(0, this);
parent.childrenAdded(path); parent.childrenAdded(path);
} }
@Override @Override
public void childrenChanged(List<ProjectTreeNode> path) { public void childrenChanged(List<ProjectTreeNode> path) {
path.add(0, this); path.add(0, this);
parent.childrenChanged(path); parent.childrenChanged(path);
} }
@Override @Override
public void childrenRemoved(List<ProjectTreeNode> path) { public void childrenRemoved(List<ProjectTreeNode> path) {
if (path.size() == 1 && this.v.getNonEmptySize() == 1) { if (path.size() == 1 && this.v.getNonEmptySize() == 1) {
@@ -227,6 +235,7 @@ public class GameDataSet implements ProjectTreeNode, Serializable {
parent.childrenRemoved(path); parent.childrenRemoved(path);
} }
} }
@Override @Override
public void notifyCreated() { public void notifyCreated() {
childrenAdded(new ArrayList<ProjectTreeNode>()); childrenAdded(new ArrayList<ProjectTreeNode>());
@@ -234,9 +243,10 @@ public class GameDataSet implements ProjectTreeNode, Serializable {
node.notifyCreated(); node.notifyCreated();
} }
} }
@Override @Override
public String getDesc() { public String getDesc() {
return (needsSaving() ? "*" : "")+"JSON data"; return (needsSaving() ? "*" : "") + "JSON data";
} }
@@ -247,7 +257,7 @@ public class GameDataSet implements ProjectTreeNode, Serializable {
public ActorCondition getActorCondition(String id) { public ActorCondition getActorCondition(String id) {
if (actorConditions == null) return null; if (actorConditions == null) return null;
for (ActorCondition gde : actorConditions) { for (ActorCondition gde : actorConditions) {
if (id.equals(gde.id)){ if (id.equals(gde.id)) {
return gde; return gde;
} }
} }
@@ -257,7 +267,7 @@ public class GameDataSet implements ProjectTreeNode, Serializable {
public Dialogue getDialogue(String id) { public Dialogue getDialogue(String id) {
if (dialogues == null) return null; if (dialogues == null) return null;
for (Dialogue gde : dialogues) { for (Dialogue gde : dialogues) {
if (id.equals(gde.id)){ if (id.equals(gde.id)) {
return gde; return gde;
} }
} }
@@ -267,7 +277,7 @@ public class GameDataSet implements ProjectTreeNode, Serializable {
public Droplist getDroplist(String id) { public Droplist getDroplist(String id) {
if (droplists == null) return null; if (droplists == null) return null;
for (Droplist gde : droplists) { for (Droplist gde : droplists) {
if (id.equals(gde.id)){ if (id.equals(gde.id)) {
return gde; return gde;
} }
} }
@@ -277,7 +287,7 @@ public class GameDataSet implements ProjectTreeNode, Serializable {
public Item getItem(String id) { public Item getItem(String id) {
if (items == null) return null; if (items == null) return null;
for (Item gde : items) { for (Item gde : items) {
if (id.equals(gde.id)){ if (id.equals(gde.id)) {
return gde; return gde;
} }
} }
@@ -287,7 +297,7 @@ public class GameDataSet implements ProjectTreeNode, Serializable {
public ItemCategory getItemCategory(String id) { public ItemCategory getItemCategory(String id) {
if (itemCategories == null) return null; if (itemCategories == null) return null;
for (ItemCategory gde : itemCategories) { for (ItemCategory gde : itemCategories) {
if (id.equals(gde.id)){ if (id.equals(gde.id)) {
return gde; return gde;
} }
} }
@@ -297,7 +307,7 @@ public class GameDataSet implements ProjectTreeNode, Serializable {
public NPC getNPC(String id) { public NPC getNPC(String id) {
if (npcs == null) return null; if (npcs == null) return null;
for (NPC gde : npcs) { for (NPC gde : npcs) {
if (id.equals(gde.id)){ if (id.equals(gde.id)) {
return gde; return gde;
} }
} }
@@ -307,7 +317,7 @@ public class GameDataSet implements ProjectTreeNode, Serializable {
public NPC getNPCIgnoreCase(String id) { public NPC getNPCIgnoreCase(String id) {
if (npcs == null) return null; if (npcs == null) return null;
for (NPC gde : npcs) { for (NPC gde : npcs) {
if (id.equalsIgnoreCase(gde.id)){ if (id.equalsIgnoreCase(gde.id)) {
return gde; return gde;
} }
} }
@@ -317,7 +327,7 @@ public class GameDataSet implements ProjectTreeNode, Serializable {
public Quest getQuest(String id) { public Quest getQuest(String id) {
if (quests == null) return null; if (quests == null) return null;
for (Quest gde : quests) { for (Quest gde : quests) {
if (id.equals(gde.id)){ if (id.equals(gde.id)) {
return gde; return gde;
} }
} }
@@ -334,14 +344,17 @@ public class GameDataSet implements ProjectTreeNode, Serializable {
public Image getIcon() { public Image getIcon() {
return getOpenIcon(); return getOpenIcon();
} }
@Override @Override
public Image getClosedIcon() { public Image getClosedIcon() {
return DefaultIcons.getJsonClosedIcon(); return DefaultIcons.getJsonClosedIcon();
} }
@Override @Override
public Image getLeafIcon() { public Image getLeafIcon() {
return DefaultIcons.getJsonClosedIcon(); return DefaultIcons.getJsonClosedIcon();
} }
@Override @Override
public Image getOpenIcon() { public Image getOpenIcon() {
return DefaultIcons.getJsonOpenIcon(); return DefaultIcons.getJsonOpenIcon();
@@ -350,7 +363,8 @@ public class GameDataSet implements ProjectTreeNode, Serializable {
public void addElement(JSONElement node) { public void addElement(JSONElement node) {
ProjectTreeNode higherEmptyParent = this; ProjectTreeNode higherEmptyParent = this;
while (higherEmptyParent != null) { while (higherEmptyParent != null) {
if (higherEmptyParent.getParent() != null && ((ProjectTreeNode)higherEmptyParent.getParent()).isEmpty()) higherEmptyParent = (ProjectTreeNode)higherEmptyParent.getParent(); if (higherEmptyParent.getParent() != null && ((ProjectTreeNode) higherEmptyParent.getParent()).isEmpty())
higherEmptyParent = (ProjectTreeNode) higherEmptyParent.getParent();
else break; else break;
} }
if (higherEmptyParent == this && !this.isEmpty()) higherEmptyParent = null; if (higherEmptyParent == this && !this.isEmpty()) higherEmptyParent = null;
@@ -383,7 +397,7 @@ public class GameDataSet implements ProjectTreeNode, Serializable {
quests.add((Quest) node); quests.add((Quest) node);
node.parent = quests; node.parent = quests;
} else { } else {
Notification.addError("Cannot add "+node.getDesc()+". Unknown data type."); Notification.addError("Cannot add " + node.getDesc() + ". Unknown data type.");
return; return;
} }
if (node.jsonFile != null && parent.type == GameSource.Type.altered) { if (node.jsonFile != null && parent.type == GameSource.Type.altered) {

View File

@@ -1,6 +1,13 @@
package com.gpl.rpg.atcontentstudio.model.gamedata; package com.gpl.rpg.atcontentstudio.model.gamedata;
import java.awt.Image; import com.gpl.rpg.atcontentstudio.Notification;
import com.gpl.rpg.atcontentstudio.model.GameDataElement;
import com.gpl.rpg.atcontentstudio.model.GameSource;
import com.gpl.rpg.atcontentstudio.model.Project;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.awt.*;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.FileReader; import java.io.FileReader;
@@ -10,13 +17,7 @@ import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.json.simple.parser.JSONParser; import static com.gpl.rpg.atcontentstudio.model.gamedata.Common.*;
import org.json.simple.parser.ParseException;
import com.gpl.rpg.atcontentstudio.Notification;
import com.gpl.rpg.atcontentstudio.model.GameDataElement;
import com.gpl.rpg.atcontentstudio.model.GameSource;
import com.gpl.rpg.atcontentstudio.model.Project;
public class Item extends JSONElement { public class Item extends JSONElement {
@@ -35,45 +36,20 @@ public class Item extends JSONElement {
public String description = null; public String description = null;
public HitEffect hit_effect = null; public HitEffect hit_effect = null;
public HitReceivedEffect hit_received_effect = null; public HitReceivedEffect hit_received_effect = null;
public KillEffect kill_effect = null; public DeathEffect kill_effect = null;
public EquipEffect equip_effect = null; public EquipEffect equip_effect = null;
//Available from linked state //Available from linked state
public ItemCategory category = null; public ItemCategory category = null;
public static class KillEffect {
//Available from parsed state
public Integer hp_boost_min = null;
public Integer hp_boost_max = null;
public Integer ap_boost_min = null;
public Integer ap_boost_max = null;
public List<TimedConditionEffect> conditions_source = null;
}
//Inheritance for code compactness, not semantically correct.
public static class HitEffect extends KillEffect {
//Available from parsed state
public List<TimedConditionEffect> conditions_target = null;
}
public static class HitReceivedEffect extends HitEffect {
//Available from parsed state
public Integer hp_boost_min_target = null;
public Integer hp_boost_max_target = null;
public Integer ap_boost_min_target = null;
public Integer ap_boost_max_target = null;
}
public static class EquipEffect { public static class EquipEffect {
//Available from parsed state //Available from parsed state
public Integer damage_boost_min = null; public Integer damage_boost_min = null;
public Integer damage_boost_max = null; public Integer damage_boost_max = null;
public Integer max_hp_boost = null; public Integer max_hp_boost = null;
public Integer max_ap_boost = null; public Integer max_ap_boost = null;
public List<ConditionEffect> conditions = null; public List<ActorConditionEffect> conditions = null;
public Integer increase_move_cost = null; public Integer increase_move_cost = null;
public Integer increase_use_item_cost = null; public Integer increase_use_item_cost = null;
public Integer increase_reequip_cost = null; public Integer increase_reequip_cost = null;
@@ -86,20 +62,6 @@ public class Item extends JSONElement {
public Integer damage_modifier = null; public Integer damage_modifier = null;
} }
public static class ConditionEffect {
//Available from parsed state
public Integer magnitude = null;
public String condition_id = null;
//Available from linked state
public ActorCondition condition = null;
}
public static class TimedConditionEffect extends ConditionEffect {
//Available from parsed state
public Integer duration = null;
public Double chance = null;
}
public static enum DisplayType { public static enum DisplayType {
ordinary, ordinary,
@@ -111,7 +73,7 @@ public class Item extends JSONElement {
@Override @Override
public String getDesc() { public String getDesc() {
return (needsSaving() ? "*" : "")+name+" ("+id+")"; return (needsSaving() ? "*" : "") + name + " (" + id + ")";
} }
public static String getStaticDesc() { public static String getStaticDesc() {
@@ -126,7 +88,7 @@ public class Item extends JSONElement {
reader = new FileReader(jsonFile); reader = new FileReader(jsonFile);
List items = (List) parser.parse(reader); List items = (List) parser.parse(reader);
for (Object obj : items) { for (Object obj : items) {
Map itemJson = (Map)obj; Map itemJson = (Map) obj;
Item item = fromJson(itemJson); Item item = fromJson(itemJson);
item.jsonFile = jsonFile; item.jsonFile = jsonFile;
item.parent = category; item.parent = category;
@@ -136,13 +98,13 @@ public class Item extends JSONElement {
category.add(item); category.add(item);
} }
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
} catch (IOException e) { } catch (IOException e) {
Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
} catch (ParseException e) { } catch (ParseException e) {
Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
if (reader != null) if (reader != null)
@@ -168,7 +130,8 @@ public class Item extends JSONElement {
item.icon_id = (String) itemJson.get("iconID"); item.icon_id = (String) itemJson.get("iconID");
item.id = (String) itemJson.get("id"); item.id = (String) itemJson.get("id");
item.name = (String) itemJson.get("name"); item.name = (String) itemJson.get("name");
if (itemJson.get("displaytype") != null) item.display_type = DisplayType.valueOf((String) itemJson.get("displaytype")); if (itemJson.get("displaytype") != null)
item.display_type = DisplayType.valueOf((String) itemJson.get("displaytype"));
return item; return item;
} }
@@ -187,8 +150,8 @@ public class Item extends JSONElement {
if (equipEffect != null) { if (equipEffect != null) {
this.equip_effect = new EquipEffect(); this.equip_effect = new EquipEffect();
if (equipEffect.get("increaseAttackDamage") != null) { if (equipEffect.get("increaseAttackDamage") != null) {
this.equip_effect.damage_boost_min = JSONElement.getInteger((Number) (((Map)equipEffect.get("increaseAttackDamage")).get("min"))); this.equip_effect.damage_boost_min = JSONElement.getInteger((Number) (((Map) equipEffect.get("increaseAttackDamage")).get("min")));
this.equip_effect.damage_boost_max = JSONElement.getInteger((Number) (((Map)equipEffect.get("increaseAttackDamage")).get("max"))); this.equip_effect.damage_boost_max = JSONElement.getInteger((Number) (((Map) equipEffect.get("increaseAttackDamage")).get("max")));
} }
this.equip_effect.max_hp_boost = JSONElement.getInteger((Number) equipEffect.get("increaseMaxHP")); this.equip_effect.max_hp_boost = JSONElement.getInteger((Number) equipEffect.get("increaseMaxHP"));
this.equip_effect.max_ap_boost = JSONElement.getInteger((Number) equipEffect.get("increaseMaxAP")); this.equip_effect.max_ap_boost = JSONElement.getInteger((Number) equipEffect.get("increaseMaxAP"));
@@ -202,15 +165,16 @@ public class Item extends JSONElement {
this.equip_effect.increase_damage_resistance = JSONElement.getInteger((Number) equipEffect.get("increaseDamageResistance")); this.equip_effect.increase_damage_resistance = JSONElement.getInteger((Number) equipEffect.get("increaseDamageResistance"));
//TODO correct game data, to unify format. //TODO correct game data, to unify format.
// this.equip_effect.critical_multiplier = JSONElement.getDouble((Number) equipEffect.get("setCriticalMultiplier")); // this.equip_effect.critical_multiplier = JSONElement.getDouble((Number) equipEffect.get("setCriticalMultiplier"));
if (equipEffect.get("setCriticalMultiplier") != null) this.equip_effect.critical_multiplier = JSONElement.getDouble(Double.parseDouble(equipEffect.get("setCriticalMultiplier").toString())); if (equipEffect.get("setCriticalMultiplier") != null)
this.equip_effect.critical_multiplier = JSONElement.getDouble(Double.parseDouble(equipEffect.get("setCriticalMultiplier").toString()));
this.equip_effect.damage_modifier = JSONElement.getInteger((Number) equipEffect.get("setNonWeaponDamageModifier")); this.equip_effect.damage_modifier = JSONElement.getInteger((Number) equipEffect.get("setNonWeaponDamageModifier"));
List conditionsJson = (List) equipEffect.get("addedConditions"); List conditionsJson = (List) equipEffect.get("addedConditions");
if (conditionsJson != null && !conditionsJson.isEmpty()) { if (conditionsJson != null && !conditionsJson.isEmpty()) {
this.equip_effect.conditions = new ArrayList<Item.ConditionEffect>(); this.equip_effect.conditions = new ArrayList<>();
for (Object conditionJsonObj : conditionsJson) { for (Object conditionJsonObj : conditionsJson) {
Map conditionJson = (Map)conditionJsonObj; Map conditionJson = (Map) conditionJsonObj;
ConditionEffect condition = new ConditionEffect(); ActorConditionEffect condition = new ActorConditionEffect();
condition.condition_id = (String) conditionJson.get("condition"); condition.condition_id = (String) conditionJson.get("condition");
condition.magnitude = JSONElement.getInteger((Number) conditionJson.get("magnitude")); condition.magnitude = JSONElement.getInteger((Number) conditionJson.get("magnitude"));
this.equip_effect.conditions.add(condition); this.equip_effect.conditions.add(condition);
@@ -221,88 +185,12 @@ public class Item extends JSONElement {
Map hitEffect = (Map) itemJson.get("hitEffect"); Map hitEffect = (Map) itemJson.get("hitEffect");
if (hitEffect != null) { if (hitEffect != null) {
this.hit_effect = new HitEffect(); this.hit_effect = parseHitEffect(hitEffect);
if (hitEffect.get("increaseCurrentHP") != null) {
this.hit_effect.hp_boost_min = JSONElement.getInteger((Number) (((Map)hitEffect.get("increaseCurrentHP")).get("min")));
this.hit_effect.hp_boost_max = JSONElement.getInteger((Number) (((Map)hitEffect.get("increaseCurrentHP")).get("max")));
}
if (hitEffect.get("increaseCurrentAP") != null) {
this.hit_effect.ap_boost_min = JSONElement.getInteger((Number) (((Map)hitEffect.get("increaseCurrentAP")).get("min")));
this.hit_effect.ap_boost_max = JSONElement.getInteger((Number) (((Map)hitEffect.get("increaseCurrentAP")).get("max")));
}
List conditionsSourceJson = (List) hitEffect.get("conditionsSource");
if (conditionsSourceJson != null && !conditionsSourceJson.isEmpty()) {
this.hit_effect.conditions_source = new ArrayList<Item.TimedConditionEffect>();
for (Object conditionJsonObj : conditionsSourceJson) {
Map conditionJson = (Map)conditionJsonObj;
TimedConditionEffect condition = new TimedConditionEffect();
condition.condition_id = (String) conditionJson.get("condition");
condition.magnitude = JSONElement.getInteger((Number) conditionJson.get("magnitude"));
condition.duration = JSONElement.getInteger((Number) conditionJson.get("duration"));
if (conditionJson.get("chance") != null) condition.chance = JSONElement.parseChance(conditionJson.get("chance").toString());
this.hit_effect.conditions_source.add(condition);
}
}
List conditionsTargetJson = (List) hitEffect.get("conditionsTarget");
if (conditionsTargetJson != null && !conditionsTargetJson.isEmpty()) {
this.hit_effect.conditions_target = new ArrayList<Item.TimedConditionEffect>();
for (Object conditionJsonObj : conditionsTargetJson) {
Map conditionJson = (Map)conditionJsonObj;
TimedConditionEffect condition = new TimedConditionEffect();
condition.condition_id = (String) conditionJson.get("condition");
condition.magnitude = JSONElement.getInteger((Number) conditionJson.get("magnitude"));
condition.duration = JSONElement.getInteger((Number) conditionJson.get("duration"));
if (conditionJson.get("chance") != null) condition.chance = JSONElement.parseChance(conditionJson.get("chance").toString());
this.hit_effect.conditions_target.add(condition);
}
}
} }
Map hitReceivedEffect = (Map) itemJson.get("hitReceivedEffect"); Map hitReceivedEffect = (Map) itemJson.get("hitReceivedEffect");
if (hitReceivedEffect != null) { if (hitReceivedEffect != null) {
this.hit_received_effect = new HitReceivedEffect(); this.hit_received_effect = parseHitReceivedEffect(hitReceivedEffect);
if (hitReceivedEffect.get("increaseCurrentHP") != null) {
this.hit_received_effect.hp_boost_min = JSONElement.getInteger((Number) (((Map)hitReceivedEffect.get("increaseCurrentHP")).get("min")));
this.hit_received_effect.hp_boost_max = JSONElement.getInteger((Number) (((Map)hitReceivedEffect.get("increaseCurrentHP")).get("max")));
}
if (hitReceivedEffect.get("increaseCurrentAP") != null) {
this.hit_received_effect.ap_boost_min = JSONElement.getInteger((Number) (((Map)hitReceivedEffect.get("increaseCurrentAP")).get("min")));
this.hit_received_effect.ap_boost_max = JSONElement.getInteger((Number) (((Map)hitReceivedEffect.get("increaseCurrentAP")).get("max")));
}
if (hitReceivedEffect.get("increaseAttackerCurrentHP") != null) {
this.hit_received_effect.hp_boost_min_target = JSONElement.getInteger((Number) (((Map)hitReceivedEffect.get("increaseAttackerCurrentHP")).get("min")));
this.hit_received_effect.hp_boost_max_target = JSONElement.getInteger((Number) (((Map)hitReceivedEffect.get("increaseAttackerCurrentHP")).get("max")));
}
if (hitReceivedEffect.get("increaseAttackerCurrentAP") != null) {
this.hit_received_effect.ap_boost_min_target = JSONElement.getInteger((Number) (((Map)hitReceivedEffect.get("increaseAttackerCurrentAP")).get("min")));
this.hit_received_effect.ap_boost_max_target = JSONElement.getInteger((Number) (((Map)hitReceivedEffect.get("increaseAttackerCurrentAP")).get("max")));
}
List conditionsSourceJson = (List) hitReceivedEffect.get("conditionsSource");
if (conditionsSourceJson != null && !conditionsSourceJson.isEmpty()) {
this.hit_received_effect.conditions_source = new ArrayList<Item.TimedConditionEffect>();
for (Object conditionJsonObj : conditionsSourceJson) {
Map conditionJson = (Map)conditionJsonObj;
TimedConditionEffect condition = new TimedConditionEffect();
condition.condition_id = (String) conditionJson.get("condition");
condition.magnitude = JSONElement.getInteger((Number) conditionJson.get("magnitude"));
condition.duration = JSONElement.getInteger((Number) conditionJson.get("duration"));
if (conditionJson.get("chance") != null) condition.chance = JSONElement.parseChance(conditionJson.get("chance").toString());
this.hit_received_effect.conditions_source.add(condition);
}
}
List conditionsTargetJson = (List) hitReceivedEffect.get("conditionsTarget");
if (conditionsTargetJson != null && !conditionsTargetJson.isEmpty()) {
this.hit_received_effect.conditions_target = new ArrayList<Item.TimedConditionEffect>();
for (Object conditionJsonObj : conditionsTargetJson) {
Map conditionJson = (Map)conditionJsonObj;
TimedConditionEffect condition = new TimedConditionEffect();
condition.condition_id = (String) conditionJson.get("condition");
condition.magnitude = JSONElement.getInteger((Number) conditionJson.get("magnitude"));
condition.duration = JSONElement.getInteger((Number) conditionJson.get("duration"));
if (conditionJson.get("chance") != null) condition.chance = JSONElement.parseChance(conditionJson.get("chance").toString());
this.hit_received_effect.conditions_target.add(condition);
}
}
} }
Map killEffect = (Map) itemJson.get("killEffect"); Map killEffect = (Map) itemJson.get("killEffect");
@@ -310,28 +198,7 @@ public class Item extends JSONElement {
killEffect = (Map) itemJson.get("useEffect"); killEffect = (Map) itemJson.get("useEffect");
} }
if (killEffect != null) { if (killEffect != null) {
this.kill_effect = new KillEffect(); this.kill_effect = parseDeathEffect(killEffect);
if (killEffect.get("increaseCurrentHP") != null) {
this.kill_effect.hp_boost_min = JSONElement.getInteger((Number) (((Map)killEffect.get("increaseCurrentHP")).get("min")));
this.kill_effect.hp_boost_max = JSONElement.getInteger((Number) (((Map)killEffect.get("increaseCurrentHP")).get("max")));
}
if (killEffect.get("increaseCurrentAP") != null) {
this.kill_effect.ap_boost_min = JSONElement.getInteger((Number) (((Map)killEffect.get("increaseCurrentAP")).get("min")));
this.kill_effect.ap_boost_max = JSONElement.getInteger((Number) (((Map)killEffect.get("increaseCurrentAP")).get("max")));
}
List conditionsSourceJson = (List) killEffect.get("conditionsSource");
if (conditionsSourceJson != null && !conditionsSourceJson.isEmpty()) {
this.kill_effect.conditions_source = new ArrayList<Item.TimedConditionEffect>();
for (Object conditionJsonObj : conditionsSourceJson) {
Map conditionJson = (Map)conditionJsonObj;
TimedConditionEffect condition = new TimedConditionEffect();
condition.condition_id = (String) conditionJson.get("condition");
condition.magnitude = JSONElement.getInteger((Number) conditionJson.get("magnitude"));
condition.duration = JSONElement.getInteger((Number) conditionJson.get("duration"));
if (conditionJson.get("chance") != null) condition.chance = JSONElement.parseChance(conditionJson.get("chance").toString());
this.kill_effect.conditions_source.add(condition);
}
}
} }
this.state = State.parsed; this.state = State.parsed;
} }
@@ -339,68 +206,30 @@ public class Item extends JSONElement {
@Override @Override
public void link() { public void link() {
if (this.state == State.created || this.state == State.modified || this.state == State.saved) { if (shouldSkipParseOrLink()) {
//This type of state is unrelated to parsing/linking.
return;
}
if (this.state == State.init) {
//Not parsed yet.
this.parse();
} else if (this.state == State.linked) {
//Already linked.
return; return;
} }
ensureParseIfNeeded();
Project proj = getProject(); Project proj = getProject();
if (proj == null) { if (proj == null) {
Notification.addError("Error linking item "+id+". No parent project found."); Notification.addError("Error linking item " + id + ". No parent project found.");
return; return;
} }
if (this.icon_id != null) { linkIcon(proj, this.icon_id, this);
String spritesheetId = this.icon_id.split(":")[0];
proj.getSpritesheet(spritesheetId).addBacklink(this);
}
if (this.category_id != null) this.category = proj.getItemCategory(this.category_id); if (this.category_id != null) this.category = proj.getItemCategory(this.category_id);
if (this.category != null) this.category.addBacklink(this); if (this.category != null) this.category.addBacklink(this);
if (this.equip_effect != null && this.equip_effect.conditions != null) { if (this.equip_effect != null && this.equip_effect.conditions != null) {
for (ConditionEffect ce : this.equip_effect.conditions) { linkConditions(this.equip_effect.conditions, proj, this);
if (ce.condition_id != null) ce.condition = proj.getActorCondition(ce.condition_id);
if (ce.condition != null) ce.condition.addBacklink(this);
}
}
if (this.hit_effect != null && this.hit_effect.conditions_source != null) {
for (TimedConditionEffect ce : this.hit_effect.conditions_source) {
if (ce.condition_id != null) ce.condition = proj.getActorCondition(ce.condition_id);
if (ce.condition != null) ce.condition.addBacklink(this);
}
}
if (this.hit_effect != null && this.hit_effect.conditions_target != null) {
for (TimedConditionEffect ce : this.hit_effect.conditions_target) {
if (ce.condition_id != null) ce.condition = proj.getActorCondition(ce.condition_id);
if (ce.condition != null) ce.condition.addBacklink(this);
}
}
if (this.hit_received_effect != null && this.hit_received_effect.conditions_source != null) {
for (TimedConditionEffect ce : this.hit_received_effect.conditions_source) {
if (ce.condition_id != null) ce.condition = proj.getActorCondition(ce.condition_id);
if (ce.condition != null) ce.condition.addBacklink(this);
}
}
if (this.hit_received_effect != null && this.hit_received_effect.conditions_target != null) {
for (TimedConditionEffect ce : this.hit_received_effect.conditions_target) {
if (ce.condition_id != null) ce.condition = proj.getActorCondition(ce.condition_id);
if (ce.condition != null) ce.condition.addBacklink(this);
}
}
if (this.kill_effect != null && this.kill_effect.conditions_source != null) {
for (TimedConditionEffect ce : this.kill_effect.conditions_source) {
if (ce.condition_id != null) ce.condition = proj.getActorCondition(ce.condition_id);
if (ce.condition != null) ce.condition.addBacklink(this);
}
} }
linkEffects(this.hit_effect, proj, this);
linkEffects(this.hit_received_effect, proj, this);
linkEffects(this.kill_effect, proj, this);
this.state = State.linked; this.state = State.linked;
} }
@Override @Override
public Image getIcon() { public Image getIcon() {
return getProject().getIcon(icon_id); return getProject().getIcon(icon_id);
@@ -444,9 +273,9 @@ public class Item extends JSONElement {
clone.equip_effect.max_ap_boost = this.equip_effect.max_ap_boost; clone.equip_effect.max_ap_boost = this.equip_effect.max_ap_boost;
clone.equip_effect.max_hp_boost = this.equip_effect.max_hp_boost; clone.equip_effect.max_hp_boost = this.equip_effect.max_hp_boost;
if (this.equip_effect.conditions != null) { if (this.equip_effect.conditions != null) {
clone.equip_effect.conditions = new ArrayList<Item.ConditionEffect>(); clone.equip_effect.conditions = new ArrayList<>();
for (ConditionEffect c : this.equip_effect.conditions) { for (ActorConditionEffect c : this.equip_effect.conditions) {
ConditionEffect cclone = new ConditionEffect(); ActorConditionEffect cclone = new ActorConditionEffect();
cclone.magnitude = c.magnitude; cclone.magnitude = c.magnitude;
cclone.condition_id = c.condition_id; cclone.condition_id = c.condition_id;
cclone.condition = c.condition; cclone.condition = c.condition;
@@ -459,103 +288,15 @@ public class Item extends JSONElement {
} }
if (this.hit_effect != null) { if (this.hit_effect != null) {
clone.hit_effect = new HitEffect(); clone.hit_effect = new HitEffect();
clone.hit_effect.ap_boost_max = this.hit_effect.ap_boost_max; copyHitEffectValues(clone.hit_effect, this.hit_effect, clone);
clone.hit_effect.ap_boost_min = this.hit_effect.ap_boost_min;
clone.hit_effect.hp_boost_max = this.hit_effect.hp_boost_max;
clone.hit_effect.hp_boost_min = this.hit_effect.hp_boost_min;
if (this.hit_effect.conditions_source != null) {
clone.hit_effect.conditions_source = new ArrayList<Item.TimedConditionEffect>();
for (TimedConditionEffect c : this.hit_effect.conditions_source) {
TimedConditionEffect cclone = new TimedConditionEffect();
cclone.magnitude = c.magnitude;
cclone.condition_id = c.condition_id;
cclone.condition = c.condition;
cclone.chance = c.chance;
cclone.duration = c.duration;
if (cclone.condition != null) {
cclone.condition.addBacklink(clone);
}
clone.hit_effect.conditions_source.add(cclone);
}
}
if (this.hit_effect.conditions_target != null) {
clone.hit_effect.conditions_target = new ArrayList<Item.TimedConditionEffect>();
for (TimedConditionEffect c : this.hit_effect.conditions_target) {
TimedConditionEffect cclone = new TimedConditionEffect();
cclone.magnitude = c.magnitude;
cclone.condition_id = c.condition_id;
cclone.condition = c.condition;
cclone.chance = c.chance;
cclone.duration = c.duration;
if (cclone.condition != null) {
cclone.condition.addBacklink(clone);
}
clone.hit_effect.conditions_target.add(cclone);
}
}
} }
if (this.hit_received_effect != null) { if (this.hit_received_effect != null) {
clone.hit_received_effect = new HitReceivedEffect(); clone.hit_received_effect = new HitReceivedEffect();
clone.hit_received_effect.ap_boost_max = this.hit_received_effect.ap_boost_max; copyHitReceivedEffectValues(clone.hit_received_effect, this.hit_received_effect, clone);
clone.hit_received_effect.ap_boost_min = this.hit_received_effect.ap_boost_min;
clone.hit_received_effect.hp_boost_max = this.hit_received_effect.hp_boost_max;
clone.hit_received_effect.hp_boost_min = this.hit_received_effect.hp_boost_min;
clone.hit_received_effect.ap_boost_max_target = this.hit_received_effect.ap_boost_max_target;
clone.hit_received_effect.ap_boost_min_target = this.hit_received_effect.ap_boost_min_target;
clone.hit_received_effect.hp_boost_max_target = this.hit_received_effect.hp_boost_max_target;
clone.hit_received_effect.hp_boost_min_target = this.hit_received_effect.hp_boost_min_target;
if (this.hit_received_effect.conditions_source != null) {
clone.hit_received_effect.conditions_source = new ArrayList<Item.TimedConditionEffect>();
for (TimedConditionEffect c : this.hit_received_effect.conditions_source) {
TimedConditionEffect cclone = new TimedConditionEffect();
cclone.magnitude = c.magnitude;
cclone.condition_id = c.condition_id;
cclone.condition = c.condition;
cclone.chance = c.chance;
cclone.duration = c.duration;
if (cclone.condition != null) {
cclone.condition.addBacklink(clone);
}
clone.hit_received_effect.conditions_source.add(cclone);
}
}
if (this.hit_received_effect.conditions_target != null) {
clone.hit_received_effect.conditions_target = new ArrayList<Item.TimedConditionEffect>();
for (TimedConditionEffect c : this.hit_received_effect.conditions_target) {
TimedConditionEffect cclone = new TimedConditionEffect();
cclone.magnitude = c.magnitude;
cclone.condition_id = c.condition_id;
cclone.condition = c.condition;
cclone.chance = c.chance;
cclone.duration = c.duration;
if (cclone.condition != null) {
cclone.condition.addBacklink(clone);
}
clone.hit_received_effect.conditions_target.add(cclone);
}
}
} }
if (this.kill_effect != null) { if (this.kill_effect != null) {
clone.kill_effect = new KillEffect(); clone.kill_effect = new DeathEffect();
clone.kill_effect.ap_boost_max = this.kill_effect.ap_boost_max; copyDeathEffectValues(clone.kill_effect, this.kill_effect, clone);
clone.kill_effect.ap_boost_min = this.kill_effect.ap_boost_min;
clone.kill_effect.hp_boost_max = this.kill_effect.hp_boost_max;
clone.kill_effect.hp_boost_min = this.kill_effect.hp_boost_min;
if (this.kill_effect.conditions_source != null) {
clone.kill_effect.conditions_source = new ArrayList<Item.TimedConditionEffect>();
for (TimedConditionEffect c : this.kill_effect.conditions_source) {
TimedConditionEffect cclone = new TimedConditionEffect();
cclone.magnitude = c.magnitude;
cclone.condition_id = c.condition_id;
cclone.condition = c.condition;
cclone.chance = c.chance;
cclone.duration = c.duration;
if (cclone.condition != null) {
cclone.condition.addBacklink(clone);
}
clone.kill_effect.conditions_source.add(cclone);
}
}
} }
return clone; return clone;
} }
@@ -567,54 +308,30 @@ public class Item extends JSONElement {
this.category = (ItemCategory) newOne; this.category = (ItemCategory) newOne;
if (newOne != null) newOne.addBacklink(this); if (newOne != null) newOne.addBacklink(this);
} else { } else {
if (this.equip_effect != null && this.equip_effect.conditions != null) { if (this.equip_effect != null) {
for (ConditionEffect c : this.equip_effect.conditions) { if (this.equip_effect.conditions != null) {
if (c.condition == oldOne) { actorConditionElementChanged(this.equip_effect.conditions, oldOne, newOne, this);
oldOne.removeBacklink(this);
c.condition = (ActorCondition) newOne;
if (newOne != null) newOne.addBacklink(this);
} }
} }
if (this.hit_effect != null) {
actorConditionElementChanged(this.hit_effect.conditions_source, oldOne, newOne, this);
actorConditionElementChanged(this.hit_effect.conditions_target, oldOne, newOne, this);
} }
if (this.hit_effect != null && this.hit_effect.conditions_source != null) {
for (TimedConditionEffect c : this.hit_effect.conditions_source) { if (this.kill_effect != null) {
if (c.condition == oldOne) { actorConditionElementChanged(this.kill_effect.conditions_source, oldOne, newOne, this);
oldOne.removeBacklink(this);
c.condition = (ActorCondition) newOne;
if (newOne != null) newOne.addBacklink(this);
}
}
}
if (this.hit_effect != null && this.hit_effect.conditions_target != null) {
for (TimedConditionEffect c : this.hit_effect.conditions_target) {
if (c.condition == oldOne) {
oldOne.removeBacklink(this);
c.condition = (ActorCondition) newOne;
if (newOne != null) newOne.addBacklink(this);
} }
} }
} }
if (this.kill_effect != null && this.kill_effect.conditions_source != null) { @SuppressWarnings({"rawtypes", "unchecked"})
for (TimedConditionEffect c : this.kill_effect.conditions_source) {
if (c.condition == oldOne) {
oldOne.removeBacklink(this);
c.condition = (ActorCondition) newOne;
if (newOne != null) newOne.addBacklink(this);
}
}
}
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override @Override
public Map toJson() { public Map toJson() {
Map itemJson = new LinkedHashMap(); Map itemJson = new LinkedHashMap();
itemJson.put("id", this.id); itemJson.put("id", this.id);
if (this.icon_id != null) itemJson.put("iconID", this.icon_id); writeIconToMap(itemJson, this.icon_id);
if (this.name != null) itemJson.put("name", this.name); if (this.name != null) itemJson.put("name", this.name);
if(this.display_type != null) itemJson.put("displaytype", this.display_type.toString()); if (this.display_type != null) itemJson.put("displaytype", this.display_type.toString());
if (this.has_manual_price != null) itemJson.put("hasManualPrice", this.has_manual_price); if (this.has_manual_price != null) itemJson.put("hasManualPrice", this.has_manual_price);
if (this.base_market_cost != null) itemJson.put("baseMarketCost", this.base_market_cost); if (this.base_market_cost != null) itemJson.put("baseMarketCost", this.base_market_cost);
@@ -623,211 +340,68 @@ public class Item extends JSONElement {
} else if (this.category_id != null) { } else if (this.category_id != null) {
itemJson.put("category", this.category_id); itemJson.put("category", this.category_id);
} }
if (this.description != null) itemJson.put("description", this.description); writeDescriptionToMap(itemJson, this.description);
if (this.equip_effect != null) { if (this.equip_effect != null) {
Map equipEffectJson = new LinkedHashMap(); Map equipEffectJson = new LinkedHashMap();
itemJson.put("equipEffect", equipEffectJson); itemJson.put("equipEffect", equipEffectJson);
if (this.equip_effect.damage_boost_min != null || this.equip_effect.damage_boost_max != null) { writeMinMaxToMap(equipEffectJson, "increaseAttackDamage", this.equip_effect.damage_boost_min, this.equip_effect.damage_boost_max, 0);
Map damageJson = new LinkedHashMap(); if (this.equip_effect.max_hp_boost != null)
equipEffectJson.put("increaseAttackDamage", damageJson); equipEffectJson.put("increaseMaxHP", this.equip_effect.max_hp_boost);
if (this.equip_effect.damage_boost_min != null) damageJson.put("min", this.equip_effect.damage_boost_min); if (this.equip_effect.max_ap_boost != null)
else damageJson.put("min", 0); equipEffectJson.put("increaseMaxAP", this.equip_effect.max_ap_boost);
if (this.equip_effect.damage_boost_max != null) damageJson.put("max", this.equip_effect.damage_boost_max); if (this.equip_effect.increase_move_cost != null)
else damageJson.put("max", 0); equipEffectJson.put("increaseMoveCost", this.equip_effect.increase_move_cost);
} if (this.equip_effect.increase_use_item_cost != null)
if (this.equip_effect.max_hp_boost != null) equipEffectJson.put("increaseMaxHP", this.equip_effect.max_hp_boost); equipEffectJson.put("increaseUseItemCost", this.equip_effect.increase_use_item_cost);
if (this.equip_effect.max_ap_boost != null) equipEffectJson.put("increaseMaxAP", this.equip_effect.max_ap_boost); if (this.equip_effect.increase_reequip_cost != null)
if (this.equip_effect.increase_move_cost != null) equipEffectJson.put("increaseMoveCost", this.equip_effect.increase_move_cost); equipEffectJson.put("increaseReequipCost", this.equip_effect.increase_reequip_cost);
if (this.equip_effect.increase_use_item_cost != null) equipEffectJson.put("increaseUseItemCost", this.equip_effect.increase_use_item_cost); if (this.equip_effect.increase_attack_cost != null)
if (this.equip_effect.increase_reequip_cost != null) equipEffectJson.put("increaseReequipCost", this.equip_effect.increase_reequip_cost); equipEffectJson.put("increaseAttackCost", this.equip_effect.increase_attack_cost);
if (this.equip_effect.increase_attack_cost != null) equipEffectJson.put("increaseAttackCost", this.equip_effect.increase_attack_cost); if (this.equip_effect.increase_attack_chance != null)
if (this.equip_effect.increase_attack_chance != null) equipEffectJson.put("increaseAttackChance", this.equip_effect.increase_attack_chance); equipEffectJson.put("increaseAttackChance", this.equip_effect.increase_attack_chance);
if (this.equip_effect.increase_critical_skill != null) equipEffectJson.put("increaseCriticalSkill", this.equip_effect.increase_critical_skill); if (this.equip_effect.increase_critical_skill != null)
if (this.equip_effect.increase_block_chance != null) equipEffectJson.put("increaseBlockChance", this.equip_effect.increase_block_chance); equipEffectJson.put("increaseCriticalSkill", this.equip_effect.increase_critical_skill);
if (this.equip_effect.increase_damage_resistance != null) equipEffectJson.put("increaseDamageResistance", this.equip_effect.increase_damage_resistance); if (this.equip_effect.increase_block_chance != null)
if (this.equip_effect.critical_multiplier != null) equipEffectJson.put("setCriticalMultiplier", this.equip_effect.critical_multiplier); equipEffectJson.put("increaseBlockChance", this.equip_effect.increase_block_chance);
if (this.equip_effect.damage_modifier != null) equipEffectJson.put("setNonWeaponDamageModifier", this.equip_effect.damage_modifier); if (this.equip_effect.increase_damage_resistance != null)
equipEffectJson.put("increaseDamageResistance", this.equip_effect.increase_damage_resistance);
if (this.equip_effect.critical_multiplier != null)
equipEffectJson.put("setCriticalMultiplier", this.equip_effect.critical_multiplier);
if (this.equip_effect.damage_modifier != null)
equipEffectJson.put("setNonWeaponDamageModifier", this.equip_effect.damage_modifier);
if (this.equip_effect.conditions != null) { if (this.equip_effect.conditions != null) {
List conditionsJson = new ArrayList(); List conditionsJson = new ArrayList();
equipEffectJson.put("addedConditions", conditionsJson); equipEffectJson.put("addedConditions", conditionsJson);
for (ConditionEffect condition : this.equip_effect.conditions) { for (ActorConditionEffect condition : this.equip_effect.conditions) {
Map conditionJson = new LinkedHashMap(); Map conditionJson = new LinkedHashMap();
conditionsJson.add(conditionJson); conditionsJson.add(conditionJson);
if (condition.condition != null) { writeConditionEffectToMap(condition, conditionJson);
conditionJson.put("condition", condition.condition.id);
} else if (condition.condition_id != null) {
conditionJson.put("condition", condition.condition_id);
}
if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude);
} }
} }
} }
if (this.hit_effect != null) { writeHitEffectToMap(itemJson, this.hit_effect, "hitEffect");
Map hitEffectJson = new LinkedHashMap(); writeHitReceivedEffectToMap(itemJson, this.hit_received_effect, "hitReceivedEffect");
itemJson.put("hitEffect", hitEffectJson);
if (this.hit_effect.hp_boost_min != null || this.hit_effect.hp_boost_max != null) { String key;
Map hpJson = new LinkedHashMap();
hitEffectJson.put("increaseCurrentHP", hpJson);
if (this.hit_effect.hp_boost_min != null) hpJson.put("min", this.hit_effect.hp_boost_min);
else hpJson.put("min", 0);
if (this.hit_effect.hp_boost_max != null) hpJson.put("max", this.hit_effect.hp_boost_max);
else hpJson.put("max", 0);
}
if (this.hit_effect.ap_boost_min != null || this.hit_effect.ap_boost_max != null) {
Map apJson = new LinkedHashMap();
hitEffectJson.put("increaseCurrentAP", apJson);
if (this.hit_effect.ap_boost_min != null) apJson.put("min", this.hit_effect.ap_boost_min);
else apJson.put("min", 0);
if (this.hit_effect.ap_boost_max != null) apJson.put("max", this.hit_effect.ap_boost_max);
else apJson.put("max", 0);
}
if (this.hit_effect.conditions_source != null) {
List conditionsSourceJson = new ArrayList();
hitEffectJson.put("conditionsSource", conditionsSourceJson);
for (TimedConditionEffect condition : this.hit_effect.conditions_source) {
Map conditionJson = new LinkedHashMap();
conditionsSourceJson.add(conditionJson);
if (condition.condition != null) {
conditionJson.put("condition", condition.condition.id);
} else if (condition.condition_id != null) {
conditionJson.put("condition", condition.condition_id);
}
if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude);
if (condition.duration != null) conditionJson.put("duration", condition.duration);
if (condition.chance != null) conditionJson.put("chance", JSONElement.printJsonChance(condition.chance));
}
}
if (this.hit_effect.conditions_target != null) {
List conditionsTargetJson = new ArrayList();
hitEffectJson.put("conditionsTarget", conditionsTargetJson);
for (TimedConditionEffect condition : this.hit_effect.conditions_target) {
Map conditionJson = new LinkedHashMap();
conditionsTargetJson.add(conditionJson);
if (condition.condition != null) {
conditionJson.put("condition", condition.condition.id);
} else if (condition.condition_id != null) {
conditionJson.put("condition", condition.condition_id);
}
if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude);
if (condition.duration != null) conditionJson.put("duration", condition.duration);
if (condition.chance != null) conditionJson.put("chance", JSONElement.printJsonChance(condition.chance));
}
}
}
if (this.hit_received_effect != null) {
Map hitReceivedEffectJson = new LinkedHashMap();
itemJson.put("hitReceivedEffect", hitReceivedEffectJson);
if (this.hit_received_effect.hp_boost_min != null || this.hit_received_effect.hp_boost_max != null) {
Map hpJson = new LinkedHashMap();
hitReceivedEffectJson.put("increaseCurrentHP", hpJson);
if (this.hit_received_effect.hp_boost_min != null) hpJson.put("min", this.hit_received_effect.hp_boost_min);
else hpJson.put("min", 0);
if (this.hit_received_effect.hp_boost_max != null) hpJson.put("max", this.hit_received_effect.hp_boost_max);
else hpJson.put("max", 0);
}
if (this.hit_received_effect.ap_boost_min != null || this.hit_received_effect.ap_boost_max != null) {
Map apJson = new LinkedHashMap();
hitReceivedEffectJson.put("increaseCurrentAP", apJson);
if (this.hit_received_effect.ap_boost_min != null) apJson.put("min", this.hit_received_effect.ap_boost_min);
else apJson.put("min", 0);
if (this.hit_received_effect.ap_boost_max != null) apJson.put("max", this.hit_received_effect.ap_boost_max);
else apJson.put("max", 0);
}
if (this.hit_received_effect.hp_boost_min_target != null || this.hit_received_effect.hp_boost_max_target != null) {
Map hpJson = new LinkedHashMap();
hitReceivedEffectJson.put("increaseAttackerCurrentHP", hpJson);
if (this.hit_received_effect.hp_boost_min_target != null) hpJson.put("min", this.hit_received_effect.hp_boost_min_target);
else hpJson.put("min", 0);
if (this.hit_received_effect.hp_boost_max_target != null) hpJson.put("max", this.hit_received_effect.hp_boost_max_target);
else hpJson.put("max", 0);
}
if (this.hit_received_effect.ap_boost_min_target != null || this.hit_received_effect.ap_boost_max_target != null) {
Map apJson = new LinkedHashMap();
hitReceivedEffectJson.put("increaseAttackerCurrentAP", apJson);
if (this.hit_received_effect.ap_boost_min_target != null) apJson.put("min", this.hit_received_effect.ap_boost_min_target);
else apJson.put("min", 0);
if (this.hit_received_effect.ap_boost_max_target != null) apJson.put("max", this.hit_received_effect.ap_boost_max_target);
else apJson.put("max", 0);
}
if (this.hit_received_effect.conditions_source != null) {
List conditionsSourceJson = new ArrayList();
hitReceivedEffectJson.put("conditionsSource", conditionsSourceJson);
for (TimedConditionEffect condition : this.hit_received_effect.conditions_source) {
Map conditionJson = new LinkedHashMap();
conditionsSourceJson.add(conditionJson);
if (condition.condition != null) {
conditionJson.put("condition", condition.condition.id);
} else if (condition.condition_id != null) {
conditionJson.put("condition", condition.condition_id);
}
if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude);
if (condition.duration != null) conditionJson.put("duration", condition.duration);
if (condition.chance != null) conditionJson.put("chance", JSONElement.printJsonChance(condition.chance));
}
}
if (this.hit_received_effect.conditions_target != null) {
List conditionsTargetJson = new ArrayList();
hitReceivedEffectJson.put("conditionsTarget", conditionsTargetJson);
for (TimedConditionEffect condition : this.hit_received_effect.conditions_target) {
Map conditionJson = new LinkedHashMap();
conditionsTargetJson.add(conditionJson);
if (condition.condition != null) {
conditionJson.put("condition", condition.condition.id);
} else if (condition.condition_id != null) {
conditionJson.put("condition", condition.condition_id);
}
if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude);
if (condition.duration != null) conditionJson.put("duration", condition.duration);
if (condition.chance != null) conditionJson.put("chance", JSONElement.printJsonChance(condition.chance));
}
}
}
if (this.kill_effect != null) {
Map killEffectJson = new LinkedHashMap();
if (this.category != null && this.category.action_type != null && this.category.action_type == ItemCategory.ActionType.equip) { if (this.category != null && this.category.action_type != null && this.category.action_type == ItemCategory.ActionType.equip) {
itemJson.put("killEffect", killEffectJson); key = "killEffect";
} else if (this.category != null && this.category.action_type != null && this.category.action_type == ItemCategory.ActionType.use) { } else if (this.category != null && this.category.action_type != null && this.category.action_type == ItemCategory.ActionType.use) {
itemJson.put("useEffect", killEffectJson); key = "useEffect";
} } else {
if (this.kill_effect.hp_boost_min != null || this.kill_effect.hp_boost_max != null) { System.out.println("Could not create JSON-Map for Item: Failed to determine if the item should be used or equipped.");
Map hpJson = new LinkedHashMap(); key = null;
killEffectJson.put("increaseCurrentHP", hpJson);
if (this.kill_effect.hp_boost_min != null) hpJson.put("min", this.kill_effect.hp_boost_min);
else hpJson.put("min", 0);
if (this.kill_effect.hp_boost_max != null) hpJson.put("max", this.kill_effect.hp_boost_max);
else hpJson.put("min", 0);
}
if (this.kill_effect.ap_boost_min != null || this.kill_effect.ap_boost_max != null) {
Map apJson = new LinkedHashMap();
killEffectJson.put("increaseCurrentAP", apJson);
if (this.kill_effect.ap_boost_min != null) apJson.put("min", this.kill_effect.ap_boost_min);
else apJson.put("min", 0);
if (this.kill_effect.ap_boost_max != null) apJson.put("max", this.kill_effect.ap_boost_max);
else apJson.put("max", 0);
}
if (this.kill_effect.conditions_source != null) {
List conditionsSourceJson = new ArrayList();
killEffectJson.put("conditionsSource", conditionsSourceJson);
for (TimedConditionEffect condition : this.kill_effect.conditions_source) {
Map conditionJson = new LinkedHashMap();
conditionsSourceJson.add(conditionJson);
if (condition.condition != null) {
conditionJson.put("condition", condition.condition.id);
} else if (condition.condition_id != null) {
conditionJson.put("condition", condition.condition_id);
}
if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude);
if (condition.duration != null) conditionJson.put("duration", condition.duration);
if (condition.chance != null) conditionJson.put("chance", JSONElement.printJsonChance(condition.chance));
}
} }
if (key != null) {
writeDeathEffectToMap(itemJson, this.kill_effect, key);
} }
return itemJson; return itemJson;
} }
@Override @Override
public String getProjectFilename() { public String getProjectFilename() {
return "itemlist_"+getProject().name+".json"; return "itemlist_" + getProject().name + ".json";
} }
public Integer computePrice() { public Integer computePrice() {
@@ -836,7 +410,7 @@ public class Item extends JSONElement {
if (category.action_type == ItemCategory.ActionType.use) { if (category.action_type == ItemCategory.ActionType.use) {
price += kill_effect == null ? 0 : calculateUseCost(); price += kill_effect == null ? 0 : calculateUseCost();
} else if (category.action_type == ItemCategory.ActionType.equip) { } else if (category.action_type == ItemCategory.ActionType.equip) {
price += equip_effect == null ? 0 : calculateEquipCost(isWeapon());; price += equip_effect == null ? 0 : calculateEquipCost(isWeapon());
price += hit_effect == null ? 0 : calculateHitCost(); price += hit_effect == null ? 0 : calculateHitCost();
price += kill_effect == null ? 0 : calculateKillCost(); price += kill_effect == null ? 0 : calculateKillCost();
} }
@@ -859,30 +433,31 @@ public class Item extends JSONElement {
public int calculateUseCost() { public int calculateUseCost() {
final float averageHPBoost = (zeroForNull(kill_effect.hp_boost_min) + zeroForNull(kill_effect.hp_boost_max)) / 2.0f; final float averageHPBoost = (zeroForNull(kill_effect.hp_boost_min) + zeroForNull(kill_effect.hp_boost_max)) / 2.0f;
if (averageHPBoost == 0) return 0; if (averageHPBoost == 0) return 0;
return (int) (0.1*Math.signum(averageHPBoost)*Math.pow(Math.abs(averageHPBoost), 2) + 3*averageHPBoost); return (int) (0.1 * Math.signum(averageHPBoost) * Math.pow(Math.abs(averageHPBoost), 2) + 3 * averageHPBoost);
} }
public int calculateEquipCost(boolean isWeapon) { public int calculateEquipCost(boolean isWeapon) {
final int costBC = (int) (3*Math.pow(Math.max(0, zeroForNull(equip_effect.increase_block_chance)), 2.5) + 28*zeroForNull(equip_effect.increase_block_chance)); final int costBC = (int) (3 * Math.pow(Math.max(0, zeroForNull(equip_effect.increase_block_chance)), 2.5) + 28 * zeroForNull(equip_effect.increase_block_chance));
final int costAC = (int) (0.4*Math.pow(Math.max(0,zeroForNull(equip_effect.increase_attack_chance)), 2.5) - 6*Math.pow(Math.abs(Math.min(0,zeroForNull(equip_effect.increase_attack_chance))),2.7)); final int costAC = (int) (0.4 * Math.pow(Math.max(0, zeroForNull(equip_effect.increase_attack_chance)), 2.5) - 6 * Math.pow(
Math.abs(Math.min(0, zeroForNull(equip_effect.increase_attack_chance))), 2.7));
final int costAP = isWeapon ? final int costAP = isWeapon ?
(int) (0.2*Math.pow(10.0f/zeroForNull(equip_effect.increase_attack_cost), 8) - 25*zeroForNull(equip_effect.increase_attack_cost)) (int) (0.2 * Math.pow(10.0f / zeroForNull(equip_effect.increase_attack_cost), 8) - 25 * zeroForNull(equip_effect.increase_attack_cost))
:-3125 * zeroForNull(equip_effect.increase_attack_cost); : -3125 * zeroForNull(equip_effect.increase_attack_cost);
final int costDR = 1325 * zeroForNull(equip_effect.increase_damage_resistance); final int costDR = 1325 * zeroForNull(equip_effect.increase_damage_resistance);
final int costDMG_Min = isWeapon ? final int costDMG_Min = isWeapon ?
(int) (10*Math.pow(Math.max(0, zeroForNull(equip_effect.damage_boost_min)), 2.5)) (int) (10 * Math.pow(Math.max(0, zeroForNull(equip_effect.damage_boost_min)), 2.5))
:(int) (10*Math.pow(Math.max(0, zeroForNull(equip_effect.damage_boost_min)), 3) + zeroForNull(equip_effect.damage_boost_min)*80); : (int) (10 * Math.pow(Math.max(0, zeroForNull(equip_effect.damage_boost_min)), 3) + zeroForNull(equip_effect.damage_boost_min) * 80);
final int costDMG_Max = isWeapon ? final int costDMG_Max = isWeapon ?
(int) (2*Math.pow(Math.max(0, zeroForNull(equip_effect.damage_boost_max)), 2.1)) (int) (2 * Math.pow(Math.max(0, zeroForNull(equip_effect.damage_boost_max)), 2.1))
:(int) (2*Math.pow(Math.max(0, zeroForNull(equip_effect.damage_boost_max)), 3) + zeroForNull(equip_effect.damage_boost_max)*20); : (int) (2 * Math.pow(Math.max(0, zeroForNull(equip_effect.damage_boost_max)), 3) + zeroForNull(equip_effect.damage_boost_max) * 20);
final int costCS = (int) (2.2*Math.pow(zeroForNull(equip_effect.increase_critical_skill), 3)); final int costCS = (int) (2.2 * Math.pow(zeroForNull(equip_effect.increase_critical_skill), 3));
final int costCM = (int) (50*Math.pow(Math.max(0, zeroForNull(equip_effect.critical_multiplier)), 2)); final int costCM = (int) (50 * Math.pow(Math.max(0, zeroForNull(equip_effect.critical_multiplier)), 2));
final int costMaxHP = (int) (30*Math.pow(Math.max(0,zeroForNull(equip_effect.max_hp_boost)), 1.2) + 70*zeroForNull(equip_effect.max_hp_boost)); final int costMaxHP = (int) (30 * Math.pow(Math.max(0, zeroForNull(equip_effect.max_hp_boost)), 1.2) + 70 * zeroForNull(equip_effect.max_hp_boost));
final int costMaxAP = (int) (50*Math.pow(Math.max(0,zeroForNull(equip_effect.max_ap_boost)), 3) + 750*zeroForNull(equip_effect.max_ap_boost)); final int costMaxAP = (int) (50 * Math.pow(Math.max(0, zeroForNull(equip_effect.max_ap_boost)), 3) + 750 * zeroForNull(equip_effect.max_ap_boost));
final int costMovement = (int) (510*Math.pow(Math.max(0,-zeroForNull(equip_effect.increase_move_cost)), 2.5) - 350*zeroForNull(equip_effect.increase_move_cost)); final int costMovement = (int) (510 * Math.pow(Math.max(0, -zeroForNull(equip_effect.increase_move_cost)), 2.5) - 350 * zeroForNull(equip_effect.increase_move_cost));
final int costUseItem = (int)(915*Math.pow(Math.max(0,-zeroForNull(equip_effect.increase_use_item_cost)), 3) - 430*zeroForNull(equip_effect.increase_use_item_cost)); final int costUseItem = (int) (915 * Math.pow(Math.max(0, -zeroForNull(equip_effect.increase_use_item_cost)), 3) - 430 * zeroForNull(equip_effect.increase_use_item_cost));
final int costReequip = (int)(450*Math.pow(Math.max(0,-zeroForNull(equip_effect.increase_reequip_cost)), 2) - 250*zeroForNull(equip_effect.increase_reequip_cost)); final int costReequip = (int) (450 * Math.pow(Math.max(0, -zeroForNull(equip_effect.increase_reequip_cost)), 2) - 250 * zeroForNull(equip_effect.increase_reequip_cost));
return costBC + costAC + costAP + costDR + costDMG_Min + costDMG_Max + costCS + costCM return costBC + costAC + costAP + costDR + costDMG_Min + costDMG_Max + costCS + costCM
+ costMaxHP + costMaxAP + costMaxHP + costMaxAP
@@ -895,8 +470,8 @@ public class Item extends JSONElement {
final float averageAPBoost = (zeroForNull(hit_effect.ap_boost_min) + zeroForNull(hit_effect.ap_boost_max)) / 2.0f; final float averageAPBoost = (zeroForNull(hit_effect.ap_boost_min) + zeroForNull(hit_effect.ap_boost_max)) / 2.0f;
if (averageHPBoost == 0 && averageAPBoost == 0) return 0; if (averageHPBoost == 0 && averageAPBoost == 0) return 0;
final int costBoostHP = (int)(2770*Math.pow(Math.max(0,averageHPBoost), 2.5) + 450*averageHPBoost); final int costBoostHP = (int) (2770 * Math.pow(Math.max(0, averageHPBoost), 2.5) + 450 * averageHPBoost);
final int costBoostAP = (int)(3100*Math.pow(Math.max(0,averageAPBoost), 2.5) + 300*averageAPBoost); final int costBoostAP = (int) (3100 * Math.pow(Math.max(0, averageAPBoost), 2.5) + 300 * averageAPBoost);
return costBoostHP + costBoostAP; return costBoostHP + costBoostAP;
} }
@@ -905,8 +480,8 @@ public class Item extends JSONElement {
final float averageAPBoost = (zeroForNull(kill_effect.ap_boost_min) + zeroForNull(kill_effect.ap_boost_max)) / 2.0f; final float averageAPBoost = (zeroForNull(kill_effect.ap_boost_min) + zeroForNull(kill_effect.ap_boost_max)) / 2.0f;
if (averageHPBoost == 0 && averageAPBoost == 0) return 0; if (averageHPBoost == 0 && averageAPBoost == 0) return 0;
final int costBoostHP = (int)(923*Math.pow(Math.max(0,averageHPBoost), 2.5) + 450*averageHPBoost); final int costBoostHP = (int) (923 * Math.pow(Math.max(0, averageHPBoost), 2.5) + 450 * averageHPBoost);
final int costBoostAP = (int)(1033*Math.pow(Math.max(0,averageAPBoost), 2.5) + 300*averageAPBoost); final int costBoostAP = (int) (1033 * Math.pow(Math.max(0, averageAPBoost), 2.5) + 300 * averageAPBoost);
return costBoostHP + costBoostAP; return costBoostHP + costBoostAP;
} }
} }

View File

@@ -1,6 +1,13 @@
package com.gpl.rpg.atcontentstudio.model.gamedata; package com.gpl.rpg.atcontentstudio.model.gamedata;
import java.awt.Image; import com.gpl.rpg.atcontentstudio.Notification;
import com.gpl.rpg.atcontentstudio.model.GameDataElement;
import com.gpl.rpg.atcontentstudio.model.GameSource;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import javax.imageio.ImageIO;
import java.awt.*;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.FileReader; import java.io.FileReader;
@@ -9,15 +16,6 @@ import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import javax.imageio.ImageIO;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import com.gpl.rpg.atcontentstudio.Notification;
import com.gpl.rpg.atcontentstudio.model.GameDataElement;
import com.gpl.rpg.atcontentstudio.model.GameSource;
public class ItemCategory extends JSONElement { public class ItemCategory extends JSONElement {
private static final long serialVersionUID = -348864002519568300L; private static final long serialVersionUID = -348864002519568300L;
@@ -99,7 +97,7 @@ public class ItemCategory extends JSONElement {
@Override @Override
public String getDesc() { public String getDesc() {
return (needsSaving() ? "*" : "")+name+" ("+id+")"; return (needsSaving() ? "*" : "") + name + " (" + id + ")";
} }
public static String getStaticDesc() { public static String getStaticDesc() {
@@ -115,7 +113,7 @@ public class ItemCategory extends JSONElement {
reader = new FileReader(jsonFile); reader = new FileReader(jsonFile);
List itemCategories = (List) parser.parse(reader); List itemCategories = (List) parser.parse(reader);
for (Object obj : itemCategories) { for (Object obj : itemCategories) {
Map itemCatJson = (Map)obj; Map itemCatJson = (Map) obj;
ItemCategory itemCat = fromJson(itemCatJson); ItemCategory itemCat = fromJson(itemCatJson);
itemCat.jsonFile = jsonFile; itemCat.jsonFile = jsonFile;
itemCat.parent = category; itemCat.parent = category;
@@ -125,13 +123,13 @@ public class ItemCategory extends JSONElement {
category.add(itemCat); category.add(itemCat);
} }
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
} catch (IOException e) { } catch (IOException e) {
Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
} catch (ParseException e) { } catch (ParseException e) {
Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
if (reader != null) if (reader != null)
@@ -156,14 +154,16 @@ public class ItemCategory extends JSONElement {
ItemCategory itemCat = new ItemCategory(); ItemCategory itemCat = new ItemCategory();
itemCat.id = (String) itemCatJson.get("id"); itemCat.id = (String) itemCatJson.get("id");
itemCat.name = (String) itemCatJson.get("name"); itemCat.name = (String) itemCatJson.get("name");
if (itemCatJson.get("inventorySlot") != null) itemCat.slot = InventorySlot.valueOf((String) itemCatJson.get("inventorySlot")); if (itemCatJson.get("inventorySlot") != null)
itemCat.slot = InventorySlot.valueOf((String) itemCatJson.get("inventorySlot"));
return itemCat; return itemCat;
} }
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
@Override @Override
public void parse(Map itemCatJson) { public void parse(Map itemCatJson) {
if (itemCatJson.get("actionType") != null) action_type = ActionType.valueOf((String) itemCatJson.get("actionType")); if (itemCatJson.get("actionType") != null)
action_type = ActionType.valueOf((String) itemCatJson.get("actionType"));
if (itemCatJson.get("size") != null) size = Size.valueOf((String) itemCatJson.get("size")); if (itemCatJson.get("size") != null) size = Size.valueOf((String) itemCatJson.get("size"));
this.state = State.parsed; this.state = State.parsed;
@@ -171,17 +171,10 @@ public class ItemCategory extends JSONElement {
@Override @Override
public void link() { public void link() {
if (this.state == State.created || this.state == State.modified || this.state == State.saved) { if (shouldSkipParseOrLink()) {
//This type of state is unrelated to parsing/linking.
return;
}
if (this.state == State.init) {
//Not parsed yet.
this.parse();
} else if (this.state == State.linked) {
//Already linked.
return; return;
} }
ensureParseIfNeeded();
//Nothing to link to :D //Nothing to link to :D
this.state = State.linked; this.state = State.linked;
@@ -264,7 +257,7 @@ public class ItemCategory extends JSONElement {
} catch (NoSuchFieldException e) { } catch (NoSuchFieldException e) {
e.printStackTrace(); e.printStackTrace();
} catch (IOException e) { } catch (IOException e) {
Notification.addError("Failed to load item category icon "+res); Notification.addError("Failed to load item category icon " + res);
e.printStackTrace(); e.printStackTrace();
} }
} }
@@ -307,7 +300,7 @@ public class ItemCategory extends JSONElement {
// Nothing to link to. // Nothing to link to.
} }
@SuppressWarnings({ "rawtypes", "unchecked" }) @SuppressWarnings({"rawtypes", "unchecked"})
@Override @Override
public Map toJson() { public Map toJson() {
Map itemCatJson = new LinkedHashMap(); Map itemCatJson = new LinkedHashMap();
@@ -322,7 +315,7 @@ public class ItemCategory extends JSONElement {
@Override @Override
public String getProjectFilename() { public String getProjectFilename() {
return "itemcategories_"+getProject().name+".json"; return "itemcategories_" + getProject().name + ".json";
} }

View File

@@ -1,21 +1,17 @@
package com.gpl.rpg.atcontentstudio.model.gamedata; package com.gpl.rpg.atcontentstudio.model.gamedata;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.StringWriter;
import java.util.List;
import java.util.Map;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import com.gpl.rpg.atcontentstudio.Notification; import com.gpl.rpg.atcontentstudio.Notification;
import com.gpl.rpg.atcontentstudio.io.JsonPrettyWriter; import com.gpl.rpg.atcontentstudio.io.JsonPrettyWriter;
import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.GameDataElement;
import com.gpl.rpg.atcontentstudio.model.SaveEvent; import com.gpl.rpg.atcontentstudio.model.SaveEvent;
import com.gpl.rpg.atcontentstudio.utils.FileUtils;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.*;
import java.util.List;
import java.util.Map;
public abstract class JSONElement extends GameDataElement { public abstract class JSONElement extends GameDataElement {
@@ -26,8 +22,7 @@ public abstract class JSONElement extends GameDataElement {
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
public void parse() { public void parse() {
if (this.state == State.created || this.state == State.modified || this.state == State.saved) { if (shouldSkipParse()) {
//This type of state is unrelated to parsing/linking.
return; return;
} }
JSONParser parser = new JSONParser(); JSONParser parser = new JSONParser();
@@ -36,31 +31,31 @@ public abstract class JSONElement extends GameDataElement {
reader = new FileReader(jsonFile); reader = new FileReader(jsonFile);
List gameDataElements = (List) parser.parse(reader); List gameDataElements = (List) parser.parse(reader);
for (Object obj : gameDataElements) { for (Object obj : gameDataElements) {
Map jsonObj = (Map)obj; Map jsonObj = (Map) obj;
String id = (String) jsonObj.get("id"); String id = (String) jsonObj.get("id");
try { try {
if (id != null && id.equals(this.id )) { if (id != null && id.equals(this.id)) {
this.parse(jsonObj); this.parse(jsonObj);
this.state = State.parsed; this.state = State.parsed;
break; break;
} }
} } catch (Exception e) {
catch(Exception e){
System.out.println("Error in ID: " + id); System.out.println("Error in ID: " + id);
System.out.println(e.getMessage());
} }
} }
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
} catch (IOException e) { } catch (IOException e) {
Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
} catch (ParseException e) { } catch (ParseException e) {
Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
System.out.println(id); System.out.println(id);
Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
if (reader != null) if (reader != null)
@@ -77,16 +72,11 @@ public abstract class JSONElement extends GameDataElement {
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
public abstract Map toJson(); public abstract Map toJson();
public String toJsonString() {
StringWriter writer = new JsonPrettyWriter();
try {
JSONObject.writeJSONString(this.toJson(), writer);
} catch (IOException e) {
//Impossible with a StringWriter
}
return writer.toString();
}
public String toJsonString() {
Map json = this.toJson();
return FileUtils.toJsonString(json);
}
@Override @Override
public GameDataSet getDataSet() { public GameDataSet getDataSet() {
@@ -98,7 +88,7 @@ public abstract class JSONElement extends GameDataElement {
public void save() { public void save() {
if (this.getParent() instanceof GameDataCategory<?> && writable) { if (this.getParent() instanceof GameDataCategory<?> && writable) {
((GameDataCategory<?>)this.getParent()).save(this.jsonFile); ((GameDataCategory<?>) this.getParent()).save(this.jsonFile);
} }
} }
@@ -106,7 +96,7 @@ public abstract class JSONElement extends GameDataElement {
* Returns null if save occurred (no notable events). * Returns null if save occurred (no notable events).
*/ */
public List<SaveEvent> attemptSave() { public List<SaveEvent> attemptSave() {
List<SaveEvent> events = ((GameDataCategory<?>)this.getParent()).attemptSave(true, this.jsonFile.getName()); List<SaveEvent> events = ((GameDataCategory<?>) this.getParent()).attemptSave(true, this.jsonFile.getName());
if (events == null || events.isEmpty()) { if (events == null || events.isEmpty()) {
return null; return null;
} }
@@ -141,18 +131,20 @@ public abstract class JSONElement extends GameDataElement {
double a = 1; double a = 1;
try { try {
a = Integer.parseInt(s.substring(0, c)); a = Integer.parseInt(s.substring(0, c));
} catch (NumberFormatException nfe) {} } catch (NumberFormatException nfe) {
}
double b = 100; double b = 100;
try { try {
b = Integer.parseInt(s.substring(c+1)); b = Integer.parseInt(s.substring(c + 1));
} catch (NumberFormatException nfe) {} } catch (NumberFormatException nfe) {
return a/b;
} }
else { return a / b;
} else {
double a = 10; double a = 10;
try { try {
a = Double.parseDouble(s); a = Double.parseDouble(s);
} catch (NumberFormatException nfe) {} } catch (NumberFormatException nfe) {
}
return a; return a;
} }
} }

View File

@@ -1,22 +1,22 @@
package com.gpl.rpg.atcontentstudio.model.gamedata; package com.gpl.rpg.atcontentstudio.model.gamedata;
import java.awt.Image;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import com.gpl.rpg.atcontentstudio.Notification; import com.gpl.rpg.atcontentstudio.Notification;
import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.GameDataElement;
import com.gpl.rpg.atcontentstudio.model.GameSource; import com.gpl.rpg.atcontentstudio.model.GameSource;
import com.gpl.rpg.atcontentstudio.model.Project; import com.gpl.rpg.atcontentstudio.model.Project;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.awt.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static com.gpl.rpg.atcontentstudio.model.gamedata.Common.*;
public class NPC extends JSONElement { public class NPC extends JSONElement {
@@ -73,43 +73,9 @@ public class NPC extends JSONElement {
wholeMap wholeMap
} }
public static class DeathEffect {
//Available from parsed state
public Integer hp_boost_min = null;
public Integer hp_boost_max = null;
public Integer ap_boost_min = null;
public Integer ap_boost_max = null;
public List<TimedConditionEffect> conditions_source = null;
}
public static class HitEffect extends DeathEffect {
//Available from parsed state
public List<TimedConditionEffect> conditions_target = null;
}
public static class HitReceivedEffect extends HitEffect {
//Available from parsed state
public Integer hp_boost_min_target = null;
public Integer hp_boost_max_target = null;
public Integer ap_boost_min_target = null;
public Integer ap_boost_max_target = null;
}
public static class TimedConditionEffect {
//Available from parsed state
public Integer magnitude = null;
public String condition_id = null;
public Integer duration = null;
public Double chance = null;
//Available from linked state
public ActorCondition condition = null;
}
@Override @Override
public String getDesc() { public String getDesc() {
return (needsSaving() ? "*" : "")+name+" ("+id+")"; return (needsSaving() ? "*" : "") + name + " (" + id + ")";
} }
public static String getStaticDesc() { public static String getStaticDesc() {
@@ -125,7 +91,7 @@ public class NPC extends JSONElement {
reader = new FileReader(jsonFile); reader = new FileReader(jsonFile);
List npcs = (List) parser.parse(reader); List npcs = (List) parser.parse(reader);
for (Object obj : npcs) { for (Object obj : npcs) {
Map npcJson = (Map)obj; Map npcJson = (Map) obj;
NPC npc = fromJson(npcJson); NPC npc = fromJson(npcJson);
npc.jsonFile = jsonFile; npc.jsonFile = jsonFile;
npc.parent = category; npc.parent = category;
@@ -135,13 +101,13 @@ public class NPC extends JSONElement {
category.add(npc); category.add(npc);
} }
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
} catch (IOException e) { } catch (IOException e) {
Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
} catch (ParseException e) { } catch (ParseException e) {
Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
if (reader != null) if (reader != null)
@@ -179,11 +145,13 @@ public class NPC extends JSONElement {
this.max_ap = JSONElement.getInteger((Number) npcJson.get("maxAP")); this.max_ap = JSONElement.getInteger((Number) npcJson.get("maxAP"));
this.move_cost = JSONElement.getInteger((Number) npcJson.get("moveCost")); this.move_cost = JSONElement.getInteger((Number) npcJson.get("moveCost"));
this.unique = JSONElement.getInteger((Number) npcJson.get("unique")); this.unique = JSONElement.getInteger((Number) npcJson.get("unique"));
if (npcJson.get("monsterClass") != null) this.monster_class = MonsterClass.valueOf((String) npcJson.get("monsterClass")); if (npcJson.get("monsterClass") != null)
if (npcJson.get("movementAggressionType") != null) this.movement_type = MovementType.valueOf((String) npcJson.get("movementAggressionType")); this.monster_class = MonsterClass.valueOf((String) npcJson.get("monsterClass"));
if (npcJson.get("movementAggressionType") != null)
this.movement_type = MovementType.valueOf((String) npcJson.get("movementAggressionType"));
if (npcJson.get("attackDamage") != null) { if (npcJson.get("attackDamage") != null) {
this.attack_damage_min = JSONElement.getInteger((Number) (((Map)npcJson.get("attackDamage")).get("min"))); this.attack_damage_min = JSONElement.getInteger((Number) (((Map) npcJson.get("attackDamage")).get("min")));
this.attack_damage_max = JSONElement.getInteger((Number) (((Map)npcJson.get("attackDamage")).get("max"))); this.attack_damage_max = JSONElement.getInteger((Number) (((Map) npcJson.get("attackDamage")).get("max")));
} }
this.spawngroup_id = (String) npcJson.get("spawnGroup"); this.spawngroup_id = (String) npcJson.get("spawnGroup");
this.faction_id = (String) npcJson.get("faction"); this.faction_id = (String) npcJson.get("faction");
@@ -194,184 +162,49 @@ public class NPC extends JSONElement {
this.critical_skill = JSONElement.getInteger((Number) npcJson.get("criticalSkill")); this.critical_skill = JSONElement.getInteger((Number) npcJson.get("criticalSkill"));
//TODO correct game data, to unify format. //TODO correct game data, to unify format.
// this.critical_multiplier = JSONElement.getDouble((Number) npcJson.get("criticalMultiplier")); // this.critical_multiplier = JSONElement.getDouble((Number) npcJson.get("criticalMultiplier"));
if (npcJson.get("criticalMultiplier") != null) this.critical_multiplier = JSONElement.getDouble(Double.parseDouble(npcJson.get("criticalMultiplier").toString())); if (npcJson.get("criticalMultiplier") != null)
this.critical_multiplier = JSONElement.getDouble(Double.parseDouble(npcJson.get("criticalMultiplier").toString()));
this.block_chance = JSONElement.getInteger((Number) npcJson.get("blockChance")); this.block_chance = JSONElement.getInteger((Number) npcJson.get("blockChance"));
this.damage_resistance = JSONElement.getInteger((Number) npcJson.get("damageResistance")); this.damage_resistance = JSONElement.getInteger((Number) npcJson.get("damageResistance"));
Map hitEffect = (Map) npcJson.get("hitEffect"); Map hitEffect = (Map) npcJson.get("hitEffect");
if (hitEffect != null) { if (hitEffect != null) {
this.hit_effect = new HitEffect(); this.hit_effect = parseHitEffect(hitEffect);
if (hitEffect.get("increaseCurrentHP") != null) {
this.hit_effect.hp_boost_max = JSONElement.getInteger((Number) (((Map)hitEffect.get("increaseCurrentHP")).get("max")));
this.hit_effect.hp_boost_min = JSONElement.getInteger((Number) (((Map)hitEffect.get("increaseCurrentHP")).get("min")));
}
if (hitEffect.get("increaseCurrentAP") != null) {
this.hit_effect.ap_boost_max = JSONElement.getInteger((Number) (((Map)hitEffect.get("increaseCurrentAP")).get("max")));
this.hit_effect.ap_boost_min = JSONElement.getInteger((Number) (((Map)hitEffect.get("increaseCurrentAP")).get("min")));
}
List conditionsSourceJson = (List) hitEffect.get("conditionsSource");
if (conditionsSourceJson != null && !conditionsSourceJson.isEmpty()) {
this.hit_effect.conditions_source = new ArrayList<NPC.TimedConditionEffect>();
for (Object conditionJsonObj : conditionsSourceJson) {
Map conditionJson = (Map)conditionJsonObj;
TimedConditionEffect condition = new TimedConditionEffect();
condition.condition_id = (String) conditionJson.get("condition");
condition.magnitude = JSONElement.getInteger((Number) conditionJson.get("magnitude"));
condition.duration = JSONElement.getInteger((Number) conditionJson.get("duration"));
if (conditionJson.get("chance") != null) condition.chance = JSONElement.parseChance(conditionJson.get("chance").toString());
this.hit_effect.conditions_source.add(condition);
}
}
List conditionsTargetJson = (List) hitEffect.get("conditionsTarget");
if (conditionsTargetJson != null && !conditionsTargetJson.isEmpty()) {
this.hit_effect.conditions_target = new ArrayList<NPC.TimedConditionEffect>();
for (Object conditionJsonObj : conditionsTargetJson) {
Map conditionJson = (Map)conditionJsonObj;
TimedConditionEffect condition = new TimedConditionEffect();
condition.condition_id = (String) conditionJson.get("condition");
condition.magnitude = JSONElement.getInteger((Number) conditionJson.get("magnitude"));
condition.duration = JSONElement.getInteger((Number) conditionJson.get("duration"));
if (conditionJson.get("chance") != null) condition.chance = JSONElement.parseChance(conditionJson.get("chance").toString());
this.hit_effect.conditions_target.add(condition);
}
}
} }
Map hitReceivedEffect = (Map) npcJson.get("hitReceivedEffect"); Map hitReceivedEffect = (Map) npcJson.get("hitReceivedEffect");
if (hitReceivedEffect != null) { if (hitReceivedEffect != null) {
this.hit_received_effect = new HitReceivedEffect(); this.hit_received_effect = parseHitReceivedEffect(hitReceivedEffect);
if (hitReceivedEffect.get("increaseCurrentHP") != null) {
this.hit_received_effect.hp_boost_max = JSONElement.getInteger((Number) (((Map)hitReceivedEffect.get("increaseCurrentHP")).get("max")));
this.hit_received_effect.hp_boost_min = JSONElement.getInteger((Number) (((Map)hitReceivedEffect.get("increaseCurrentHP")).get("min")));
}
if (hitReceivedEffect.get("increaseCurrentAP") != null) {
this.hit_received_effect.ap_boost_max = JSONElement.getInteger((Number) (((Map)hitReceivedEffect.get("increaseCurrentAP")).get("max")));
this.hit_received_effect.ap_boost_min = JSONElement.getInteger((Number) (((Map)hitReceivedEffect.get("increaseCurrentAP")).get("min")));
}
if (hitReceivedEffect.get("increaseAttackerCurrentHP") != null) {
this.hit_received_effect.hp_boost_max_target = JSONElement.getInteger((Number) (((Map)hitReceivedEffect.get("increaseAttackerCurrentHP")).get("max")));
this.hit_received_effect.hp_boost_min_target = JSONElement.getInteger((Number) (((Map)hitReceivedEffect.get("increaseAttackerCurrentHP")).get("min")));
}
if (hitReceivedEffect.get("increaseAttackerCurrentAP") != null) {
this.hit_received_effect.ap_boost_max_target = JSONElement.getInteger((Number) (((Map)hitReceivedEffect.get("increaseAttackerCurrentAP")).get("max")));
this.hit_received_effect.ap_boost_min_target = JSONElement.getInteger((Number) (((Map)hitReceivedEffect.get("increaseAttackerCurrentAP")).get("min")));
}
List conditionsSourceJson = (List) hitReceivedEffect.get("conditionsSource");
if (conditionsSourceJson != null && !conditionsSourceJson.isEmpty()) {
this.hit_received_effect.conditions_source = new ArrayList<NPC.TimedConditionEffect>();
for (Object conditionJsonObj : conditionsSourceJson) {
Map conditionJson = (Map)conditionJsonObj;
TimedConditionEffect condition = new TimedConditionEffect();
condition.condition_id = (String) conditionJson.get("condition");
condition.magnitude = JSONElement.getInteger((Number) conditionJson.get("magnitude"));
condition.duration = JSONElement.getInteger((Number) conditionJson.get("duration"));
if (conditionJson.get("chance") != null) condition.chance = JSONElement.parseChance(conditionJson.get("chance").toString());
this.hit_received_effect.conditions_source.add(condition);
}
}
List conditionsTargetJson = (List) hitReceivedEffect.get("conditionsTarget");
if (conditionsTargetJson != null && !conditionsTargetJson.isEmpty()) {
this.hit_received_effect.conditions_target = new ArrayList<NPC.TimedConditionEffect>();
for (Object conditionJsonObj : conditionsTargetJson) {
Map conditionJson = (Map)conditionJsonObj;
TimedConditionEffect condition = new TimedConditionEffect();
condition.condition_id = (String) conditionJson.get("condition");
condition.magnitude = JSONElement.getInteger((Number) conditionJson.get("magnitude"));
condition.duration = JSONElement.getInteger((Number) conditionJson.get("duration"));
if (conditionJson.get("chance") != null) condition.chance = JSONElement.parseChance(conditionJson.get("chance").toString());
this.hit_received_effect.conditions_target.add(condition);
}
}
} }
Map deathEffect = (Map) npcJson.get("deathEffect"); Map deathEffect = (Map) npcJson.get("deathEffect");
if (deathEffect != null) { if (deathEffect != null) {
this.death_effect = new HitEffect(); this.death_effect = parseDeathEffect(deathEffect);
if (deathEffect.get("increaseCurrentHP") != null) {
this.death_effect.hp_boost_max = JSONElement.getInteger((Number) (((Map)deathEffect.get("increaseCurrentHP")).get("max")));
this.death_effect.hp_boost_min = JSONElement.getInteger((Number) (((Map)deathEffect.get("increaseCurrentHP")).get("min")));
} }
if (deathEffect.get("increaseCurrentAP") != null) {
this.death_effect.ap_boost_max = JSONElement.getInteger((Number) (((Map)deathEffect.get("increaseCurrentAP")).get("max")));
this.death_effect.ap_boost_min = JSONElement.getInteger((Number) (((Map)deathEffect.get("increaseCurrentAP")).get("min")));
}
List conditionsSourceJson = (List) deathEffect.get("conditionsSource");
if (conditionsSourceJson != null && !conditionsSourceJson.isEmpty()) {
this.death_effect.conditions_source = new ArrayList<NPC.TimedConditionEffect>();
for (Object conditionJsonObj : conditionsSourceJson) {
Map conditionJson = (Map)conditionJsonObj;
TimedConditionEffect condition = new TimedConditionEffect();
condition.condition_id = (String) conditionJson.get("condition");
condition.magnitude = JSONElement.getInteger((Number) conditionJson.get("magnitude"));
condition.duration = JSONElement.getInteger((Number) conditionJson.get("duration"));
if (conditionJson.get("chance") != null) condition.chance = JSONElement.parseChance(conditionJson.get("chance").toString());
this.death_effect.conditions_source.add(condition);
}
}
}
} }
@Override @Override
public void link() { public void link() {
if (this.state == State.created || this.state == State.modified || this.state == State.saved) { if (shouldSkipParseOrLink()) {
//This type of state is unrelated to parsing/linking.
return;
}
if (this.state == State.init) {
//Not parsed yet.
this.parse();
} else if (this.state == State.linked) {
//Already linked.
return; return;
} }
ensureParseIfNeeded();
Project proj = getProject(); Project proj = getProject();
if (proj == null) { if (proj == null) {
Notification.addError("Error linking item "+id+". No parent project found."); Notification.addError("Error linking item " + id + ". No parent project found.");
return; return;
} }
if (this.icon_id != null) { linkIcon(proj, this.icon_id, this);
String spritesheetId = this.icon_id.split(":")[0];
proj.getSpritesheet(spritesheetId).addBacklink(this);
}
if (this.dialogue_id != null) this.dialogue = proj.getDialogue(this.dialogue_id); if (this.dialogue_id != null) this.dialogue = proj.getDialogue(this.dialogue_id);
if (this.dialogue != null) this.dialogue.addBacklink(this); if (this.dialogue != null) this.dialogue.addBacklink(this);
if (this.droplist_id != null) this.droplist = proj.getDroplist(this.droplist_id); if (this.droplist_id != null) this.droplist = proj.getDroplist(this.droplist_id);
if (this.droplist != null) this.droplist.addBacklink(this); if (this.droplist != null) this.droplist.addBacklink(this);
if (this.hit_effect != null && this.hit_effect.conditions_source != null) { linkEffects(this.hit_effect, proj, this);
for (TimedConditionEffect ce : this.hit_effect.conditions_source) { linkEffects(this.hit_received_effect, proj, this);
if (ce.condition_id != null) ce.condition = proj.getActorCondition(ce.condition_id); linkEffects(this.death_effect, proj, this);
if (ce.condition != null) ce.condition.addBacklink(this);
}
}
if (this.hit_effect != null && this.hit_effect.conditions_target != null) {
for (TimedConditionEffect ce : this.hit_effect.conditions_target) {
if (ce.condition_id != null) ce.condition = proj.getActorCondition(ce.condition_id);
if (ce.condition != null) ce.condition.addBacklink(this);
}
}
if (this.hit_received_effect != null && this.hit_received_effect.conditions_source != null) {
for (TimedConditionEffect ce : this.hit_received_effect.conditions_source) {
if (ce.condition_id != null) ce.condition = proj.getActorCondition(ce.condition_id);
if (ce.condition != null) ce.condition.addBacklink(this);
}
}
if (this.hit_received_effect != null && this.hit_received_effect.conditions_target != null) {
for (TimedConditionEffect ce : this.hit_received_effect.conditions_target) {
if (ce.condition_id != null) ce.condition = proj.getActorCondition(ce.condition_id);
if (ce.condition != null) ce.condition.addBacklink(this);
}
}
if (this.death_effect != null && this.death_effect.conditions_source != null) {
for (TimedConditionEffect ce : this.death_effect.conditions_source) {
if (ce.condition_id != null) ce.condition = proj.getActorCondition(ce.condition_id);
if (ce.condition != null) ce.condition.addBacklink(this);
}
}
this.state = State.linked; this.state = State.linked;
} }
@@ -413,103 +246,15 @@ public class NPC extends JSONElement {
clone.faction_id = this.faction_id; clone.faction_id = this.faction_id;
if (this.hit_effect != null) { if (this.hit_effect != null) {
clone.hit_effect = new HitEffect(); clone.hit_effect = new HitEffect();
clone.hit_effect.ap_boost_max = this.hit_effect.ap_boost_max; copyHitEffectValues(clone.hit_effect, this.hit_effect, clone);
clone.hit_effect.ap_boost_min = this.hit_effect.ap_boost_min;
clone.hit_effect.hp_boost_max = this.hit_effect.hp_boost_max;
clone.hit_effect.hp_boost_min = this.hit_effect.hp_boost_min;
if (this.hit_effect.conditions_source != null) {
clone.hit_effect.conditions_source = new ArrayList<TimedConditionEffect>();
for (TimedConditionEffect c : this.hit_effect.conditions_source) {
TimedConditionEffect cclone = new TimedConditionEffect();
cclone.magnitude = c.magnitude;
cclone.condition_id = c.condition_id;
cclone.condition = c.condition;
cclone.chance = c.chance;
cclone.duration = c.duration;
if (cclone.condition != null) {
cclone.condition.addBacklink(clone);
}
clone.hit_effect.conditions_source.add(cclone);
}
}
if (this.hit_effect.conditions_target != null) {
clone.hit_effect.conditions_target = new ArrayList<TimedConditionEffect>();
for (TimedConditionEffect c : this.hit_effect.conditions_target) {
TimedConditionEffect cclone = new TimedConditionEffect();
cclone.magnitude = c.magnitude;
cclone.condition_id = c.condition_id;
cclone.condition = c.condition;
cclone.chance = c.chance;
cclone.duration = c.duration;
if (cclone.condition != null) {
cclone.condition.addBacklink(clone);
}
clone.hit_effect.conditions_target.add(cclone);
}
}
} }
if (this.hit_received_effect != null) { if (this.hit_received_effect != null) {
clone.hit_received_effect = new HitReceivedEffect(); clone.hit_received_effect = new HitReceivedEffect();
clone.hit_received_effect.ap_boost_max = this.hit_received_effect.ap_boost_max; copyHitReceivedEffectValues(clone.hit_received_effect, this.hit_received_effect, clone);
clone.hit_received_effect.ap_boost_min = this.hit_received_effect.ap_boost_min;
clone.hit_received_effect.hp_boost_max = this.hit_received_effect.hp_boost_max;
clone.hit_received_effect.hp_boost_min = this.hit_received_effect.hp_boost_min;
clone.hit_received_effect.ap_boost_max_target = this.hit_received_effect.ap_boost_max_target;
clone.hit_received_effect.ap_boost_min_target = this.hit_received_effect.ap_boost_min_target;
clone.hit_received_effect.hp_boost_max_target = this.hit_received_effect.hp_boost_max_target;
clone.hit_received_effect.hp_boost_min_target = this.hit_received_effect.hp_boost_min_target;
if (this.hit_received_effect.conditions_source != null) {
clone.hit_received_effect.conditions_source = new ArrayList<TimedConditionEffect>();
for (TimedConditionEffect c : this.hit_received_effect.conditions_source) {
TimedConditionEffect cclone = new TimedConditionEffect();
cclone.magnitude = c.magnitude;
cclone.condition_id = c.condition_id;
cclone.condition = c.condition;
cclone.chance = c.chance;
cclone.duration = c.duration;
if (cclone.condition != null) {
cclone.condition.addBacklink(clone);
}
clone.hit_received_effect.conditions_source.add(cclone);
}
}
if (this.hit_received_effect.conditions_target != null) {
clone.hit_received_effect.conditions_target = new ArrayList<TimedConditionEffect>();
for (TimedConditionEffect c : this.hit_received_effect.conditions_target) {
TimedConditionEffect cclone = new TimedConditionEffect();
cclone.magnitude = c.magnitude;
cclone.condition_id = c.condition_id;
cclone.condition = c.condition;
cclone.chance = c.chance;
cclone.duration = c.duration;
if (cclone.condition != null) {
cclone.condition.addBacklink(clone);
}
clone.hit_received_effect.conditions_target.add(cclone);
}
}
} }
if (this.death_effect != null) { if (this.death_effect != null) {
clone.death_effect = new DeathEffect(); clone.death_effect = new DeathEffect();
clone.death_effect.ap_boost_max = this.death_effect.ap_boost_max; copyDeathEffectValues(clone.death_effect, this.death_effect, clone);
clone.death_effect.ap_boost_min = this.death_effect.ap_boost_min;
clone.death_effect.hp_boost_max = this.death_effect.hp_boost_max;
clone.death_effect.hp_boost_min = this.death_effect.hp_boost_min;
if (this.death_effect.conditions_source != null) {
clone.death_effect.conditions_source = new ArrayList<TimedConditionEffect>();
for (TimedConditionEffect c : this.death_effect.conditions_source) {
TimedConditionEffect cclone = new TimedConditionEffect();
cclone.magnitude = c.magnitude;
cclone.condition_id = c.condition_id;
cclone.condition = c.condition;
cclone.chance = c.chance;
cclone.duration = c.duration;
if (cclone.condition != null) {
cclone.condition.addBacklink(clone);
}
clone.death_effect.conditions_source.add(cclone);
}
}
} }
clone.max_ap = this.max_ap; clone.max_ap = this.max_ap;
clone.max_hp = this.max_hp; clone.max_hp = this.max_hp;
@@ -533,49 +278,28 @@ public class NPC extends JSONElement {
this.droplist = (Droplist) newOne; this.droplist = (Droplist) newOne;
if (newOne != null) newOne.addBacklink(this); if (newOne != null) newOne.addBacklink(this);
} else { } else {
if (this.hit_effect != null && this.hit_effect.conditions_source != null) { if (this.hit_effect != null) {
for (TimedConditionEffect tce : this.hit_effect.conditions_source) { actorConditionElementChanged(this.hit_effect.conditions_source, oldOne, newOne, this);
if (tce.condition == oldOne) { actorConditionElementChanged(this.hit_effect.conditions_target, oldOne, newOne, this);
oldOne.removeBacklink(this);
tce.condition = (ActorCondition) newOne;
if (newOne != null) newOne.addBacklink(this);
}
}
}
if (this.hit_effect != null && this.hit_effect.conditions_target != null) {
for (TimedConditionEffect tce : this.hit_effect.conditions_target) {
if (tce.condition == oldOne) {
oldOne.removeBacklink(this);
tce.condition = (ActorCondition) newOne;
if (newOne != null) newOne.addBacklink(this);
}
}
} }
} }
} }
} }
@SuppressWarnings({ "rawtypes", "unchecked" }) @SuppressWarnings({"rawtypes", "unchecked"})
@Override @Override
public Map toJson() { public Map toJson() {
Map npcJson = new LinkedHashMap(); Map npcJson = new LinkedHashMap();
npcJson.put("id", this.id); npcJson.put("id", this.id);
if (this.name != null) npcJson.put("name", this.name); if (this.name != null) npcJson.put("name", this.name);
if (this.icon_id != null) npcJson.put("iconID", this.icon_id); writeIconToMap(npcJson, this.icon_id);
if (this.max_hp != null) npcJson.put("maxHP", this.max_hp); if (this.max_hp != null) npcJson.put("maxHP", this.max_hp);
if (this.max_ap != null) npcJson.put("maxAP", this.max_ap); if (this.max_ap != null) npcJson.put("maxAP", this.max_ap);
if (this.move_cost != null) npcJson.put("moveCost", this.move_cost); if (this.move_cost != null) npcJson.put("moveCost", this.move_cost);
if (this.unique != null) npcJson.put("unique", this.unique); if (this.unique != null) npcJson.put("unique", this.unique);
if (this.monster_class != null) npcJson.put("monsterClass", this.monster_class.toString()); if (this.monster_class != null) npcJson.put("monsterClass", this.monster_class.toString());
if (this.movement_type != null) npcJson.put("movementAggressionType", this.movement_type.toString()); if (this.movement_type != null) npcJson.put("movementAggressionType", this.movement_type.toString());
if (this.attack_damage_min != null || this.attack_damage_max != null) { writeMinMaxToMap(npcJson, "attackDamage", this.attack_damage_min, attack_damage_max, 0);
Map adJson = new LinkedHashMap();
npcJson.put("attackDamage", adJson);
if (this.attack_damage_min != null) adJson.put("min", this.attack_damage_min);
else adJson.put("min", 0);
if (this.attack_damage_max != null) adJson.put("max", this.attack_damage_max);
else adJson.put("max", 0);
}
if (this.spawngroup_id != null) npcJson.put("spawnGroup", this.spawngroup_id); if (this.spawngroup_id != null) npcJson.put("spawnGroup", this.spawngroup_id);
if (this.faction_id != null) npcJson.put("faction", this.faction_id); if (this.faction_id != null) npcJson.put("faction", this.faction_id);
if (this.dialogue != null) { if (this.dialogue != null) {
@@ -594,186 +318,34 @@ public class NPC extends JSONElement {
if (this.critical_multiplier != null) npcJson.put("criticalMultiplier", this.critical_multiplier); if (this.critical_multiplier != null) npcJson.put("criticalMultiplier", this.critical_multiplier);
if (this.block_chance != null) npcJson.put("blockChance", this.block_chance); if (this.block_chance != null) npcJson.put("blockChance", this.block_chance);
if (this.damage_resistance != null) npcJson.put("damageResistance", this.damage_resistance); if (this.damage_resistance != null) npcJson.put("damageResistance", this.damage_resistance);
if (this.hit_effect != null) { writeHitEffectToMap(npcJson, this.hit_effect, "hitEffect");
Map hitEffectJson = new LinkedHashMap(); writeHitReceivedEffectToMap(npcJson, this.hit_received_effect, "hitReceivedEffect");
npcJson.put("hitEffect", hitEffectJson); writeDeathEffectToMap(npcJson, this.death_effect, "deathEffect");
if (this.hit_effect.hp_boost_min != null || this.hit_effect.hp_boost_max != null) {
Map hpJson = new LinkedHashMap();
hitEffectJson.put("increaseCurrentHP", hpJson);
if (this.hit_effect.hp_boost_min != null) hpJson.put("min", this.hit_effect.hp_boost_min);
else hpJson.put("min", 0);
if (this.hit_effect.hp_boost_max != null) hpJson.put("max", this.hit_effect.hp_boost_max);
else hpJson.put("max", 0);
}
if (this.hit_effect.ap_boost_min != null || this.hit_effect.ap_boost_max != null) {
Map apJson = new LinkedHashMap();
hitEffectJson.put("increaseCurrentAP", apJson);
if (this.hit_effect.ap_boost_min != null) apJson.put("min", this.hit_effect.ap_boost_min);
else apJson.put("min", 0);
if (this.hit_effect.ap_boost_max != null) apJson.put("max", this.hit_effect.ap_boost_max);
else apJson.put("max", 0);
}
if (this.hit_effect.conditions_source != null) {
List conditionsSourceJson = new ArrayList();
hitEffectJson.put("conditionsSource", conditionsSourceJson);
for (TimedConditionEffect condition : this.hit_effect.conditions_source) {
Map conditionJson = new LinkedHashMap();
conditionsSourceJson.add(conditionJson);
if (condition.condition != null) {
conditionJson.put("condition", condition.condition.id);
} else if (condition.condition_id != null) {
conditionJson.put("condition", condition.condition_id);
}
if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude);
if (condition.duration != null) conditionJson.put("duration", condition.duration);
if (condition.chance != null) conditionJson.put("chance", JSONElement.printJsonChance(condition.chance));
}
}
if (this.hit_effect.conditions_target != null) {
List conditionsTargetJson = new ArrayList();
hitEffectJson.put("conditionsTarget", conditionsTargetJson);
for (TimedConditionEffect condition : this.hit_effect.conditions_target) {
Map conditionJson = new LinkedHashMap();
conditionsTargetJson.add(conditionJson);
if (condition.condition != null) {
conditionJson.put("condition", condition.condition.id);
} else if (condition.condition_id != null) {
conditionJson.put("condition", condition.condition_id);
}
if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude);
if (condition.duration != null) conditionJson.put("duration", condition.duration);
if (condition.chance != null) conditionJson.put("chance", JSONElement.printJsonChance(condition.chance));
}
}
}
if (this.hit_received_effect != null) {
Map hitReceivedEffectJson = new LinkedHashMap();
npcJson.put("hitReceivedEffect", hitReceivedEffectJson);
if (this.hit_received_effect.hp_boost_min != null || this.hit_received_effect.hp_boost_max != null) {
Map hpJson = new LinkedHashMap();
hitReceivedEffectJson.put("increaseCurrentHP", hpJson);
if (this.hit_received_effect.hp_boost_min != null) hpJson.put("min", this.hit_received_effect.hp_boost_min);
else hpJson.put("min", 0);
if (this.hit_received_effect.hp_boost_max != null) hpJson.put("max", this.hit_received_effect.hp_boost_max);
else hpJson.put("max", 0);
}
if (this.hit_received_effect.ap_boost_min != null || this.hit_received_effect.ap_boost_max != null) {
Map apJson = new LinkedHashMap();
hitReceivedEffectJson.put("increaseCurrentAP", apJson);
if (this.hit_received_effect.ap_boost_min != null) apJson.put("min", this.hit_received_effect.ap_boost_min);
else apJson.put("min", 0);
if (this.hit_received_effect.ap_boost_max != null) apJson.put("max", this.hit_received_effect.ap_boost_max);
else apJson.put("max", 0);
}
if (this.hit_received_effect.hp_boost_min_target != null || this.hit_received_effect.hp_boost_max_target != null) {
Map hpJson = new LinkedHashMap();
hitReceivedEffectJson.put("increaseAttackerCurrentHP", hpJson);
if (this.hit_received_effect.hp_boost_min_target != null) hpJson.put("min", this.hit_received_effect.hp_boost_min_target);
else hpJson.put("min", 0);
if (this.hit_received_effect.hp_boost_max_target != null) hpJson.put("max", this.hit_received_effect.hp_boost_max_target);
else hpJson.put("max", 0);
}
if (this.hit_received_effect.ap_boost_min_target != null || this.hit_received_effect.ap_boost_max_target != null) {
Map apJson = new LinkedHashMap();
hitReceivedEffectJson.put("increaseAttackerCurrentAP", apJson);
if (this.hit_received_effect.ap_boost_min_target != null) apJson.put("min", this.hit_received_effect.ap_boost_min_target);
else apJson.put("min", 0);
if (this.hit_received_effect.ap_boost_max_target != null) apJson.put("max", this.hit_received_effect.ap_boost_max_target);
else apJson.put("max", 0);
}
if (this.hit_received_effect.conditions_source != null) {
List conditionsSourceJson = new ArrayList();
hitReceivedEffectJson.put("conditionsSource", conditionsSourceJson);
for (TimedConditionEffect condition : this.hit_received_effect.conditions_source) {
Map conditionJson = new LinkedHashMap();
conditionsSourceJson.add(conditionJson);
if (condition.condition != null) {
conditionJson.put("condition", condition.condition.id);
} else if (condition.condition_id != null) {
conditionJson.put("condition", condition.condition_id);
}
if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude);
if (condition.duration != null) conditionJson.put("duration", condition.duration);
if (condition.chance != null) conditionJson.put("chance", JSONElement.printJsonChance(condition.chance));
}
}
if (this.hit_received_effect.conditions_target != null) {
List conditionsTargetJson = new ArrayList();
hitReceivedEffectJson.put("conditionsTarget", conditionsTargetJson);
for (TimedConditionEffect condition : this.hit_received_effect.conditions_target) {
Map conditionJson = new LinkedHashMap();
conditionsTargetJson.add(conditionJson);
if (condition.condition != null) {
conditionJson.put("condition", condition.condition.id);
} else if (condition.condition_id != null) {
conditionJson.put("condition", condition.condition_id);
}
if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude);
if (condition.duration != null) conditionJson.put("duration", condition.duration);
if (condition.chance != null) conditionJson.put("chance", JSONElement.printJsonChance(condition.chance));
}
}
}
if (this.death_effect != null) {
Map deathEffectJson = new LinkedHashMap();
npcJson.put("deathEffect", deathEffectJson);
if (this.death_effect.hp_boost_min != null || this.death_effect.hp_boost_max != null) {
Map hpJson = new LinkedHashMap();
deathEffectJson.put("increaseCurrentHP", hpJson);
if (this.death_effect.hp_boost_min != null) hpJson.put("min", this.death_effect.hp_boost_min);
else hpJson.put("min", 0);
if (this.death_effect.hp_boost_max != null) hpJson.put("max", this.death_effect.hp_boost_max);
else hpJson.put("max", 0);
}
if (this.death_effect.ap_boost_min != null || this.death_effect.ap_boost_max != null) {
Map apJson = new LinkedHashMap();
deathEffectJson.put("increaseCurrentAP", apJson);
if (this.death_effect.ap_boost_min != null) apJson.put("min", this.death_effect.ap_boost_min);
else apJson.put("min", 0);
if (this.death_effect.ap_boost_max != null) apJson.put("max", this.death_effect.ap_boost_max);
else apJson.put("max", 0);
}
if (this.death_effect.conditions_source != null) {
List conditionsSourceJson = new ArrayList();
deathEffectJson.put("conditionsSource", conditionsSourceJson);
for (TimedConditionEffect condition : this.death_effect.conditions_source) {
Map conditionJson = new LinkedHashMap();
conditionsSourceJson.add(conditionJson);
if (condition.condition != null) {
conditionJson.put("condition", condition.condition.id);
} else if (condition.condition_id != null) {
conditionJson.put("condition", condition.condition_id);
}
if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude);
if (condition.duration != null) conditionJson.put("duration", condition.duration);
if (condition.chance != null) conditionJson.put("chance", JSONElement.printJsonChance(condition.chance));
}
}
}
return npcJson; return npcJson;
} }
@Override @Override
public String getProjectFilename() { public String getProjectFilename() {
return "monsterlist_"+getProject().name+".json"; return "monsterlist_" + getProject().name + ".json";
} }
public int getMonsterExperience() { public int getMonsterExperience() {
double EXP_FACTOR_DAMAGERESISTANCE = 9; double EXP_FACTOR_DAMAGERESISTANCE = 9;
double EXP_FACTOR_SCALING = 0.7; double EXP_FACTOR_SCALING = 0.7;
double attacksPerTurn = Math.floor((double)(max_ap != null ? max_ap : 10.0) / (double)(attack_cost != null ? attack_cost : 10.0)); double attacksPerTurn = Math.floor((double) (max_ap != null ? max_ap : 10.0) / (double) (attack_cost != null ? attack_cost : 10.0));
double avgDamagePotential = 0; double avgDamagePotential = 0;
if (attack_damage_min != null || attack_damage_max != null) { if (attack_damage_min != null || attack_damage_max != null) {
avgDamagePotential = ((double)(attack_damage_min != null ? attack_damage_min : 0) + (double)(attack_damage_max != null ? attack_damage_max : 0)) / 2.0; avgDamagePotential = ((double) (attack_damage_min != null ? attack_damage_min : 0) + (double) (attack_damage_max != null ? attack_damage_max : 0)) / 2.0;
} }
double avgCrit = 0; double avgCrit = 0;
if (critical_skill != null && critical_multiplier != null) { if (critical_skill != null && critical_multiplier != null) {
avgCrit = (double)(critical_skill / 100.0) * critical_multiplier; avgCrit = (double) (critical_skill / 100.0) * critical_multiplier;
} }
double avgAttackHP = attacksPerTurn * ((double)(attack_chance != null ? attack_chance : 0) / 100.0) * avgDamagePotential * (1 + avgCrit); double avgAttackHP = attacksPerTurn * ((double) (attack_chance != null ? attack_chance : 0) / 100.0) * avgDamagePotential * (1 + avgCrit);
double avgDefenseHP = ((max_hp != null ? max_hp : 1) * (1 + ((double)(block_chance != null ? block_chance : 0) / 100.0))) + ( EXP_FACTOR_DAMAGERESISTANCE * (damage_resistance != null ? damage_resistance : 0)); double avgDefenseHP = ((max_hp != null ? max_hp : 1) * (1 + ((double) (block_chance != null ? block_chance : 0) / 100.0))) +
(EXP_FACTOR_DAMAGERESISTANCE * (damage_resistance != null ? damage_resistance : 0));
double attackConditionBonus = 0; double attackConditionBonus = 0;
if (hit_effect != null && hit_effect.conditions_target != null && hit_effect.conditions_target.size() > 0) { if (hit_effect != null && hit_effect.conditions_target != null && hit_effect.conditions_target.size() > 0) {
attackConditionBonus = 50; attackConditionBonus = 50;
@@ -781,7 +353,7 @@ public class NPC extends JSONElement {
double experience = (((avgAttackHP * 3) + avgDefenseHP) * EXP_FACTOR_SCALING) + attackConditionBonus; double experience = (((avgAttackHP * 3) + avgDefenseHP) * EXP_FACTOR_SCALING) + attackConditionBonus;
return new Double(Math.ceil(experience)).intValue(); return new Double(Math.ceil(experience)).intValue();
}; }
} }

View File

@@ -1,6 +1,13 @@
package com.gpl.rpg.atcontentstudio.model.gamedata; package com.gpl.rpg.atcontentstudio.model.gamedata;
import java.awt.Image; import com.gpl.rpg.atcontentstudio.Notification;
import com.gpl.rpg.atcontentstudio.model.GameDataElement;
import com.gpl.rpg.atcontentstudio.model.GameSource;
import com.gpl.rpg.atcontentstudio.ui.DefaultIcons;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.awt.*;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.FileReader; import java.io.FileReader;
@@ -10,14 +17,6 @@ import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import com.gpl.rpg.atcontentstudio.Notification;
import com.gpl.rpg.atcontentstudio.model.GameDataElement;
import com.gpl.rpg.atcontentstudio.model.GameSource;
import com.gpl.rpg.atcontentstudio.ui.DefaultIcons;
public class Quest extends JSONElement { public class Quest extends JSONElement {
private static final long serialVersionUID = 2004839647483250099L; private static final long serialVersionUID = 2004839647483250099L;
@@ -32,7 +31,7 @@ public class Quest extends JSONElement {
@Override @Override
public String getDesc() { public String getDesc() {
return (needsSaving() ? "*" : "")+name+" ("+id+")"; return (needsSaving() ? "*" : "") + name + " (" + id + ")";
} }
public static String getStaticDesc() { public static String getStaticDesc() {
@@ -48,7 +47,7 @@ public class Quest extends JSONElement {
reader = new FileReader(jsonFile); reader = new FileReader(jsonFile);
List quests = (List) parser.parse(reader); List quests = (List) parser.parse(reader);
for (Object obj : quests) { for (Object obj : quests) {
Map questJson = (Map)obj; Map questJson = (Map) obj;
Quest quest = fromJson(questJson); Quest quest = fromJson(questJson);
quest.jsonFile = jsonFile; quest.jsonFile = jsonFile;
quest.parent = category; quest.parent = category;
@@ -58,13 +57,13 @@ public class Quest extends JSONElement {
category.add(quest); category.add(quest);
} }
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
} catch (IOException e) { } catch (IOException e) {
Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
} catch (ParseException e) { } catch (ParseException e) {
Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
if (reader != null) if (reader != null)
@@ -102,7 +101,7 @@ public class Quest extends JSONElement {
this.stages = new ArrayList<QuestStage>(); this.stages = new ArrayList<QuestStage>();
if (questStagesJson != null && !questStagesJson.isEmpty()) { if (questStagesJson != null && !questStagesJson.isEmpty()) {
for (Object questStageJsonObj : questStagesJson) { for (Object questStageJsonObj : questStagesJson) {
Map questStageJson = (Map)questStageJsonObj; Map questStageJson = (Map) questStageJsonObj;
QuestStage questStage = new QuestStage(this); QuestStage questStage = new QuestStage(this);
questStage.parse(questStageJson); questStage.parse(questStageJson);
this.stages.add(questStage); this.stages.add(questStage);
@@ -113,17 +112,10 @@ public class Quest extends JSONElement {
@Override @Override
public void link() { public void link() {
if (this.state == State.created || this.state == State.modified || this.state == State.saved) { if (shouldSkipParseOrLink()) {
//This type of state is unrelated to parsing/linking.
return;
}
if (this.state == State.init) {
//Not parsed yet.
this.parse();
} else if (this.state == State.linked) {
//Already linked.
return; return;
} }
ensureParseIfNeeded();
for (QuestStage stage : stages) { for (QuestStage stage : stages) {
stage.link(); stage.link();
@@ -151,7 +143,7 @@ public class Quest extends JSONElement {
clone.visible_in_log = this.visible_in_log; clone.visible_in_log = this.visible_in_log;
if (this.stages != null) { if (this.stages != null) {
clone.stages = new ArrayList<QuestStage>(); clone.stages = new ArrayList<QuestStage>();
for (QuestStage stage : this.stages){ for (QuestStage stage : this.stages) {
clone.stages.add((QuestStage) stage.clone(clone)); clone.stages.add((QuestStage) stage.clone(clone));
} }
} }
@@ -163,7 +155,7 @@ public class Quest extends JSONElement {
//Nothing to link to. //Nothing to link to.
} }
@SuppressWarnings({ "rawtypes", "unchecked" }) @SuppressWarnings({"rawtypes", "unchecked"})
@Override @Override
public Map toJson() { public Map toJson() {
Map questJson = new LinkedHashMap(); Map questJson = new LinkedHashMap();
@@ -183,7 +175,7 @@ public class Quest extends JSONElement {
@Override @Override
public String getProjectFilename() { public String getProjectFilename() {
return "questlist_"+getProject().name+".json"; return "questlist_" + getProject().name + ".json";
} }
public QuestStage getStage(Integer stageId) { public QuestStage getStage(Integer stageId) {

View File

@@ -1,12 +1,12 @@
package com.gpl.rpg.atcontentstudio.model.gamedata; package com.gpl.rpg.atcontentstudio.model.gamedata;
import java.awt.Image;
import java.util.LinkedHashMap;
import java.util.Map;
import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.GameDataElement;
import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons;
import java.awt.*;
import java.util.LinkedHashMap;
import java.util.Map;
public class QuestStage extends JSONElement { public class QuestStage extends JSONElement {
private static final long serialVersionUID = 8313645819951513431L; private static final long serialVersionUID = 8313645819951513431L;
@@ -16,7 +16,7 @@ public class QuestStage extends JSONElement {
public Integer exp_reward = null; public Integer exp_reward = null;
public Integer finishes_quest = null; public Integer finishes_quest = null;
public QuestStage(Quest parent){ public QuestStage(Quest parent) {
this.parent = parent; this.parent = parent;
} }
@@ -34,14 +34,14 @@ public class QuestStage extends JSONElement {
@Override @Override
public void parse(Map jsonObj) { public void parse(Map jsonObj) {
progress = JSONElement.getInteger((Number) jsonObj.get("progress")); progress = JSONElement.getInteger((Number) jsonObj.get("progress"));
this.id = ((Quest)parent).id+":"+progress; this.id = ((Quest) parent).id + ":" + progress;
log_text = (String) jsonObj.get("logText"); log_text = (String) jsonObj.get("logText");
exp_reward = JSONElement.getInteger((Number) jsonObj.get("rewardExperience")); exp_reward = JSONElement.getInteger((Number) jsonObj.get("rewardExperience"));
finishes_quest = JSONElement.getInteger((Number) jsonObj.get("finishesQuest")); finishes_quest = JSONElement.getInteger((Number) jsonObj.get("finishesQuest"));
state = State.parsed; state = State.parsed;
} }
@SuppressWarnings({ "rawtypes", "unchecked" }) @SuppressWarnings({"rawtypes", "unchecked"})
@Override @Override
public Map toJson() { public Map toJson() {
Map stageJson = new LinkedHashMap(); Map stageJson = new LinkedHashMap();
@@ -54,22 +54,15 @@ public class QuestStage extends JSONElement {
@Override @Override
public String getDesc() { public String getDesc() {
return progress+" - "+(exp_reward != null ? "["+exp_reward+"XP]" : "")+((finishes_quest != null) && (finishes_quest == 1) ? "[END]" : "")+log_text; return progress + " - " + (exp_reward != null ? "[" + exp_reward + "XP]" : "") + ((finishes_quest != null) && (finishes_quest == 1) ? "[END]" : "") + log_text;
} }
@Override @Override
public void link() { public void link() {
if (this.state == State.created || this.state == State.modified || this.state == State.saved) { if (shouldSkipParseOrLink()) {
//This type of state is unrelated to parsing/linking.
return;
}
if (this.state == State.init) {
//Not parsed yet.
this.parse();
} else if (this.state == State.linked) {
//Already linked.
return; return;
} }
ensureParseIfNeeded();
//Nothing to link to :D //Nothing to link to :D
this.state = State.linked; this.state = State.linked;
@@ -82,7 +75,7 @@ public class QuestStage extends JSONElement {
@Override @Override
public String getProjectFilename() { public String getProjectFilename() {
return ((Quest)parent).getProjectFilename(); return ((Quest) parent).getProjectFilename();
} }
@Override @Override

View File

@@ -1,14 +1,14 @@
package com.gpl.rpg.atcontentstudio.model.gamedata; package com.gpl.rpg.atcontentstudio.model.gamedata;
import com.gpl.rpg.atcontentstudio.Notification;
import com.gpl.rpg.atcontentstudio.model.GameDataElement;
import com.gpl.rpg.atcontentstudio.model.Project;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import com.gpl.rpg.atcontentstudio.Notification;
import com.gpl.rpg.atcontentstudio.model.GameDataElement;
import com.gpl.rpg.atcontentstudio.model.Project;
public class Requirement extends JSONElement { public class Requirement extends JSONElement {
private static final long serialVersionUID = 7295593297142310955L; private static final long serialVersionUID = 7295593297142310955L;
@@ -68,70 +68,39 @@ public class Requirement extends JSONElement {
} }
public enum SkillID { public enum SkillID {
weaponChance weaponChance, weaponDmg, barter, dodge, barkSkin, moreCriticals, betterCriticals, speed // Raises max ap
,weaponDmg , coinfinder, moreExp, cleave // +10ap on kill
,barter , eater // +1hp per kill
,dodge , fortitude // +N hp per levelup
,barkSkin , evasion // increase successful flee chance & reduce chance of monster attack
,moreCriticals , regeneration // +N hp per round
,betterCriticals , lowerExploss, magicfinder, resistanceMental // lowers chance to get negative active conditions by monsters (Mental like Dazed)
,speed // Raises max ap , resistancePhysical // lowers chance to get negative active conditions by monsters (Physical Capacity like Minor fatigue)
,coinfinder , resistanceBlood // lowers chance to get negative active conditions by monsters (Blood Disorder like Weak Poison)
,moreExp , shadowBless, sporeImmunity, crit1 // lowers atk ability
,cleave // +10ap on kill , crit2 // lowers def ability ,rejuvenation // Reduces magnitudes of conditions
,eater // +1hp per kill , rejuvenation // Reduces magnitudes of conditions
,fortitude // +N hp per levelup , taunt // Causes AP loss of attackers that miss
,evasion // increase successful flee chance & reduce chance of monster attack , concussion // AC loss for monsters with (AC-BC)>N
,regeneration // +N hp per round , weaponProficiencyDagger, weaponProficiency1hsword, weaponProficiency2hsword, weaponProficiencyAxe, weaponProficiencyBlunt, weaponProficiencyUnarmed, weaponProficiencyPole, armorProficiencyShield, armorProficiencyUnarmored, armorProficiencyLight, armorProficiencyHeavy, fightstyleDualWield, fightstyle2hand, fightstyleWeaponShield, specializationDualWield, specialization2hand, specializationWeaponShield
,lowerExploss
,magicfinder
,resistanceMental // lowers chance to get negative active conditions by monsters (Mental like Dazed)
,resistancePhysical // lowers chance to get negative active conditions by monsters (Physical Capacity like Minor fatigue)
,resistanceBlood // lowers chance to get negative active conditions by monsters (Blood Disorder like Weak Poison)
,shadowBless
,sporeImmunity
,crit1 // lowers atk ability
,crit2 // lowers def ability ,rejuvenation // Reduces magnitudes of conditions
,rejuvenation // Reduces magnitudes of conditions
,taunt // Causes AP loss of attackers that miss
,concussion // AC loss for monsters with (AC-BC)>N
,weaponProficiencyDagger
,weaponProficiency1hsword
,weaponProficiency2hsword
,weaponProficiencyAxe
,weaponProficiencyBlunt
,weaponProficiencyUnarmed
,weaponProficiencyPole
,armorProficiencyShield
,armorProficiencyUnarmored
,armorProficiencyLight
,armorProficiencyHeavy
,fightstyleDualWield
,fightstyle2hand
,fightstyleWeaponShield
,specializationDualWield
,specialization2hand
,specializationWeaponShield
} }
@Override @Override
public String getDesc() { public String getDesc() {
String obj_id = ""; String obj_id = "";
if (required_obj_id != null) if (required_obj_id != null) {
{
obj_id = required_obj_id; obj_id = required_obj_id;
if (type != null && type == RequirementType.random){ if (type != null && type == RequirementType.random) {
obj_id = " Chance " + obj_id + (required_obj_id.contains("/") ? "" : "%"); obj_id = " Chance " + obj_id + (required_obj_id.contains("/") ? "" : "%");
} } else {
else {
obj_id += ":"; obj_id += ":";
} }
} }
return ((negated != null && negated) ? "NOT " : "") return ((negated != null && negated) ? "NOT " : "")
+(type == null ? "" : type.toString()+":") + (type == null ? "" : type.toString() + ":")
+obj_id + obj_id
+(required_value == null ? "" : required_value.toString()); + (required_value == null ? "" : required_value.toString());
} }
@Override @Override
@@ -153,20 +122,13 @@ public class Requirement extends JSONElement {
@Override @Override
public void link() { public void link() {
if (this.state == State.created || this.state == State.modified || this.state == State.saved) { if (shouldSkipParseOrLink()) {
//This type of state is unrelated to parsing/linking.
return;
}
if (this.state == State.init) {
//Not parsed yet.
this.parse();
} else if (this.state == State.linked) {
//Already linked.
return; return;
} }
ensureParseIfNeeded();
Project proj = getProject(); Project proj = getProject();
if (proj == null) { if (proj == null) {
Notification.addError("Error linking requirement "+getDesc()+". No parent project found."); Notification.addError("Error linking requirement " + getDesc() + ". No parent project found.");
return; return;
} }
switch (type) { switch (type) {
@@ -187,7 +149,7 @@ public class Requirement extends JSONElement {
case questProgress: case questProgress:
this.required_obj = proj.getQuest(required_obj_id); this.required_obj = proj.getQuest(required_obj_id);
if (this.required_obj != null && this.required_value != null) { if (this.required_obj != null && this.required_value != null) {
QuestStage stage = ((Quest)this.required_obj).getStage(this.required_value); QuestStage stage = ((Quest) this.required_obj).getStage(this.required_value);
if (stage != null) { if (stage != null) {
stage.addBacklink((GameDataElement) this.parent); stage.addBacklink((GameDataElement) this.parent);
} }
@@ -245,6 +207,7 @@ public class Requirement extends JSONElement {
} }
} }
} }
@Override @Override
public String getProjectFilename() { public String getProjectFilename() {
throw new Error("Thou shalt not reach this method."); throw new Error("Thou shalt not reach this method.");
@@ -257,8 +220,7 @@ public class Requirement extends JSONElement {
required_value = null; required_value = null;
} }
if(destType==RequirementType.random) if (destType == RequirementType.random) {
{
required_obj_id = "50/100"; required_obj_id = "50/100";
} }

View File

@@ -1,16 +1,17 @@
package com.gpl.rpg.atcontentstudio.model.maps; package com.gpl.rpg.atcontentstudio.model.maps;
import java.awt.Image;
import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.GameDataElement;
import com.gpl.rpg.atcontentstudio.model.gamedata.Droplist; import com.gpl.rpg.atcontentstudio.model.gamedata.Droplist;
import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons;
import java.awt.*;
public class ContainerArea extends MapObject { public class ContainerArea extends MapObject {
public Droplist droplist = null; public Droplist droplist = null;
public ContainerArea(tiled.core.MapObject obj) {} public ContainerArea(tiled.core.MapObject obj) {
}
@Override @Override
public void link() { public void link() {

View File

@@ -1,18 +1,18 @@
package com.gpl.rpg.atcontentstudio.model.maps; package com.gpl.rpg.atcontentstudio.model.maps;
import java.awt.Image;
import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.GameDataElement;
import com.gpl.rpg.atcontentstudio.model.gamedata.Dialogue; import com.gpl.rpg.atcontentstudio.model.gamedata.Dialogue;
import com.gpl.rpg.atcontentstudio.model.gamedata.Requirement; import com.gpl.rpg.atcontentstudio.model.gamedata.Requirement;
import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons;
import java.awt.*;
public class KeyArea extends MapObject { public class KeyArea extends MapObject {
public String dialogue_id = null; public String dialogue_id;
public Dialogue dialogue = null; public Dialogue dialogue = null;
public Requirement requirement = null; public Requirement requirement;
public boolean oldSchoolRequirement = true; public boolean oldSchoolRequirement;
public KeyArea(tiled.core.MapObject obj) { public KeyArea(tiled.core.MapObject obj) {
dialogue_id = obj.getProperties().getProperty("phrase"); dialogue_id = obj.getProperties().getProperty("phrase");
@@ -79,7 +79,7 @@ public class KeyArea extends MapObject {
} }
if (requirement != null) { if (requirement != null) {
if (oldSchoolRequirement && Requirement.RequirementType.questProgress.equals(requirement.type) && (requirement.negated == null || !requirement.negated)) { if (oldSchoolRequirement && Requirement.RequirementType.questProgress.equals(requirement.type) && (requirement.negated == null || !requirement.negated)) {
tmxObject.setName(requirement.required_obj_id+":"+((requirement.required_value == null) ? "" : Integer.toString(requirement.required_value))); tmxObject.setName(requirement.required_obj_id + ":" + ((requirement.required_value == null) ? "" : Integer.toString(requirement.required_value)));
} else { } else {
if (requirement.type != null) { if (requirement.type != null) {
tmxObject.getProperties().setProperty("requireType", requirement.type.toString()); tmxObject.getProperties().setProperty("requireType", requirement.type.toString());
@@ -101,7 +101,8 @@ public class KeyArea extends MapObject {
public void updateNameFromRequirementChange() { public void updateNameFromRequirementChange() {
if (oldSchoolRequirement && Requirement.RequirementType.questProgress.equals(requirement.type) && (requirement.negated == null || !requirement.negated)) { if (oldSchoolRequirement && Requirement.RequirementType.questProgress.equals(requirement.type) && (requirement.negated == null || !requirement.negated)) {
name = (requirement.negated != null && requirement.negated) ? "NOT " : "" + requirement.required_obj_id+":"+((requirement.required_value == null) ? "" : Integer.toString(requirement.required_value)); name = (requirement.negated != null && requirement.negated) ? "NOT " : "" + requirement.required_obj_id + ":" + ((requirement.required_value == null) ? "" : Integer.toString(
requirement.required_value));
} else if (oldSchoolRequirement) { } else if (oldSchoolRequirement) {
int i = 0; int i = 0;
String futureName = requirement.type.toString() + "#" + Integer.toString(i); String futureName = requirement.type.toString() + "#" + Integer.toString(i);

View File

@@ -1,17 +1,16 @@
package com.gpl.rpg.atcontentstudio.model.maps; package com.gpl.rpg.atcontentstudio.model.maps;
import java.awt.Image;
import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.GameDataElement;
import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons;
import java.awt.*;
public class MapChange extends MapObject { public class MapChange extends MapObject {
public String map_id = null; public String map_id;
public TMXMap map = null; public TMXMap map = null;
public String place_id = null; public String place_id;
public MapChange(tiled.core.MapObject obj) { public MapChange(tiled.core.MapObject obj) {
this.map_id = obj.getProperties().getProperty("map"); this.map_id = obj.getProperties().getProperty("map");

View File

@@ -1,10 +1,10 @@
package com.gpl.rpg.atcontentstudio.model.maps; package com.gpl.rpg.atcontentstudio.model.maps;
import java.awt.Image;
import com.gpl.rpg.atcontentstudio.Notification; import com.gpl.rpg.atcontentstudio.Notification;
import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.GameDataElement;
import java.awt.*;
public abstract class MapObject { public abstract class MapObject {
public int x, y, w, h; public int x, y, w, h;
@@ -64,7 +64,7 @@ public abstract class MapObject {
break; break;
} }
} else { } else {
Notification.addWarn("Unknown map object type: "+obj.getType()+"with name "+obj.getName()+" in map "+parentMap.id); Notification.addWarn("Unknown map object type: " + obj.getType() + "with name " + obj.getName() + " in map " + parentMap.id);
} }
if (result != null) { if (result != null) {
result.x = obj.getX(); result.x = obj.getX();

View File

@@ -1,10 +1,10 @@
package com.gpl.rpg.atcontentstudio.model.maps; package com.gpl.rpg.atcontentstudio.model.maps;
import com.gpl.rpg.atcontentstudio.model.GameDataElement;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import com.gpl.rpg.atcontentstudio.model.GameDataElement;
public class MapObjectGroup { public class MapObjectGroup {

View File

@@ -1,17 +1,17 @@
package com.gpl.rpg.atcontentstudio.model.maps; package com.gpl.rpg.atcontentstudio.model.maps;
import java.awt.Image;
import java.util.ArrayList;
import java.util.List;
import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.GameDataElement;
import com.gpl.rpg.atcontentstudio.model.gamedata.Requirement; import com.gpl.rpg.atcontentstudio.model.gamedata.Requirement;
import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
public class ReplaceArea extends MapObject { public class ReplaceArea extends MapObject {
public Requirement requirement = null; public Requirement requirement;
public boolean oldSchoolRequirement = false; public boolean oldSchoolRequirement = false;
public List<ReplaceArea.Replacement> replacements = null; public List<ReplaceArea.Replacement> replacements = null;
@@ -66,34 +66,20 @@ public class ReplaceArea extends MapObject {
requirement.elementChanged(oldOne, newOne); requirement.elementChanged(oldOne, newOne);
} }
public ReplaceArea.Replacement addReplacement(String source, String target) { public ReplaceArea.Replacement createReplacement(String source, String target) {
Replacement repl = new Replacement(source, target); Replacement repl = new Replacement(source, target);
addReplacement(repl);
return repl; return repl;
} }
public void addReplacement(ReplaceArea.Replacement repl) {
if (replacements == null) replacements = new ArrayList<ReplaceArea.Replacement>();
replacements.add(repl);
}
// public void removeReplacement(String source, String target) {
// replacedLayers.remove(source);
// }
public void removeReplacement(Replacement repl) {
replacements.remove(repl);
}
@Override @Override
public void savePropertiesInTmxObject(tiled.core.MapObject tmxObject) { public void savePropertiesInTmxObject(tiled.core.MapObject tmxObject) {
if (replacements != null) { if (replacements != null) {
for(Replacement r : replacements) for (Replacement r : replacements)
tmxObject.getProperties().setProperty(r.sourceLayer, r.targetLayer); tmxObject.getProperties().setProperty(r.sourceLayer, r.targetLayer);
} }
if (requirement != null) { if (requirement != null) {
if (oldSchoolRequirement && Requirement.RequirementType.questProgress.equals(requirement.type) && (requirement.negated == null || !requirement.negated)) { if (oldSchoolRequirement && Requirement.RequirementType.questProgress.equals(requirement.type) && (requirement.negated == null || !requirement.negated)) {
tmxObject.setName(requirement.required_obj_id+":"+((requirement.required_value == null) ? "" : Integer.toString(requirement.required_value))); tmxObject.setName(requirement.required_obj_id + ":" + ((requirement.required_value == null) ? "" : Integer.toString(requirement.required_value)));
} else { } else {
if (requirement.type != null) { if (requirement.type != null) {
tmxObject.getProperties().setProperty("requireType", requirement.type.toString()); tmxObject.getProperties().setProperty("requireType", requirement.type.toString());
@@ -116,7 +102,8 @@ public class ReplaceArea extends MapObject {
//Don't use yet ! //Don't use yet !
public void updateNameFromRequirementChange() { public void updateNameFromRequirementChange() {
if (oldSchoolRequirement && Requirement.RequirementType.questProgress.equals(requirement.type) && (requirement.negated == null || !requirement.negated)) { if (oldSchoolRequirement && Requirement.RequirementType.questProgress.equals(requirement.type) && (requirement.negated == null || !requirement.negated)) {
name = (requirement.negated != null && requirement.negated) ? "NOT " : "" + requirement.required_obj_id+":"+((requirement.required_value == null) ? "" : Integer.toString(requirement.required_value)); name = (requirement.negated != null && requirement.negated) ? "NOT " : "" + requirement.required_obj_id + ":" + ((requirement.required_value == null) ? "" : Integer.toString(
requirement.required_value));
} else if (oldSchoolRequirement) { } else if (oldSchoolRequirement) {
int i = 0; int i = 0;
String futureName = requirement.type.toString() + "#" + Integer.toString(i); String futureName = requirement.type.toString() + "#" + Integer.toString(i);
@@ -130,6 +117,7 @@ public class ReplaceArea extends MapObject {
public class Replacement { public class Replacement {
public String sourceLayer, targetLayer; public String sourceLayer, targetLayer;
public Replacement(String source, String target) { public Replacement(String source, String target) {
this.sourceLayer = source; this.sourceLayer = source;
this.targetLayer = target; this.targetLayer = target;

View File

@@ -1,17 +1,19 @@
package com.gpl.rpg.atcontentstudio.model.maps; package com.gpl.rpg.atcontentstudio.model.maps;
import java.awt.Image;
import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.GameDataElement;
import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons;
import java.awt.*;
public class RestArea extends MapObject { public class RestArea extends MapObject {
public RestArea(tiled.core.MapObject obj) {} public RestArea(tiled.core.MapObject obj) {
}
@Override @Override
public void link() {} public void link() {
}
@Override @Override
public Image getIcon() { public Image getIcon() {

View File

@@ -1,11 +1,11 @@
package com.gpl.rpg.atcontentstudio.model.maps; package com.gpl.rpg.atcontentstudio.model.maps;
import java.awt.Image;
import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.GameDataElement;
import com.gpl.rpg.atcontentstudio.model.gamedata.Dialogue; import com.gpl.rpg.atcontentstudio.model.gamedata.Dialogue;
import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons;
import java.awt.*;
public class ScriptArea extends MapObject { public class ScriptArea extends MapObject {
public Dialogue dialogue = null; public Dialogue dialogue = null;

View File

@@ -1,11 +1,11 @@
package com.gpl.rpg.atcontentstudio.model.maps; package com.gpl.rpg.atcontentstudio.model.maps;
import java.awt.Image;
import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.GameDataElement;
import com.gpl.rpg.atcontentstudio.model.gamedata.Dialogue; import com.gpl.rpg.atcontentstudio.model.gamedata.Dialogue;
import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons;
import java.awt.*;
public class SignArea extends MapObject { public class SignArea extends MapObject {
public Dialogue dialogue = null; public Dialogue dialogue = null;

View File

@@ -1,13 +1,13 @@
package com.gpl.rpg.atcontentstudio.model.maps; package com.gpl.rpg.atcontentstudio.model.maps;
import java.awt.Image;
import java.util.ArrayList;
import java.util.List;
import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.GameDataElement;
import com.gpl.rpg.atcontentstudio.model.gamedata.NPC; import com.gpl.rpg.atcontentstudio.model.gamedata.NPC;
import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
public class SpawnArea extends MapObject { public class SpawnArea extends MapObject {
public int quantity = 1; public int quantity = 1;
@@ -32,7 +32,7 @@ public class SpawnArea extends MapObject {
} }
if (obj.getProperties().getProperty("spawngroup") != null) { if (obj.getProperties().getProperty("spawngroup") != null) {
this.spawngroup_id = obj.getProperties().getProperty("spawngroup"); this.spawngroup_id = obj.getProperties().getProperty("spawngroup");
} else if (obj.getName() != null ){ } else if (obj.getName() != null) {
this.spawngroup_id = obj.getName(); this.spawngroup_id = obj.getName();
} }
} }

View File

@@ -1,35 +1,21 @@
package com.gpl.rpg.atcontentstudio.model.maps; package com.gpl.rpg.atcontentstudio.model.maps;
import java.awt.Image;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.swing.tree.TreeNode;
import tiled.io.TMXMapReader;
import tiled.io.TMXMapWriter;
import com.gpl.rpg.atcontentstudio.Notification; import com.gpl.rpg.atcontentstudio.Notification;
import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.*;
import com.gpl.rpg.atcontentstudio.model.GameSource;
import com.gpl.rpg.atcontentstudio.model.GameSource.Type; import com.gpl.rpg.atcontentstudio.model.GameSource.Type;
import com.gpl.rpg.atcontentstudio.model.Project;
import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode;
import com.gpl.rpg.atcontentstudio.model.SaveEvent;
import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet; import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet;
import com.gpl.rpg.atcontentstudio.model.gamedata.NPC; import com.gpl.rpg.atcontentstudio.model.gamedata.NPC;
import com.gpl.rpg.atcontentstudio.model.sprites.Spritesheet; import com.gpl.rpg.atcontentstudio.model.sprites.Spritesheet;
import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons;
import tiled.io.TMXMapReader;
import tiled.io.TMXMapWriter;
import javax.swing.tree.TreeNode;
import java.awt.*;
import java.io.*;
import java.util.List;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
public class TMXMap extends GameDataElement { public class TMXMap extends GameDataElement {
@@ -54,7 +40,7 @@ public class TMXMap extends GameDataElement {
bluetint bluetint
} }
public File tmxFile = null; public File tmxFile;
public tiled.core.Map tmxMap = null; public tiled.core.Map tmxMap = null;
public Set<Spritesheet> usedSpritesheets = null; public Set<Spritesheet> usedSpritesheets = null;
public List<MapObjectGroup> groups = null; public List<MapObjectGroup> groups = null;
@@ -86,9 +72,9 @@ public class TMXMap extends GameDataElement {
colorFilter = ColorFilter.valueOf(((String) tmxMap.getProperties().get("colorfilter"))); colorFilter = ColorFilter.valueOf(((String) tmxMap.getProperties().get("colorfilter")));
} }
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
Notification.addError("Impossible to load TMX map file "+tmxFile.getAbsolutePath()); Notification.addError("Impossible to load TMX map file " + tmxFile.getAbsolutePath());
} catch (Exception e) { } catch (Exception e) {
Notification.addError("Error while loading TMX map file "+tmxFile.getAbsolutePath()+": "+e.getMessage()); Notification.addError("Error while loading TMX map file " + tmxFile.getAbsolutePath() + ": " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
} }
for (tiled.core.MapLayer layer : tmxMap.getLayers()) { for (tiled.core.MapLayer layer : tmxMap.getLayers()) {
@@ -137,7 +123,7 @@ public class TMXMap extends GameDataElement {
s.addBacklink(clone); s.addBacklink(clone);
} }
} catch (Exception e) { } catch (Exception e) {
Notification.addError("Error while cloning map "+this.id+" : "+e.getMessage()); Notification.addError("Error while cloning map " + this.id + " : " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
} }
@@ -181,28 +167,30 @@ public class TMXMap extends GameDataElement {
@Override @Override
public void childrenAdded(List<ProjectTreeNode> path) { public void childrenAdded(List<ProjectTreeNode> path) {
path.add(0,this); path.add(0, this);
parent.childrenAdded(path); parent.childrenAdded(path);
} }
@Override @Override
public void childrenChanged(List<ProjectTreeNode> path) { public void childrenChanged(List<ProjectTreeNode> path) {
path.add(0,this); path.add(0, this);
parent.childrenChanged(path); parent.childrenChanged(path);
} }
@Override @Override
public void childrenRemoved(List<ProjectTreeNode> path) { public void childrenRemoved(List<ProjectTreeNode> path) {
path.add(0,this); path.add(0, this);
parent.childrenRemoved(path); parent.childrenRemoved(path);
} }
@Override @Override
public void notifyCreated() { public void notifyCreated() {
childrenAdded(new ArrayList<ProjectTreeNode>()); childrenAdded(new ArrayList<ProjectTreeNode>());
} }
@Override @Override
public String getDesc() { public String getDesc() {
return (needsSaving() ? "*" : "")+id; return (needsSaving() ? "*" : "") + id;
} }
@Override @Override
@@ -214,14 +202,21 @@ public class TMXMap extends GameDataElement {
public Image getIcon() { public Image getIcon() {
return DefaultIcons.getTiledIconIcon(); return DefaultIcons.getTiledIconIcon();
} }
@Override @Override
public Image getLeafIcon() { public Image getLeafIcon() {
return DefaultIcons.getTiledIconIcon(); return DefaultIcons.getTiledIconIcon();
} }
@Override @Override
public Image getClosedIcon() {return null;} public Image getClosedIcon() {
return null;
}
@Override @Override
public Image getOpenIcon() {return null;} public Image getOpenIcon() {
return null;
}
@Override @Override
public GameDataSet getDataSet() { public GameDataSet getDataSet() {
@@ -258,10 +253,10 @@ public class TMXMap extends GameDataElement {
if (getDataType() == GameSource.Type.source) { if (getDataType() == GameSource.Type.source) {
writer.writeMap(tmxMap, baos, tmxFile.getAbsolutePath()); writer.writeMap(tmxMap, baos, tmxFile.getAbsolutePath());
} else { } else {
writer.writeMap(tmxMap, baos, ((TMXMapSet)this.parent).mapFolder.getAbsolutePath()+File.separator+"placeholder.tmx"); writer.writeMap(tmxMap, baos, ((TMXMapSet) this.parent).mapFolder.getAbsolutePath() + File.separator + "placeholder.tmx");
} }
} catch (Exception e) { } catch (Exception e) {
Notification.addError("Error while converting map "+getDesc()+" to XML: "+e.getMessage()); Notification.addError("Error while converting map " + getDesc() + " to XML: " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
} }
return baos.toString(); return baos.toString();
@@ -283,9 +278,9 @@ public class TMXMap extends GameDataElement {
w.close(); w.close();
this.state = State.saved; this.state = State.saved;
changedOnDisk = false; changedOnDisk = false;
Notification.addSuccess("TMX file "+tmxFile.getAbsolutePath()+" saved."); Notification.addSuccess("TMX file " + tmxFile.getAbsolutePath() + " saved.");
} catch (IOException e) { } catch (IOException e) {
Notification.addError("Error while writing TMX file "+tmxFile.getAbsolutePath()+" : "+e.getMessage()); Notification.addError("Error while writing TMX file " + tmxFile.getAbsolutePath() + " : " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
} }
} }
@@ -302,12 +297,12 @@ public class TMXMap extends GameDataElement {
if (writable) { if (writable) {
if (tmxFile.exists()) { if (tmxFile.exists()) {
if (tmxFile.delete()) { if (tmxFile.delete()) {
Notification.addSuccess("TMX file "+tmxFile.getAbsolutePath()+" deleted."); Notification.addSuccess("TMX file " + tmxFile.getAbsolutePath() + " deleted.");
} else { } else {
Notification.addError("Error while deleting TMX file "+tmxFile.getAbsolutePath()); Notification.addError("Error while deleting TMX file " + tmxFile.getAbsolutePath());
} }
} }
((TMXMapSet)parent).tmxMaps.remove(this); ((TMXMapSet) parent).tmxMaps.remove(this);
//TODO clear blacklinks ? //TODO clear blacklinks ?
} }
} }
@@ -413,22 +408,24 @@ public class TMXMap extends GameDataElement {
for (MapObjectGroup g : groups) { for (MapObjectGroup g : groups) {
for (MapObject o : g.mapObjects) { for (MapObject o : g.mapObjects) {
if (o instanceof ContainerArea) { if (o instanceof ContainerArea) {
if (((ContainerArea)o).droplist != null) ((ContainerArea)o).droplist.elementChanged(this, null); if (((ContainerArea) o).droplist != null) ((ContainerArea) o).droplist.elementChanged(this, null);
} else if (o instanceof KeyArea) { } else if (o instanceof KeyArea) {
if (((KeyArea)o).dialogue != null) ((KeyArea)o).dialogue.elementChanged(this, null); if (((KeyArea) o).dialogue != null) ((KeyArea) o).dialogue.elementChanged(this, null);
if (((KeyArea)o).requirement != null && ((KeyArea)o).requirement.required_obj != null) ((KeyArea)o).requirement.required_obj.elementChanged(this, null); if (((KeyArea) o).requirement != null && ((KeyArea) o).requirement.required_obj != null)
((KeyArea) o).requirement.required_obj.elementChanged(this, null);
} else if (o instanceof MapChange) { } else if (o instanceof MapChange) {
if (((MapChange)o).map != null) ((MapChange)o).map.elementChanged(this, null); if (((MapChange) o).map != null) ((MapChange) o).map.elementChanged(this, null);
} else if (o instanceof ReplaceArea) { } else if (o instanceof ReplaceArea) {
if (((ReplaceArea)o).requirement != null && ((ReplaceArea)o).requirement.required_obj != null) ((ReplaceArea)o).requirement.required_obj.elementChanged(this, null); if (((ReplaceArea) o).requirement != null && ((ReplaceArea) o).requirement.required_obj != null)
((ReplaceArea) o).requirement.required_obj.elementChanged(this, null);
} else if (o instanceof RestArea) { } else if (o instanceof RestArea) {
} else if (o instanceof ScriptArea) { } else if (o instanceof ScriptArea) {
if (((ScriptArea)o).dialogue != null) ((ScriptArea)o).dialogue.elementChanged(this, null); if (((ScriptArea) o).dialogue != null) ((ScriptArea) o).dialogue.elementChanged(this, null);
} else if (o instanceof SignArea) { } else if (o instanceof SignArea) {
if (((SignArea)o).dialogue != null) ((SignArea)o).dialogue.elementChanged(this, null); if (((SignArea) o).dialogue != null) ((SignArea) o).dialogue.elementChanged(this, null);
} else if (o instanceof SpawnArea) { } else if (o instanceof SpawnArea) {
if (((SpawnArea)o).spawnGroup != null) { if (((SpawnArea) o).spawnGroup != null) {
for (NPC n : ((SpawnArea)o).spawnGroup) { for (NPC n : ((SpawnArea) o).spawnGroup) {
n.elementChanged(this, null); n.elementChanged(this, null);
} }
} }
@@ -461,6 +458,7 @@ public class TMXMap extends GameDataElement {
public interface MapChangedOnDiskListener { public interface MapChangedOnDiskListener {
public void mapChanged(); public void mapChanged();
public void mapReloaded(); public void mapReloaded();
} }

View File

@@ -1,24 +1,5 @@
package com.gpl.rpg.atcontentstudio.model.maps; package com.gpl.rpg.atcontentstudio.model.maps;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.swing.tree.TreeNode;
import com.gpl.rpg.atcontentstudio.Notification; import com.gpl.rpg.atcontentstudio.Notification;
import com.gpl.rpg.atcontentstudio.model.GameSource; import com.gpl.rpg.atcontentstudio.model.GameSource;
import com.gpl.rpg.atcontentstudio.model.GameSource.Type; import com.gpl.rpg.atcontentstudio.model.GameSource.Type;
@@ -29,11 +10,20 @@ import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet;
import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons;
import com.gpl.rpg.atcontentstudio.utils.FileUtils; import com.gpl.rpg.atcontentstudio.utils.FileUtils;
import javax.swing.tree.TreeNode;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.util.List;
import java.util.*;
import java.util.concurrent.TimeUnit;
public class TMXMapSet implements ProjectTreeNode { public class TMXMapSet implements ProjectTreeNode {
public static final String DEFAULT_REL_PATH_IN_SOURCE = "res"+File.separator+"xml"+File.separator; public static final String DEFAULT_REL_PATH_IN_SOURCE = "res" + File.separator + "xml" + File.separator;
public static final String DEFAULT_REL_PATH_IN_PROJECT = "maps"+File.separator; public static final String DEFAULT_REL_PATH_IN_PROJECT = "maps" + File.separator;
public static final String DEFAULT_REL_PATH_TO_DRAWABLE = ".."+File.separator+"drawable"+File.separator; public static final String DEFAULT_REL_PATH_TO_DRAWABLE = ".." + File.separator + "drawable" + File.separator;
public static final String GAME_MAPS_ARRAY_NAME = "loadresource_maps"; public static final String GAME_MAPS_ARRAY_NAME = "loadresource_maps";
public static final String DEBUG_SUFFIX = "_debug"; public static final String DEBUG_SUFFIX = "_debug";
@@ -49,27 +39,26 @@ public class TMXMapSet implements ProjectTreeNode {
this.parent = source; this.parent = source;
if (source.type == GameSource.Type.source) { if (source.type == GameSource.Type.source) {
this.mapFolder = new File(source.baseFolder, DEFAULT_REL_PATH_IN_SOURCE); this.mapFolder = new File(source.baseFolder, DEFAULT_REL_PATH_IN_SOURCE);
} } else if (source.type == GameSource.Type.created | source.type == GameSource.Type.altered) {
else if (source.type == GameSource.Type.created | source.type == GameSource.Type.altered) {
this.mapFolder = new File(source.baseFolder, DEFAULT_REL_PATH_IN_PROJECT); this.mapFolder = new File(source.baseFolder, DEFAULT_REL_PATH_IN_PROJECT);
if (!this.mapFolder.exists()) { if (!this.mapFolder.exists()) {
this.mapFolder.mkdirs(); this.mapFolder.mkdirs();
} }
FileUtils.makeSymlink(getProject().baseContent.gameSprites.drawableFolder, new File(mapFolder.getAbsolutePath()+File.separator+DEFAULT_REL_PATH_TO_DRAWABLE)); FileUtils.makeSymlink(getProject().baseContent.gameSprites.drawableFolder, new File(mapFolder.getAbsolutePath() + File.separator + DEFAULT_REL_PATH_TO_DRAWABLE));
} }
this.tmxMaps = new ArrayList<TMXMap>(); this.tmxMaps = new ArrayList<TMXMap>();
if (source.type == GameSource.Type.source && (source.parent.sourceSetToUse == ResourceSet.debugData || source.parent.sourceSetToUse == ResourceSet.gameData)) { if (source.type == GameSource.Type.source && (source.parent.sourceSetToUse == ResourceSet.debugData || source.parent.sourceSetToUse == ResourceSet.gameData)) {
String suffix = (source.parent.sourceSetToUse == ResourceSet.debugData) ? DEBUG_SUFFIX : ""; String suffix = (source.parent.sourceSetToUse == ResourceSet.debugData) ? DEBUG_SUFFIX : "";
if (source.referencedSourceFiles.get(GAME_MAPS_ARRAY_NAME+suffix) != null) { if (source.referencedSourceFiles.get(GAME_MAPS_ARRAY_NAME + suffix) != null) {
for (String resource : source.referencedSourceFiles.get(GAME_MAPS_ARRAY_NAME+suffix)) { for (String resource : source.referencedSourceFiles.get(GAME_MAPS_ARRAY_NAME + suffix)) {
File f = new File(mapFolder, resource.replaceAll(RESOURCE_PREFIX, "")+FILENAME_SUFFIX); File f = new File(mapFolder, resource.replaceAll(RESOURCE_PREFIX, "") + FILENAME_SUFFIX);
if (f.exists()) { if (f.exists()) {
TMXMap map = new TMXMap(this, f); TMXMap map = new TMXMap(this, f);
tmxMaps.add(map); tmxMaps.add(map);
} else { } else {
Notification.addWarn("Unable to locate resource "+resource+" in the game source for project "+getProject().name); Notification.addWarn("Unable to locate resource " + resource + " in the game source for project " + getProject().name);
} }
} }
} }
@@ -93,16 +82,18 @@ public class TMXMapSet implements ProjectTreeNode {
}); });
if (source.type == GameSource.Type.created | source.type == GameSource.Type.altered) { if (source.type == GameSource.Type.created | source.type == GameSource.Type.altered) {
final Path folderPath = Paths.get(mapFolder.getAbsolutePath()); final Path folderPath = Paths.get(mapFolder.getAbsolutePath());
Thread watcher = new Thread("Map folder watcher for "+getProject().name+"/"+source.type) { Thread watcher = new Thread("Map folder watcher for " + getProject().name + "/" + source.type) {
public void run() { public void run() {
WatchService watchService; WatchService watchService;
while(getProject().open) { while (getProject().open) {
try { try {
watchService = FileSystems.getDefault().newWatchService(); watchService = FileSystems.getDefault().newWatchService();
/*WatchKey watchKey = */folderPath.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_CREATE); /*WatchKey watchKey = */
folderPath.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_CREATE);
WatchKey wk; WatchKey wk;
validService: while(getProject().open) { validService:
while (getProject().open) {
wk = watchService.poll(10, TimeUnit.SECONDS); wk = watchService.poll(10, TimeUnit.SECONDS);
if (wk != null) { if (wk != null) {
for (WatchEvent<?> event : wk.pollEvents()) { for (WatchEvent<?> event : wk.pollEvents()) {
@@ -114,7 +105,7 @@ public class TMXMapSet implements ProjectTreeNode {
map.mapChangedOnDisk(); map.mapChangedOnDisk();
} }
} }
if(!wk.reset()) { if (!wk.reset()) {
watchService.close(); watchService.close();
break validService; break validService;
} }
@@ -126,7 +117,8 @@ public class TMXMapSet implements ProjectTreeNode {
e.printStackTrace(); e.printStackTrace();
} }
} }
}; }
}; };
watcher.start(); watcher.start();
} }
@@ -136,40 +128,49 @@ public class TMXMapSet implements ProjectTreeNode {
public Enumeration<TMXMap> children() { public Enumeration<TMXMap> children() {
return Collections.enumeration(tmxMaps); return Collections.enumeration(tmxMaps);
} }
@Override @Override
public boolean getAllowsChildren() { public boolean getAllowsChildren() {
return true; return true;
} }
@Override @Override
public TreeNode getChildAt(int arg0) { public TreeNode getChildAt(int arg0) {
return tmxMaps.get(arg0); return tmxMaps.get(arg0);
} }
@Override @Override
public int getChildCount() { public int getChildCount() {
return tmxMaps.size(); return tmxMaps.size();
} }
@Override @Override
public int getIndex(TreeNode arg0) { public int getIndex(TreeNode arg0) {
return tmxMaps.indexOf(arg0); return tmxMaps.indexOf(arg0);
} }
@Override @Override
public TreeNode getParent() { public TreeNode getParent() {
return parent; return parent;
} }
@Override @Override
public boolean isLeaf() { public boolean isLeaf() {
return false; return false;
} }
@Override @Override
public void childrenAdded(List<ProjectTreeNode> path) { public void childrenAdded(List<ProjectTreeNode> path) {
path.add(0, this); path.add(0, this);
parent.childrenAdded(path); parent.childrenAdded(path);
} }
@Override @Override
public void childrenChanged(List<ProjectTreeNode> path) { public void childrenChanged(List<ProjectTreeNode> path) {
path.add(0, this); path.add(0, this);
parent.childrenChanged(path); parent.childrenChanged(path);
} }
@Override @Override
public void childrenRemoved(List<ProjectTreeNode> path) { public void childrenRemoved(List<ProjectTreeNode> path) {
if (path.size() == 1 && this.getChildCount() == 1) { if (path.size() == 1 && this.getChildCount() == 1) {
@@ -179,6 +180,7 @@ public class TMXMapSet implements ProjectTreeNode {
parent.childrenRemoved(path); parent.childrenRemoved(path);
} }
} }
@Override @Override
public void notifyCreated() { public void notifyCreated() {
childrenAdded(new ArrayList<ProjectTreeNode>()); childrenAdded(new ArrayList<ProjectTreeNode>());
@@ -186,9 +188,10 @@ public class TMXMapSet implements ProjectTreeNode {
map.notifyCreated(); map.notifyCreated();
} }
} }
@Override @Override
public String getDesc() { public String getDesc() {
return (needsSaving() ? "*" : "")+"TMX Maps"; return (needsSaving() ? "*" : "") + "TMX Maps";
} }
@Override @Override
@@ -201,14 +204,17 @@ public class TMXMapSet implements ProjectTreeNode {
public Image getIcon() { public Image getIcon() {
return getOpenIcon(); return getOpenIcon();
} }
@Override @Override
public Image getClosedIcon() { public Image getClosedIcon() {
return DefaultIcons.getTmxClosedIcon(); return DefaultIcons.getTmxClosedIcon();
} }
@Override @Override
public Image getLeafIcon() { public Image getLeafIcon() {
return DefaultIcons.getTmxClosedIcon(); return DefaultIcons.getTmxClosedIcon();
} }
@Override @Override
public Image getOpenIcon() { public Image getOpenIcon() {
return DefaultIcons.getTmxOpenIcon(); return DefaultIcons.getTmxOpenIcon();
@@ -232,7 +238,7 @@ public class TMXMapSet implements ProjectTreeNode {
public TMXMap getMap(String id) { public TMXMap getMap(String id) {
if (tmxMaps == null) return null; if (tmxMaps == null) return null;
for (TMXMap map : tmxMaps) { for (TMXMap map : tmxMaps) {
if (id.equals(map.id)){ if (id.equals(map.id)) {
return map; return map;
} }
} }
@@ -242,7 +248,8 @@ public class TMXMapSet implements ProjectTreeNode {
public void addMap(TMXMap node) { public void addMap(TMXMap node) {
ProjectTreeNode higherEmptyParent = this; ProjectTreeNode higherEmptyParent = this;
while (higherEmptyParent != null) { while (higherEmptyParent != null) {
if (higherEmptyParent.getParent() != null && ((ProjectTreeNode)higherEmptyParent.getParent()).isEmpty()) higherEmptyParent = (ProjectTreeNode)higherEmptyParent.getParent(); if (higherEmptyParent.getParent() != null && ((ProjectTreeNode) higherEmptyParent.getParent()).isEmpty())
higherEmptyParent = (ProjectTreeNode) higherEmptyParent.getParent();
else break; else break;
} }
if (higherEmptyParent == this && !this.isEmpty()) higherEmptyParent = null; if (higherEmptyParent == this && !this.isEmpty()) higherEmptyParent = null;
@@ -252,7 +259,7 @@ public class TMXMapSet implements ProjectTreeNode {
node.tmxFile = new File(this.mapFolder, node.tmxFile.getName()); node.tmxFile = new File(this.mapFolder, node.tmxFile.getName());
} else { } else {
//Created node. //Created node.
node.tmxFile = new File(this.mapFolder, node.id+".tmx"); node.tmxFile = new File(this.mapFolder, node.id + ".tmx");
} }
node.parent = this; node.parent = this;
if (higherEmptyParent != null) higherEmptyParent.notifyCreated(); if (higherEmptyParent != null) higherEmptyParent.notifyCreated();

View File

@@ -1,40 +1,5 @@
package com.gpl.rpg.atcontentstudio.model.maps; package com.gpl.rpg.atcontentstudio.model.maps;
import java.awt.Image;
import java.awt.Point;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.swing.tree.TreeNode;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.GameDataElement;
import com.gpl.rpg.atcontentstudio.model.GameSource; import com.gpl.rpg.atcontentstudio.model.GameSource;
import com.gpl.rpg.atcontentstudio.model.GameSource.Type; import com.gpl.rpg.atcontentstudio.model.GameSource.Type;
@@ -42,18 +7,35 @@ import com.gpl.rpg.atcontentstudio.model.Project;
import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode; import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode;
import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet; import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet;
import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import javax.swing.tree.TreeNode;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.awt.*;
import java.io.*;
import java.util.List;
import java.util.*;
public class Worldmap extends ArrayList<WorldmapSegment> implements ProjectTreeNode { public class Worldmap extends ArrayList<WorldmapSegment> implements ProjectTreeNode {
private static final long serialVersionUID = 4590409256594556179L; private static final long serialVersionUID = 4590409256594556179L;
public static final String DEFAULT_REL_PATH_IN_SOURCE = "res/xml/worldmap.xml"; public static final String DEFAULT_REL_PATH_IN_SOURCE = "res/xml/worldmap.xml";
public static final String DEFAULT_REL_PATH_IN_PROJECT = "maps"+File.separator+"worldmap.xml"; public static final String DEFAULT_REL_PATH_IN_PROJECT = "maps" + File.separator + "worldmap.xml";
public File worldmapFile; public File worldmapFile;
public GameSource parent; public GameSource parent;
public Map<String, Map<String, Point>> segments = new LinkedHashMap<String, Map<String,Point>>(); public Map<String, Map<String, Point>> segments = new LinkedHashMap<String, Map<String, Point>>();
public Worldmap(GameSource gameSource) { public Worldmap(GameSource gameSource) {
this.parent = gameSource; this.parent = gameSource;
@@ -152,13 +134,13 @@ public class Worldmap extends ArrayList<WorldmapSegment> implements ProjectTreeN
@Override @Override
public void childrenAdded(List<ProjectTreeNode> path) { public void childrenAdded(List<ProjectTreeNode> path) {
path.add(0,this); path.add(0, this);
parent.childrenAdded(path); parent.childrenAdded(path);
} }
@Override @Override
public void childrenChanged(List<ProjectTreeNode> path) { public void childrenChanged(List<ProjectTreeNode> path) {
path.add(0,this); path.add(0, this);
parent.childrenChanged(path); parent.childrenChanged(path);
} }
@@ -174,8 +156,9 @@ public class Worldmap extends ArrayList<WorldmapSegment> implements ProjectTreeN
@Override @Override
public String getDesc() { public String getDesc() {
return (needsSaving() ? "*" : "")+"Worldmap"; return (needsSaving() ? "*" : "") + "Worldmap";
} }
@Override @Override
public void notifyCreated() { public void notifyCreated() {
childrenAdded(new ArrayList<ProjectTreeNode>()); childrenAdded(new ArrayList<ProjectTreeNode>());
@@ -190,14 +173,17 @@ public class Worldmap extends ArrayList<WorldmapSegment> implements ProjectTreeN
public Image getIcon() { public Image getIcon() {
return DefaultIcons.getMapClosedIcon(); return DefaultIcons.getMapClosedIcon();
} }
@Override @Override
public Image getLeafIcon() { public Image getLeafIcon() {
return null; return null;
} }
@Override @Override
public Image getClosedIcon() { public Image getClosedIcon() {
return DefaultIcons.getMapClosedIcon(); return DefaultIcons.getMapClosedIcon();
} }
@Override @Override
public Image getOpenIcon() { public Image getOpenIcon() {
return DefaultIcons.getMapOpenIcon(); return DefaultIcons.getMapOpenIcon();
@@ -245,7 +231,8 @@ public class Worldmap extends ArrayList<WorldmapSegment> implements ProjectTreeN
public void addSegment(WorldmapSegment node) { public void addSegment(WorldmapSegment node) {
ProjectTreeNode higherEmptyParent = this; ProjectTreeNode higherEmptyParent = this;
while (higherEmptyParent != null) { while (higherEmptyParent != null) {
if (higherEmptyParent.getParent() != null && ((ProjectTreeNode)higherEmptyParent.getParent()).isEmpty()) higherEmptyParent = (ProjectTreeNode)higherEmptyParent.getParent(); if (higherEmptyParent.getParent() != null && ((ProjectTreeNode) higherEmptyParent.getParent()).isEmpty())
higherEmptyParent = (ProjectTreeNode) higherEmptyParent.getParent();
else break; else break;
} }
if (higherEmptyParent == this && !this.isEmpty()) higherEmptyParent = null; if (higherEmptyParent == this && !this.isEmpty()) higherEmptyParent = null;

View File

@@ -1,34 +1,26 @@
package com.gpl.rpg.atcontentstudio.model.maps; package com.gpl.rpg.atcontentstudio.model.maps;
import java.awt.Image;
import java.awt.Point;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import com.gpl.rpg.atcontentstudio.ATContentStudio; import com.gpl.rpg.atcontentstudio.ATContentStudio;
import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.GameDataElement;
import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode; import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode;
import com.gpl.rpg.atcontentstudio.model.SaveEvent; import com.gpl.rpg.atcontentstudio.model.SaveEvent;
import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet; import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet;
import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.awt.*;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class WorldmapSegment extends GameDataElement { public class WorldmapSegment extends GameDataElement {
@@ -56,7 +48,7 @@ public class WorldmapSegment extends GameDataElement {
@Override @Override
public String getDesc() { public String getDesc() {
return (needsSaving() ? "*" : "")+id; return (needsSaving() ? "*" : "") + id;
} }
@Override @Override
@@ -99,7 +91,7 @@ public class WorldmapSegment extends GameDataElement {
@Override @Override
public WorldmapSegment clone() { public WorldmapSegment clone() {
WorldmapSegment clone = new WorldmapSegment((Worldmap)parent, id, (Element) xmlNode.cloneNode(true)); WorldmapSegment clone = new WorldmapSegment((Worldmap) parent, id, (Element) xmlNode.cloneNode(true));
return clone; return clone;
} }
@@ -130,7 +122,7 @@ public class WorldmapSegment extends GameDataElement {
} }
oldOne.removeBacklink(this); oldOne.removeBacklink(this);
if(newOne != null) newOne.addBacklink(this); if (newOne != null) newOne.addBacklink(this);
if (modified) { if (modified) {
this.state = GameDataElement.State.modified; this.state = GameDataElement.State.modified;
@@ -146,7 +138,7 @@ public class WorldmapSegment extends GameDataElement {
@Override @Override
public void save() { public void save() {
((Worldmap)parent).save(); ((Worldmap) parent).save();
} }
public String toXml() { public String toXml() {
@@ -232,6 +224,7 @@ public class WorldmapSegment extends GameDataElement {
public Image getIcon() { public Image getIcon() {
return DefaultIcons.getUIMapIcon(); return DefaultIcons.getUIMapIcon();
} }
@Override @Override
public Image getLeafIcon() { public Image getLeafIcon() {
return DefaultIcons.getUIMapIcon(); return DefaultIcons.getUIMapIcon();

View File

@@ -1,177 +0,0 @@
package com.gpl.rpg.atcontentstudio.model.saves;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import javax.swing.tree.TreeNode;
import com.gpl.rpg.andorstrainer.io.SavedGameIO;
import com.gpl.rpg.atcontentstudio.model.GameDataElement;
import com.gpl.rpg.atcontentstudio.model.GameSource.Type;
import com.gpl.rpg.atcontentstudio.model.Project;
import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode;
import com.gpl.rpg.atcontentstudio.model.SaveEvent;
import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet;
import com.gpl.rpg.atcontentstudio.ui.DefaultIcons;
public class SavedGame extends GameDataElement {
private static final long serialVersionUID = -6443495534761084990L;
public File savedFile;
transient public com.gpl.rpg.andorstrainer.model.SavedGame loadedSave = null;
transient public SavedGamesSet parent;
public SavedGame(SavedGamesSet parent, File f) throws IOException {
savedFile = f;
refreshTransients(parent);
}
public void refreshTransients(SavedGamesSet parent) throws IOException {
this.parent = parent;
this.loadedSave = SavedGameIO.loadFile(savedFile);
if (this.loadedSave == null) {
throw new IOException("Unable to load save: "+savedFile.getAbsolutePath());
}
}
@Override
public Enumeration<ProjectTreeNode> children() {
return null;
}
@Override
public boolean getAllowsChildren() {
return false;
}
@Override
public TreeNode getChildAt(int arg0) {
return null;
}
@Override
public int getChildCount() {
return 0;
}
@Override
public int getIndex(TreeNode arg0) {
return 0;
}
@Override
public TreeNode getParent() {
return parent;
}
@Override
public boolean isLeaf() {
return true;
}
@Override
public void childrenAdded(List<ProjectTreeNode> path) {
path.add(0,this);
parent.childrenAdded(path);
}
@Override
public void childrenChanged(List<ProjectTreeNode> path) {
path.add(0,this);
parent.childrenChanged(path);
}
@Override
public void childrenRemoved(List<ProjectTreeNode> path) {
path.add(0,this);
parent.childrenRemoved(path);
}
@Override
public void notifyCreated() {
childrenAdded(new ArrayList<ProjectTreeNode>());
}
@Override
public String getDesc() {
return (needsSaving() ? "*" : "")+loadedSave.displayInfo;
}
@Override
public Project getProject() {
return parent.getProject();
}
@Override
public Image getIcon() {
return DefaultIcons.getHeroIcon();
}
@Override
public Image getLeafIcon() {
return DefaultIcons.getHeroIcon();
}
@Override
public Image getClosedIcon() {return null;}
@Override
public Image getOpenIcon() {return null;}
@Override
public GameDataSet getDataSet() {
return null;
}
@Override
public Type getDataType() {
return null;
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public void parse() {
// TODO Auto-generated method stub
}
@Override
public void link() {
// TODO Auto-generated method stub
}
@Override
public GameDataElement clone() {
// TODO Auto-generated method stub
return null;
}
@Override
public void elementChanged(GameDataElement oldOne, GameDataElement newOne) {
// TODO Auto-generated method stub
}
@Override
public String getProjectFilename() {
// TODO Auto-generated method stub
return null;
}
@Override
public void save() {
// TODO Auto-generated method stub
}
@Override
public List<SaveEvent> attemptSave() {
// TODO Auto-generated method stub
return null;
}
}

View File

@@ -1,180 +0,0 @@
package com.gpl.rpg.atcontentstudio.model.saves;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Vector;
import javax.swing.tree.TreeNode;
import com.gpl.rpg.atcontentstudio.Notification;
import com.gpl.rpg.atcontentstudio.model.GameSource.Type;
import com.gpl.rpg.atcontentstudio.model.Project;
import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode;
import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet;
import com.gpl.rpg.atcontentstudio.ui.DefaultIcons;
public class SavedGamesSet implements ProjectTreeNode, Serializable {
private static final long serialVersionUID = -6565834239789184087L;
public Vector<SavedGame> saves; //For simulations.
public Project parent;
public SavedGamesSet(Project parent) {
this.parent = parent;
saves = new Vector<SavedGame>();
}
public void refreshTransients() {
for (SavedGame save : saves) {
try {
save.refreshTransients(this);
} catch (IOException e) {
Notification.addError(e.getMessage());
}
}
}
public void addSave(File f) {
try {
ProjectTreeNode higherEmptyParent = this;
while (higherEmptyParent != null) {
if (higherEmptyParent.getParent() != null && ((ProjectTreeNode)higherEmptyParent.getParent()).isEmpty()) higherEmptyParent = (ProjectTreeNode)higherEmptyParent.getParent();
else break;
}
if (higherEmptyParent == this && !this.isEmpty()) higherEmptyParent = null;
SavedGame node = new SavedGame(this, f);
saves.add(node);
if (higherEmptyParent != null) higherEmptyParent.notifyCreated();
else node.notifyCreated();
} catch (IOException e) {
Notification.addError(e.getMessage());
}
}
public SavedGame getSave(File f) {
for (SavedGame save : saves) {
if (save.savedFile.equals(f)) return save;
}
return null;
}
@Override
public Enumeration<? extends ProjectTreeNode> children() {
return saves.elements();
}
@Override
public boolean getAllowsChildren() {
return true;
}
@Override
public TreeNode getChildAt(int arg0) {
return saves.elementAt(arg0);
}
@Override
public int getChildCount() {
return saves.size();
}
@Override
public int getIndex(TreeNode arg0) {
return saves.indexOf(arg0);
}
@Override
public TreeNode getParent() {
return parent;
}
@Override
public boolean isLeaf() {
return false;
}
@Override
public void childrenAdded(List<ProjectTreeNode> path) {
path.add(0, this);
parent.childrenAdded(path);
}
@Override
public void childrenChanged(List<ProjectTreeNode> path) {
path.add(0, this);
parent.childrenChanged(path);
}
@Override
public void childrenRemoved(List<ProjectTreeNode> path) {
if (path.size() == 1 && this.getChildCount() == 1) {
childrenRemoved(new ArrayList<ProjectTreeNode>());
} else {
path.add(0, this);
parent.childrenRemoved(path);
}
}
@Override
public void notifyCreated() {
childrenAdded(new ArrayList<ProjectTreeNode>());
for (SavedGame s : saves) {
s.notifyCreated();
}
}
@Override
public String getDesc() {
return (needsSaving() ? "*" : "")+"Saved games";
}
@Override
public Project getProject() {
return parent.getProject();
}
@Override
public Image getIcon() {
return getOpenIcon();
}
@Override
public Image getClosedIcon() {
return DefaultIcons.getSavClosedIcon();
}
@Override
public Image getLeafIcon() {
return DefaultIcons.getSavClosedIcon();
}
@Override
public Image getOpenIcon() {
return DefaultIcons.getSavOpenIcon();
}
@Override
public GameDataSet getDataSet() {
return null;
}
@Override
public Type getDataType() {
return null;
}
@Override
public boolean isEmpty() {
return saves.isEmpty();
}
@Override
public boolean needsSaving() {
for (ProjectTreeNode node : saves) {
if (node.needsSaving()) return true;
}
return false;
}
}

View File

@@ -1,14 +1,5 @@
package com.gpl.rpg.atcontentstudio.model.sprites; package com.gpl.rpg.atcontentstudio.model.sprites;
import java.awt.Image;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import javax.swing.tree.TreeNode;
import com.gpl.rpg.atcontentstudio.model.GameSource; import com.gpl.rpg.atcontentstudio.model.GameSource;
import com.gpl.rpg.atcontentstudio.model.GameSource.Type; import com.gpl.rpg.atcontentstudio.model.GameSource.Type;
import com.gpl.rpg.atcontentstudio.model.Project; import com.gpl.rpg.atcontentstudio.model.Project;
@@ -16,10 +7,16 @@ import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode;
import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet; import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet;
import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons;
import javax.swing.tree.TreeNode;
import java.awt.*;
import java.io.File;
import java.util.*;
import java.util.List;
public class SpriteSheetSet implements ProjectTreeNode { public class SpriteSheetSet implements ProjectTreeNode {
public static final String DEFAULT_REL_PATH_IN_SOURCE = "res"+File.separator+"drawable"+File.separator; public static final String DEFAULT_REL_PATH_IN_SOURCE = "res" + File.separator + "drawable" + File.separator;
public static final String DEFAULT_REL_PATH_IN_PROJECT = "spritesheets"+File.separator; public static final String DEFAULT_REL_PATH_IN_PROJECT = "spritesheets" + File.separator;
public File drawableFolder = null; public File drawableFolder = null;
@@ -29,7 +26,8 @@ public class SpriteSheetSet implements ProjectTreeNode {
public SpriteSheetSet(GameSource source) { public SpriteSheetSet(GameSource source) {
this.parent = source; this.parent = source;
if (source.type == GameSource.Type.source) this.drawableFolder = new File(source.baseFolder, DEFAULT_REL_PATH_IN_SOURCE); if (source.type == GameSource.Type.source)
this.drawableFolder = new File(source.baseFolder, DEFAULT_REL_PATH_IN_SOURCE);
else if (source.type == GameSource.Type.created | source.type == GameSource.Type.altered) { else if (source.type == GameSource.Type.created | source.type == GameSource.Type.altered) {
this.drawableFolder = new File(source.baseFolder, DEFAULT_REL_PATH_IN_PROJECT); this.drawableFolder = new File(source.baseFolder, DEFAULT_REL_PATH_IN_PROJECT);
if (!this.drawableFolder.exists()) { if (!this.drawableFolder.exists()) {
@@ -44,46 +42,56 @@ public class SpriteSheetSet implements ProjectTreeNode {
} }
} }
} }
spritesheets.sort(Comparator.comparing(s -> s.id));
} }
@Override @Override
public Enumeration<Spritesheet> children() { public Enumeration<Spritesheet> children() {
return Collections.enumeration(spritesheets); return Collections.enumeration(spritesheets);
} }
@Override @Override
public boolean getAllowsChildren() { public boolean getAllowsChildren() {
return true; return true;
} }
@Override @Override
public TreeNode getChildAt(int arg0) { public TreeNode getChildAt(int arg0) {
return spritesheets.get(arg0); return spritesheets.get(arg0);
} }
@Override @Override
public int getChildCount() { public int getChildCount() {
return spritesheets.size(); return spritesheets.size();
} }
@Override @Override
public int getIndex(TreeNode arg0) { public int getIndex(TreeNode arg0) {
return spritesheets.indexOf(arg0); return spritesheets.indexOf(arg0);
} }
@Override @Override
public TreeNode getParent() { public TreeNode getParent() {
return parent; return parent;
} }
@Override @Override
public boolean isLeaf() { public boolean isLeaf() {
return false; return false;
} }
@Override @Override
public void childrenAdded(List<ProjectTreeNode> path) { public void childrenAdded(List<ProjectTreeNode> path) {
path.add(0, this); path.add(0, this);
parent.childrenAdded(path); parent.childrenAdded(path);
} }
@Override @Override
public void childrenChanged(List<ProjectTreeNode> path) { public void childrenChanged(List<ProjectTreeNode> path) {
path.add(0, this); path.add(0, this);
parent.childrenChanged(path); parent.childrenChanged(path);
} }
@Override @Override
public void childrenRemoved(List<ProjectTreeNode> path) { public void childrenRemoved(List<ProjectTreeNode> path) {
if (path.size() == 1 && this.getChildCount() == 1) { if (path.size() == 1 && this.getChildCount() == 1) {
@@ -93,6 +101,7 @@ public class SpriteSheetSet implements ProjectTreeNode {
parent.childrenRemoved(path); parent.childrenRemoved(path);
} }
} }
@Override @Override
public void notifyCreated() { public void notifyCreated() {
childrenAdded(new ArrayList<ProjectTreeNode>()); childrenAdded(new ArrayList<ProjectTreeNode>());
@@ -100,9 +109,10 @@ public class SpriteSheetSet implements ProjectTreeNode {
s.notifyCreated(); s.notifyCreated();
} }
} }
@Override @Override
public String getDesc() { public String getDesc() {
return (needsSaving() ? "*" : "")+"Spritesheets"; return (needsSaving() ? "*" : "") + "Spritesheets";
} }
@Override @Override
@@ -114,14 +124,17 @@ public class SpriteSheetSet implements ProjectTreeNode {
public Image getIcon() { public Image getIcon() {
return getOpenIcon(); return getOpenIcon();
} }
@Override @Override
public Image getClosedIcon() { public Image getClosedIcon() {
return DefaultIcons.getSpriteClosedIcon(); return DefaultIcons.getSpriteClosedIcon();
} }
@Override @Override
public Image getLeafIcon() { public Image getLeafIcon() {
return DefaultIcons.getSpriteClosedIcon(); return DefaultIcons.getSpriteClosedIcon();
} }
@Override @Override
public Image getOpenIcon() { public Image getOpenIcon() {
return DefaultIcons.getSpriteOpenIcon(); return DefaultIcons.getSpriteOpenIcon();
@@ -145,7 +158,7 @@ public class SpriteSheetSet implements ProjectTreeNode {
public Spritesheet getSpritesheet(String id) { public Spritesheet getSpritesheet(String id) {
if (spritesheets == null) return null; if (spritesheets == null) return null;
for (Spritesheet sheet : spritesheets) { for (Spritesheet sheet : spritesheets) {
if (id.equals(sheet.id)){ if (id.equals(sheet.id)) {
return sheet; return sheet;
} }
} }

View File

@@ -1,19 +1,5 @@
package com.gpl.rpg.atcontentstudio.model.sprites; package com.gpl.rpg.atcontentstudio.model.sprites;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.swing.tree.TreeNode;
import com.gpl.rpg.atcontentstudio.ATContentStudio; import com.gpl.rpg.atcontentstudio.ATContentStudio;
import com.gpl.rpg.atcontentstudio.Notification; import com.gpl.rpg.atcontentstudio.Notification;
import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.GameDataElement;
@@ -23,6 +9,15 @@ import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode;
import com.gpl.rpg.atcontentstudio.model.SaveEvent; import com.gpl.rpg.atcontentstudio.model.SaveEvent;
import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet; import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet;
import javax.imageio.ImageIO;
import javax.swing.tree.TreeNode;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.*;
public class Spritesheet extends GameDataElement { public class Spritesheet extends GameDataElement {
private static final long serialVersionUID = -5981708088278528586L; private static final long serialVersionUID = -5981708088278528586L;
@@ -40,7 +35,7 @@ public class Spritesheet extends GameDataElement {
monster, monster,
item, item,
actorcondition actorcondition
}; }
//Lazy initialization. //Lazy initialization.
public BufferedImage spritesheet = null; public BufferedImage spritesheet = null;
@@ -52,19 +47,19 @@ public class Spritesheet extends GameDataElement {
this.id = f.getName().substring(0, f.getName().lastIndexOf(".")); this.id = f.getName().substring(0, f.getName().lastIndexOf("."));
this.parent = parent; this.parent = parent;
String cat = getProject().getSpritesheetsProperty("atcs.spritesheet."+this.id+".category"); String cat = getProject().getSpritesheetsProperty("atcs.spritesheet." + this.id + ".category");
if (cat != null) { if (cat != null) {
this.category = Category.valueOf(cat); this.category = Category.valueOf(cat);
} }
String sizex = getProject().getSpritesheetsProperty("atcs.spritesheet."+this.id+".sizex"); String sizex = getProject().getSpritesheetsProperty("atcs.spritesheet." + this.id + ".sizex");
if (sizex != null) { if (sizex != null) {
this.spriteWidth = Integer.parseInt(sizex); this.spriteWidth = Integer.parseInt(sizex);
} }
String sizey = getProject().getSpritesheetsProperty("atcs.spritesheet."+this.id+".sizey"); String sizey = getProject().getSpritesheetsProperty("atcs.spritesheet." + this.id + ".sizey");
if (sizey != null) { if (sizey != null) {
this.spriteHeight = Integer.parseInt(sizey); this.spriteHeight = Integer.parseInt(sizey);
} }
String anim = getProject().getSpritesheetsProperty("atcs.spritesheet."+this.id+".animate"); String anim = getProject().getSpritesheetsProperty("atcs.spritesheet." + this.id + ".animate");
if (anim != null) { if (anim != null) {
this.animated = Boolean.parseBoolean(anim); this.animated = Boolean.parseBoolean(anim);
} }
@@ -74,52 +69,63 @@ public class Spritesheet extends GameDataElement {
public Enumeration<ProjectTreeNode> children() { public Enumeration<ProjectTreeNode> children() {
return null; return null;
} }
@Override @Override
public boolean getAllowsChildren() { public boolean getAllowsChildren() {
return false; return false;
} }
@Override @Override
public TreeNode getChildAt(int arg0) { public TreeNode getChildAt(int arg0) {
return null; return null;
} }
@Override @Override
public int getChildCount() { public int getChildCount() {
return 0; return 0;
} }
@Override @Override
public int getIndex(TreeNode arg0) { public int getIndex(TreeNode arg0) {
return 0; return 0;
} }
@Override @Override
public TreeNode getParent() { public TreeNode getParent() {
return parent; return parent;
} }
@Override @Override
public boolean isLeaf() { public boolean isLeaf() {
return true; return true;
} }
@Override @Override
public void childrenAdded(List<ProjectTreeNode> path) { public void childrenAdded(List<ProjectTreeNode> path) {
path.add(0, this); path.add(0, this);
parent.childrenAdded(path); parent.childrenAdded(path);
} }
@Override @Override
public void childrenChanged(List<ProjectTreeNode> path) { public void childrenChanged(List<ProjectTreeNode> path) {
path.add(0, this); path.add(0, this);
parent.childrenChanged(path); parent.childrenChanged(path);
} }
@Override @Override
public void childrenRemoved(List<ProjectTreeNode> path) { public void childrenRemoved(List<ProjectTreeNode> path) {
path.add(0, this); path.add(0, this);
parent.childrenRemoved(path); parent.childrenRemoved(path);
} }
@Override @Override
public void notifyCreated() { public void notifyCreated() {
childrenAdded(new ArrayList<ProjectTreeNode>()); childrenAdded(new ArrayList<ProjectTreeNode>());
} }
@Override @Override
public String getDesc() { public String getDesc() {
return (needsSaving() ? "*" : "")+spritesheetFile.getName(); return (needsSaving() ? "*" : "") + spritesheetFile.getName();
} }
@Override @Override
@@ -132,12 +138,12 @@ public class Spritesheet extends GameDataElement {
try { try {
spritesheet = ImageIO.read(spritesheetFile); spritesheet = ImageIO.read(spritesheetFile);
} catch (IOException e) { } catch (IOException e) {
Notification.addError("Error loading image "+spritesheetFile.getAbsolutePath()+" : "+e.getMessage()); Notification.addError("Error loading image " + spritesheetFile.getAbsolutePath() + " : " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
return 0; return 0;
} }
} }
return (int) (Math.ceil(((double)spritesheet.getWidth()) / ((double)spriteWidth)) * Math.ceil(((double)spritesheet.getHeight()) / ((double)spriteHeight))); return (int) (Math.ceil(((double) spritesheet.getWidth()) / ((double) spriteWidth)) * Math.ceil(((double) spritesheet.getHeight()) / ((double) spriteHeight)));
} }
public BufferedImage getImage(int index) { public BufferedImage getImage(int index) {
@@ -145,7 +151,7 @@ public class Spritesheet extends GameDataElement {
try { try {
spritesheet = ImageIO.read(spritesheetFile); spritesheet = ImageIO.read(spritesheetFile);
} catch (IOException e) { } catch (IOException e) {
Notification.addError("Error loading image "+spritesheetFile.getAbsolutePath()+" : "+e.getMessage()); Notification.addError("Error loading image " + spritesheetFile.getAbsolutePath() + " : " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
return null; return null;
} }
@@ -175,7 +181,7 @@ public class Spritesheet extends GameDataElement {
} }
Image result = getImage(index); Image result = getImage(index);
if (result == null) return null; if (result == null) return null;
result = result.getScaledInstance((int)(16*ATContentStudio.SCALING), (int)(16*ATContentStudio.SCALING), Image.SCALE_SMOOTH); result = result.getScaledInstance((int) (16 * ATContentStudio.SCALING), (int) (16 * ATContentStudio.SCALING), Image.SCALE_SMOOTH);
cache_icon.put(index, result); cache_icon.put(index, result);
return result; return result;
} }
@@ -190,14 +196,21 @@ public class Spritesheet extends GameDataElement {
public Image getIcon() { public Image getIcon() {
return getIcon(0); return getIcon(0);
} }
@Override @Override
public Image getLeafIcon() { public Image getLeafIcon() {
return getIcon(); return getIcon();
} }
@Override @Override
public Image getClosedIcon() {return null;} public Image getClosedIcon() {
return null;
}
@Override @Override
public Image getOpenIcon() {return null;} public Image getOpenIcon() {
return null;
}
@Override @Override
@@ -217,7 +230,7 @@ public class Spritesheet extends GameDataElement {
@Override @Override
public void parse() { public void parse() {
if(this.state == GameDataElement.State.init){ if (this.state == GameDataElement.State.init) {
this.state = GameDataElement.State.parsed; this.state = GameDataElement.State.parsed;
} }
} }
@@ -227,7 +240,7 @@ public class Spritesheet extends GameDataElement {
if (this.state == GameDataElement.State.init) { if (this.state == GameDataElement.State.init) {
this.parse(); this.parse();
} }
if(this.state == GameDataElement.State.parsed) { if (this.state == GameDataElement.State.parsed) {
this.state = GameDataElement.State.linked; this.state = GameDataElement.State.linked;
} }
} }
@@ -255,10 +268,14 @@ public class Spritesheet extends GameDataElement {
@Override @Override
public void save() { public void save() {
if (this.category != null) getProject().setSpritesheetsProperty("atcs.spritesheet."+this.id+".category", this.category.toString()); if (this.category != null)
if (this.spriteWidth != 32) getProject().setSpritesheetsProperty("atcs.spritesheet."+this.id+".sizex", Integer.toString(this.spriteWidth)); getProject().setSpritesheetsProperty("atcs.spritesheet." + this.id + ".category", this.category.toString());
if (this.spriteHeight != 32) getProject().setSpritesheetsProperty("atcs.spritesheet."+this.id+".sizey", Integer.toString(this.spriteHeight)); if (this.spriteWidth != 32)
if (this.animated)getProject().setSpritesheetsProperty("atcs.spritesheet."+this.id+".animate", Boolean.toString(this.animated)); getProject().setSpritesheetsProperty("atcs.spritesheet." + this.id + ".sizex", Integer.toString(this.spriteWidth));
if (this.spriteHeight != 32)
getProject().setSpritesheetsProperty("atcs.spritesheet." + this.id + ".sizey", Integer.toString(this.spriteHeight));
if (this.animated)
getProject().setSpritesheetsProperty("atcs.spritesheet." + this.id + ".animate", Boolean.toString(this.animated));
getProject().save(); getProject().save();
this.state = GameDataElement.State.saved; this.state = GameDataElement.State.saved;

View File

@@ -1,11 +1,6 @@
package com.gpl.rpg.atcontentstudio.model.tools.i18n; package com.gpl.rpg.atcontentstudio.model.tools.i18n;
import java.io.File; import java.io.*;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.LinkedList; import java.util.LinkedList;

View File

@@ -1,41 +1,34 @@
package com.gpl.rpg.atcontentstudio.model.tools.i18n; package com.gpl.rpg.atcontentstudio.model.tools.i18n;
import java.io.File;
import java.io.FileFilter;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import javax.swing.JOptionPane;
import com.gpl.rpg.atcontentstudio.model.Project; import com.gpl.rpg.atcontentstudio.model.Project;
import net.launchpad.tobal.poparser.POEntry; import net.launchpad.tobal.poparser.POEntry;
import net.launchpad.tobal.poparser.POFile; import net.launchpad.tobal.poparser.POFile;
import net.launchpad.tobal.poparser.POParser; import net.launchpad.tobal.poparser.POParser;
import javax.swing.*;
import java.io.File;
import java.io.FileFilter;
import java.util.*;
/** /**
*
* @author Kevin * @author Kevin
* * <p>
* To use this, paste the following script in the beanshell console of ATCS. * To use this, paste the following script in the beanshell console of ATCS.
* Don't forget to change the project number to suit your needs. * Don't forget to change the project number to suit your needs.
* <p>
* <code>
* *
import com.gpl.rpg.atcontentstudio.model.Workspace; * import com.gpl.rpg.atcontentstudio.model.Workspace;
import com.gpl.rpg.atcontentstudio.model.tools.i18n.PotGenerator; * import com.gpl.rpg.atcontentstudio.model.tools.i18n.PotGenerator;
import com.gpl.rpg.atcontentstudio.model.tools.i18n.PotComparator; * import com.gpl.rpg.atcontentstudio.model.tools.i18n.PotComparator;
proj = Workspace.activeWorkspace.projects.get(7);
PotGenerator.generatePotFileForProject(proj);
comp = new PotComparator(proj);
comp.compare();
comp.updatePoFiles(proj);
*
*
* *
* proj = Workspace.activeWorkspace.projects.get(7);
* PotGenerator.generatePotFileForProject(proj);
* comp = new PotComparator(proj);
* comp.compare();
* comp.updatePoFiles(proj);
* </code>
*/ */
public class PotComparator { public class PotComparator {
@@ -53,15 +46,15 @@ public class PotComparator {
public PotComparator(Project proj) { public PotComparator(Project proj) {
POParser parser = new POParser(); POParser parser = new POParser();
POFile newPot = parser.parseFile(new File(proj.alteredContent.baseFolder.getAbsolutePath()+File.separator+"english.pot")); POFile newPot = parser.parseFile(new File(proj.alteredContent.baseFolder.getAbsolutePath() + File.separator + "english.pot"));
if (newPot == null) { if (newPot == null) {
System.err.println("Cannot locate new english.pot file at "+proj.alteredContent.baseFolder.getAbsolutePath()+File.separator); System.err.println("Cannot locate new english.pot file at " + proj.alteredContent.baseFolder.getAbsolutePath() + File.separator);
} }
extractFromPoFile(newPot, stringsResourcesNew, resourcesStringsNew); extractFromPoFile(newPot, stringsResourcesNew, resourcesStringsNew);
POFile oldPot = parser.parseFile(new File(proj.baseContent.baseFolder.getAbsolutePath()+File.separator+"assets"+File.separator+"translation"+File.separator+"english.pot")); POFile oldPot = parser.parseFile(new File(proj.baseContent.baseFolder.getAbsolutePath() + File.separator + "assets" + File.separator + "translation" + File.separator + "english.pot"));
if (oldPot == null) { if (oldPot == null) {
System.err.println("Cannot locate old english.pot file at "+proj.baseContent.baseFolder.getAbsolutePath()+File.separator+"assets"+File.separator+"translations"+File.separator); System.err.println("Cannot locate old english.pot file at " + proj.baseContent.baseFolder.getAbsolutePath() + File.separator + "assets" + File.separator + "translations" + File.separator);
} }
extractFromPoFile(oldPot, stringsResourcesOld, resourcesStringsOld); extractFromPoFile(oldPot, stringsResourcesOld, resourcesStringsOld);
} }
@@ -80,7 +73,7 @@ public class PotComparator {
} }
if (msgid.contains("\\n")) { if (msgid.contains("\\n")) {
msgid = msgid.replaceAll("\\\\n", "\\\\n\"\n\""); msgid = msgid.replaceAll("\\\\n", "\\\\n\"\n\"");
msgid = "\"\n\""+msgid; msgid = "\"\n\"" + msgid;
} }
for (String resLine : resources) { for (String resLine : resources) {
String[] resArray = resLine.split(" "); String[] resArray = resLine.split(" ");
@@ -107,23 +100,23 @@ public class PotComparator {
sb.append("---------------------------------------------\n"); sb.append("---------------------------------------------\n");
sb.append("--- TYPO CHECK ------------------------------\n"); sb.append("--- TYPO CHECK ------------------------------\n");
sb.append("---------------------------------------------\n"); sb.append("---------------------------------------------\n");
sb.append("String at: "+oldRes+"\n"); sb.append("String at: " + oldRes + "\n");
if (allOldResources.size() > 1) { if (allOldResources.size() > 1) {
sb.append("Also present at:\n"); sb.append("Also present at:\n");
for (String res : allOldResources) { for (String res : allOldResources) {
if (!res.equals(oldRes)) { if (!res.equals(oldRes)) {
sb.append("- "+res+"\n"); sb.append("- " + res + "\n");
} }
} }
} }
if (allNewResources != null) { if (allNewResources != null) {
sb.append("Still present at: \n"); sb.append("Still present at: \n");
for (String res : allNewResources) { for (String res : allNewResources) {
sb.append("- "+res+"\n"); sb.append("- " + res + "\n");
} }
} }
sb.append("Was : \""+oldString+"\"\n"); sb.append("Was : \"" + oldString + "\"\n");
sb.append("Now : \""+newString+"\"\n"); sb.append("Now : \"" + newString + "\"\n");
System.out.println(sb.toString()); System.out.println(sb.toString());
showTypoDialog(oldString, newString, sb.toString()); showTypoDialog(oldString, newString, sb.toString());
} }
@@ -134,29 +127,30 @@ public class PotComparator {
System.out.println("---------------------------------------------"); System.out.println("---------------------------------------------");
System.out.println("--- REMOVED RESOURCE ------------------------"); System.out.println("--- REMOVED RESOURCE ------------------------");
System.out.println("---------------------------------------------"); System.out.println("---------------------------------------------");
System.out.println("String at: "+oldRes); System.out.println("String at: " + oldRes);
if (allOldResources.size() > 1) { if (allOldResources.size() > 1) {
System.out.println("And also at:"); System.out.println("And also at:");
for (String res : allOldResources) { for (String res : allOldResources) {
if (!res.equals(oldRes)) { if (!res.equals(oldRes)) {
System.out.println("- "+res); System.out.println("- " + res);
} }
} }
} }
System.out.println("Was: \""+oldString+"\""); System.out.println("Was: \"" + oldString + "\"");
if (allNewResources == null) { if (allNewResources == null) {
System.out.println("Absent from new."); System.out.println("Absent from new.");
} else { } else {
System.out.println("Still present at: "); System.out.println("Still present at: ");
for (String res : allNewResources) { for (String res : allNewResources) {
System.out.println("- "+res); System.out.println("- " + res);
} }
} }
} }
} }
} }
removedStrings: for (String oldString : stringsResourcesOld.keySet()) { removedStrings:
for (String oldString : stringsResourcesOld.keySet()) {
if (stringsResourcesNew.get(oldString) == null) { if (stringsResourcesNew.get(oldString) == null) {
List<String> allOldResources = stringsResourcesOld.get(oldString); List<String> allOldResources = stringsResourcesOld.get(oldString);
if (allOldResources.size() >= 1) { if (allOldResources.size() >= 1) {
@@ -171,11 +165,11 @@ public class PotComparator {
System.out.println("---------------------------------------------"); System.out.println("---------------------------------------------");
System.out.println("--- REMOVED STRING --------------------------"); System.out.println("--- REMOVED STRING --------------------------");
System.out.println("---------------------------------------------"); System.out.println("---------------------------------------------");
System.out.println("String: \""+oldString+"\""); System.out.println("String: \"" + oldString + "\"");
if (allOldResources.size() > 0) { if (allOldResources.size() > 0) {
System.out.println("Was at:"); System.out.println("Was at:");
for (String res : allOldResources) { for (String res : allOldResources) {
System.out.println("- "+res); System.out.println("- " + res);
} }
} }
System.out.println("This string is absent from the new file, and its attached resources are missing too."); System.out.println("This string is absent from the new file, and its attached resources are missing too.");
@@ -189,7 +183,7 @@ public class PotComparator {
String review = "Review"; String review = "Review";
String outdated = "Outdated"; String outdated = "Outdated";
String none = "None"; String none = "None";
Object[] options = new Object[] {typo, review, outdated, none}; Object[] options = new Object[]{typo, review, outdated, none};
int result = JOptionPane.showOptionDialog(null, checkReport, "Choose action", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, typo); int result = JOptionPane.showOptionDialog(null, checkReport, "Choose action", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, typo);
@@ -198,7 +192,7 @@ public class PotComparator {
return; return;
} }
System.out.println("Decision: "+options[result]); System.out.println("Decision: " + options[result]);
if (options[result] != none) { if (options[result] != none) {
msgIdToReplace.put(oldMsg, newMsg); msgIdToReplace.put(oldMsg, newMsg);
@@ -213,7 +207,7 @@ public class PotComparator {
public void updatePoFiles(Project proj) { public void updatePoFiles(Project proj) {
File poFolder = new File(proj.baseContent.baseFolder.getAbsolutePath()+File.separator+"assets"+File.separator+"translation"); File poFolder = new File(proj.baseContent.baseFolder.getAbsolutePath() + File.separator + "assets" + File.separator + "translation");
File[] poFiles = poFolder.listFiles(new FileFilter() { File[] poFiles = poFolder.listFiles(new FileFilter() {
@Override @Override
public boolean accept(File arg0) { public boolean accept(File arg0) {
@@ -261,7 +255,7 @@ public class PotComparator {
} }
if (msgid.contains("\\n")) { if (msgid.contains("\\n")) {
msgid = msgid.replaceAll("\\\\n", "\\\\n\"\n\""); msgid = msgid.replaceAll("\\\\n", "\\\\n\"\n\"");
msgid = "\"\n\""+msgid; msgid = "\"\n\"" + msgid;
} }
String translation = ""; String translation = "";
if (!msgstrs.isEmpty()) { if (!msgstrs.isEmpty()) {
@@ -274,7 +268,7 @@ public class PotComparator {
} }
if (translation.contains("\\n")) { if (translation.contains("\\n")) {
translation = translation.replaceAll("\\\\n", "\\\\n\"\n\""); translation = translation.replaceAll("\\\\n", "\\\\n\"\n\"");
translation = "\"\n\""+translation; translation = "\"\n\"" + translation;
} }
} }
translations.put(msgid, translation); translations.put(msgid, translation);
@@ -293,18 +287,18 @@ public class PotComparator {
for (String msgid : msgIdToReview) { for (String msgid : msgIdToReview) {
if (translations.containsKey(msgid)) { if (translations.containsKey(msgid)) {
String trans = translations.get(msgid); String trans = translations.get(msgid);
if (trans != null && trans.length() >= 1) translations.put(msgid, "[REVIEW]"+trans); if (trans != null && trans.length() >= 1) translations.put(msgid, "[REVIEW]" + trans);
} }
} }
for (String msgid : msgIdOutdated) { for (String msgid : msgIdOutdated) {
if (translations.containsKey(msgid)) { if (translations.containsKey(msgid)) {
String trans = translations.get(msgid); String trans = translations.get(msgid);
if (trans != null && trans.length() >= 1) translations.put(msgid, "[OUTDATED]"+trans); if (trans != null && trans.length() >= 1) translations.put(msgid, "[OUTDATED]" + trans);
} }
} }
PoPotWriter.writePoFile(stringsResourcesNew, translations, new File(proj.alteredContent.baseFolder.getAbsolutePath()+File.separator+f.getName())); PoPotWriter.writePoFile(stringsResourcesNew, translations, new File(proj.alteredContent.baseFolder.getAbsolutePath() + File.separator + f.getName()));
} }
} }

View File

@@ -1,23 +1,16 @@
package com.gpl.rpg.atcontentstudio.model.tools.i18n; package com.gpl.rpg.atcontentstudio.model.tools.i18n;
import com.gpl.rpg.atcontentstudio.model.GameSource;
import com.gpl.rpg.atcontentstudio.model.Project;
import com.gpl.rpg.atcontentstudio.model.gamedata.*;
import com.gpl.rpg.atcontentstudio.model.maps.WorldmapSegment;
import java.io.File; import java.io.File;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import com.gpl.rpg.atcontentstudio.model.GameSource;
import com.gpl.rpg.atcontentstudio.model.Project;
import com.gpl.rpg.atcontentstudio.model.gamedata.ActorCondition;
import com.gpl.rpg.atcontentstudio.model.gamedata.Dialogue;
import com.gpl.rpg.atcontentstudio.model.gamedata.Item;
import com.gpl.rpg.atcontentstudio.model.gamedata.ItemCategory;
import com.gpl.rpg.atcontentstudio.model.gamedata.JSONElement;
import com.gpl.rpg.atcontentstudio.model.gamedata.NPC;
import com.gpl.rpg.atcontentstudio.model.gamedata.Quest;
import com.gpl.rpg.atcontentstudio.model.gamedata.QuestStage;
import com.gpl.rpg.atcontentstudio.model.maps.WorldmapSegment;
public class PotGenerator { public class PotGenerator {
public static void generatePotFileForProject(Project proj) { public static void generatePotFileForProject(Project proj) {
@@ -28,14 +21,15 @@ public class PotGenerator {
for (ActorCondition ac : gsrc.gameData.actorConditions) { for (ActorCondition ac : gsrc.gameData.actorConditions) {
pushString(stringsResources, resourcesStrings, ac.display_name, getPotContextComment(ac)); pushString(stringsResources, resourcesStrings, ac.display_name, getPotContextComment(ac));
pushString(stringsResources, resourcesStrings, ac.description, getPotContextComment(ac) + ":description");
} }
for (Dialogue d : gsrc.gameData.dialogues ) { for (Dialogue d : gsrc.gameData.dialogues) {
pushString(stringsResources, resourcesStrings, d.message, getPotContextComment(d)); pushString(stringsResources, resourcesStrings, d.message, getPotContextComment(d));
if (d.replies == null) continue; if (d.replies == null) continue;
for (Dialogue.Reply r : d.replies) { for (Dialogue.Reply r : d.replies) {
if (r.text != null && !r.text.equals(Dialogue.Reply.GO_NEXT_TEXT) ) { if (r.text != null && !r.text.equals(Dialogue.Reply.GO_NEXT_TEXT)) {
pushString(stringsResources, resourcesStrings, r.text, getPotContextComment(d)+":"+d.replies.indexOf(r)); pushString(stringsResources, resourcesStrings, r.text, getPotContextComment(d) + ":" + d.replies.indexOf(r));
} }
} }
} }
@@ -46,10 +40,10 @@ public class PotGenerator {
for (Item i : gsrc.gameData.items) { for (Item i : gsrc.gameData.items) {
pushString(stringsResources, resourcesStrings, i.name, getPotContextComment(i)); pushString(stringsResources, resourcesStrings, i.name, getPotContextComment(i));
pushString(stringsResources, resourcesStrings, i.description, getPotContextComment(i)+":description"); pushString(stringsResources, resourcesStrings, i.description, getPotContextComment(i) + ":description");
} }
for (NPC npc : gsrc.gameData.npcs ) { for (NPC npc : gsrc.gameData.npcs) {
pushString(stringsResources, resourcesStrings, npc.name, getPotContextComment(npc)); pushString(stringsResources, resourcesStrings, npc.name, getPotContextComment(npc));
} }
@@ -57,14 +51,14 @@ public class PotGenerator {
if (q.visible_in_log != null && q.visible_in_log != 0) { if (q.visible_in_log != null && q.visible_in_log != 0) {
pushString(stringsResources, resourcesStrings, q.name, getPotContextComment(q)); pushString(stringsResources, resourcesStrings, q.name, getPotContextComment(q));
for (QuestStage qs : q.stages) { for (QuestStage qs : q.stages) {
pushString(stringsResources, resourcesStrings, qs.log_text, getPotContextComment(q)+":"+Integer.toString(qs.progress)); pushString(stringsResources, resourcesStrings, qs.log_text, getPotContextComment(q) + ":" + Integer.toString(qs.progress));
} }
} }
} }
for (WorldmapSegment ws : gsrc.worldmap) { for (WorldmapSegment ws : gsrc.worldmap) {
for (WorldmapSegment.NamedArea area : ws.labels.values()) { for (WorldmapSegment.NamedArea area : ws.labels.values()) {
pushString(stringsResources, resourcesStrings, area.name, gsrc.worldmap.worldmapFile.getName()+":"+ws.id+":"+area.id); pushString(stringsResources, resourcesStrings, area.name, gsrc.worldmap.worldmapFile.getName() + ":" + ws.id + ":" + area.id);
} }
} }
@@ -73,7 +67,7 @@ public class PotGenerator {
} }
private static void pushString (Map<String, List<String>> stringsResources, Map<String, String> resourcesStrings, String translatableString, String resourceIdentifier) { private static void pushString(Map<String, List<String>> stringsResources, Map<String, String> resourcesStrings, String translatableString, String resourceIdentifier) {
if (translatableString == null) return; if (translatableString == null) return;
if (translatableString.length() == 0) return; if (translatableString.length() == 0) return;
if (translatableString.contains("\"")) { if (translatableString.contains("\"")) {
@@ -81,7 +75,7 @@ public class PotGenerator {
} }
if (translatableString.contains("\n")) { if (translatableString.contains("\n")) {
translatableString = translatableString.replaceAll("\n", "\\\\n\"\n\""); translatableString = translatableString.replaceAll("\n", "\\\\n\"\n\"");
translatableString = "\"\n\""+translatableString; translatableString = "\"\n\"" + translatableString;
} }
resourcesStrings.put(resourceIdentifier, translatableString); resourcesStrings.put(resourceIdentifier, translatableString);
List<String> resourceIdentifiers = stringsResources.get(translatableString); List<String> resourceIdentifiers = stringsResources.get(translatableString);
@@ -93,7 +87,7 @@ public class PotGenerator {
} }
private static String getPotContextComment(JSONElement e) { private static String getPotContextComment(JSONElement e) {
return e.jsonFile.getName()+":"+e.id; return e.jsonFile.getName() + ":" + e.id;
} }

View File

@@ -1,30 +1,7 @@
package com.gpl.rpg.atcontentstudio.model.tools.resoptimizer; package com.gpl.rpg.atcontentstudio.model.tools.resoptimizer;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.CharBuffer;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.imageio.ImageIO;
import org.json.simple.JSONArray;
import com.gpl.rpg.atcontentstudio.io.JsonPrettyWriter; import com.gpl.rpg.atcontentstudio.io.JsonPrettyWriter;
import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.GameDataElement;
import com.gpl.rpg.atcontentstudio.model.GameSource;
import com.gpl.rpg.atcontentstudio.model.Project; import com.gpl.rpg.atcontentstudio.model.Project;
import com.gpl.rpg.atcontentstudio.model.gamedata.ActorCondition; import com.gpl.rpg.atcontentstudio.model.gamedata.ActorCondition;
import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet; import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet;
@@ -38,27 +15,34 @@ import com.whoischarles.util.json.Minify;
import com.whoischarles.util.json.Minify.UnterminatedCommentException; import com.whoischarles.util.json.Minify.UnterminatedCommentException;
import com.whoischarles.util.json.Minify.UnterminatedRegExpLiteralException; import com.whoischarles.util.json.Minify.UnterminatedRegExpLiteralException;
import com.whoischarles.util.json.Minify.UnterminatedStringLiteralException; import com.whoischarles.util.json.Minify.UnterminatedStringLiteralException;
import org.json.simple.JSONArray;
import tiled.core.TileSet; import tiled.core.TileSet;
import tiled.io.TMXMapWriter; import tiled.io.TMXMapWriter;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.List;
import java.util.*;
/** /**
*
* @author Kevin * @author Kevin
* * <p>
* To use this, paste the following script in the beanshell console of ATCS. * To use this, paste the following script in the beanshell console of ATCS.
* Don't forget to change the project number to suit your needs. * Don't forget to change the project number to suit your needs.
* <p>
* <code>
* import com.gpl.rpg.atcontentstudio.model.tools.resoptimizer.ResourcesCompactor;
* import com.gpl.rpg.atcontentstudio.model.Workspace;
* *
import com.gpl.rpg.atcontentstudio.model.tools.resoptimizer.ResourcesCompactor; * proj = Workspace.activeWorkspace.projects.get(0);
import com.gpl.rpg.atcontentstudio.model.Workspace; * new ResourcesCompactor(proj).compactData();
* </code>
proj = Workspace.activeWorkspace.projects.get(0);
new ResourcesCompactor(proj).compactData();
*
*/ */
public class ResourcesCompactor { public class ResourcesCompactor {
public static String DEFAULT_REL_PATH_IN_PROJECT = "compressed"+File.separator; public static String DEFAULT_REL_PATH_IN_PROJECT = "compressed" + File.separator;
private Project proj; private Project proj;
private File baseFolder; private File baseFolder;
@@ -82,11 +66,11 @@ public class ResourcesCompactor {
public void compactData() { public void compactData() {
compactJsonData(); compactJsonData();
for(CompressedSpritesheet cs : compressedSpritesheets) { for (CompressedSpritesheet cs : compressedSpritesheets) {
cs.drawFile(); cs.drawFile();
} }
for (File preserved : preservedSpritesheets) { for (File preserved : preservedSpritesheets) {
FileUtils.copyFile(preserved, new File(baseFolder.getAbsolutePath()+File.separator+DEFAULT_DRAWABLE_REL_PATH+File.separator+preserved.getName())); FileUtils.copyFile(preserved, new File(baseFolder.getAbsolutePath() + File.separator + DEFAULT_DRAWABLE_REL_PATH + File.separator + preserved.getName()));
} }
compactMaps(); compactMaps();
} }
@@ -94,7 +78,7 @@ public class ResourcesCompactor {
public void compactJsonData() { public void compactJsonData() {
final List<File> filesCovered = new LinkedList<File>(); final List<File> filesCovered = new LinkedList<File>();
File folder = new File(baseFolder.getAbsolutePath()+File.separator+GameDataSet.DEFAULT_REL_PATH_IN_SOURCE); File folder = new File(baseFolder.getAbsolutePath() + File.separator + GameDataSet.DEFAULT_REL_PATH_IN_SOURCE);
if (!folder.exists()) folder.mkdirs(); if (!folder.exists()) folder.mkdirs();
for (ActorCondition ac : proj.baseContent.gameData.actorConditions) { for (ActorCondition ac : proj.baseContent.gameData.actorConditions) {
@@ -161,16 +145,12 @@ public class ResourcesCompactor {
private Minify jsonMinifier = new Minify(); private Minify jsonMinifier = new Minify();
private void writeJson(List<Map> dataToSave, File target) { private void writeJson(List<Map> dataToSave, File target) {
StringWriter writer = new JsonPrettyWriter(); String toWrite = FileUtils.toJsonString(dataToSave);
try { toWrite = jsonMinifier.minify(toWrite);
JSONArray.writeJSONString(dataToSave, writer); FileUtils.writeStringToFile(toWrite, target, null);
} catch (IOException e) {
//Impossible with a StringWriter
}
String toWrite = writer.toString();
try { try {
FileWriter w = new FileWriter(target); FileWriter w = new FileWriter(target);
w.write(jsonMinifier.minify(toWrite)); w.write(toWrite);
w.close(); w.close();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
@@ -195,6 +175,7 @@ public class ResourcesCompactor {
e.printStackTrace(); e.printStackTrace();
} }
} }
private void compactMaps() { private void compactMaps() {
for (TMXMap map : proj.baseContent.gameMaps.tmxMaps) { for (TMXMap map : proj.baseContent.gameMaps.tmxMaps) {
TMXMap clone = map.clone(); TMXMap clone = map.clone();
@@ -206,12 +187,11 @@ public class ResourcesCompactor {
compactMap(tmx, map.id); compactMap(tmx, map.id);
clone.tmxMap = null; clone.tmxMap = null;
clone.groups.clear(); clone.groups.clear();
clone = null;
} }
} }
private void compactMap(tiled.core.Map tmx, String name) { private void compactMap(tiled.core.Map tmx, String name) {
File target = new File(baseFolder.getAbsolutePath()+File.separator+TMXMapSet.DEFAULT_REL_PATH_IN_SOURCE+File.separator+name+".tmx"); File target = new File(baseFolder.getAbsolutePath() + File.separator + TMXMapSet.DEFAULT_REL_PATH_IN_SOURCE + File.separator + name + ".tmx");
if (!target.getParentFile().exists()) target.getParentFile().mkdirs(); if (!target.getParentFile().exists()) target.getParentFile().mkdirs();
Map<tiled.core.Tile, SpritesheetId> localConvertions = new LinkedHashMap<tiled.core.Tile, SpritesheetId>(); Map<tiled.core.Tile, SpritesheetId> localConvertions = new LinkedHashMap<tiled.core.Tile, SpritesheetId>();
@@ -251,7 +231,7 @@ public class ResourcesCompactor {
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
ts.setName(cs.prefix+Integer.toString(cs.index)); ts.setName(cs.prefix + Integer.toString(cs.index));
//ts.setSource("../drawable/"+ts.getName()+TILESHEET_SUFFIX); //ts.setSource("../drawable/"+ts.getName()+TILESHEET_SUFFIX);
tmx.addTileset(ts); tmx.addTileset(ts);
} }
@@ -334,9 +314,9 @@ public class ResourcesCompactor {
this.prefix = prefix; this.prefix = prefix;
this.index = index; this.index = index;
File folder = new File(ResourcesCompactor.this.baseFolder.getAbsolutePath()+File.separator+DEFAULT_DRAWABLE_REL_PATH); File folder = new File(ResourcesCompactor.this.baseFolder.getAbsolutePath() + File.separator + DEFAULT_DRAWABLE_REL_PATH);
if (!folder.exists()) folder.mkdirs(); if (!folder.exists()) folder.mkdirs();
this.f = new File(folder, prefix+Integer.toString(index)+TILESHEET_SUFFIX); this.f = new File(folder, prefix + Integer.toString(index) + TILESHEET_SUFFIX);
} }
public boolean hasFreeSlot() { public boolean hasFreeSlot() {
@@ -347,14 +327,14 @@ public class ResourcesCompactor {
mustDraw = true; mustDraw = true;
originalSpritesId[nextFreeSlot] = spriteId; originalSpritesId[nextFreeSlot] = spriteId;
nextFreeSlot++; nextFreeSlot++;
return SpritesheetId.getInstance(prefix+Integer.toString(index), nextFreeSlot - 1); return SpritesheetId.getInstance(prefix + Integer.toString(index), nextFreeSlot - 1);
} }
public void drawFile() { public void drawFile() {
if (!mustDraw) return; if (!mustDraw) return;
BufferedImage img = new BufferedImage(TILESHEET_WIDTH_IN_SPRITES * TILE_WIDTH_IN_PIXELS, TILESHEET_HEIGHT_IN_SPRITES * TILE_HEIGHT_IN_PIXELS, BufferedImage.TYPE_INT_ARGB); BufferedImage img = new BufferedImage(TILESHEET_WIDTH_IN_SPRITES * TILE_WIDTH_IN_PIXELS, TILESHEET_HEIGHT_IN_SPRITES * TILE_HEIGHT_IN_PIXELS, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = (Graphics2D)img.getGraphics(); Graphics2D g = (Graphics2D) img.getGraphics();
Color transparent = new Color(0, 0, 0, 0); Color transparent = new Color(0, 0, 0, 0);
g.setColor(transparent); g.setColor(transparent);
g.fillRect(0, 0, img.getWidth(), img.getHeight()); g.fillRect(0, 0, img.getWidth(), img.getHeight());

View File

@@ -32,7 +32,7 @@ public class SpritesheetId {
} }
static String toStringID(String tileset, int offset) { static String toStringID(String tileset, int offset) {
return tileset+":"+Integer.toString(offset); return tileset + ":" + Integer.toString(offset);
} }
} }

View File

@@ -1,6 +1,17 @@
package com.gpl.rpg.atcontentstudio.model.tools.writermode; package com.gpl.rpg.atcontentstudio.model.tools.writermode;
import java.awt.Image; import com.gpl.rpg.atcontentstudio.Notification;
import com.gpl.rpg.atcontentstudio.model.GameDataElement;
import com.gpl.rpg.atcontentstudio.model.Project;
import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode;
import com.gpl.rpg.atcontentstudio.model.SaveEvent;
import com.gpl.rpg.atcontentstudio.model.gamedata.Dialogue;
import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet;
import com.gpl.rpg.atcontentstudio.ui.DefaultIcons;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.awt.*;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.FileReader; import java.io.FileReader;
@@ -12,18 +23,6 @@ import java.util.Map;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import com.gpl.rpg.atcontentstudio.Notification;
import com.gpl.rpg.atcontentstudio.model.GameDataElement;
import com.gpl.rpg.atcontentstudio.model.Project;
import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode;
import com.gpl.rpg.atcontentstudio.model.SaveEvent;
import com.gpl.rpg.atcontentstudio.model.gamedata.Dialogue;
import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet;
import com.gpl.rpg.atcontentstudio.ui.DefaultIcons;
public class WriterModeData extends GameDataElement { public class WriterModeData extends GameDataElement {
private static final long serialVersionUID = -7062544089063979696L; private static final long serialVersionUID = -7062544089063979696L;
@@ -42,7 +41,7 @@ public class WriterModeData extends GameDataElement {
public Map<String, Integer> threadsNextIndex = new LinkedHashMap<String, Integer>(); public Map<String, Integer> threadsNextIndex = new LinkedHashMap<String, Integer>();
public WriterModeData(String id_prefix){ public WriterModeData(String id_prefix) {
this.id = id_prefix; this.id = id_prefix;
} }
@@ -63,7 +62,7 @@ public class WriterModeData extends GameDataElement {
public int getNextIndex(String id_prefix) { public int getNextIndex(String id_prefix) {
Integer index = threadsNextIndex.get(id_prefix); Integer index = threadsNextIndex.get(id_prefix);
if (index == null) index = 0; if (index == null) index = 0;
while (getProject().getDialogue(id_prefix+index) != null) { while (getProject().getDialogue(id_prefix + index) != null) {
index++; index++;
} }
threadsNextIndex.put(id_prefix, index + 1); threadsNextIndex.put(id_prefix, index + 1);
@@ -95,7 +94,8 @@ public class WriterModeData extends GameDataElement {
public String dialogue_id; public String dialogue_id;
public Dialogue dialogue; public Dialogue dialogue;
public WriterDialogue() {} public WriterDialogue() {
}
public WriterDialogue(Dialogue dialogue) { public WriterDialogue(Dialogue dialogue) {
this.dialogue = dialogue; this.dialogue = dialogue;
@@ -107,7 +107,7 @@ public class WriterModeData extends GameDataElement {
this.id_prefix = m.group(1); this.id_prefix = m.group(1);
this.index = Integer.parseInt(m.group(2)); this.index = Integer.parseInt(m.group(2));
} else { } else {
this.id_prefix = this.id+"_"; this.id_prefix = this.id + "_";
} }
nodesById.put(this.id, this); nodesById.put(this.id, this);
if (dialogue.replies != null) { if (dialogue.replies != null) {
@@ -129,14 +129,14 @@ public class WriterModeData extends GameDataElement {
@Override @Override
public String getTitle() { public String getTitle() {
return "Dialogue "+getID(); return "Dialogue " + getID();
} }
public String getID() { public String getID() {
return this.id != null ? this.id : this.id_prefix+this.index; return this.id != null ? this.id : this.id_prefix + this.index;
} }
@SuppressWarnings({ "rawtypes", "unchecked" }) @SuppressWarnings({"rawtypes", "unchecked"})
public void toJson(List<WriterDialogue> visited, List<Map> jsonData) { public void toJson(List<WriterDialogue> visited, List<Map> jsonData) {
if (visited.contains(this)) return; if (visited.contains(this)) return;
visited.add(this); visited.add(this);
@@ -165,28 +165,30 @@ public class WriterModeData extends GameDataElement {
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
public WriterDialogue(Map json) { public WriterDialogue(Map json) {
this.id = (String) json.get("id"); this.id = (String) json.get("id");
this.index = ((Number)json.get("index")).intValue(); this.index = ((Number) json.get("index")).intValue();
this.id_prefix = (String) json.get("id_prefix"); this.id_prefix = (String) json.get("id_prefix");
if (threadsNextIndex.get(id_prefix) == null || threadsNextIndex.get(id_prefix) <= index) { if (threadsNextIndex.get(id_prefix) == null || threadsNextIndex.get(id_prefix) <= index) {
threadsNextIndex.put(id_prefix, index+1); threadsNextIndex.put(id_prefix, index + 1);
} }
this.text = (String) json.get("text"); this.text = (String) json.get("text");
this.dialogue_id = (String) json.get("dialogue"); this.dialogue_id = (String) json.get("dialogue");
if (json.get("begin") != null && ((Boolean)json.get("begin"))) begin = this; if (json.get("begin") != null && ((Boolean) json.get("begin"))) begin = this;
if (json.get("replies") != null) { if (json.get("replies") != null) {
List repliesJson = (List) json.get("replies"); List repliesJson = (List) json.get("replies");
for (Object rJson : repliesJson) { for (Object rJson : repliesJson) {
if (((Map)rJson).get("special") != null && (Boolean)((Map)rJson).get("special")) { if (((Map) rJson).get("special") != null && (Boolean) ((Map) rJson).get("special")) {
//TODO Check different cases. But there are none currently. //TODO Check different cases. But there are none currently.
this.replies.add(new EmptyReply(this, ((Map)rJson))); this.replies.add(new EmptyReply(this, ((Map) rJson)));
} else { } else {
this.replies.add(new WriterReply(this, (Map)rJson)); this.replies.add(new WriterReply(this, (Map) rJson));
} }
} }
} }
} }
public boolean isSpecial() {return false;} public boolean isSpecial() {
return false;
}
public Dialogue toDialogue(Map<WriterDialogue, Dialogue> visited, List<Dialogue> created, List<Dialogue> modified) { public Dialogue toDialogue(Map<WriterDialogue, Dialogue> visited, List<Dialogue> created, List<Dialogue> modified) {
@@ -241,7 +243,7 @@ public class WriterModeData extends GameDataElement {
public boolean hasChanged() { public boolean hasChanged() {
return dialogue == null || return dialogue == null ||
text == null ? dialogue.message!=null : !text.equals(dialogue.message) || text == null ? dialogue.message != null : !text.equals(dialogue.message) ||
repliesHaveChanged(); repliesHaveChanged();
} }
@@ -260,35 +262,63 @@ public class WriterModeData extends GameDataElement {
public abstract class SpecialDialogue extends WriterDialogue { public abstract class SpecialDialogue extends WriterDialogue {
public SpecialDialogue() {} public SpecialDialogue() {
public boolean isSpecial() {return true;} }
public boolean isSpecial() {
return true;
}
public abstract SpecialDialogue duplicate(); public abstract SpecialDialogue duplicate();
public SpecialDialogue(Dialogue dialogue) { public SpecialDialogue(Dialogue dialogue) {
super(dialogue); super(dialogue);
} }
} }
public class SelectorDialogue extends SpecialDialogue { public class SelectorDialogue extends SpecialDialogue {
public SelectorDialogue() {} public SelectorDialogue() {
public SpecialDialogue duplicate() {return new SelectorDialogue();} }
public SpecialDialogue duplicate() {
return new SelectorDialogue();
}
public SelectorDialogue(Dialogue dialogue) { public SelectorDialogue(Dialogue dialogue) {
super(dialogue); super(dialogue);
} }
} }
public class ShopDialogue extends SpecialDialogue { public class ShopDialogue extends SpecialDialogue {
public static final String id = Dialogue.Reply.SHOP_PHRASE_ID; public static final String id = Dialogue.Reply.SHOP_PHRASE_ID;
public SpecialDialogue duplicate() {return new ShopDialogue();}
public SpecialDialogue duplicate() {
return new ShopDialogue();
} }
}
public class FightDialogue extends SpecialDialogue { public class FightDialogue extends SpecialDialogue {
public static final String id = Dialogue.Reply.FIGHT_PHRASE_ID; public static final String id = Dialogue.Reply.FIGHT_PHRASE_ID;
public SpecialDialogue duplicate() {return new FightDialogue();}
public SpecialDialogue duplicate() {
return new FightDialogue();
} }
}
public class EndDialogue extends SpecialDialogue { public class EndDialogue extends SpecialDialogue {
public static final String id = Dialogue.Reply.EXIT_PHRASE_ID; public static final String id = Dialogue.Reply.EXIT_PHRASE_ID;
public SpecialDialogue duplicate() {return new EndDialogue();}
public SpecialDialogue duplicate() {
return new EndDialogue();
} }
}
public class RemoveNPCDialogue extends SpecialDialogue { public class RemoveNPCDialogue extends SpecialDialogue {
public static final String id = Dialogue.Reply.REMOVE_PHRASE_ID; public static final String id = Dialogue.Reply.REMOVE_PHRASE_ID;
public SpecialDialogue duplicate() {return new RemoveNPCDialogue();}
public SpecialDialogue duplicate() {
return new RemoveNPCDialogue();
}
} }
public class WriterReply extends WriterNode { public class WriterReply extends WriterNode {
@@ -297,7 +327,8 @@ public class WriterModeData extends GameDataElement {
public WriterDialogue next_dialogue; public WriterDialogue next_dialogue;
public Dialogue.Reply reply; public Dialogue.Reply reply;
public WriterReply() {} public WriterReply() {
}
public WriterReply(WriterDialogue parent) { public WriterReply(WriterDialogue parent) {
this.parent = parent; this.parent = parent;
@@ -312,7 +343,7 @@ public class WriterModeData extends GameDataElement {
this.next_dialogue_id = reply.next_phrase_id; this.next_dialogue_id = reply.next_phrase_id;
if (nodesById.get(this.next_dialogue_id) != null) { if (nodesById.get(this.next_dialogue_id) != null) {
this.next_dialogue = nodesById.get(this.next_dialogue_id); this.next_dialogue = nodesById.get(this.next_dialogue_id);
} else if (reply.next_phrase != null ){ } else if (reply.next_phrase != null) {
this.next_dialogue = new WriterDialogue(reply.next_phrase); this.next_dialogue = new WriterDialogue(reply.next_phrase);
} }
} }
@@ -328,10 +359,10 @@ public class WriterModeData extends GameDataElement {
@Override @Override
public String getTitle() { public String getTitle() {
return "Reply in "+parent.id_prefix+parent.index; return "Reply in " + parent.id_prefix + parent.index;
} }
@SuppressWarnings({ "rawtypes", "unchecked" }) @SuppressWarnings({"rawtypes", "unchecked"})
public Map toJson(List<WriterDialogue> visited, List<Map> jsonData) { public Map toJson(List<WriterDialogue> visited, List<Map> jsonData) {
Map replyJson = new LinkedHashMap(); Map replyJson = new LinkedHashMap();
replyJson.put("text", text); replyJson.put("text", text);
@@ -343,7 +374,9 @@ public class WriterModeData extends GameDataElement {
return replyJson; return replyJson;
} }
public boolean isSpecial() {return false;} public boolean isSpecial() {
return false;
}
public Dialogue.Reply toReply(Map<WriterDialogue, Dialogue> visited, List<Dialogue> created, List<Dialogue> modified) { public Dialogue.Reply toReply(Map<WriterDialogue, Dialogue> visited, List<Dialogue> created, List<Dialogue> modified) {
if (reply == null) { if (reply == null) {
@@ -375,12 +408,13 @@ public class WriterModeData extends GameDataElement {
} }
} }
public class SpecialReply extends WriterReply { public class SpecialReply extends WriterReply {
public boolean isSpecial() {return true;} public boolean isSpecial() {
return true;
}
public SpecialReply(WriterDialogue parent, Dialogue.Reply reply) { public SpecialReply(WriterDialogue parent, Dialogue.Reply reply) {
super(parent, reply); super(parent, reply);
@@ -394,6 +428,7 @@ public class WriterModeData extends GameDataElement {
super(parent, json); super(parent, json);
} }
} }
public class EmptyReply extends SpecialReply { public class EmptyReply extends SpecialReply {
public EmptyReply(WriterDialogue parent, Dialogue.Reply reply) { public EmptyReply(WriterDialogue parent, Dialogue.Reply reply) {
@@ -413,11 +448,11 @@ public class WriterModeData extends GameDataElement {
} }
@Override @Override
public String getDesc() { public String getDesc() {
return (needsSaving() ? "*" : "")+id; return (needsSaving() ? "*" : "") + id;
} }
@Override @Override
public Project getProject() { public Project getProject() {
return parent.getProject(); return parent.getProject();
@@ -427,18 +462,22 @@ public class WriterModeData extends GameDataElement {
public Image getIcon() { public Image getIcon() {
return DefaultIcons.getDialogueIcon(); return DefaultIcons.getDialogueIcon();
} }
@Override @Override
public Image getOpenIcon() { public Image getOpenIcon() {
return null; return null;
} }
@Override @Override
public Image getClosedIcon() { public Image getClosedIcon() {
return null; return null;
} }
@Override @Override
public Image getLeafIcon() { public Image getLeafIcon() {
return getIcon(); return getIcon();
} }
@Override @Override
public GameDataSet getDataSet() { public GameDataSet getDataSet() {
return null; return null;
@@ -449,11 +488,13 @@ public class WriterModeData extends GameDataElement {
//TODO //TODO
return null; return null;
} }
@Override @Override
public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { public void elementChanged(GameDataElement oldOne, GameDataElement newOne) {
// Useless here. // Useless here.
} }
@Override @Override
public String getProjectFilename() { public String getProjectFilename() {
return WriterModeDataSet.DEFAULT_REL_PATH_IN_PROJECT; return WriterModeDataSet.DEFAULT_REL_PATH_IN_PROJECT;
@@ -461,12 +502,12 @@ public class WriterModeData extends GameDataElement {
@Override @Override
public void save() { public void save() {
((WriterModeDataSet)this.getParent()).save(this.jsonFile); ((WriterModeDataSet) this.getParent()).save(this.jsonFile);
} }
@Override @Override
public List<SaveEvent> attemptSave() { public List<SaveEvent> attemptSave() {
List<SaveEvent> events = ((WriterModeDataSet)parent).attemptSave(); List<SaveEvent> events = ((WriterModeDataSet) parent).attemptSave();
if (events == null || events.isEmpty()) { if (events == null || events.isEmpty()) {
return null; return null;
} }
@@ -477,7 +518,7 @@ public class WriterModeData extends GameDataElement {
return events; return events;
} }
@SuppressWarnings({ "rawtypes", "unchecked" }) @SuppressWarnings({"rawtypes", "unchecked"})
public Map toJson() { public Map toJson() {
List<Map> jsonData = new ArrayList<Map>(); List<Map> jsonData = new ArrayList<Map>();
begin.toJson(new ArrayList<WriterModeData.WriterDialogue>(), jsonData); begin.toJson(new ArrayList<WriterModeData.WriterDialogue>(), jsonData);
@@ -489,32 +530,29 @@ public class WriterModeData extends GameDataElement {
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
public void parse() { public void parse() {
if (this.state == State.created || this.state == State.modified || this.state == State.saved) { if (shouldSkipParse()) return;
//This type of state is unrelated to parsing/linking.
return;
}
JSONParser parser = new JSONParser(); JSONParser parser = new JSONParser();
FileReader reader = null; FileReader reader = null;
try { try {
reader = new FileReader(jsonFile); reader = new FileReader(jsonFile);
List gameDataElements = (List) parser.parse(reader); List gameDataElements = (List) parser.parse(reader);
for (Object obj : gameDataElements) { for (Object obj : gameDataElements) {
Map jsonObj = (Map)obj; Map jsonObj = (Map) obj;
String id = (String) jsonObj.get("id"); String id = (String) jsonObj.get("id");
if (id != null && id.equals(this.id )) { if (id != null && id.equals(this.id)) {
this.parse(jsonObj); this.parse(jsonObj);
this.state = State.parsed; this.state = State.parsed;
break; break;
} }
} }
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
} catch (IOException e) { } catch (IOException e) {
Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
} catch (ParseException e) { } catch (ParseException e) {
Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
if (reader != null) if (reader != null)
@@ -540,7 +578,7 @@ public class WriterModeData extends GameDataElement {
List jsonDialogues = (List) json.get("dialogues"); List jsonDialogues = (List) json.get("dialogues");
if (jsonDialogues != null) { if (jsonDialogues != null) {
for (Object jsonDialogue : jsonDialogues) { for (Object jsonDialogue : jsonDialogues) {
WriterDialogue dialogue = new WriterDialogue((Map)jsonDialogue); WriterDialogue dialogue = new WriterDialogue((Map) jsonDialogue);
nodesById.put(dialogue.getID(), dialogue); nodesById.put(dialogue.getID(), dialogue);
} }
} }
@@ -562,8 +600,8 @@ public class WriterModeData extends GameDataElement {
} }
if (this.state == State.parsed) { if (this.state == State.parsed) {
for (String prefix : threadsNextIndex.keySet()) { for (String prefix : threadsNextIndex.keySet()) {
while (getProject().getDialogue(prefix+threadsNextIndex.get(prefix)) != null) { while (getProject().getDialogue(prefix + threadsNextIndex.get(prefix)) != null) {
threadsNextIndex.put(prefix, threadsNextIndex.get(prefix)+1); threadsNextIndex.put(prefix, threadsNextIndex.get(prefix) + 1);
} }
} }
for (WriterDialogue dialogue : nodesById.values()) { for (WriterDialogue dialogue : nodesById.values()) {
@@ -592,11 +630,13 @@ public class WriterModeData extends GameDataElement {
score = 0; score = 0;
//Arbitrary values... hopefully this gives good results. //Arbitrary values... hopefully this gives good results.
//Same target gives good hope of preserving at least the structure. //Same target gives good hope of preserving at least the structure.
if (dReply.next_phrase_id != null && dReply.next_phrase_id.equals(reply.next_dialogue_id)) score +=50; if (dReply.next_phrase_id != null && dReply.next_phrase_id.equals(reply.next_dialogue_id))
score += 50;
//Same text is almost as good as an ID, but there may be duplicates due to requirements system... //Same text is almost as good as an ID, but there may be duplicates due to requirements system...
if (dReply.text != null && dReply.text.equals(reply.text)) score +=40; if (dReply.text != null && dReply.text.equals(reply.text)) score += 40;
//Same slot in the list. That's not so bad if all else fails, and could help sort duplicates with same text. //Same slot in the list. That's not so bad if all else fails, and could help sort duplicates with same text.
if (dialogue.dialogue.replies.indexOf(dReply) == dialogue.replies.indexOf(reply)) score +=20; if (dialogue.dialogue.replies.indexOf(dReply) == dialogue.replies.indexOf(reply))
score += 20;
//Both have null text. It's not much, but it's something.... //Both have null text. It's not much, but it's something....
if (dReply.text == null && reply.text == null) score += 10; if (dReply.text == null && reply.text == null) score += 10;
if (score > maxScore) { if (score > maxScore) {
@@ -643,7 +683,7 @@ public class WriterModeData extends GameDataElement {
return null; return null;
} }
public List<Dialogue> toDialogue(){ public List<Dialogue> toDialogue() {
Map<WriterModeData.WriterDialogue, Dialogue> visited = new LinkedHashMap<WriterModeData.WriterDialogue, Dialogue>(); Map<WriterModeData.WriterDialogue, Dialogue> visited = new LinkedHashMap<WriterModeData.WriterDialogue, Dialogue>();
List<Dialogue> created = new ArrayList<Dialogue>(); List<Dialogue> created = new ArrayList<Dialogue>();
List<Dialogue> modified = new ArrayList<Dialogue>(); List<Dialogue> modified = new ArrayList<Dialogue>();

View File

@@ -1,35 +1,21 @@
package com.gpl.rpg.atcontentstudio.model.tools.writermode; package com.gpl.rpg.atcontentstudio.model.tools.writermode;
import java.awt.Image; import com.gpl.rpg.atcontentstudio.Notification;
import java.io.File; import com.gpl.rpg.atcontentstudio.io.JsonPrettyWriter;
import java.io.FileNotFoundException; import com.gpl.rpg.atcontentstudio.model.*;
import java.io.FileReader; import com.gpl.rpg.atcontentstudio.model.GameSource.Type;
import java.io.FileWriter; import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet;
import java.io.IOException; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons;
import java.io.Serializable; import com.gpl.rpg.atcontentstudio.utils.FileUtils;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import javax.swing.tree.TreeNode;
import org.json.simple.JSONArray; import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser; import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException; import org.json.simple.parser.ParseException;
import com.gpl.rpg.atcontentstudio.Notification; import javax.swing.tree.TreeNode;
import com.gpl.rpg.atcontentstudio.io.JsonPrettyWriter; import java.awt.*;
import com.gpl.rpg.atcontentstudio.model.GameDataElement; import java.io.*;
import com.gpl.rpg.atcontentstudio.model.GameSource; import java.util.List;
import com.gpl.rpg.atcontentstudio.model.GameSource.Type; import java.util.*;
import com.gpl.rpg.atcontentstudio.model.Project;
import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode;
import com.gpl.rpg.atcontentstudio.model.SaveEvent;
import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet;
import com.gpl.rpg.atcontentstudio.ui.DefaultIcons;
public class WriterModeDataSet implements ProjectTreeNode, Serializable { public class WriterModeDataSet implements ProjectTreeNode, Serializable {
@@ -86,19 +72,19 @@ public class WriterModeDataSet implements ProjectTreeNode, Serializable {
@Override @Override
public void childrenAdded(List<ProjectTreeNode> path) { public void childrenAdded(List<ProjectTreeNode> path) {
path.add(0,this); path.add(0, this);
parent.childrenAdded(path); parent.childrenAdded(path);
} }
@Override @Override
public void childrenChanged(List<ProjectTreeNode> path) { public void childrenChanged(List<ProjectTreeNode> path) {
path.add(0,this); path.add(0, this);
parent.childrenChanged(path); parent.childrenChanged(path);
} }
@Override @Override
public void childrenRemoved(List<ProjectTreeNode> path) { public void childrenRemoved(List<ProjectTreeNode> path) {
path.add(0,this); path.add(0, this);
parent.childrenRemoved(path); parent.childrenRemoved(path);
} }
@@ -109,7 +95,7 @@ public class WriterModeDataSet implements ProjectTreeNode, Serializable {
@Override @Override
public String getDesc() { public String getDesc() {
return (needsSaving() ? "*" : "")+"Dialogue sketches"; return (needsSaving() ? "*" : "") + "Dialogue sketches";
} }
@Override @Override
@@ -163,31 +149,19 @@ public class WriterModeDataSet implements ProjectTreeNode, Serializable {
} }
if (dataToSave.isEmpty() && writerFile.exists()) { if (dataToSave.isEmpty() && writerFile.exists()) {
if (writerFile.delete()) { if (writerFile.delete()) {
Notification.addSuccess("File "+writerFile.getAbsolutePath()+" deleted."); Notification.addSuccess("File " + writerFile.getAbsolutePath() + " deleted.");
} else { } else {
Notification.addError("Error deleting file "+writerFile.getAbsolutePath()); Notification.addError("Error deleting file " + writerFile.getAbsolutePath());
} }
return; return;
} }
StringWriter writer = new JsonPrettyWriter();
try { String toWrite = FileUtils.toJsonString(dataToSave);
JSONArray.writeJSONString(dataToSave, writer); if(FileUtils.writeStringToFile(toWrite, writerFile, "Json file " + writerFile.getAbsolutePath())) {
} catch (IOException e) {
//Impossible with a StringWriter
}
String toWrite = writer.toString();
try {
FileWriter w = new FileWriter(writerFile);
w.write(toWrite);
w.close();
for (WriterModeData element : writerModeDataList) { for (WriterModeData element : writerModeDataList) {
element.state = GameDataElement.State.saved; element.state = GameDataElement.State.saved;
} }
Notification.addSuccess("Json file "+writerFile.getAbsolutePath()+" saved.");
} catch (IOException e) {
Notification.addError("Error while writing json file "+writerFile.getAbsolutePath()+" : "+e.getMessage());
e.printStackTrace();
} }
} }
@@ -210,19 +184,19 @@ public class WriterModeDataSet implements ProjectTreeNode, Serializable {
reader = new FileReader(writerFile); reader = new FileReader(writerFile);
List writerDataListJson = (List) parser.parse(reader); List writerDataListJson = (List) parser.parse(reader);
for (Object obj : writerDataListJson) { for (Object obj : writerDataListJson) {
Map jsonObj = (Map)obj; Map jsonObj = (Map) obj;
WriterModeData data = new WriterModeData(this, jsonObj); WriterModeData data = new WriterModeData(this, jsonObj);
data.writable = true; data.writable = true;
writerModeDataList.add(data); writerModeDataList.add(data);
} }
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
Notification.addError("Error while parsing JSON file "+writerFile.getAbsolutePath()+": "+e.getMessage()); Notification.addError("Error while parsing JSON file " + writerFile.getAbsolutePath() + ": " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
} catch (IOException e) { } catch (IOException e) {
Notification.addError("Error while parsing JSON file "+writerFile.getAbsolutePath()+": "+e.getMessage()); Notification.addError("Error while parsing JSON file " + writerFile.getAbsolutePath() + ": " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
} catch (ParseException e) { } catch (ParseException e) {
Notification.addError("Error while parsing JSON file "+writerFile.getAbsolutePath()+": "+e.getMessage()); Notification.addError("Error while parsing JSON file " + writerFile.getAbsolutePath() + ": " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
if (reader != null) if (reader != null)
@@ -236,7 +210,7 @@ public class WriterModeDataSet implements ProjectTreeNode, Serializable {
public WriterModeData getWriterSketch(String id) { public WriterModeData getWriterSketch(String id) {
for (WriterModeData sketch : writerModeDataList) { for (WriterModeData sketch : writerModeDataList) {
if (id.equals(sketch.id)){ if (id.equals(sketch.id)) {
return sketch; return sketch;
} }
} }
@@ -250,7 +224,8 @@ public class WriterModeDataSet implements ProjectTreeNode, Serializable {
public void add(WriterModeData node) { public void add(WriterModeData node) {
ProjectTreeNode higherEmptyParent = this; ProjectTreeNode higherEmptyParent = this;
while (higherEmptyParent != null) { while (higherEmptyParent != null) {
if (higherEmptyParent.getParent() != null && ((ProjectTreeNode)higherEmptyParent.getParent()).isEmpty()) higherEmptyParent = (ProjectTreeNode)higherEmptyParent.getParent(); if (higherEmptyParent.getParent() != null && ((ProjectTreeNode) higherEmptyParent.getParent()).isEmpty())
higherEmptyParent = (ProjectTreeNode) higherEmptyParent.getParent();
else break; else break;
} }
if (higherEmptyParent == this && !this.isEmpty()) higherEmptyParent = null; if (higherEmptyParent == this && !this.isEmpty()) higherEmptyParent = null;

View File

@@ -1,26 +1,21 @@
package com.gpl.rpg.atcontentstudio.ui; package com.gpl.rpg.atcontentstudio.ui;
import java.awt.BorderLayout;
import java.awt.Desktop;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Scanner;
import javax.swing.ImageIcon;
import javax.swing.JEditorPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkEvent.EventType;
import javax.swing.event.HyperlinkListener;
import com.gpl.rpg.atcontentstudio.ATContentStudio; import com.gpl.rpg.atcontentstudio.ATContentStudio;
import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.GameDataElement;
import com.gpl.rpg.atcontentstudio.model.SaveEvent; import com.gpl.rpg.atcontentstudio.model.SaveEvent;
import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet; import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet;
import com.jidesoft.swing.JideTabbedPane; import com.jidesoft.swing.JideTabbedPane;
import javax.swing.*;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkEvent.EventType;
import javax.swing.event.HyperlinkListener;
import java.awt.*;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Scanner;
public class AboutEditor extends Editor { public class AboutEditor extends Editor {
private static final long serialVersionUID = 6230549148222457139L; private static final long serialVersionUID = 6230549148222457139L;
@@ -30,8 +25,8 @@ public class AboutEditor extends Editor {
"<meta http-equiv=\\\"Content-Type\\\" content=\\\"text/html; charset=UTF-8\\\" />" + "<meta http-equiv=\\\"Content-Type\\\" content=\\\"text/html; charset=UTF-8\\\" />" +
"</head><body>" + "</head><body>" +
"<table><tr valign=\"top\">" + "<table><tr valign=\"top\">" +
"<td><img src=\""+ATContentStudio.class.getResource("/com/gpl/rpg/atcontentstudio/img/atcs_border_banner.png")+"\"/></td>" + "<td><img src=\"" + ATContentStudio.class.getResource("/com/gpl/rpg/atcontentstudio/img/atcs_border_banner.png") + "\"/></td>" +
"<td><font size=+1>Welcome to "+ATContentStudio.APP_NAME+" "+ATContentStudio.APP_VERSION+"</font><br/>" + "<td><font size=+1>Welcome to " + ATContentStudio.APP_NAME + " " + ATContentStudio.APP_VERSION + "</font><br/>" +
"<br/>" + "<br/>" +
"This is a content editor for Andor's Trail.<br/>" + "This is a content editor for Andor's Trail.<br/>" +
"<b>Right click on the left area or use the \"File\" menu to create a project.</b><br/>" + "<b>Right click on the left area or use the \"File\" menu to create a project.</b><br/>" +
@@ -55,6 +50,7 @@ public class AboutEditor extends Editor {
"Quentin Delvallet<br/>" + "Quentin Delvallet<br/>" +
"Žižkin<br/>" + "Žižkin<br/>" +
"Gonk<br/>" + "Gonk<br/>" +
"<a href=\"https://github.com/OMGeeky\">OMGeeky</a><br/>" +
"<br/>" + "<br/>" +
"This project uses the following libraries:<br/>" + "This project uses the following libraries:<br/>" +
"<a href=\"http://code.google.com/p/json-simple/\">JSON.simple</a> by Yidong Fang & Chris Nokleberg.<br/>" + "<a href=\"http://code.google.com/p/json-simple/\">JSON.simple</a> by Yidong Fang & Chris Nokleberg.<br/>" +
@@ -97,30 +93,54 @@ public class AboutEditor extends Editor {
public static final AboutEditor instance = new AboutEditor(); public static final AboutEditor instance = new AboutEditor();
@SuppressWarnings("resource") @SuppressWarnings("resource")
private AboutEditor() { private AboutEditor() {
this.name="About "+ATContentStudio.APP_NAME; this.name = "About " + ATContentStudio.APP_NAME;
this.icon = new ImageIcon(DefaultIcons.getMainIconIcon()); this.icon = new ImageIcon(DefaultIcons.getMainIconIcon());
this.target = new GameDataElement(){ this.target = new GameDataElement() {
private static final long serialVersionUID = -227480102288529682L; private static final long serialVersionUID = -227480102288529682L;
@Override @Override
public GameDataSet getDataSet() {return null;} public GameDataSet getDataSet() {
return null;
}
@Override @Override
public String getDesc() {return null;} public String getDesc() {
return null;
}
@Override @Override
public void parse() {} public void parse() {
}
@Override @Override
public void link() {} public void link() {
}
@Override @Override
public GameDataElement clone() {return null;} public GameDataElement clone() {
return null;
}
@Override @Override
public void elementChanged(GameDataElement oldOne, GameDataElement newOne) {} public void elementChanged(GameDataElement oldOne, GameDataElement newOne) {
}
@Override @Override
public String getProjectFilename() {return null;} public String getProjectFilename() {
return null;
}
@Override @Override
public void save() {} public void save() {
}
@Override @Override
public List<SaveEvent> attemptSave() {return null;} public List<SaveEvent> attemptSave() {
return null;
}
}; };
setLayout(new BorderLayout()); setLayout(new BorderLayout());
@@ -132,12 +152,14 @@ public class AboutEditor extends Editor {
editorTabsHolder.add("Welcome", getInfoPane(WELCOME_STRING, "text/html")); editorTabsHolder.add("Welcome", getInfoPane(WELCOME_STRING, "text/html"));
editorTabsHolder.add("JSON.simple License", getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/LICENSE.JSON.simple.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text")); editorTabsHolder.add("JSON.simple License", getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/LICENSE.JSON.simple.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text"));
editorTabsHolder.add("RSyntaxTextArea License", getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/RSyntaxTextArea.License.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text")); editorTabsHolder.add("RSyntaxTextArea License",
getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/RSyntaxTextArea.License.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text"));
editorTabsHolder.add("JIDE Common Layer License", getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/LICENSE.JIDE.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text")); editorTabsHolder.add("JIDE Common Layer License", getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/LICENSE.JIDE.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text"));
editorTabsHolder.add("libtiled-java License", getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/LICENSE.libtiled.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text")); editorTabsHolder.add("libtiled-java License", getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/LICENSE.libtiled.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text"));
editorTabsHolder.add("prefuse License", getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/license-prefuse.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text")); editorTabsHolder.add("prefuse License", getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/license-prefuse.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text"));
editorTabsHolder.add("BeanShell License", getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/LICENSE.LGPLv3.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text")); editorTabsHolder.add("BeanShell License", getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/LICENSE.LGPLv3.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text"));
editorTabsHolder.add("SipHash for Java License", getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/LICENSE.siphash-zackehh.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text")); editorTabsHolder.add("SipHash for Java License",
getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/LICENSE.siphash-zackehh.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text"));
editorTabsHolder.add("jsoup License", getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/LICENSE.jsoup.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text")); editorTabsHolder.add("jsoup License", getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/LICENSE.jsoup.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text"));
editorTabsHolder.add("General PO Parser License", getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/LICENSE.GPLv3.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text")); editorTabsHolder.add("General PO Parser License", getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/LICENSE.GPLv3.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text"));
editorTabsHolder.add("Minify.java License", getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/LICENSE.minify.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text")); editorTabsHolder.add("Minify.java License", getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/LICENSE.minify.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text"));
@@ -175,6 +197,7 @@ public class AboutEditor extends Editor {
@Override @Override
public void targetUpdated() {} public void targetUpdated() {
}
} }

View File

@@ -1,6 +1,6 @@
package com.gpl.rpg.atcontentstudio.ui; package com.gpl.rpg.atcontentstudio.ui;
import javax.swing.JCheckBox; import javax.swing.*;
public class BooleanBasedCheckBox extends JCheckBox { public class BooleanBasedCheckBox extends JCheckBox {

View File

@@ -1,17 +1,9 @@
package com.gpl.rpg.atcontentstudio.ui; package com.gpl.rpg.atcontentstudio.ui;
import java.awt.BorderLayout; import javax.swing.*;
import java.awt.Component;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.border.TitledBorder; import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.*;
public class CollapsiblePanel extends JPanel { public class CollapsiblePanel extends JPanel {
@@ -42,6 +34,7 @@ public class CollapsiblePanel extends JPanel {
public void componentShown(ComponentEvent e) { public void componentShown(ComponentEvent e) {
updateBorderTitle(); updateBorderTitle();
} }
@Override @Override
public void componentHidden(ComponentEvent e) { public void componentHidden(ComponentEvent e) {
updateBorderTitle(); updateBorderTitle();
@@ -132,9 +125,9 @@ public class CollapsiblePanel extends JPanel {
protected void updateBorderTitle() { protected void updateBorderTitle() {
String arrow = ""; String arrow = "";
if (getComponentCount() > 0) { if (getComponentCount() > 0) {
arrow = (hasInvisibleComponent()?"[+] ":"[-] "); arrow = (hasInvisibleComponent() ? "[+] " : "[-] ");
} }
border.setTitle(arrow+title); border.setTitle(arrow + title);
repaint(); repaint();
} }
@@ -150,9 +143,11 @@ public class CollapsiblePanel extends JPanel {
public void collapse() { public void collapse() {
toggleVisibility(false); toggleVisibility(false);
} }
public void expand() { public void expand() {
toggleVisibility(true); toggleVisibility(true);
} }
public void setExpanded(boolean expand) { public void setExpanded(boolean expand) {
toggleVisibility(expand); toggleVisibility(expand);
} }

View File

@@ -1,15 +1,14 @@
package com.gpl.rpg.atcontentstudio.ui; package com.gpl.rpg.atcontentstudio.ui;
import java.awt.Image;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import com.gpl.rpg.atcontentstudio.ATContentStudio; import com.gpl.rpg.atcontentstudio.ATContentStudio;
import com.gpl.rpg.atcontentstudio.Notification; import com.gpl.rpg.atcontentstudio.Notification;
import javax.imageio.ImageIO;
import java.awt.*;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
public class DefaultIcons { public class DefaultIcons {
private static Map<String, Image> imageCache = new LinkedHashMap<String, Image>(); private static Map<String, Image> imageCache = new LinkedHashMap<String, Image>();
@@ -17,288 +16,714 @@ public class DefaultIcons {
private static String MAIN_ICON_RES = "/com/gpl/rpg/atcontentstudio/img/andorstrainer.png"; private static String MAIN_ICON_RES = "/com/gpl/rpg/atcontentstudio/img/andorstrainer.png";
public static Image getMainIconImage() { return getImage(MAIN_ICON_RES); }
public static Image getMainIconIcon() { return getIcon(MAIN_ICON_RES); } public static Image getMainIconImage() {
return getImage(MAIN_ICON_RES);
}
public static Image getMainIconIcon() {
return getIcon(MAIN_ICON_RES);
}
private static String FOLDER_STD_CLOSED_RES = "/com/gpl/rpg/atcontentstudio/img/folder_std_closed.png"; private static String FOLDER_STD_CLOSED_RES = "/com/gpl/rpg/atcontentstudio/img/folder_std_closed.png";
public static Image getStdClosedImage() { return getImage(FOLDER_STD_CLOSED_RES); }
public static Image getStdClosedIcon() { return getIcon(FOLDER_STD_CLOSED_RES); } public static Image getStdClosedImage() {
return getImage(FOLDER_STD_CLOSED_RES);
}
public static Image getStdClosedIcon() {
return getIcon(FOLDER_STD_CLOSED_RES);
}
private static String FOLDER_STD_OPEN_RES = "/com/gpl/rpg/atcontentstudio/img/folder_std_open.png"; private static String FOLDER_STD_OPEN_RES = "/com/gpl/rpg/atcontentstudio/img/folder_std_open.png";
public static Image getStdOpenImage() { return getImage(FOLDER_STD_OPEN_RES); }
public static Image getStdOpenIcon() { return getIcon(FOLDER_STD_OPEN_RES); } public static Image getStdOpenImage() {
return getImage(FOLDER_STD_OPEN_RES);
}
public static Image getStdOpenIcon() {
return getIcon(FOLDER_STD_OPEN_RES);
}
private static String FOLDER_JSON_CLOSED_RES = "/com/gpl/rpg/atcontentstudio/img/folder_json_closed.png"; private static String FOLDER_JSON_CLOSED_RES = "/com/gpl/rpg/atcontentstudio/img/folder_json_closed.png";
public static Image getJsonClosedImage() { return getImage(FOLDER_JSON_CLOSED_RES); }
public static Image getJsonClosedIcon() { return getIcon(FOLDER_JSON_CLOSED_RES); } public static Image getJsonClosedImage() {
return getImage(FOLDER_JSON_CLOSED_RES);
}
public static Image getJsonClosedIcon() {
return getIcon(FOLDER_JSON_CLOSED_RES);
}
private static String FOLDER_JSON_OPEN_RES = "/com/gpl/rpg/atcontentstudio/img/folder_json_open.png"; private static String FOLDER_JSON_OPEN_RES = "/com/gpl/rpg/atcontentstudio/img/folder_json_open.png";
public static Image getJsonOpenImage() { return getImage(FOLDER_JSON_OPEN_RES); }
public static Image getJsonOpenIcon() { return getIcon(FOLDER_JSON_OPEN_RES); } public static Image getJsonOpenImage() {
return getImage(FOLDER_JSON_OPEN_RES);
}
public static Image getJsonOpenIcon() {
return getIcon(FOLDER_JSON_OPEN_RES);
}
private static String FOLDER_SAV_CLOSED_RES = "/com/gpl/rpg/atcontentstudio/img/folder_sav_closed.png"; private static String FOLDER_SAV_CLOSED_RES = "/com/gpl/rpg/atcontentstudio/img/folder_sav_closed.png";
public static Image getSavClosedImage() { return getImage(FOLDER_SAV_CLOSED_RES); }
public static Image getSavClosedIcon() { return getIcon(FOLDER_SAV_CLOSED_RES); } public static Image getSavClosedImage() {
return getImage(FOLDER_SAV_CLOSED_RES);
}
public static Image getSavClosedIcon() {
return getIcon(FOLDER_SAV_CLOSED_RES);
}
private static String FOLDER_SAV_OPEN_RES = "/com/gpl/rpg/atcontentstudio/img/folder_sav_open.png"; private static String FOLDER_SAV_OPEN_RES = "/com/gpl/rpg/atcontentstudio/img/folder_sav_open.png";
public static Image getSavOpenImage() { return getImage(FOLDER_SAV_OPEN_RES); }
public static Image getSavOpenIcon() { return getIcon(FOLDER_SAV_OPEN_RES); } public static Image getSavOpenImage() {
return getImage(FOLDER_SAV_OPEN_RES);
}
public static Image getSavOpenIcon() {
return getIcon(FOLDER_SAV_OPEN_RES);
}
private static String FOLDER_SPRITE_CLOSED_RES = "/com/gpl/rpg/atcontentstudio/img/folder_sprite_closed.png"; private static String FOLDER_SPRITE_CLOSED_RES = "/com/gpl/rpg/atcontentstudio/img/folder_sprite_closed.png";
public static Image getSpriteClosedImage() { return getImage(FOLDER_SPRITE_CLOSED_RES); }
public static Image getSpriteClosedIcon() { return getIcon(FOLDER_SPRITE_CLOSED_RES); } public static Image getSpriteClosedImage() {
return getImage(FOLDER_SPRITE_CLOSED_RES);
}
public static Image getSpriteClosedIcon() {
return getIcon(FOLDER_SPRITE_CLOSED_RES);
}
private static String FOLDER_SPRITE_OPEN_RES = "/com/gpl/rpg/atcontentstudio/img/folder_sprite_open.png"; private static String FOLDER_SPRITE_OPEN_RES = "/com/gpl/rpg/atcontentstudio/img/folder_sprite_open.png";
public static Image getSpriteOpenImage() { return getImage(FOLDER_SPRITE_OPEN_RES); }
public static Image getSpriteOpenIcon() { return getIcon(FOLDER_SPRITE_OPEN_RES); } public static Image getSpriteOpenImage() {
return getImage(FOLDER_SPRITE_OPEN_RES);
}
public static Image getSpriteOpenIcon() {
return getIcon(FOLDER_SPRITE_OPEN_RES);
}
private static String FOLDER_TMX_CLOSED_RES = "/com/gpl/rpg/atcontentstudio/img/folder_tmx_closed.png"; private static String FOLDER_TMX_CLOSED_RES = "/com/gpl/rpg/atcontentstudio/img/folder_tmx_closed.png";
public static Image getTmxClosedImage() { return getImage(FOLDER_TMX_CLOSED_RES); }
public static Image getTmxClosedIcon() { return getIcon(FOLDER_TMX_CLOSED_RES); } public static Image getTmxClosedImage() {
return getImage(FOLDER_TMX_CLOSED_RES);
}
public static Image getTmxClosedIcon() {
return getIcon(FOLDER_TMX_CLOSED_RES);
}
private static String FOLDER_TMX_OPEN_RES = "/com/gpl/rpg/atcontentstudio/img/folder_tmx_open.png"; private static String FOLDER_TMX_OPEN_RES = "/com/gpl/rpg/atcontentstudio/img/folder_tmx_open.png";
public static Image getTmxOpenImage() { return getImage(FOLDER_TMX_OPEN_RES); }
public static Image getTmxOpenIcon() { return getIcon(FOLDER_TMX_OPEN_RES); } public static Image getTmxOpenImage() {
return getImage(FOLDER_TMX_OPEN_RES);
}
public static Image getTmxOpenIcon() {
return getIcon(FOLDER_TMX_OPEN_RES);
}
private static String FOLDER_MAP_CLOSED_RES = "/com/gpl/rpg/atcontentstudio/img/folder_map_closed.png"; private static String FOLDER_MAP_CLOSED_RES = "/com/gpl/rpg/atcontentstudio/img/folder_map_closed.png";
public static Image getMapClosedImage() { return getImage(FOLDER_MAP_CLOSED_RES); }
public static Image getMapClosedIcon() { return getIcon(FOLDER_MAP_CLOSED_RES); } public static Image getMapClosedImage() {
return getImage(FOLDER_MAP_CLOSED_RES);
}
public static Image getMapClosedIcon() {
return getIcon(FOLDER_MAP_CLOSED_RES);
}
private static String FOLDER_MAP_OPEN_RES = "/com/gpl/rpg/atcontentstudio/img/folder_map_open.png"; private static String FOLDER_MAP_OPEN_RES = "/com/gpl/rpg/atcontentstudio/img/folder_map_open.png";
public static Image getMapOpenImage() { return getImage(FOLDER_MAP_OPEN_RES); }
public static Image getMapOpenIcon() { return getIcon(FOLDER_MAP_OPEN_RES); } public static Image getMapOpenImage() {
return getImage(FOLDER_MAP_OPEN_RES);
}
public static Image getMapOpenIcon() {
return getIcon(FOLDER_MAP_OPEN_RES);
}
private static String FOLDER_AT_CLOSED_RES = "/com/gpl/rpg/atcontentstudio/img/folder_at_closed.png"; private static String FOLDER_AT_CLOSED_RES = "/com/gpl/rpg/atcontentstudio/img/folder_at_closed.png";
public static Image getATClosedImage() { return getImage(FOLDER_AT_CLOSED_RES); }
public static Image getATClosedIcon() { return getIcon(FOLDER_AT_CLOSED_RES); } public static Image getATClosedImage() {
return getImage(FOLDER_AT_CLOSED_RES);
}
public static Image getATClosedIcon() {
return getIcon(FOLDER_AT_CLOSED_RES);
}
private static String FOLDER_AT_OPEN_RES = "/com/gpl/rpg/atcontentstudio/img/folder_at_open.png"; private static String FOLDER_AT_OPEN_RES = "/com/gpl/rpg/atcontentstudio/img/folder_at_open.png";
public static Image getATOpenImage() { return getImage(FOLDER_AT_OPEN_RES); }
public static Image getATOpenIcon() { return getIcon(FOLDER_AT_OPEN_RES); } public static Image getATOpenImage() {
return getImage(FOLDER_AT_OPEN_RES);
}
public static Image getATOpenIcon() {
return getIcon(FOLDER_AT_OPEN_RES);
}
private static String FOLDER_BOOKMARK_CLOSED_RES = "/com/gpl/rpg/atcontentstudio/img/folder_bookmark_closed.png"; private static String FOLDER_BOOKMARK_CLOSED_RES = "/com/gpl/rpg/atcontentstudio/img/folder_bookmark_closed.png";
public static Image getBookmarkClosedImage() { return getImage(FOLDER_BOOKMARK_CLOSED_RES); }
public static Image getBookmarkClosedIcon() { return getIcon(FOLDER_BOOKMARK_CLOSED_RES); } public static Image getBookmarkClosedImage() {
return getImage(FOLDER_BOOKMARK_CLOSED_RES);
}
public static Image getBookmarkClosedIcon() {
return getIcon(FOLDER_BOOKMARK_CLOSED_RES);
}
private static String FOLDER_BOOKMARK_OPEN_RES = "/com/gpl/rpg/atcontentstudio/img/folder_bookmark_open.png"; private static String FOLDER_BOOKMARK_OPEN_RES = "/com/gpl/rpg/atcontentstudio/img/folder_bookmark_open.png";
public static Image getBookmarkOpenImage() { return getImage(FOLDER_BOOKMARK_OPEN_RES); }
public static Image getBookmarkOpenIcon() { return getIcon(FOLDER_BOOKMARK_OPEN_RES); } public static Image getBookmarkOpenImage() {
return getImage(FOLDER_BOOKMARK_OPEN_RES);
}
public static Image getBookmarkOpenIcon() {
return getIcon(FOLDER_BOOKMARK_OPEN_RES);
}
private static String TILED_ICON_RES = "/com/gpl/rpg/atcontentstudio/img/tiled-icon.png"; private static String TILED_ICON_RES = "/com/gpl/rpg/atcontentstudio/img/tiled-icon.png";
public static Image getTiledIconImage() { return getImage(TILED_ICON_RES); }
public static Image getTiledIconIcon() { return getIcon(TILED_ICON_RES); } public static Image getTiledIconImage() {
return getImage(TILED_ICON_RES);
}
public static Image getTiledIconIcon() {
return getIcon(TILED_ICON_RES);
}
private static String UI_MAP_RES = "/com/gpl/rpg/atcontentstudio/img/ui_icon_map.png"; private static String UI_MAP_RES = "/com/gpl/rpg/atcontentstudio/img/ui_icon_map.png";
public static Image getUIMapImage() { return getImage(UI_MAP_RES); }
public static Image getUIMapIcon() { return getIcon(UI_MAP_RES); } public static Image getUIMapImage() {
return getImage(UI_MAP_RES);
}
public static Image getUIMapIcon() {
return getIcon(UI_MAP_RES);
}
private static String HERO_RES = "/com/gpl/rpg/atcontentstudio/img/char_hero.png"; private static String HERO_RES = "/com/gpl/rpg/atcontentstudio/img/char_hero.png";
public static Image getHeroImage() { return getImage(HERO_RES); }
public static Image getHeroIcon() { return getIcon(HERO_RES); } public static Image getHeroImage() {
return getImage(HERO_RES);
}
public static Image getHeroIcon() {
return getIcon(HERO_RES);
}
private static String TILE_LAYER_RES = "/com/gpl/rpg/atcontentstudio/img/tile_layer.png"; private static String TILE_LAYER_RES = "/com/gpl/rpg/atcontentstudio/img/tile_layer.png";
public static Image getTileLayerImage() { return getImage(TILE_LAYER_RES); }
public static Image getTileLayerIcon() { return getIcon(TILE_LAYER_RES); } public static Image getTileLayerImage() {
return getImage(TILE_LAYER_RES);
}
public static Image getTileLayerIcon() {
return getIcon(TILE_LAYER_RES);
}
private static String OBJECT_LAYER_RES = "/com/gpl/rpg/atcontentstudio/img/object_layer.png"; private static String OBJECT_LAYER_RES = "/com/gpl/rpg/atcontentstudio/img/object_layer.png";
public static Image getObjectLayerImage() { return getImage(OBJECT_LAYER_RES); }
public static Image getObjectLayerIcon() { return getIcon(OBJECT_LAYER_RES); } public static Image getObjectLayerImage() {
return getImage(OBJECT_LAYER_RES);
}
public static Image getObjectLayerIcon() {
return getIcon(OBJECT_LAYER_RES);
}
private static String ACTOR_CONDITION_RES = "/com/gpl/rpg/atcontentstudio/img/actor_condition.png"; private static String ACTOR_CONDITION_RES = "/com/gpl/rpg/atcontentstudio/img/actor_condition.png";
public static Image getActorConditionImage() { return getImage(ACTOR_CONDITION_RES); }
public static Image getActorConditionIcon() { return getIcon(ACTOR_CONDITION_RES); } public static Image getActorConditionImage() {
return getImage(ACTOR_CONDITION_RES);
}
public static Image getActorConditionIcon() {
return getIcon(ACTOR_CONDITION_RES);
}
private static String ITEM_RES = "/com/gpl/rpg/atcontentstudio/img/item.png"; private static String ITEM_RES = "/com/gpl/rpg/atcontentstudio/img/item.png";
public static Image getItemImage() { return getImage(ITEM_RES); }
public static Image getItemIcon() { return getIcon(ITEM_RES); } public static Image getItemImage() {
return getImage(ITEM_RES);
}
public static Image getItemIcon() {
return getIcon(ITEM_RES);
}
private static String NPC_RES = "/com/gpl/rpg/atcontentstudio/img/npc.png"; private static String NPC_RES = "/com/gpl/rpg/atcontentstudio/img/npc.png";
public static Image getNPCImage() { return getImage(NPC_RES); }
public static Image getNPCIcon() { return getIcon(NPC_RES); } public static Image getNPCImage() {
return getImage(NPC_RES);
}
public static Image getNPCIcon() {
return getIcon(NPC_RES);
}
private static String BONEMEAL_RES = "/com/gpl/rpg/atcontentstudio/img/bonemeal.png"; private static String BONEMEAL_RES = "/com/gpl/rpg/atcontentstudio/img/bonemeal.png";
public static Image getBonemealImage() { return getImage(BONEMEAL_RES); }
public static Image getBonemealIcon() { return getIcon(BONEMEAL_RES); } public static Image getBonemealImage() {
return getImage(BONEMEAL_RES);
}
public static Image getBonemealIcon() {
return getIcon(BONEMEAL_RES);
}
private static String NPC_CLOSE_RES = "/com/gpl/rpg/atcontentstudio/img/npc_close.png"; private static String NPC_CLOSE_RES = "/com/gpl/rpg/atcontentstudio/img/npc_close.png";
public static Image getNPCCloseImage() { return getImage(NPC_CLOSE_RES); }
public static Image getNPCCloseIcon() { return getIcon(NPC_CLOSE_RES); } public static Image getNPCCloseImage() {
return getImage(NPC_CLOSE_RES);
}
public static Image getNPCCloseIcon() {
return getIcon(NPC_CLOSE_RES);
}
private static String DIALOGUE_RES = "/com/gpl/rpg/atcontentstudio/img/dialogue.png"; private static String DIALOGUE_RES = "/com/gpl/rpg/atcontentstudio/img/dialogue.png";
public static Image getDialogueImage() { return getImage(DIALOGUE_RES); }
public static Image getDialogueIcon() { return getIcon(DIALOGUE_RES); } public static Image getDialogueImage() {
return getImage(DIALOGUE_RES);
}
public static Image getDialogueIcon() {
return getIcon(DIALOGUE_RES);
}
private static String QUEST_RES = "/com/gpl/rpg/atcontentstudio/img/ui_icon_quest.png"; private static String QUEST_RES = "/com/gpl/rpg/atcontentstudio/img/ui_icon_quest.png";
public static Image getQuestImage() { return getImage(QUEST_RES); }
public static Image getQuestIcon() { return getIcon(QUEST_RES); } public static Image getQuestImage() {
return getImage(QUEST_RES);
}
public static Image getQuestIcon() {
return getIcon(QUEST_RES);
}
private static String DROPLIST_RES = "/com/gpl/rpg/atcontentstudio/img/ui_icon_equipment.png"; private static String DROPLIST_RES = "/com/gpl/rpg/atcontentstudio/img/ui_icon_equipment.png";
public static Image getDroplistImage() { return getImage(DROPLIST_RES); }
public static Image getDroplistIcon() { return getIcon(DROPLIST_RES); } public static Image getDroplistImage() {
return getImage(DROPLIST_RES);
}
public static Image getDroplistIcon() {
return getIcon(DROPLIST_RES);
}
private static String COMBAT_RES = "/com/gpl/rpg/atcontentstudio/img/ui_icon_combat.png"; private static String COMBAT_RES = "/com/gpl/rpg/atcontentstudio/img/ui_icon_combat.png";
public static Image getCombatImage() { return getImage(COMBAT_RES); }
public static Image getCombatIcon() { return getIcon(COMBAT_RES); } public static Image getCombatImage() {
return getImage(COMBAT_RES);
}
public static Image getCombatIcon() {
return getIcon(COMBAT_RES);
}
private static String GOLD_RES = "/com/gpl/rpg/atcontentstudio/img/ui_icon_coins.png"; private static String GOLD_RES = "/com/gpl/rpg/atcontentstudio/img/ui_icon_coins.png";
public static Image getGoldImage() { return getImage(GOLD_RES); }
public static Image getGoldIcon() { return getIcon(GOLD_RES); } public static Image getGoldImage() {
return getImage(GOLD_RES);
}
public static Image getGoldIcon() {
return getIcon(GOLD_RES);
}
private static String SKILL_RES = "/com/gpl/rpg/atcontentstudio/img/ui_icon_skill.png"; private static String SKILL_RES = "/com/gpl/rpg/atcontentstudio/img/ui_icon_skill.png";
public static Image getSkillImage() { return getImage(SKILL_RES); }
public static Image getSkillIcon() { return getIcon(SKILL_RES); } public static Image getSkillImage() {
return getImage(SKILL_RES);
}
public static Image getSkillIcon() {
return getIcon(SKILL_RES);
}
private static String IMMUNITY_RES = "/com/gpl/rpg/atcontentstudio/img/ui_icon_immunity.png"; private static String IMMUNITY_RES = "/com/gpl/rpg/atcontentstudio/img/ui_icon_immunity.png";
public static Image getImmunityImage() { return getImage(IMMUNITY_RES); }
public static Image getImmunityIcon() { return getIcon(IMMUNITY_RES); } public static Image getImmunityImage() {
return getImage(IMMUNITY_RES);
}
public static Image getImmunityIcon() {
return getIcon(IMMUNITY_RES);
}
private static String ITEM_CATEGORY_RES = "/com/gpl/rpg/atcontentstudio/img/equip_weapon.png"; private static String ITEM_CATEGORY_RES = "/com/gpl/rpg/atcontentstudio/img/equip_weapon.png";
public static Image getItemCategoryImage() { return getImage(ITEM_CATEGORY_RES); }
public static Image getItemCategoryIcon() { return getIcon(ITEM_CATEGORY_RES); } public static Image getItemCategoryImage() {
return getImage(ITEM_CATEGORY_RES);
}
public static Image getItemCategoryIcon() {
return getIcon(ITEM_CATEGORY_RES);
}
private static String NULLIFY_RES = "/com/gpl/rpg/atcontentstudio/img/nullify.png"; private static String NULLIFY_RES = "/com/gpl/rpg/atcontentstudio/img/nullify.png";
public static Image getNullifyImage() { return getImage(NULLIFY_RES); }
public static Image getNullifyIcon() { return getIcon(NULLIFY_RES); } public static Image getNullifyImage() {
return getImage(NULLIFY_RES);
}
public static Image getNullifyIcon() {
return getIcon(NULLIFY_RES);
}
private static String CREATE_RES = "/com/gpl/rpg/atcontentstudio/img/file_create.png"; private static String CREATE_RES = "/com/gpl/rpg/atcontentstudio/img/file_create.png";
public static Image getCreateImage() { return getImage(CREATE_RES); }
public static Image getCreateIcon() { return getIcon(CREATE_RES); } public static Image getCreateImage() {
return getImage(CREATE_RES);
}
public static Image getCreateIcon() {
return getIcon(CREATE_RES);
}
private static String ARROW_UP_RES = "/com/gpl/rpg/atcontentstudio/img/arrow_up.png"; private static String ARROW_UP_RES = "/com/gpl/rpg/atcontentstudio/img/arrow_up.png";
public static Image getArrowUpImage() { return getImage(ARROW_UP_RES); }
public static Image getArrowUpIcon() { return getIcon(ARROW_UP_RES); } public static Image getArrowUpImage() {
return getImage(ARROW_UP_RES);
}
public static Image getArrowUpIcon() {
return getIcon(ARROW_UP_RES);
}
private static String ARROW_DOWN_RES = "/com/gpl/rpg/atcontentstudio/img/arrow_down.png"; private static String ARROW_DOWN_RES = "/com/gpl/rpg/atcontentstudio/img/arrow_down.png";
public static Image getArrowDownImage() { return getImage(ARROW_DOWN_RES); }
public static Image getArrowDownIcon() { return getIcon(ARROW_DOWN_RES); } public static Image getArrowDownImage() {
return getImage(ARROW_DOWN_RES);
}
public static Image getArrowDownIcon() {
return getIcon(ARROW_DOWN_RES);
}
private static String ARROW_LEFT_RES = "/com/gpl/rpg/atcontentstudio/img/arrow_left.png"; private static String ARROW_LEFT_RES = "/com/gpl/rpg/atcontentstudio/img/arrow_left.png";
public static Image getArrowLeftImage() { return getImage(ARROW_LEFT_RES); }
public static Image getArrowLeftIcon() { return getIcon(ARROW_LEFT_RES); } public static Image getArrowLeftImage() {
return getImage(ARROW_LEFT_RES);
}
public static Image getArrowLeftIcon() {
return getIcon(ARROW_LEFT_RES);
}
private static String ARROW_RIGHT_RES = "/com/gpl/rpg/atcontentstudio/img/arrow_right.png"; private static String ARROW_RIGHT_RES = "/com/gpl/rpg/atcontentstudio/img/arrow_right.png";
public static Image getArrowRightImage() { return getImage(ARROW_RIGHT_RES); }
public static Image getArrowRightIcon() { return getIcon(ARROW_RIGHT_RES); } public static Image getArrowRightImage() {
return getImage(ARROW_RIGHT_RES);
}
public static Image getArrowRightIcon() {
return getIcon(ARROW_RIGHT_RES);
}
private static String CONTAINER_RES = "/com/gpl/rpg/atcontentstudio/img/container.png"; private static String CONTAINER_RES = "/com/gpl/rpg/atcontentstudio/img/container.png";
public static Image getContainerImage() { return getImage(CONTAINER_RES); }
public static Image getContainerIcon() { return getIcon(CONTAINER_RES); } public static Image getContainerImage() {
return getImage(CONTAINER_RES);
}
public static Image getContainerIcon() {
return getIcon(CONTAINER_RES);
}
private static String KEY_RES = "/com/gpl/rpg/atcontentstudio/img/key.png"; private static String KEY_RES = "/com/gpl/rpg/atcontentstudio/img/key.png";
public static Image getKeyImage() { return getImage(KEY_RES); }
public static Image getKeyIcon() { return getIcon(KEY_RES); } public static Image getKeyImage() {
return getImage(KEY_RES);
}
public static Image getKeyIcon() {
return getIcon(KEY_RES);
}
private static String MAPCHANGE_RES = "/com/gpl/rpg/atcontentstudio/img/mapchange.png"; private static String MAPCHANGE_RES = "/com/gpl/rpg/atcontentstudio/img/mapchange.png";
public static Image getMapchangeImage() { return getImage(MAPCHANGE_RES); }
public static Image getMapchangeIcon() { return getIcon(MAPCHANGE_RES); } public static Image getMapchangeImage() {
return getImage(MAPCHANGE_RES);
}
public static Image getMapchangeIcon() {
return getIcon(MAPCHANGE_RES);
}
private static String REPLACE_RES = "/com/gpl/rpg/atcontentstudio/img/replace.png"; private static String REPLACE_RES = "/com/gpl/rpg/atcontentstudio/img/replace.png";
public static Image getReplaceImage() { return getImage(REPLACE_RES); }
public static Image getReplaceIcon() { return getIcon(REPLACE_RES); } public static Image getReplaceImage() {
return getImage(REPLACE_RES);
}
public static Image getReplaceIcon() {
return getIcon(REPLACE_RES);
}
private static String REST_RES = "/com/gpl/rpg/atcontentstudio/img/rest.png"; private static String REST_RES = "/com/gpl/rpg/atcontentstudio/img/rest.png";
public static Image getRestImage() { return getImage(REST_RES); }
public static Image getRestIcon() { return getIcon(REST_RES); } public static Image getRestImage() {
return getImage(REST_RES);
}
public static Image getRestIcon() {
return getIcon(REST_RES);
}
private static String SCRIPT_RES = "/com/gpl/rpg/atcontentstudio/img/script.png"; private static String SCRIPT_RES = "/com/gpl/rpg/atcontentstudio/img/script.png";
public static Image getScriptImage() { return getImage(SCRIPT_RES); }
public static Image getScriptIcon() { return getIcon(SCRIPT_RES); } public static Image getScriptImage() {
return getImage(SCRIPT_RES);
}
public static Image getScriptIcon() {
return getIcon(SCRIPT_RES);
}
private static String SIGN_RES = "/com/gpl/rpg/atcontentstudio/img/sign.png"; private static String SIGN_RES = "/com/gpl/rpg/atcontentstudio/img/sign.png";
public static Image getSignImage() { return getImage(SIGN_RES); }
public static Image getSignIcon() { return getIcon(SIGN_RES); } public static Image getSignImage() {
return getImage(SIGN_RES);
}
public static Image getSignIcon() {
return getIcon(SIGN_RES);
}
private static String CREATE_CONTAINER_RES = "/com/gpl/rpg/atcontentstudio/img/create_container.png"; private static String CREATE_CONTAINER_RES = "/com/gpl/rpg/atcontentstudio/img/create_container.png";
public static Image getCreateContainerImage() { return getImage(CREATE_CONTAINER_RES); }
public static Image getCreateContainerIcon() { return getIcon(CREATE_CONTAINER_RES); } public static Image getCreateContainerImage() {
return getImage(CREATE_CONTAINER_RES);
}
public static Image getCreateContainerIcon() {
return getIcon(CREATE_CONTAINER_RES);
}
private static String CREATE_KEY_RES = "/com/gpl/rpg/atcontentstudio/img/create_key.png"; private static String CREATE_KEY_RES = "/com/gpl/rpg/atcontentstudio/img/create_key.png";
public static Image getCreateKeyImage() { return getImage(CREATE_KEY_RES); }
public static Image getCreateKeyIcon() { return getIcon(CREATE_KEY_RES); } public static Image getCreateKeyImage() {
return getImage(CREATE_KEY_RES);
}
public static Image getCreateKeyIcon() {
return getIcon(CREATE_KEY_RES);
}
private static String CREATE_REPLACE_RES = "/com/gpl/rpg/atcontentstudio/img/create_replace.png"; private static String CREATE_REPLACE_RES = "/com/gpl/rpg/atcontentstudio/img/create_replace.png";
public static Image getCreateReplaceImage() { return getImage(CREATE_REPLACE_RES); }
public static Image getCreateReplaceIcon() { return getIcon(CREATE_REPLACE_RES); } public static Image getCreateReplaceImage() {
return getImage(CREATE_REPLACE_RES);
}
public static Image getCreateReplaceIcon() {
return getIcon(CREATE_REPLACE_RES);
}
private static String CREATE_REST_RES = "/com/gpl/rpg/atcontentstudio/img/create_rest.png"; private static String CREATE_REST_RES = "/com/gpl/rpg/atcontentstudio/img/create_rest.png";
public static Image getCreateRestImage() { return getImage(CREATE_REST_RES); }
public static Image getCreateRestIcon() { return getIcon(CREATE_REST_RES); } public static Image getCreateRestImage() {
return getImage(CREATE_REST_RES);
}
public static Image getCreateRestIcon() {
return getIcon(CREATE_REST_RES);
}
private static String CREATE_SCRIPT_RES = "/com/gpl/rpg/atcontentstudio/img/create_script.png"; private static String CREATE_SCRIPT_RES = "/com/gpl/rpg/atcontentstudio/img/create_script.png";
public static Image getCreateScriptImage() { return getImage(CREATE_SCRIPT_RES); }
public static Image getCreateScriptIcon() { return getIcon(CREATE_SCRIPT_RES); } public static Image getCreateScriptImage() {
return getImage(CREATE_SCRIPT_RES);
}
public static Image getCreateScriptIcon() {
return getIcon(CREATE_SCRIPT_RES);
}
private static String CREATE_SIGN_RES = "/com/gpl/rpg/atcontentstudio/img/create_sign.png"; private static String CREATE_SIGN_RES = "/com/gpl/rpg/atcontentstudio/img/create_sign.png";
public static Image getCreateSignImage() { return getImage(CREATE_SIGN_RES); }
public static Image getCreateSignIcon() { return getIcon(CREATE_SIGN_RES); } public static Image getCreateSignImage() {
return getImage(CREATE_SIGN_RES);
}
public static Image getCreateSignIcon() {
return getIcon(CREATE_SIGN_RES);
}
private static String CREATE_SPAWNAREA_RES = "/com/gpl/rpg/atcontentstudio/img/create_spawnarea.png"; private static String CREATE_SPAWNAREA_RES = "/com/gpl/rpg/atcontentstudio/img/create_spawnarea.png";
public static Image getCreateSpawnareaImage() { return getImage(CREATE_SPAWNAREA_RES); }
public static Image getCreateSpawnareaIcon() { return getIcon(CREATE_SPAWNAREA_RES); } public static Image getCreateSpawnareaImage() {
return getImage(CREATE_SPAWNAREA_RES);
}
public static Image getCreateSpawnareaIcon() {
return getIcon(CREATE_SPAWNAREA_RES);
}
private static String CREATE_MAPCHANGE_RES = "/com/gpl/rpg/atcontentstudio/img/create_tiled.png"; private static String CREATE_MAPCHANGE_RES = "/com/gpl/rpg/atcontentstudio/img/create_tiled.png";
public static Image getCreateMapchangeImage() { return getImage(CREATE_MAPCHANGE_RES); }
public static Image getCreateMapchangeIcon() { return getIcon(CREATE_MAPCHANGE_RES); } public static Image getCreateMapchangeImage() {
return getImage(CREATE_MAPCHANGE_RES);
}
public static Image getCreateMapchangeIcon() {
return getIcon(CREATE_MAPCHANGE_RES);
}
private static String CREATE_OBJECT_GROUP_RES = "/com/gpl/rpg/atcontentstudio/img/create_object_group.png"; private static String CREATE_OBJECT_GROUP_RES = "/com/gpl/rpg/atcontentstudio/img/create_object_group.png";
public static Image getCreateObjectGroupImage() { return getImage(CREATE_OBJECT_GROUP_RES); }
public static Image getCreateObjectGroupIcon() { return getIcon(CREATE_OBJECT_GROUP_RES); } public static Image getCreateObjectGroupImage() {
return getImage(CREATE_OBJECT_GROUP_RES);
}
public static Image getCreateObjectGroupIcon() {
return getIcon(CREATE_OBJECT_GROUP_RES);
}
private static String CREATE_TILE_LAYER_RES = "/com/gpl/rpg/atcontentstudio/img/create_tile_layer.png"; private static String CREATE_TILE_LAYER_RES = "/com/gpl/rpg/atcontentstudio/img/create_tile_layer.png";
public static Image getCreateTileLayerImage() { return getImage(CREATE_TILE_LAYER_RES); }
public static Image getCreateTileLayerIcon() { return getIcon(CREATE_TILE_LAYER_RES); } public static Image getCreateTileLayerImage() {
return getImage(CREATE_TILE_LAYER_RES);
}
public static Image getCreateTileLayerIcon() {
return getIcon(CREATE_TILE_LAYER_RES);
}
private static String LABEL_RES = "/com/gpl/rpg/atcontentstudio/img/label.png"; private static String LABEL_RES = "/com/gpl/rpg/atcontentstudio/img/label.png";
public static Image getLabelImage() { return getImage(LABEL_RES); }
public static Image getLabelIcon() { return getIcon(LABEL_RES); } public static Image getLabelImage() {
return getImage(LABEL_RES);
}
public static Image getLabelIcon() {
return getIcon(LABEL_RES);
}
private static String ZOOM_RES = "/com/gpl/rpg/atcontentstudio/img/zoom.png"; private static String ZOOM_RES = "/com/gpl/rpg/atcontentstudio/img/zoom.png";
public static Image getZoomImage() { return getImage(ZOOM_RES); }
public static Image getZoomIcon() { return getIcon(ZOOM_RES); } public static Image getZoomImage() {
return getImage(ZOOM_RES);
}
public static Image getZoomIcon() {
return getIcon(ZOOM_RES);
}
private static String TIMER_RES = "/com/gpl/rpg/atcontentstudio/img/timer.png"; private static String TIMER_RES = "/com/gpl/rpg/atcontentstudio/img/timer.png";
public static Image getTimerImage() { return getImage(TIMER_RES); }
public static Image getTimerIcon() { return getIcon(TIMER_RES); } public static Image getTimerImage() {
return getImage(TIMER_RES);
}
public static Image getTimerIcon() {
return getIcon(TIMER_RES);
}
private static String DATE_RES = "/com/gpl/rpg/atcontentstudio/img/date.png"; private static String DATE_RES = "/com/gpl/rpg/atcontentstudio/img/date.png";
public static Image getDateImage() { return getImage(DATE_RES); }
public static Image getDateIcon() { return getIcon(DATE_RES); } public static Image getDateImage() {
return getImage(DATE_RES);
}
public static Image getDateIcon() {
return getIcon(DATE_RES);
}
private static String TIME_RES = "/com/gpl/rpg/atcontentstudio/img/date.png"; private static String TIME_RES = "/com/gpl/rpg/atcontentstudio/img/date.png";
public static Image getTimeImage() { return getImage(TIME_RES); }
public static Image getTimeIcon() { return getIcon(TIME_RES); } public static Image getTimeImage() {
return getImage(TIME_RES);
}
public static Image getTimeIcon() {
return getIcon(TIME_RES);
}
private static String ALIGNMENT_RES = "/com/gpl/rpg/atcontentstudio/img/alignment.png"; private static String ALIGNMENT_RES = "/com/gpl/rpg/atcontentstudio/img/alignment.png";
public static Image getAlignmentImage() { return getImage(ALIGNMENT_RES); }
public static Image getAlignmentIcon() { return getIcon(ALIGNMENT_RES); } public static Image getAlignmentImage() {
return getImage(ALIGNMENT_RES);
}
public static Image getAlignmentIcon() {
return getIcon(ALIGNMENT_RES);
}
private static String STATUS_RED_RES = "/com/gpl/rpg/atcontentstudio/img/status_red.png"; private static String STATUS_RED_RES = "/com/gpl/rpg/atcontentstudio/img/status_red.png";
public static Image getStatusRedImage() { return getImage(STATUS_RED_RES); }
public static Image getStatusRedIcon() { return getIcon(STATUS_RED_RES); } public static Image getStatusRedImage() {
return getImage(STATUS_RED_RES);
}
public static Image getStatusRedIcon() {
return getIcon(STATUS_RED_RES);
}
private static String STATUS_ORANGE_RES = "/com/gpl/rpg/atcontentstudio/img/status_orange.png"; private static String STATUS_ORANGE_RES = "/com/gpl/rpg/atcontentstudio/img/status_orange.png";
public static Image getStatusOrangeImage() { return getImage(STATUS_ORANGE_RES); }
public static Image getStatusOrangeIcon() { return getIcon(STATUS_ORANGE_RES); } public static Image getStatusOrangeImage() {
return getImage(STATUS_ORANGE_RES);
}
public static Image getStatusOrangeIcon() {
return getIcon(STATUS_ORANGE_RES);
}
private static String STATUS_GREEN_RES = "/com/gpl/rpg/atcontentstudio/img/status_green.png"; private static String STATUS_GREEN_RES = "/com/gpl/rpg/atcontentstudio/img/status_green.png";
public static Image getStatusGreenImage() { return getImage(STATUS_GREEN_RES); }
public static Image getStatusGreenIcon() { return getIcon(STATUS_GREEN_RES); } public static Image getStatusGreenImage() {
return getImage(STATUS_GREEN_RES);
}
public static Image getStatusGreenIcon() {
return getIcon(STATUS_GREEN_RES);
}
private static String STATUS_BLUE_RES = "/com/gpl/rpg/atcontentstudio/img/status_blue.png"; private static String STATUS_BLUE_RES = "/com/gpl/rpg/atcontentstudio/img/status_blue.png";
public static Image getStatusBlueImage() { return getImage(STATUS_BLUE_RES); }
public static Image getStatusBlueIcon() { return getIcon(STATUS_BLUE_RES); } public static Image getStatusBlueImage() {
return getImage(STATUS_BLUE_RES);
}
public static Image getStatusBlueIcon() {
return getIcon(STATUS_BLUE_RES);
}
private static String STATUS_UNKNOWN_RES = "/com/gpl/rpg/atcontentstudio/img/status_unknown.png"; private static String STATUS_UNKNOWN_RES = "/com/gpl/rpg/atcontentstudio/img/status_unknown.png";
public static Image getStatusUnknownImage() { return getImage(STATUS_UNKNOWN_RES); }
public static Image getStatusUnknownIcon() { return getIcon(STATUS_UNKNOWN_RES); } public static Image getStatusUnknownImage() {
return getImage(STATUS_UNKNOWN_RES);
}
public static Image getStatusUnknownIcon() {
return getIcon(STATUS_UNKNOWN_RES);
}
private static String BOOKMARK_INACTIVE = "/com/gpl/rpg/atcontentstudio/img/bookmark_inactive.png"; private static String BOOKMARK_INACTIVE = "/com/gpl/rpg/atcontentstudio/img/bookmark_inactive.png";
public static Image getBookmarkInactiveImage() { return getImage(BOOKMARK_INACTIVE); }
public static Image getBookmarkInactiveIcon() { return getIcon(BOOKMARK_INACTIVE); } public static Image getBookmarkInactiveImage() {
return getImage(BOOKMARK_INACTIVE);
}
public static Image getBookmarkInactiveIcon() {
return getIcon(BOOKMARK_INACTIVE);
}
private static String BOOKMARK_ACTIVE = "/com/gpl/rpg/atcontentstudio/img/bookmark_active.png"; private static String BOOKMARK_ACTIVE = "/com/gpl/rpg/atcontentstudio/img/bookmark_active.png";
public static Image getBookmarkActiveImage() { return getImage(BOOKMARK_ACTIVE); }
public static Image getBookmarkActiveIcon() { return getIcon(BOOKMARK_ACTIVE); } public static Image getBookmarkActiveImage() {
return getImage(BOOKMARK_ACTIVE);
}
public static Image getBookmarkActiveIcon() {
return getIcon(BOOKMARK_ACTIVE);
}
private static Image getImage(String res) { private static Image getImage(String res) {
@@ -307,7 +732,7 @@ public class DefaultIcons {
Image img = ImageIO.read(DefaultIcons.class.getResourceAsStream(res)); Image img = ImageIO.read(DefaultIcons.class.getResourceAsStream(res));
imageCache.put(res, img); imageCache.put(res, img);
} catch (IOException e) { } catch (IOException e) {
Notification.addError("Failed to load image "+res); Notification.addError("Failed to load image " + res);
e.printStackTrace(); e.printStackTrace();
} }
} }
@@ -316,7 +741,7 @@ public class DefaultIcons {
private static Image getIcon(String res) { private static Image getIcon(String res) {
if (iconCache.get(res) == null) { if (iconCache.get(res) == null) {
Image icon = getImage(res).getScaledInstance((int)(16*ATContentStudio.SCALING), (int)(16*ATContentStudio.SCALING), Image.SCALE_SMOOTH); Image icon = getImage(res).getScaledInstance((int) (16 * ATContentStudio.SCALING), (int) (16 * ATContentStudio.SCALING), Image.SCALE_SMOOTH);
iconCache.put(res, icon); iconCache.put(res, icon);
} }
return iconCache.get(res); return iconCache.get(res);

View File

@@ -1,78 +1,40 @@
package com.gpl.rpg.atcontentstudio.ui; package com.gpl.rpg.atcontentstudio.ui;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.regex.Matcher;
import javax.swing.AbstractListModel;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultListCellRenderer;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.JSpinner.NumberEditor;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ListModel;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import javax.swing.text.DefaultFormatter;
import javax.swing.text.JTextComponent;
import com.gpl.rpg.atcontentstudio.ATContentStudio; import com.gpl.rpg.atcontentstudio.ATContentStudio;
import com.gpl.rpg.atcontentstudio.Notification; import com.gpl.rpg.atcontentstudio.Notification;
import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.GameDataElement;
import com.gpl.rpg.atcontentstudio.model.Project; import com.gpl.rpg.atcontentstudio.model.Project;
import com.gpl.rpg.atcontentstudio.model.ProjectElementListener; import com.gpl.rpg.atcontentstudio.model.ProjectElementListener;
import com.gpl.rpg.atcontentstudio.model.Workspace; import com.gpl.rpg.atcontentstudio.model.Workspace;
import com.gpl.rpg.atcontentstudio.model.gamedata.ActorCondition; import com.gpl.rpg.atcontentstudio.model.gamedata.*;
import com.gpl.rpg.atcontentstudio.model.gamedata.Dialogue;
import com.gpl.rpg.atcontentstudio.model.gamedata.Droplist;
import com.gpl.rpg.atcontentstudio.model.gamedata.Item;
import com.gpl.rpg.atcontentstudio.model.gamedata.ItemCategory;
import com.gpl.rpg.atcontentstudio.model.gamedata.JSONElement;
import com.gpl.rpg.atcontentstudio.model.gamedata.NPC;
import com.gpl.rpg.atcontentstudio.model.gamedata.Quest;
import com.gpl.rpg.atcontentstudio.model.gamedata.QuestStage;
import com.gpl.rpg.atcontentstudio.model.maps.TMXMap; import com.gpl.rpg.atcontentstudio.model.maps.TMXMap;
import com.gpl.rpg.atcontentstudio.utils.WeblateIntegration; import com.gpl.rpg.atcontentstudio.utils.WeblateIntegration;
import com.jidesoft.swing.ComboBoxSearchable; import com.jidesoft.swing.ComboBoxSearchable;
import com.jidesoft.swing.JideBoxLayout; import com.jidesoft.swing.JideBoxLayout;
import javax.swing.*;
import javax.swing.JSpinner.NumberEditor;
import javax.swing.event.*;
import javax.swing.text.DefaultFormatter;
import javax.swing.text.JTextComponent;
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.regex.Matcher;
public abstract class Editor extends JPanel implements ProjectElementListener { public abstract class Editor extends JPanel implements ProjectElementListener {
private static final long serialVersionUID = 241750514033596878L; private static final long serialVersionUID = 241750514033596878L;
private static final FieldUpdateListener nullListener = new FieldUpdateListener() {@Override public void valueChanged(JComponent source, Object value) {}}; private static final FieldUpdateListener nullListener = new FieldUpdateListener() {
@Override
public void valueChanged(JComponent source, Object value) {
}
};
public static final String SAVE = "Save"; public static final String SAVE = "Save";
public static final String DELETE = "Delete"; public static final String DELETE = "Delete";
@@ -117,7 +79,8 @@ public abstract class Editor extends JPanel implements ProjectElementListener {
return addTextField(pane, label, value, false, nullListener); return addTextField(pane, label, value, false, nullListener);
} }
public static void addTranslationPane(JPanel pane, final JTextComponent tfComponent, final String initialValue) {if (Workspace.activeWorkspace.settings.translatorLanguage.getCurrentValue() != null) { public static void addTranslationPane(JPanel pane, final JTextComponent tfComponent, final String initialValue) {
if (Workspace.activeWorkspace.settings.translatorLanguage.getCurrentValue() != null) {
JPanel labelPane = new JPanel(); JPanel labelPane = new JPanel();
labelPane.setLayout(new JideBoxLayout(labelPane, JideBoxLayout.LINE_AXIS, 6)); labelPane.setLayout(new JideBoxLayout(labelPane, JideBoxLayout.LINE_AXIS, 6));
final JLabel translateLinkLabel = new JLabel(getWeblateLabelLink(initialValue)); final JLabel translateLinkLabel = new JLabel(getWeblateLabelLink(initialValue));
@@ -161,7 +124,8 @@ public abstract class Editor extends JPanel implements ProjectElementListener {
break; break;
} }
translationStatus.setText(unit.translatedText); translationStatus.setText(unit.translatedText);
}; }
}.start(); }.start();
pane.add(labelPane, JideBoxLayout.FIX); pane.add(labelPane, JideBoxLayout.FIX);
tfComponent.getDocument().addDocumentListener(new DocumentListener() { tfComponent.getDocument().addDocumentListener(new DocumentListener() {
@@ -171,12 +135,14 @@ public abstract class Editor extends JPanel implements ProjectElementListener {
translateLinkLabel.revalidate(); translateLinkLabel.revalidate();
translateLinkLabel.repaint(); translateLinkLabel.repaint();
} }
@Override @Override
public void insertUpdate(DocumentEvent e) { public void insertUpdate(DocumentEvent e) {
translateLinkLabel.setText(getWeblateLabelLink(tfComponent.getText().replaceAll("\n", Matcher.quoteReplacement("\n")))); translateLinkLabel.setText(getWeblateLabelLink(tfComponent.getText().replaceAll("\n", Matcher.quoteReplacement("\n"))));
translateLinkLabel.revalidate(); translateLinkLabel.revalidate();
translateLinkLabel.repaint(); translateLinkLabel.repaint();
} }
@Override @Override
public void changedUpdate(DocumentEvent e) { public void changedUpdate(DocumentEvent e) {
translateLinkLabel.setText(getWeblateLabelLink(tfComponent.getText().replaceAll("\n", Matcher.quoteReplacement("\n")))); translateLinkLabel.setText(getWeblateLabelLink(tfComponent.getText().replaceAll("\n", Matcher.quoteReplacement("\n"))));
@@ -209,17 +175,34 @@ public abstract class Editor extends JPanel implements ProjectElementListener {
} }
public static String getWeblateLabelLink(String text) { public static String getWeblateLabelLink(String text) {
return "<html><a href=\""+WeblateIntegration.getWeblateLabelURI(text)+"\">Translate on weblate</a></html>"; return "<html><a href=\"" + WeblateIntegration.getWeblateLabelURI(text) + "\">Translate on weblate</a></html>";
} }
public static JTextField addTextField(JPanel pane, String label, String initialValue, boolean editable, final FieldUpdateListener listener) { public static JTextField addTextField(JPanel pane, String label, String initialValue, boolean editable, final FieldUpdateListener listener) {
final JTextField tfField = new JTextField(initialValue);
addTextComponent(pane, label, editable, listener, tfField, false, false);
tfField.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
listener.valueChanged(tfField, tfField.getText());
}
});
return tfField;
}
public static <T extends JTextComponent> T addTextComponent(JPanel pane, String label, boolean editable, final FieldUpdateListener listener, T tfField, boolean specialNewLinesHandling, boolean scrollable) {
JPanel tfPane = new JPanel(); JPanel tfPane = new JPanel();
tfPane.setLayout(new JideBoxLayout(tfPane, JideBoxLayout.LINE_AXIS, 6)); tfPane.setLayout(new JideBoxLayout(tfPane, JideBoxLayout.LINE_AXIS, 6));
JLabel tfLabel = new JLabel(label); JLabel tfLabel = new JLabel(label);
tfPane.add(tfLabel, JideBoxLayout.FIX); tfPane.add(tfLabel, JideBoxLayout.FIX);
final JTextField tfField = new JTextField(initialValue);
tfField.setEditable(editable); tfField.setEditable(editable);
tfPane.add(tfField, JideBoxLayout.VARY); JComponent component;
if (scrollable) {
component = new JScrollPane(tfField);
} else {
component = tfField;
}
tfPane.add(component, JideBoxLayout.VARY);
JButton nullify = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); JButton nullify = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon()));
tfPane.add(nullify, JideBoxLayout.FIX); tfPane.add(nullify, JideBoxLayout.FIX);
nullify.setEnabled(editable); nullify.setEnabled(editable);
@@ -235,21 +218,23 @@ public abstract class Editor extends JPanel implements ProjectElementListener {
tfField.getDocument().addDocumentListener(new DocumentListener() { tfField.getDocument().addDocumentListener(new DocumentListener() {
@Override @Override
public void removeUpdate(DocumentEvent e) { public void removeUpdate(DocumentEvent e) {
listener.valueChanged(tfField, tfField.getText()); String text = tfField.getText();
if (specialNewLinesHandling) text = text.replaceAll("\n", Matcher.quoteReplacement("\n"));
listener.valueChanged(tfField, text);
} }
@Override @Override
public void insertUpdate(DocumentEvent e) { public void insertUpdate(DocumentEvent e) {
listener.valueChanged(tfField, tfField.getText()); String text = tfField.getText();
if (specialNewLinesHandling) text = text.replaceAll("\n", Matcher.quoteReplacement("\n"));
listener.valueChanged(tfField, text);
} }
@Override @Override
public void changedUpdate(DocumentEvent e) { public void changedUpdate(DocumentEvent e) {
listener.valueChanged(tfField, tfField.getText()); String text = tfField.getText();
} if (specialNewLinesHandling) text = text.replaceAll("\n", Matcher.quoteReplacement("\n"));
}); listener.valueChanged(tfField, text);
tfField.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
listener.valueChanged(tfField, tfField.getText());
} }
}); });
return tfField; return tfField;
@@ -263,50 +248,13 @@ public abstract class Editor extends JPanel implements ProjectElementListener {
} }
public static JTextArea addTextArea(JPanel pane, String label, String initialValue, boolean editable, final FieldUpdateListener listener) { public static JTextArea addTextArea(JPanel pane, String label, String initialValue, boolean editable, final FieldUpdateListener listener) {
String text= initialValue == null ? "" : initialValue.replaceAll("\\n", "\n"); String text = initialValue == null ? "" : initialValue.replaceAll("\\n", "\n");
JPanel tfPane = new JPanel();
tfPane.setLayout(new JideBoxLayout(tfPane, JideBoxLayout.LINE_AXIS, 6));
JLabel tfLabel = new JLabel(label);
tfPane.add(tfLabel, JideBoxLayout.FIX);
final JTextArea tfArea = new JTextArea(text); final JTextArea tfArea = new JTextArea(text);
tfArea.setEditable(editable);
tfArea.setRows(2); tfArea.setRows(2);
tfArea.setLineWrap(true); tfArea.setLineWrap(true);
tfArea.setWrapStyleWord(true); tfArea.setWrapStyleWord(true);
tfPane.add(new JScrollPane(tfArea), JideBoxLayout.VARY);
JButton nullify = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon()));
tfPane.add(nullify, JideBoxLayout.FIX);
nullify.setEnabled(editable);
pane.add(tfPane, JideBoxLayout.FIX);
nullify.addActionListener(new ActionListener() { addTextComponent(pane, label, editable, listener, tfArea, true, true);
@Override
public void actionPerformed(ActionEvent e) {
tfArea.setText("");
listener.valueChanged(tfArea, null);
}
});
tfArea.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void removeUpdate(DocumentEvent e) {
listener.valueChanged(tfArea, tfArea.getText().replaceAll("\n", Matcher.quoteReplacement("\n")));
}
@Override
public void insertUpdate(DocumentEvent e) {
listener.valueChanged(tfArea, tfArea.getText().replaceAll("\n", Matcher.quoteReplacement("\n")));
}
@Override
public void changedUpdate(DocumentEvent e) {
listener.valueChanged(tfArea, tfArea.getText().replaceAll("\n", Matcher.quoteReplacement("\n")));
}
});
// tfArea.addActionListener(new ActionListener() {
// @Override
// public void actionPerformed(ActionEvent e) {
// listener.valueChanged(tfArea, tfArea.getText().replaceAll("\n", "\\n"));
// }
// });
return tfArea; return tfArea;
} }
@@ -318,49 +266,63 @@ public abstract class Editor extends JPanel implements ProjectElementListener {
return addIntegerField(pane, label, initialValue, 0, allowNegatives, editable, listener); return addIntegerField(pane, label, initialValue, 0, allowNegatives, editable, listener);
} }
public static JSpinner addIntegerField(JPanel pane, String label, Integer initialValue, Integer defaultValue, boolean allowNegatives, boolean editable, final FieldUpdateListener listener) { public static <T extends Number & Comparable<T>> JSpinner addNumberField(JPanel pane, String label, boolean editable, final FieldUpdateListener listener, T minimum, T maximum, Number stepSize, T value, T defaultValue) {
JPanel tfPane = new JPanel(); JPanel tfPane = new JPanel();
tfPane.setLayout(new JideBoxLayout(tfPane, JideBoxLayout.LINE_AXIS, 6)); tfPane.setLayout(new JideBoxLayout(tfPane, JideBoxLayout.LINE_AXIS, 6));
JLabel tfLabel = new JLabel(label); JLabel tfLabel = new JLabel(label);
tfPane.add(tfLabel, JideBoxLayout.FIX); tfPane.add(tfLabel, JideBoxLayout.FIX);
final JSpinner spinner = new JSpinner(new SpinnerNumberModel(initialValue != null ? initialValue.intValue() : defaultValue.intValue(), allowNegatives ? Integer.MIN_VALUE : 0, Integer.MAX_VALUE, 1)); if (!(((minimum == null) || (minimum.compareTo(value) <= 0)) &&
((JSpinner.DefaultEditor)spinner.getEditor()).getTextField().setHorizontalAlignment(JTextField.LEFT); ((maximum == null) || (maximum.compareTo(value) >= 0)))) {
System.err.printf("Value for number field outside of range: %s <= %s <= %s is false%n", minimum, value, maximum);
value = defaultValue;
}
final JSpinner spinner = new JSpinner(new SpinnerNumberModel(value, minimum, maximum, stepSize));
((JSpinner.DefaultEditor) spinner.getEditor()).getTextField().setHorizontalAlignment(JTextField.LEFT);
spinner.setEnabled(editable); spinner.setEnabled(editable);
((DefaultFormatter)((NumberEditor)spinner.getEditor()).getTextField().getFormatter()).setCommitsOnValidEdit(true); ((DefaultFormatter) ((NumberEditor) spinner.getEditor()).getTextField().getFormatter()).setCommitsOnValidEdit(true);
tfPane.add(spinner, JideBoxLayout.VARY); tfPane.add(spinner, JideBoxLayout.VARY);
JButton nullify = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); JButton nullify = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon()));
tfPane.add(nullify, JideBoxLayout.FIX); tfPane.add(nullify, JideBoxLayout.FIX);
nullify.setEnabled(editable); nullify.setEnabled(editable);
pane.add(tfPane, JideBoxLayout.FIX); pane.add(tfPane, JideBoxLayout.FIX);
spinner.addChangeListener(new ChangeListener() { spinner.addChangeListener(e -> listener.valueChanged(spinner, spinner.getValue()));
@Override nullify.addActionListener(e -> {
public void stateChanged(ChangeEvent e) {
listener.valueChanged(spinner, spinner.getValue());
}
});
nullify.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
spinner.setValue(0); spinner.setValue(0);
listener.valueChanged(spinner, null); listener.valueChanged(spinner, null);
}
}); });
return spinner; return spinner;
} }
public static JSpinner addIntegerField(JPanel pane, String label, Integer initialValue, Integer defaultValue, boolean allowNegatives, boolean editable, final FieldUpdateListener listener) {
int value = initialValue != null ? initialValue : defaultValue;
int minimum = allowNegatives ? Integer.MIN_VALUE : 0;
int maximum = Integer.MAX_VALUE;
return addNumberField(pane, label, editable, listener, minimum, maximum, 1, value, defaultValue);
}
private static final String percent = "%"; private static final String percent = "%";
private static final String ratio = "x/y"; private static final String ratio = "x/y";
public static JComponent addChanceField(JPanel pane, String label, String initialValue, String defaultValue, boolean editable, final FieldUpdateListener listener) { public static JComponent addChanceField(JPanel pane, String label, String initialValue, String defaultValue, boolean editable, final FieldUpdateListener listener) {
int defaultChance = 1; int defaultChance = 1;
int defaultMaxChance = 100; int defaultMaxChance = 100;
if (defaultValue != null) { if (defaultValue != null) {
if (defaultValue.contains("/")) { if (defaultValue.contains("/")) {
int c = defaultValue.indexOf('/'); int c = defaultValue.indexOf('/');
try { defaultChance = Integer.parseInt(defaultValue.substring(0, c)); } catch (NumberFormatException nfe) {}; try {
try { defaultMaxChance = Integer.parseInt(defaultValue.substring(c+1)); } catch (NumberFormatException nfe) {}; defaultChance = Integer.parseInt(defaultValue.substring(0, c));
} catch (NumberFormatException nfe) {
}
try {
defaultMaxChance = Integer.parseInt(defaultValue.substring(c + 1));
} catch (NumberFormatException nfe) {
}
} else { } else {
try { defaultChance = Integer.parseInt(defaultValue); } catch (NumberFormatException nfe) {}; try {
defaultChance = Integer.parseInt(defaultValue);
} catch (NumberFormatException nfe) {
}
} }
} }
@@ -370,13 +332,20 @@ public abstract class Editor extends JPanel implements ProjectElementListener {
if (initialValue != null) { if (initialValue != null) {
if (initialValue.contains("/")) { if (initialValue.contains("/")) {
int c = initialValue.indexOf('/'); int c = initialValue.indexOf('/');
try { chance = Integer.parseInt(initialValue.substring(0, c)); } catch (NumberFormatException nfe) {}; try {
try { maxChance = Integer.parseInt(initialValue.substring(c+1)); } catch (NumberFormatException nfe) {}; chance = Integer.parseInt(initialValue.substring(0, c));
} catch (NumberFormatException nfe) {
}
try {
maxChance = Integer.parseInt(initialValue.substring(c + 1));
} catch (NumberFormatException nfe) {
}
} else { } else {
try { try {
chance = Integer.parseInt(initialValue); chance = Integer.parseInt(initialValue);
currentFormIsRatio = false; currentFormIsRatio = false;
} catch (NumberFormatException nfe) {}; } catch (NumberFormatException nfe) {
}
} }
} }
@@ -385,7 +354,7 @@ public abstract class Editor extends JPanel implements ProjectElementListener {
JLabel tfLabel = new JLabel(label); JLabel tfLabel = new JLabel(label);
tfPane.add(tfLabel, JideBoxLayout.FIX); tfPane.add(tfLabel, JideBoxLayout.FIX);
final JComboBox<String> entryTypeBox = new JComboBox<String>(new String[] {percent, ratio}); final JComboBox<String> entryTypeBox = new JComboBox<String>(new String[]{percent, ratio});
if (currentFormIsRatio) { if (currentFormIsRatio) {
entryTypeBox.setSelectedItem(ratio); entryTypeBox.setSelectedItem(ratio);
} else { } else {
@@ -394,22 +363,26 @@ public abstract class Editor extends JPanel implements ProjectElementListener {
entryTypeBox.setEnabled(editable); entryTypeBox.setEnabled(editable);
tfPane.add(entryTypeBox, JideBoxLayout.FIX); tfPane.add(entryTypeBox, JideBoxLayout.FIX);
/////////////////////////////////////////////////////////////////////////////////////////////////// make sure "chance" is between 1 and 100. If lower than 1 get 1. If higher than 100, get chance/maxChance * 100... Then do the same with defaultChance, in case no value exist. /////////////////////////////////////////////////////////////////////////////////////////////////// make sure "chance" is between 1 and 100. If lower than 1 get 1. If higher than 100, get chance/maxChance * 100... Then do the same with defaultChance, in case no value exist.
final SpinnerNumberModel percentModel = new SpinnerNumberModel(initialValue != null ? ((chance > 1 ? chance : 1) < 100 ? chance : (chance * 100 / maxChance)) : ((defaultChance > 1 ? defaultChance : 1) < 100 ? defaultChance : (defaultChance * 100 / defaultMaxChance)) , 1, 100, 1); final SpinnerNumberModel percentModel = new SpinnerNumberModel(
initialValue != null ? ((chance > 1 ? chance : 1) < 100 ? chance : (chance * 100 / maxChance)) : ((defaultChance > 1 ? defaultChance : 1) < 100 ? defaultChance : (defaultChance * 100 /
defaultMaxChance)),
1, 100, 1);
final SpinnerNumberModel ratioChanceModel = new SpinnerNumberModel(initialValue != null ? chance : defaultChance, 1, Integer.MAX_VALUE, 1); final SpinnerNumberModel ratioChanceModel = new SpinnerNumberModel(initialValue != null ? chance : defaultChance, 1, Integer.MAX_VALUE, 1);
final JSpinner chanceSpinner = new JSpinner(currentFormIsRatio ? ratioChanceModel : percentModel); final JSpinner chanceSpinner = new JSpinner(currentFormIsRatio ? ratioChanceModel : percentModel);
if (!currentFormIsRatio) ((JSpinner.DefaultEditor)chanceSpinner.getEditor()).getTextField().setHorizontalAlignment(JTextField.LEFT); if (!currentFormIsRatio)
((JSpinner.DefaultEditor) chanceSpinner.getEditor()).getTextField().setHorizontalAlignment(JTextField.LEFT);
chanceSpinner.setEnabled(editable); chanceSpinner.setEnabled(editable);
((DefaultFormatter)((NumberEditor)chanceSpinner.getEditor()).getTextField().getFormatter()).setCommitsOnValidEdit(true); ((DefaultFormatter) ((NumberEditor) chanceSpinner.getEditor()).getTextField().getFormatter()).setCommitsOnValidEdit(true);
tfPane.add(chanceSpinner, JideBoxLayout.FLEXIBLE); tfPane.add(chanceSpinner, JideBoxLayout.FLEXIBLE);
final JLabel ratioLabel = new JLabel("/"); final JLabel ratioLabel = new JLabel("/");
tfPane.add(ratioLabel, JideBoxLayout.FIX); tfPane.add(ratioLabel, JideBoxLayout.FIX);
final JSpinner maxChanceSpinner = new JSpinner(new SpinnerNumberModel(initialValue != null ? maxChance : defaultMaxChance, 1, Integer.MAX_VALUE, 1)); final JSpinner maxChanceSpinner = new JSpinner(new SpinnerNumberModel(initialValue != null ? maxChance : defaultMaxChance, 1, Integer.MAX_VALUE, 1));
((JSpinner.DefaultEditor)maxChanceSpinner.getEditor()).getTextField().setHorizontalAlignment(JTextField.LEFT); ((JSpinner.DefaultEditor) maxChanceSpinner.getEditor()).getTextField().setHorizontalAlignment(JTextField.LEFT);
maxChanceSpinner.setEnabled(editable); maxChanceSpinner.setEnabled(editable);
((DefaultFormatter)((NumberEditor)maxChanceSpinner.getEditor()).getTextField().getFormatter()).setCommitsOnValidEdit(true); ((DefaultFormatter) ((NumberEditor) maxChanceSpinner.getEditor()).getTextField().getFormatter()).setCommitsOnValidEdit(true);
tfPane.add(maxChanceSpinner, JideBoxLayout.FLEXIBLE); tfPane.add(maxChanceSpinner, JideBoxLayout.FLEXIBLE);
if (!currentFormIsRatio) { if (!currentFormIsRatio) {
@@ -428,21 +401,21 @@ public abstract class Editor extends JPanel implements ProjectElementListener {
@Override @Override
public void actionPerformed(ActionEvent e) { public void actionPerformed(ActionEvent e) {
if (entryTypeBox.getSelectedItem() == percent) { if (entryTypeBox.getSelectedItem() == percent) {
int chance = ((Integer)chanceSpinner.getValue()); int chance = ((Integer) chanceSpinner.getValue());
int maxChance = ((Integer)maxChanceSpinner.getValue()); int maxChance = ((Integer) maxChanceSpinner.getValue());
chance *= 100; chance *= 100;
chance /= maxChance; chance /= maxChance;
chance = Math.max(0, Math.min(100, chance)); chance = Math.max(0, Math.min(100, chance));
chanceSpinner.setModel(percentModel); chanceSpinner.setModel(percentModel);
chanceSpinner.setValue(chance); chanceSpinner.setValue(chance);
((JSpinner.DefaultEditor)chanceSpinner.getEditor()).getTextField().setHorizontalAlignment(JTextField.LEFT); ((JSpinner.DefaultEditor) chanceSpinner.getEditor()).getTextField().setHorizontalAlignment(JTextField.LEFT);
ratioLabel.setVisible(false); ratioLabel.setVisible(false);
maxChanceSpinner.setVisible(false); maxChanceSpinner.setVisible(false);
tfPane.revalidate(); tfPane.revalidate();
tfPane.repaint(); tfPane.repaint();
listener.valueChanged(chanceSpinner, chanceSpinner.getValue().toString()); listener.valueChanged(chanceSpinner, chanceSpinner.getValue().toString());
} else if (entryTypeBox.getSelectedItem() == ratio) { } else if (entryTypeBox.getSelectedItem() == ratio) {
int chance = ((Integer)chanceSpinner.getValue()); int chance = ((Integer) chanceSpinner.getValue());
chanceSpinner.setModel(ratioChanceModel); chanceSpinner.setModel(ratioChanceModel);
chanceSpinner.setValue(chance); chanceSpinner.setValue(chance);
maxChanceSpinner.setValue(100); maxChanceSpinner.setValue(100);
@@ -485,34 +458,11 @@ public abstract class Editor extends JPanel implements ProjectElementListener {
// } // }
public static JSpinner addDoubleField(JPanel pane, String label, Double initialValue, boolean editable, final FieldUpdateListener listener) { public static JSpinner addDoubleField(JPanel pane, String label, Double initialValue, boolean editable, final FieldUpdateListener listener) {
JPanel tfPane = new JPanel(); double minimum = 0.0d;
tfPane.setLayout(new JideBoxLayout(tfPane, JideBoxLayout.LINE_AXIS, 6)); double defaultValue = 0.0d;
JLabel tfLabel = new JLabel(label); double value = initialValue != null ? initialValue : minimum;
tfPane.add(tfLabel, JideBoxLayout.FIX); double maximum = Float.valueOf(Float.MAX_VALUE).doubleValue();
final JSpinner spinner = new JSpinner(new SpinnerNumberModel(initialValue != null ? initialValue.doubleValue() : 0.0d, 0.0d, new Float(Float.MAX_VALUE).doubleValue(), 1.0d)); return addNumberField(pane, label, editable, listener, minimum, maximum, 1.0d, value, defaultValue);
((JSpinner.DefaultEditor)spinner.getEditor()).getTextField().setHorizontalAlignment(JTextField.LEFT);
spinner.setEnabled(editable);
((DefaultFormatter)((NumberEditor)spinner.getEditor()).getTextField().getFormatter()).setCommitsOnValidEdit(true);
tfPane.add(spinner, JideBoxLayout.VARY);
JButton nullify = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon()));
tfPane.add(nullify, JideBoxLayout.FIX);
nullify.setEnabled(editable);
pane.add(tfPane, JideBoxLayout.FIX);
pane.add(tfPane, JideBoxLayout.FIX);
spinner.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
listener.valueChanged(spinner, spinner.getValue());
}
});
nullify.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
spinner.setValue(0.0d);
listener.valueChanged(spinner, null);
}
});
return spinner;
} }
public static IntegerBasedCheckBox addIntegerBasedCheckBox(JPanel pane, String label, Integer initialValue, boolean editable) { public static IntegerBasedCheckBox addIntegerBasedCheckBox(JPanel pane, String label, Integer initialValue, boolean editable) {
@@ -559,7 +509,11 @@ public abstract class Editor extends JPanel implements ProjectElementListener {
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
public static JComboBox addEnumValueBox(JPanel pane, String label, Enum[] values, Enum initialValue, boolean writable) { public static JComboBox addEnumValueBox(JPanel pane, String label, Enum[] values, Enum initialValue, boolean writable) {
return addEnumValueBox(pane, label, values, initialValue, writable, new FieldUpdateListener() {@Override public void valueChanged(JComponent source, Object value) {}}); return addEnumValueBox(pane, label, values, initialValue, writable, new FieldUpdateListener() {
@Override
public void valueChanged(JComponent source, Object value) {
}
});
} }
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
@@ -568,8 +522,7 @@ public abstract class Editor extends JPanel implements ProjectElementListener {
comboPane.setLayout(new JideBoxLayout(comboPane, JideBoxLayout.LINE_AXIS, 6)); comboPane.setLayout(new JideBoxLayout(comboPane, JideBoxLayout.LINE_AXIS, 6));
JLabel comboLabel = new JLabel(label); JLabel comboLabel = new JLabel(label);
comboPane.add(comboLabel, JideBoxLayout.FIX); comboPane.add(comboLabel, JideBoxLayout.FIX);
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked") final JComboBox enumValuesCombo = new JComboBox(values);
final JComboBox enumValuesCombo = new JComboBox(values);
enumValuesCombo.setEnabled(writable); enumValuesCombo.setEnabled(writable);
enumValuesCombo.setSelectedItem(initialValue); enumValuesCombo.setSelectedItem(initialValue);
comboPane.add(enumValuesCombo, JideBoxLayout.VARY); comboPane.add(enumValuesCombo, JideBoxLayout.VARY);
@@ -598,120 +551,136 @@ public abstract class Editor extends JPanel implements ProjectElementListener {
public MyComboBox addNPCBox(JPanel pane, Project proj, String label, NPC npc, boolean writable, FieldUpdateListener listener) { public MyComboBox addNPCBox(JPanel pane, Project proj, String label, NPC npc, boolean writable, FieldUpdateListener listener) {
final GDEComboModel<NPC> comboModel = new GDEComboModel<NPC>(proj, npc){ final GDEComboModel<NPC> comboModel = new GDEComboModel<NPC>(proj, npc) {
private static final long serialVersionUID = 2638082961277241764L; private static final long serialVersionUID = 2638082961277241764L;
@Override @Override
public NPC getTypedElementAt(int index) { public NPC getTypedElementAt(int index) {
return project.getNPC(index); return project.getNPC(index);
} }
@Override @Override
public int getSize() { public int getSize() {
return project.getNPCCount()+1; return project.getNPCCount() + 1;
} }
}; };
return addGDEBox(pane, label, npc, NPC.class, comboModel, writable, listener); return addGDEBox(pane, label, npc, NPC.class, comboModel, writable, listener);
} }
public MyComboBox addActorConditionBox(JPanel pane, Project proj, String label, ActorCondition acond, boolean writable, FieldUpdateListener listener) { public MyComboBox addActorConditionBox(JPanel pane, Project proj, String label, ActorCondition acond, boolean writable, FieldUpdateListener listener) {
final GDEComboModel<ActorCondition> comboModel = new GDEComboModel<ActorCondition>(proj, acond){ final GDEComboModel<ActorCondition> comboModel = new GDEComboModel<ActorCondition>(proj, acond) {
private static final long serialVersionUID = 2638082961277241764L; private static final long serialVersionUID = 2638082961277241764L;
@Override @Override
public ActorCondition getTypedElementAt(int index) { public ActorCondition getTypedElementAt(int index) {
return project.getActorCondition(index); return project.getActorCondition(index);
} }
@Override @Override
public int getSize() { public int getSize() {
return project.getActorConditionCount()+1; return project.getActorConditionCount() + 1;
} }
}; };
return addGDEBox(pane, label, acond, ActorCondition.class, comboModel, writable, listener); return addGDEBox(pane, label, acond, ActorCondition.class, comboModel, writable, listener);
} }
public MyComboBox addItemBox(JPanel pane, Project proj, String label, Item item, boolean writable, FieldUpdateListener listener) { public MyComboBox addItemBox(JPanel pane, Project proj, String label, Item item, boolean writable, FieldUpdateListener listener) {
final GDEComboModel<Item> comboModel = new GDEComboModel<Item>(proj, item){ final GDEComboModel<Item> comboModel = new GDEComboModel<Item>(proj, item) {
private static final long serialVersionUID = 2638082961277241764L; private static final long serialVersionUID = 2638082961277241764L;
@Override @Override
public Item getTypedElementAt(int index) { public Item getTypedElementAt(int index) {
return project.getItem(index); return project.getItem(index);
} }
@Override @Override
public int getSize() { public int getSize() {
return project.getItemCount()+1; return project.getItemCount() + 1;
} }
}; };
return addGDEBox(pane, label, item, Item.class, comboModel, writable, listener); return addGDEBox(pane, label, item, Item.class, comboModel, writable, listener);
} }
public MyComboBox addItemCategoryBox(JPanel pane, Project proj, String label, ItemCategory ic, boolean writable, FieldUpdateListener listener) { public MyComboBox addItemCategoryBox(JPanel pane, Project proj, String label, ItemCategory ic, boolean writable, FieldUpdateListener listener) {
final GDEComboModel<ItemCategory> comboModel = new GDEComboModel<ItemCategory>(proj, ic){ final GDEComboModel<ItemCategory> comboModel = new GDEComboModel<ItemCategory>(proj, ic) {
private static final long serialVersionUID = 2638082961277241764L; private static final long serialVersionUID = 2638082961277241764L;
@Override @Override
public ItemCategory getTypedElementAt(int index) { public ItemCategory getTypedElementAt(int index) {
return project.getItemCategory(index); return project.getItemCategory(index);
} }
@Override @Override
public int getSize() { public int getSize() {
return project.getItemCategoryCount()+1; return project.getItemCategoryCount() + 1;
} }
}; };
return addGDEBox(pane, label, ic, ItemCategory.class, comboModel, writable, listener); return addGDEBox(pane, label, ic, ItemCategory.class, comboModel, writable, listener);
} }
public MyComboBox addQuestBox(JPanel pane, Project proj, String label, Quest quest, boolean writable, FieldUpdateListener listener) { public MyComboBox addQuestBox(JPanel pane, Project proj, String label, Quest quest, boolean writable, FieldUpdateListener listener) {
final GDEComboModel<Quest> comboModel = new GDEComboModel<Quest>(proj, quest){ final GDEComboModel<Quest> comboModel = new GDEComboModel<Quest>(proj, quest) {
private static final long serialVersionUID = 2638082961277241764L; private static final long serialVersionUID = 2638082961277241764L;
@Override @Override
public Quest getTypedElementAt(int index) { public Quest getTypedElementAt(int index) {
return project.getQuest(index); return project.getQuest(index);
} }
@Override @Override
public int getSize() { public int getSize() {
return project.getQuestCount()+1; return project.getQuestCount() + 1;
} }
}; };
return addGDEBox(pane, label, quest, Quest.class, comboModel, writable, listener); return addGDEBox(pane, label, quest, Quest.class, comboModel, writable, listener);
} }
public MyComboBox addDroplistBox(JPanel pane, Project proj, String label, Droplist droplist, boolean writable, FieldUpdateListener listener) { public MyComboBox addDroplistBox(JPanel pane, Project proj, String label, Droplist droplist, boolean writable, FieldUpdateListener listener) {
final GDEComboModel<Droplist> comboModel = new GDEComboModel<Droplist>(proj, droplist){ final GDEComboModel<Droplist> comboModel = new GDEComboModel<Droplist>(proj, droplist) {
private static final long serialVersionUID = 2638082961277241764L; private static final long serialVersionUID = 2638082961277241764L;
@Override @Override
public Droplist getTypedElementAt(int index) { public Droplist getTypedElementAt(int index) {
return project.getDroplist(index); return project.getDroplist(index);
} }
@Override @Override
public int getSize() { public int getSize() {
return project.getDroplistCount()+1; return project.getDroplistCount() + 1;
} }
}; };
return addGDEBox(pane, label, droplist, Droplist.class, comboModel, writable, listener); return addGDEBox(pane, label, droplist, Droplist.class, comboModel, writable, listener);
} }
public MyComboBox addDialogueBox(JPanel pane, Project proj, String label, Dialogue dialogue, boolean writable, final FieldUpdateListener listener) { public MyComboBox addDialogueBox(JPanel pane, Project proj, String label, Dialogue dialogue, boolean writable, final FieldUpdateListener listener) {
final GDEComboModel<Dialogue> comboModel = new GDEComboModel<Dialogue>(proj, dialogue){ final GDEComboModel<Dialogue> comboModel = new GDEComboModel<Dialogue>(proj, dialogue) {
private static final long serialVersionUID = 2638082961277241764L; private static final long serialVersionUID = 2638082961277241764L;
@Override @Override
public Dialogue getTypedElementAt(int index) { public Dialogue getTypedElementAt(int index) {
return project.getDialogue(index); return project.getDialogue(index);
} }
@Override @Override
public int getSize() { public int getSize() {
return project.getDialogueCount()+1; return project.getDialogueCount() + 1;
} }
}; };
return addGDEBox(pane, label, dialogue, Dialogue.class, comboModel, writable, listener); return addGDEBox(pane, label, dialogue, Dialogue.class, comboModel, writable, listener);
} }
public MyComboBox addMapBox(JPanel pane, Project proj, String label, TMXMap map, boolean writable, final FieldUpdateListener listener) { public MyComboBox addMapBox(JPanel pane, Project proj, String label, TMXMap map, boolean writable, final FieldUpdateListener listener) {
final GDEComboModel<TMXMap> comboModel = new GDEComboModel<TMXMap>(proj, map){ final GDEComboModel<TMXMap> comboModel = new GDEComboModel<TMXMap>(proj, map) {
private static final long serialVersionUID = 2638082961277241764L; private static final long serialVersionUID = 2638082961277241764L;
@Override @Override
public TMXMap getTypedElementAt(int index) { public TMXMap getTypedElementAt(int index) {
return project.getMap(index); return project.getMap(index);
} }
@Override @Override
public int getSize() { public int getSize() {
return project.getMapCount()+1; return project.getMapCount() + 1;
} }
}; };
return addGDEBox(pane, label, map, TMXMap.class, comboModel, writable, listener); return addGDEBox(pane, label, map, TMXMap.class, comboModel, writable, listener);
@@ -725,11 +694,11 @@ public abstract class Editor extends JPanel implements ProjectElementListener {
gdePane.add(gdeLabel, JideBoxLayout.FIX); gdePane.add(gdeLabel, JideBoxLayout.FIX);
final MyComboBox gdeBox = new MyComboBox(dataClass, comboModel); final MyComboBox gdeBox = new MyComboBox(dataClass, comboModel);
gdeBox.setRenderer(new GDERenderer(false, writable)); gdeBox.setRenderer(new GDERenderer(false, writable));
new ComboBoxSearchable(gdeBox){ new ComboBoxSearchable(gdeBox) {
@Override @Override
protected String convertElementToString(Object object) { protected String convertElementToString(Object object) {
if (object == null) return "none"; if (object == null) return "none";
else return ((GameDataElement)object).getDesc(); else return ((GameDataElement) object).getDesc();
} }
}; };
gdeBox.setEnabled(writable); gdeBox.setEnabled(writable);
@@ -739,12 +708,12 @@ public abstract class Editor extends JPanel implements ProjectElementListener {
goToGde.addActionListener(new ActionListener() { goToGde.addActionListener(new ActionListener() {
@Override @Override
public void actionPerformed(ActionEvent e) { public void actionPerformed(ActionEvent e) {
GameDataElement selected = ((GameDataElement)comboModel.getSelectedItem()); GameDataElement selected = ((GameDataElement) comboModel.getSelectedItem());
if (selected != null) { if (selected != null) {
ATContentStudio.frame.openEditor(((GameDataElement)comboModel.getSelectedItem())); ATContentStudio.frame.openEditor(((GameDataElement) comboModel.getSelectedItem()));
ATContentStudio.frame.selectInTree((GameDataElement)comboModel.getSelectedItem()); ATContentStudio.frame.selectInTree((GameDataElement) comboModel.getSelectedItem());
} else if (writable) { } else if (writable) {
JSONCreationWizard wizard = new JSONCreationWizard(((GameDataElement)target).getProject(), dataClass); JSONCreationWizard wizard = new JSONCreationWizard(((GameDataElement) target).getProject(), dataClass);
wizard.addCreationListener(new JSONCreationWizard.CreationCompletedListener() { wizard.addCreationListener(new JSONCreationWizard.CreationCompletedListener() {
@Override @Override
@@ -764,7 +733,7 @@ public abstract class Editor extends JPanel implements ProjectElementListener {
goToGde.setIcon((writable ? new ImageIcon(DefaultIcons.getCreateIcon()) : null)); goToGde.setIcon((writable ? new ImageIcon(DefaultIcons.getCreateIcon()) : null));
goToGde.setEnabled(writable); goToGde.setEnabled(writable);
} else { } else {
goToGde.setIcon(new ImageIcon(((GameDataElement)comboModel.getSelectedItem()).getIcon())); goToGde.setIcon(new ImageIcon(((GameDataElement) comboModel.getSelectedItem()).getIcon()));
goToGde.setEnabled(true); goToGde.setEnabled(true);
} }
listener.valueChanged(gdeBox, gdeBox.getModel().getSelectedItem()); listener.valueChanged(gdeBox, gdeBox.getModel().getSelectedItem());
@@ -797,11 +766,11 @@ public abstract class Editor extends JPanel implements ProjectElementListener {
final QuestStageComboModel comboModel = new QuestStageComboModel(proj, initial, quest); final QuestStageComboModel comboModel = new QuestStageComboModel(proj, initial, quest);
final JComboBox<QuestStage> combo = new JComboBox<QuestStage>(comboModel); final JComboBox<QuestStage> combo = new JComboBox<QuestStage>(comboModel);
combo.setRenderer(new GDERenderer(false, writable)); combo.setRenderer(new GDERenderer(false, writable));
new ComboBoxSearchable(combo){ new ComboBoxSearchable(combo) {
@Override @Override
protected String convertElementToString(Object object) { protected String convertElementToString(Object object) {
if (object == null) return "none"; if (object == null) return "none";
else return ((GameDataElement)object).getDesc(); else return ((GameDataElement) object).getDesc();
} }
}; };
questSelectionBox.addActionListener(new ActionListener() { questSelectionBox.addActionListener(new ActionListener() {
@@ -823,7 +792,6 @@ public abstract class Editor extends JPanel implements ProjectElementListener {
}); });
combo.setEnabled(writable); combo.setEnabled(writable);
gdePane.add(combo, JideBoxLayout.VARY); gdePane.add(combo, JideBoxLayout.VARY);
@@ -833,21 +801,20 @@ public abstract class Editor extends JPanel implements ProjectElementListener {
} }
@SuppressWarnings({"rawtypes"})
@SuppressWarnings({ "rawtypes"})
public JList addBacklinksList(JPanel pane, GameDataElement gde) { public JList addBacklinksList(JPanel pane, GameDataElement gde) {
return addBacklinksList(pane, gde, "Elements linking to this one"); return addBacklinksList(pane, gde, "Elements linking to this one");
} }
@SuppressWarnings({ "rawtypes", "unchecked" }) @SuppressWarnings({"rawtypes", "unchecked"})
public JList addBacklinksList(JPanel pane, GameDataElement gde, String title) { public JList addBacklinksList(JPanel pane, GameDataElement gde, String title) {
final JList list = new JList(new GDEBacklinksListModel(gde)); final JList list = new JList(new GDEBacklinksListModel(gde));
list.addMouseListener(new MouseAdapter() { list.addMouseListener(new MouseAdapter() {
@Override @Override
public void mouseClicked(MouseEvent e) { public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) { if (e.getClickCount() == 2) {
ATContentStudio.frame.openEditor((GameDataElement)list.getSelectedValue()); ATContentStudio.frame.openEditor((GameDataElement) list.getSelectedValue());
ATContentStudio.frame.selectInTree((GameDataElement)list.getSelectedValue()); ATContentStudio.frame.selectInTree((GameDataElement) list.getSelectedValue());
} }
} }
}); });
@@ -855,8 +822,8 @@ public abstract class Editor extends JPanel implements ProjectElementListener {
@Override @Override
public void keyPressed(KeyEvent e) { public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) { if (e.getKeyCode() == KeyEvent.VK_ENTER) {
ATContentStudio.frame.openEditor((GameDataElement)list.getSelectedValue()); ATContentStudio.frame.openEditor((GameDataElement) list.getSelectedValue());
ATContentStudio.frame.selectInTree((GameDataElement)list.getSelectedValue()); ATContentStudio.frame.selectInTree((GameDataElement) list.getSelectedValue());
} }
} }
}); });
@@ -922,8 +889,8 @@ public abstract class Editor extends JPanel implements ProjectElementListener {
private static final long serialVersionUID = 6819681566800482793L; private static final long serialVersionUID = 6819681566800482793L;
private boolean includeType = false; private boolean includeType;
private boolean writable = false; private boolean writable;
public GDERenderer(boolean includeType, boolean writable) { public GDERenderer(boolean includeType, boolean writable) {
super(); super();
@@ -936,33 +903,33 @@ public abstract class Editor extends JPanel implements ProjectElementListener {
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (value == null) { if (value == null) {
label.setText("None"+(writable ? ". Click on the button to create one." : "")); label.setText("None" + (writable ? ". Click on the button to create one." : ""));
} else { } else {
if (includeType && ((GameDataElement)value).getDataType() != null) { if (includeType && ((GameDataElement) value).getDataType() != null) {
if (value instanceof QuestStage) { if (value instanceof QuestStage) {
String text = ((GameDataElement)value).getDesc(); String text = ((GameDataElement) value).getDesc();
if (text.length() > 60) { if (text.length() > 60) {
text = text.substring(0, 57)+"..."; text = text.substring(0, 57) + "...";
} }
label.setText(((GameDataElement)value).getDataType().toString()+"/"+((Quest)((QuestStage)value).parent).id+"#"+((QuestStage)value).progress+":"+text); label.setText(((GameDataElement) value).getDataType().toString() + "/" + ((Quest) ((QuestStage) value).parent).id + "#" + ((QuestStage) value).progress + ":" + text);
} else { } else {
label.setText(((GameDataElement)value).getDataType().toString()+"/"+((GameDataElement)value).getDesc()); label.setText(((GameDataElement) value).getDataType().toString() + "/" + ((GameDataElement) value).getDesc());
} }
} else { } else {
if (value instanceof QuestStage) { if (value instanceof QuestStage) {
String text = ((GameDataElement)value).getDesc(); String text = ((GameDataElement) value).getDesc();
if (text.length() > 60) { if (text.length() > 60) {
text = text.substring(0, 57)+"..."; text = text.substring(0, 57) + "...";
} }
label.setText(text); label.setText(text);
} else { } else {
label.setText(((GameDataElement)value).getDesc()); label.setText(((GameDataElement) value).getDesc());
} }
} }
if (((GameDataElement)value).getIcon() == null) { if (((GameDataElement) value).getIcon() == null) {
Notification.addError("Unable to find icon for "+((GameDataElement)value).getDesc()); Notification.addError("Unable to find icon for " + ((GameDataElement) value).getDesc());
} else { } else {
label.setIcon(new ImageIcon(((GameDataElement)value).getIcon())); label.setIcon(new ImageIcon(((GameDataElement) value).getIcon()));
} }
} }
return label; return label;
@@ -987,7 +954,7 @@ public abstract class Editor extends JPanel implements ProjectElementListener {
@Override @Override
public int getSize() { public int getSize() {
if (currentQuest == null) return 1; if (currentQuest == null) return 1;
return currentQuest.stages.size()+1; return currentQuest.stages.size() + 1;
} }
@Override @Override
@@ -1028,7 +995,7 @@ public abstract class Editor extends JPanel implements ProjectElementListener {
} }
public static class GDEBacklinksListModel implements ListModel<GameDataElement> { public static class GDEBacklinksListModel implements ListenerCollectionModel<GameDataElement> {
GameDataElement source; GameDataElement source;
@@ -1040,6 +1007,7 @@ public abstract class Editor extends JPanel implements ProjectElementListener {
public void backlinkRemoved(GameDataElement gde) { public void backlinkRemoved(GameDataElement gde) {
fireListChanged(); fireListChanged();
} }
@Override @Override
public void backlinkAdded(GameDataElement gde) { public void backlinkAdded(GameDataElement gde) {
fireListChanged(); fireListChanged();
@@ -1048,36 +1016,17 @@ public abstract class Editor extends JPanel implements ProjectElementListener {
} }
@Override @Override
public int getSize() { public Collection<GameDataElement> getElements() {
return source.getBacklinks().size(); return source.getBacklinks();
}
@Override
public GameDataElement getElementAt(int index) {
for (GameDataElement gde : source.getBacklinks()) {
if (index == 0) return gde;
index --;
}
return null;
} }
List<ListDataListener> listeners = new CopyOnWriteArrayList<ListDataListener>(); List<ListDataListener> listeners = new CopyOnWriteArrayList<ListDataListener>();
@Override @Override
public void addListDataListener(ListDataListener l) { public List<ListDataListener> getListeners() {
listeners.add(l); return listeners;
} }
@Override
public void removeListDataListener(ListDataListener l) {
listeners.remove(l);
}
public void fireListChanged() {
for (ListDataListener l : listeners) {
l.contentsChanged(new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, 0, this.getSize()));
}
}
} }
@SuppressWarnings({"rawtypes", "unchecked"}) @SuppressWarnings({"rawtypes", "unchecked"})
@@ -1095,12 +1044,12 @@ public abstract class Editor extends JPanel implements ProjectElementListener {
@Override @Override
public void elementAdded(GameDataElement added, int index) { public void elementAdded(GameDataElement added, int index) {
((GDEComboModel)getModel()).itemAdded(added, index); ((GDEComboModel) getModel()).itemAdded(added, index);
} }
@Override @Override
public void elementRemoved(GameDataElement removed, int index) { public void elementRemoved(GameDataElement removed, int index) {
((GDEComboModel)getModel()).itemRemoved(removed, index); ((GDEComboModel) getModel()).itemRemoved(removed, index);
} }
@Override @Override
@@ -1113,7 +1062,6 @@ public abstract class Editor extends JPanel implements ProjectElementListener {
public abstract void targetUpdated(); public abstract void targetUpdated();
transient Map<Class<? extends GameDataElement>, List<ProjectElementListener>> projectElementListeners = new HashMap<Class<? extends GameDataElement>, List<ProjectElementListener>>(); transient Map<Class<? extends GameDataElement>, List<ProjectElementListener>> projectElementListeners = new HashMap<Class<? extends GameDataElement>, List<ProjectElementListener>>();
public void addElementListener(Class<? extends GameDataElement> interestingType, ProjectElementListener listener) { public void addElementListener(Class<? extends GameDataElement> interestingType, ProjectElementListener listener) {
@@ -1162,4 +1110,21 @@ public abstract class Editor extends JPanel implements ProjectElementListener {
} }
public <E extends Common.ActorConditionEffect, T extends OrderedListenerListModel<?, E>> void updateConditionEffect(ActorCondition value,
GameDataElement backlink,
E selectedHitEffectTargetCondition,
T hitTargetConditionsModel) {
if (selectedHitEffectTargetCondition.condition != null) {
selectedHitEffectTargetCondition.condition.removeBacklink(backlink);
}
selectedHitEffectTargetCondition.condition = value;
if (selectedHitEffectTargetCondition.condition != null) {
selectedHitEffectTargetCondition.condition_id = selectedHitEffectTargetCondition.condition.id;
selectedHitEffectTargetCondition.condition.addBacklink(backlink);
} else {
selectedHitEffectTargetCondition.condition_id = null;
}
hitTargetConditionsModel.itemChanged(selectedHitEffectTargetCondition);
}
} }

View File

@@ -1,42 +1,25 @@
package com.gpl.rpg.atcontentstudio.ui; package com.gpl.rpg.atcontentstudio.ui;
import java.awt.BorderLayout; import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode;
import com.gpl.rpg.atcontentstudio.model.gamedata.*;
import com.gpl.rpg.atcontentstudio.model.maps.TMXMap;
import com.gpl.rpg.atcontentstudio.model.maps.WorldmapSegment;
import com.gpl.rpg.atcontentstudio.model.sprites.Spritesheet;
import com.gpl.rpg.atcontentstudio.model.tools.writermode.WriterModeData;
import com.gpl.rpg.atcontentstudio.ui.gamedataeditors.*;
import com.gpl.rpg.atcontentstudio.ui.map.TMXMapEditor;
import com.gpl.rpg.atcontentstudio.ui.map.WorldMapEditor;
import com.gpl.rpg.atcontentstudio.ui.sprites.SpritesheetEditor;
import com.gpl.rpg.atcontentstudio.ui.tools.writermode.WriterModeEditor;
import com.jidesoft.swing.JideTabbedPane;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent; import java.awt.event.ActionEvent;
import java.beans.PropertyChangeListener; import java.beans.PropertyChangeListener;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.Map; import java.util.Map;
import javax.swing.Action;
import javax.swing.JPanel;
import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode;
import com.gpl.rpg.atcontentstudio.model.gamedata.ActorCondition;
import com.gpl.rpg.atcontentstudio.model.gamedata.Dialogue;
import com.gpl.rpg.atcontentstudio.model.gamedata.Droplist;
import com.gpl.rpg.atcontentstudio.model.gamedata.Item;
import com.gpl.rpg.atcontentstudio.model.gamedata.ItemCategory;
import com.gpl.rpg.atcontentstudio.model.gamedata.JSONElement;
import com.gpl.rpg.atcontentstudio.model.gamedata.NPC;
import com.gpl.rpg.atcontentstudio.model.gamedata.Quest;
import com.gpl.rpg.atcontentstudio.model.maps.TMXMap;
import com.gpl.rpg.atcontentstudio.model.maps.WorldmapSegment;
import com.gpl.rpg.atcontentstudio.model.saves.SavedGame;
import com.gpl.rpg.atcontentstudio.model.sprites.Spritesheet;
import com.gpl.rpg.atcontentstudio.model.tools.writermode.WriterModeData;
import com.gpl.rpg.atcontentstudio.ui.gamedataeditors.ActorConditionEditor;
import com.gpl.rpg.atcontentstudio.ui.gamedataeditors.DialogueEditor;
import com.gpl.rpg.atcontentstudio.ui.gamedataeditors.DroplistEditor;
import com.gpl.rpg.atcontentstudio.ui.gamedataeditors.ItemCategoryEditor;
import com.gpl.rpg.atcontentstudio.ui.gamedataeditors.ItemEditor;
import com.gpl.rpg.atcontentstudio.ui.gamedataeditors.NPCEditor;
import com.gpl.rpg.atcontentstudio.ui.gamedataeditors.QuestEditor;
import com.gpl.rpg.atcontentstudio.ui.map.TMXMapEditor;
import com.gpl.rpg.atcontentstudio.ui.map.WorldMapEditor;
import com.gpl.rpg.atcontentstudio.ui.saves.SavedGameEditor;
import com.gpl.rpg.atcontentstudio.ui.sprites.SpritesheetEditor;
import com.gpl.rpg.atcontentstudio.ui.tools.writermode.WriterModeEditor;
import com.jidesoft.swing.JideTabbedPane;
public class EditorsArea extends JPanel { public class EditorsArea extends JPanel {
private static final long serialVersionUID = 8801849846876081538L; private static final long serialVersionUID = 8801849846876081538L;
@@ -61,20 +44,25 @@ public class EditorsArea extends JPanel {
@Override @Override
public void setEnabled(boolean b) { public void setEnabled(boolean b) {
} }
@Override @Override
public void removePropertyChangeListener(PropertyChangeListener listener) { public void removePropertyChangeListener(PropertyChangeListener listener) {
} }
@Override @Override
public void putValue(String key, Object value) { public void putValue(String key, Object value) {
} }
@Override @Override
public boolean isEnabled() { public boolean isEnabled() {
return true; return true;
} }
@Override @Override
public Object getValue(String key) { public Object getValue(String key) {
return null; return null;
} }
@Override @Override
public void addPropertyChangeListener(PropertyChangeListener listener) { public void addPropertyChangeListener(PropertyChangeListener listener) {
} }
@@ -104,7 +92,7 @@ public class EditorsArea extends JPanel {
return; return;
} }
if (node instanceof Quest) { if (node instanceof Quest) {
openEditor(new QuestEditor((Quest)node)); openEditor(new QuestEditor((Quest) node));
} else if (node instanceof Dialogue) { } else if (node instanceof Dialogue) {
openEditor(new DialogueEditor((Dialogue) node)); openEditor(new DialogueEditor((Dialogue) node));
} else if (node instanceof Droplist) { } else if (node instanceof Droplist) {
@@ -139,15 +127,6 @@ public class EditorsArea extends JPanel {
} }
public void openEditor(SavedGame save) {
if (editors.containsKey(save)) {
tabHolder.setSelectedComponent(editors.get(save));
return;
}
openEditor(new SavedGameEditor(save));
}
public void openEditor(WorldmapSegment node) { public void openEditor(WorldmapSegment node) {
if (editors.containsKey(node)) { if (editors.containsKey(node)) {
tabHolder.setSelectedComponent(editors.get(node)); tabHolder.setSelectedComponent(editors.get(node));

View File

@@ -1,21 +1,5 @@
package com.gpl.rpg.atcontentstudio.ui; package com.gpl.rpg.atcontentstudio.ui;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import com.gpl.rpg.atcontentstudio.ATContentStudio; import com.gpl.rpg.atcontentstudio.ATContentStudio;
import com.gpl.rpg.atcontentstudio.model.Project; import com.gpl.rpg.atcontentstudio.model.Project;
import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet; import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet;
@@ -23,6 +7,12 @@ import com.gpl.rpg.atcontentstudio.model.maps.TMXMapSet;
import com.gpl.rpg.atcontentstudio.model.sprites.SpriteSheetSet; import com.gpl.rpg.atcontentstudio.model.sprites.SpriteSheetSet;
import com.jidesoft.swing.JideBoxLayout; import com.jidesoft.swing.JideBoxLayout;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
public class ExportProjectWizard extends JDialog { public class ExportProjectWizard extends JDialog {
private static final long serialVersionUID = -8745083621008868612L; private static final long serialVersionUID = -8745083621008868612L;
@@ -78,8 +68,9 @@ public class ExportProjectWizard extends JDialog {
browse.addActionListener(new ActionListener() { browse.addActionListener(new ActionListener() {
@Override @Override
public void actionPerformed(ActionEvent e) { public void actionPerformed(ActionEvent e) {
JFileChooser jfc = new JFileChooser(){ JFileChooser jfc = new JFileChooser() {
private static final long serialVersionUID = -3001082967957619011L; private static final long serialVersionUID = -3001082967957619011L;
@Override @Override
public boolean accept(File f) { public boolean accept(File f) {
if (asZip.isSelected()) { if (asZip.isSelected()) {
@@ -100,7 +91,7 @@ public class ExportProjectWizard extends JDialog {
if (result == JFileChooser.APPROVE_OPTION) { if (result == JFileChooser.APPROVE_OPTION) {
File f = jfc.getSelectedFile(); File f = jfc.getSelectedFile();
if (asZip.isSelected() && !f.getAbsolutePath().substring(f.getAbsolutePath().length() - 4, f.getAbsolutePath().length()).equalsIgnoreCase(".zip")) { if (asZip.isSelected() && !f.getAbsolutePath().substring(f.getAbsolutePath().length() - 4, f.getAbsolutePath().length()).equalsIgnoreCase(".zip")) {
f = new File(f.getAbsolutePath()+".zip"); f = new File(f.getAbsolutePath() + ".zip");
} }
target.setSelectedItem(f.getAbsolutePath()); target.setSelectedItem(f.getAbsolutePath());
updateState(); updateState();
@@ -157,12 +148,12 @@ public class ExportProjectWizard extends JDialog {
getContentPane().setLayout(new BorderLayout()); getContentPane().setLayout(new BorderLayout());
getContentPane().add(pane, BorderLayout.CENTER); getContentPane().add(pane, BorderLayout.CENTER);
setMinimumSize(new Dimension(500,150)); setMinimumSize(new Dimension(500, 150));
pack(); pack();
Dimension sdim = Toolkit.getDefaultToolkit().getScreenSize(); Dimension sdim = Toolkit.getDefaultToolkit().getScreenSize();
Dimension wdim = getSize(); Dimension wdim = getSize();
setLocation((sdim.width - wdim.width)/2, (sdim.height - wdim.height)/2); setLocation((sdim.width - wdim.width) / 2, (sdim.height - wdim.height) / 2);
} }
private void updateState() { private void updateState() {

View File

@@ -1,6 +1,6 @@
package com.gpl.rpg.atcontentstudio.ui; package com.gpl.rpg.atcontentstudio.ui;
import javax.swing.JComponent; import javax.swing.*;
public interface FieldUpdateListener { public interface FieldUpdateListener {

View File

@@ -1,25 +1,16 @@
package com.gpl.rpg.atcontentstudio.ui; package com.gpl.rpg.atcontentstudio.ui;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import java.util.Vector;
import javax.swing.DefaultListCellRenderer;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import com.gpl.rpg.atcontentstudio.ATContentStudio; import com.gpl.rpg.atcontentstudio.ATContentStudio;
import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.GameDataElement;
import com.jidesoft.swing.JideBoxLayout; import com.jidesoft.swing.JideBoxLayout;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import java.util.Vector;
public class IdChangeImpactWizard extends JDialog { public class IdChangeImpactWizard extends JDialog {
private static final long serialVersionUID = 8532169707953315739L; private static final long serialVersionUID = 8532169707953315739L;
@@ -35,7 +26,7 @@ public class IdChangeImpactWizard extends JDialog {
JPanel pane = new JPanel(); JPanel pane = new JPanel();
pane.setLayout(new JideBoxLayout(pane, JideBoxLayout.PAGE_AXIS)); pane.setLayout(new JideBoxLayout(pane, JideBoxLayout.PAGE_AXIS));
pane.add(new JLabel("Changing the id for \""+changing.getDesc()+"\" has impacts on your project:"), JideBoxLayout.FIX); pane.add(new JLabel("Changing the id for \"" + changing.getDesc() + "\" has impacts on your project:"), JideBoxLayout.FIX);
pane.add(new JLabel("The following elements from your project will be modified:"), JideBoxLayout.FIX); pane.add(new JLabel("The following elements from your project will be modified:"), JideBoxLayout.FIX);
JList<GameDataElement> modifList = new JList<GameDataElement>(new Vector<GameDataElement>(toModify)); JList<GameDataElement> modifList = new JList<GameDataElement>(new Vector<GameDataElement>(toModify));
modifList.setCellRenderer(new ChangeImpactListCellRenderer()); modifList.setCellRenderer(new ChangeImpactListCellRenderer());
@@ -88,9 +79,9 @@ public class IdChangeImpactWizard extends JDialog {
Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (c instanceof JLabel) { if (c instanceof JLabel) {
JLabel label = (JLabel) c; JLabel label = (JLabel) c;
GameDataElement target = ((GameDataElement)value); GameDataElement target = ((GameDataElement) value);
label.setIcon(new ImageIcon(target.getIcon())); label.setIcon(new ImageIcon(target.getIcon()));
label.setText(target.getDataType().toString()+"/"+target.getDesc()); label.setText(target.getDataType().toString() + "/" + target.getDesc());
} }
return c; return c;
} }

View File

@@ -1,6 +1,6 @@
package com.gpl.rpg.atcontentstudio.ui; package com.gpl.rpg.atcontentstudio.ui;
import javax.swing.JCheckBox; import javax.swing.*;
public class IntegerBasedCheckBox extends JCheckBox { public class IntegerBasedCheckBox extends JCheckBox {

View File

@@ -1,12 +1,7 @@
package com.gpl.rpg.atcontentstudio.ui; package com.gpl.rpg.atcontentstudio.ui;
import java.awt.Color; import javax.swing.*;
import java.awt.GradientPaint; import java.awt.*;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Paint;
import javax.swing.JComponent;
public class JMovingIdler extends JComponent { public class JMovingIdler extends JComponent {
@@ -14,8 +9,8 @@ public class JMovingIdler extends JComponent {
private static final long serialVersionUID = -2980521421870322717L; private static final long serialVersionUID = -2980521421870322717L;
int position = 0; int position = 0;
boolean destroyed=false, running=false; boolean destroyed = false, running = false;
Thread moverThread = new Thread(){ Thread moverThread = new Thread() {
public void run() { public void run() {
while (!destroyed) { while (!destroyed) {
boolean back = false; boolean back = false;
@@ -33,7 +28,8 @@ public class JMovingIdler extends JComponent {
} }
try { try {
sleep(10); sleep(10);
} catch (InterruptedException e) {} } catch (InterruptedException e) {
}
JMovingIdler.this.revalidate(); JMovingIdler.this.revalidate();
JMovingIdler.this.repaint(); JMovingIdler.this.repaint();
} }
@@ -57,7 +53,8 @@ public class JMovingIdler extends JComponent {
running = false; running = false;
try { try {
moverThread.join(); moverThread.join();
} catch (InterruptedException e) {} } catch (InterruptedException e) {
}
} }
protected void paintComponent(Graphics g) { protected void paintComponent(Graphics g) {
@@ -67,23 +64,23 @@ public class JMovingIdler extends JComponent {
int h = this.getHeight(); int h = this.getHeight();
g2.setColor(getBackground()); g2.setColor(getBackground());
g2.fillRect(0,0,w,h); g2.fillRect(0, 0, w, h);
int x = w * position / 100; int x = w * position / 100;
Paint p = new GradientPaint(x - (w/8), 0, getBackground(), x , 0, getForeground()); Paint p = new GradientPaint(x - (w / 8), 0, getBackground(), x, 0, getForeground());
g2.setPaint(p); g2.setPaint(p);
g2.fillRect(Math.max(0,x-(w/8)),0, Math.min(x, w), h); g2.fillRect(Math.max(0, x - (w / 8)), 0, Math.min(x, w), h);
p = new GradientPaint(x, 0, getForeground(), x + (w/8), 0, getBackground()); p = new GradientPaint(x, 0, getForeground(), x + (w / 8), 0, getBackground());
g2.setPaint(p); g2.setPaint(p);
g2.fillRect(Math.max(0,x),0, Math.min(x+(w/8), w), h); g2.fillRect(Math.max(0, x), 0, Math.min(x + (w / 8), w), h);
g2.setColor(Color.BLACK); g2.setColor(Color.BLACK);
g2.drawLine(0,0,0,h); g2.drawLine(0, 0, 0, h);
g2.drawLine(0,0,w,0); g2.drawLine(0, 0, w, 0);
g2.drawLine(w,0,w,h); g2.drawLine(w, 0, w, h);
g2.drawLine(0,h,w,h); g2.drawLine(0, h, w, h);
} }
@Override @Override

Some files were not shown because too many files have changed in this diff Show More