Merged revision(s) 491 from branches/SFML2:

Uniformized paranthese padding with AStyle, use AStyle 2.04

........
Merged revision(s) 489 from branches/SFML2:
Removed all empty translations to avoid confusion
Save language as string to avoid problems when languages.lst changes

........
Merged revision(s) 488 from branches/SFML2:
New features:
- Translatability of statistics at end of race
- Adapt GUI particle count to screen size

Fixes:
- Remember selected race in GUI
- Fixed crash in Debug mode when loading course without any trees
- Simplified collision detection

........
Merged revision(s) 487 from branches/SFML2:
Refactorizations:
- Check for gl_error automatically (in states)
- Cleaned up some unnecessary includes
- Removed some index maps that offer no performance gain
- Load credit text on demand and unload it when leaving credits menu
- Replaced loadIdentity+multMatrix by loadMatrix

........

git-svn-id: https://svn.code.sf.net/p/extremetuxracer/code/trunk@516 0420edf4-82e4-42fc-9478-35b55e6d67a3
master
pkeus 2014-07-11 07:58:50 +00:00
parent fc2a8e62e3
commit df4a95d199
93 changed files with 4154 additions and 4813 deletions

View File

@ -4,4 +4,5 @@
--indent=tab --indent=tab
--indent-switches --indent-switches
--pad-header --pad-header
--unpad-paren
--keep-one-line-blocks --keep-one-line-blocks

View File

@ -3,20 +3,9 @@ pkgdatadir = $(datadir)/$(PACKAGE)/translations
pkgdata_DATA = \ pkgdata_DATA = \
languages.lst \ languages.lst \
eu_ES.lst \
de_DE.lst \ de_DE.lst \
es_ES.lst \ es_ES.lst \
fr_FR.lst \ fr_FR.lst \
it_IT.lst \ pl_PL.lst
nl_NL.lst \
nb_NO.lst \
nn_NO.lst \
pl_PL.lst \
pt_PT.lst \
ru_RU.lst \
ro_RO.lst \
sk_SK.lst \
fi_FI.lst \
sv_SE.lst
EXTRA_DIST = $(pkgdata_DATA) EXTRA_DIST = $(pkgdata_DATA)

View File

@ -103,4 +103,12 @@
*[idx] 83 [engl] Randomize settings [trans] Zufällige Einstellungen *[idx] 83 [engl] Randomize settings [trans] Zufällige Einstellungen
*[idx] 84 [engl] Fullscreen setting has changed, [trans] Damit die Vollbild-Einstellung geändert wird, *[idx] 84 [engl] Fullscreen setting has changed, [trans] Damit die Vollbild-Einstellung geändert wird,
*[idx] 85 [engl] You need to restart the game [trans] muss das Spiel neugestartet werden. *[idx] 85 [engl] You need to restart the game [trans] muss das Spiel neugestartet werden.
*[idx] 86 [engl] Score [trans] Punkte
*[idx] 87 [engl] Herring [trans] Herringe
*[idx] 88 [engl] Time [trans] Zeit
*[idx] 89 [engl] Path length [trans] Streckenlänge
*[idx] 90 [engl] Average speed [trans] Durchschnittsgeschwindigkeit
*[idx] 91 [engl] Position [trans] Platz
*[idx] 92 [engl] in highscore list [trans] in der Punktelilste.

View File

@ -1,54 +0,0 @@
# Please, don't change the idx
*[idx] 0 [engl] PRESS ANY KEY TO START [trans]
*[idx] 1 [engl] Enter an event [trans]
*[idx] 2 [engl] Practice [trans]
*[idx] 3 [engl] Configuration [trans]
*[idx] 4 [engl] Credits [trans]
*[idx] 5 [engl] Quit [trans]
*[idx] 6 [engl] Select an event [trans]
*[idx] 7 [engl] Select a cup [trans]
*[idx] 8 [engl] Back [trans]
*[idx] 9 [engl] Continue [trans]
*[idx] 10 [engl] You cannot enter this cup yet
[trans]
*[idx] 11 [engl] Herring: [trans]
*[idx] 12 [engl] Time: [trans]
*[idx] 13 [engl] Race! [trans]
*[idx] 14 [engl] seconds [trans]
*[idx] 15 [engl] Ok [trans]
*[idx] 16 [engl] Congratulations! You won the cup!
[trans]
*[idx] 17 [engl] You have reached level [trans]
*[idx] 18 [engl] Sorry, you didn't advance [trans]
*[idx] 19 [engl] You don't have any lives left [trans]
*[idx] 20 [engl] Select a race [trans]
*[idx] 21 [engl] Failed, -1 Tuxlive [trans]
*[idx] 22 [engl] Success, +/- 0 Tuxlive [trans]
*[idx] 23 [engl] Success, +1 Tuxlive [trans]
*[idx] 24 [engl] Success, +2 Tuxlive [trans]
*[idx] 25 [engl] Race aborted [trans]
*[idx] 26 [engl] Score: [trans]
*[idx] 27 [engl] points [trans]
*[idx] 28 [engl] Cancel [trans]
*[idx] 29 [engl] Loading [trans]
*[idx] 30 [engl] Please wait... [trans]
*[idx] 31 [engl] Fullscreen: [trans]
*[idx] 32 [engl] Resolution: [trans]
*[idx] 33 [engl] Music volume: [trans]
*[idx] 34 [engl] Sound volume: [trans]
*[idx] 35 [engl] Language: [trans]
*[idx] 36 [engl] Level of detail: [trans]
*[idx] 37 [engl] Contributed by: [trans]
*[idx] 38 [engl] Event: [trans]
*[idx] 39 [engl] Cup: [trans]
*[idx] 40 [engl] Race Over [trans]
*[idx] 41 [engl] For more configuration options, please edit the
[trans]
*[idx] 42 [engl] file 'options.lst' and read the documentation.
[trans]

View File

@ -1,54 +0,0 @@
# Please, don't change the idx
*[idx] 0 [engl] PRESS ANY KEY TO START [trans]
*[idx] 1 [engl] Enter an event [trans]
*[idx] 2 [engl] Practice [trans]
*[idx] 3 [engl] Configuration [trans]
*[idx] 4 [engl] Credits [trans]
*[idx] 5 [engl] Quit [trans]
*[idx] 6 [engl] Select an event [trans]
*[idx] 7 [engl] Select a cup [trans]
*[idx] 8 [engl] Back [trans]
*[idx] 9 [engl] Continue [trans]
*[idx] 10 [engl] You cannot enter this cup yet
[trans]
*[idx] 11 [engl] Herring: [trans]
*[idx] 12 [engl] Time: [trans]
*[idx] 13 [engl] Race! [trans]
*[idx] 14 [engl] seconds [trans]
*[idx] 15 [engl] Ok [trans]
*[idx] 16 [engl] Congratulations! You won the cup!
[trans]
*[idx] 17 [engl] You have reached level [trans]
*[idx] 18 [engl] Sorry, you didn't advance [trans]
*[idx] 19 [engl] You don't have any lives left [trans]
*[idx] 20 [engl] Select a race [trans]
*[idx] 21 [engl] Failed, -1 Tuxlive [trans]
*[idx] 22 [engl] Success, +/- 0 Tuxlive [trans]
*[idx] 23 [engl] Success, +1 Tuxlive [trans]
*[idx] 24 [engl] Success, +2 Tuxlive [trans]
*[idx] 25 [engl] Race aborted [trans]
*[idx] 26 [engl] Score: [trans]
*[idx] 27 [engl] points [trans]
*[idx] 28 [engl] Cancel [trans]
*[idx] 29 [engl] Loading [trans]
*[idx] 30 [engl] Please wait... [trans]
*[idx] 31 [engl] Fullscreen: [trans]
*[idx] 32 [engl] Resolution: [trans]
*[idx] 33 [engl] Music volume: [trans]
*[idx] 34 [engl] Sound volume: [trans]
*[idx] 35 [engl] Language: [trans]
*[idx] 36 [engl] Level of detail: [trans]
*[idx] 37 [engl] Contributed by: [trans]
*[idx] 38 [engl] Event: [trans]
*[idx] 39 [engl] Cup: [trans]
*[idx] 40 [engl] Race Over [trans]
*[idx] 41 [engl] For more configuration options, please edit the
[trans]
*[idx] 42 [engl] file 'options.lst' and read the documentation.
[trans]

View File

@ -1,54 +0,0 @@
# Please, don't change the idx
*[idx] 0 [engl] PRESS ANY KEY TO START [trans]
*[idx] 1 [engl] Enter an event [trans]
*[idx] 2 [engl] Practice [trans]
*[idx] 3 [engl] Configuration [trans]
*[idx] 4 [engl] Credits [trans]
*[idx] 5 [engl] Quit [trans]
*[idx] 6 [engl] Select an event [trans]
*[idx] 7 [engl] Select a cup [trans]
*[idx] 8 [engl] Back [trans]
*[idx] 9 [engl] Continue [trans]
*[idx] 10 [engl] You cannot enter this cup yet
[trans]
*[idx] 11 [engl] Herring: [trans]
*[idx] 12 [engl] Time: [trans]
*[idx] 13 [engl] Race! [trans]
*[idx] 14 [engl] seconds [trans]
*[idx] 15 [engl] Ok [trans]
*[idx] 16 [engl] Congratulations! You won the cup!
[trans]
*[idx] 17 [engl] You have reached level [trans]
*[idx] 18 [engl] Sorry, you didn't advance [trans]
*[idx] 19 [engl] You don't have any lives left [trans]
*[idx] 20 [engl] Select a race [trans]
*[idx] 21 [engl] Failed, -1 Tuxlive [trans]
*[idx] 22 [engl] Success, +/- 0 Tuxlive [trans]
*[idx] 23 [engl] Success, +1 Tuxlive [trans]
*[idx] 24 [engl] Success, +2 Tuxlive [trans]
*[idx] 25 [engl] Race aborted [trans]
*[idx] 26 [engl] Score: [trans]
*[idx] 27 [engl] points [trans]
*[idx] 28 [engl] Cancel [trans]
*[idx] 29 [engl] Loading [trans]
*[idx] 30 [engl] Please wait... [trans]
*[idx] 31 [engl] Fullscreen: [trans]
*[idx] 32 [engl] Resolution: [trans]
*[idx] 33 [engl] Music volume: [trans]
*[idx] 34 [engl] Sound volume: [trans]
*[idx] 35 [engl] Language: [trans]
*[idx] 36 [engl] Level of detail: [trans]
*[idx] 37 [engl] Contributed by: [trans]
*[idx] 38 [engl] Event: [trans]
*[idx] 39 [engl] Cup: [trans]
*[idx] 40 [engl] Race Over [trans]
*[idx] 41 [engl] For more configuration options, please edit the
[trans]
*[idx] 42 [engl] file 'options.lst' and read the documentation.
[trans]

View File

@ -1,15 +1,4 @@
*[lang] eu_ES [language] Basque
*[lang] de_DE [language] Deutsch *[lang] de_DE [language] Deutsch
*[lang] es_ES [language] Español *[lang] es_ES [language] Español
*[lang] fr_FR [language] français *[lang] fr_FR [language] français
*[lang] it_IT [language] Italian *[lang] pl_PL [language] polski
*[lang] nl_NL [language] Nederlands
*[lang] nb_NO [language] Norsk (bokmål)
*[lang] nn_NO [language] Norsk (nynorsk)
*[lang] pl_PL [language] polski
*[lang] pt_PT [language] Português
*[lang] ru_RU [language] Русский
*[lang] ro_RO [language] românã
*[lang] sk_SK [language] Slovenčina
*[lang] fi_FI [language] Suomi
*[lang] sv_SE [language] Svenska

View File

@ -1,54 +0,0 @@
# Please, don't change the idx
*[idx] 0 [engl] PRESS ANY KEY TO START [trans]
*[idx] 1 [engl] Enter an event [trans]
*[idx] 2 [engl] Practice [trans]
*[idx] 3 [engl] Configuration [trans]
*[idx] 4 [engl] Credits [trans]
*[idx] 5 [engl] Quit [trans]
*[idx] 6 [engl] Select an event [trans]
*[idx] 7 [engl] Select a cup [trans]
*[idx] 8 [engl] Back [trans]
*[idx] 9 [engl] Continue [trans]
*[idx] 10 [engl] You cannot enter this cup yet
[trans]
*[idx] 11 [engl] Herring: [trans]
*[idx] 12 [engl] Time: [trans]
*[idx] 13 [engl] Race! [trans]
*[idx] 14 [engl] seconds [trans]
*[idx] 15 [engl] Ok [trans]
*[idx] 16 [engl] Congratulations! You won the cup!
[trans]
*[idx] 17 [engl] You have reached level [trans]
*[idx] 18 [engl] Sorry, you didn't advance [trans]
*[idx] 19 [engl] You don't have any lives left [trans]
*[idx] 20 [engl] Select a race [trans]
*[idx] 21 [engl] Failed, -1 Tuxlive [trans]
*[idx] 22 [engl] Success, +/- 0 Tuxlive [trans]
*[idx] 23 [engl] Success, +1 Tuxlive [trans]
*[idx] 24 [engl] Success, +2 Tuxlive [trans]
*[idx] 25 [engl] Race aborted [trans]
*[idx] 26 [engl] Score: [trans]
*[idx] 27 [engl] points [trans]
*[idx] 28 [engl] Cancel [trans]
*[idx] 29 [engl] Loading [trans]
*[idx] 30 [engl] Please wait... [trans]
*[idx] 31 [engl] Fullscreen: [trans]
*[idx] 32 [engl] Resolution: [trans]
*[idx] 33 [engl] Music volume: [trans]
*[idx] 34 [engl] Sound volume: [trans]
*[idx] 35 [engl] Language: [trans]
*[idx] 36 [engl] Level of detail: [trans]
*[idx] 37 [engl] Contributed by: [trans]
*[idx] 38 [engl] Event: [trans]
*[idx] 39 [engl] Cup: [trans]
*[idx] 40 [engl] Race Over [trans]
*[idx] 41 [engl] For more configuration options, please edit the
[trans]
*[idx] 42 [engl] file 'options.lst' and read the documentation.
[trans]

View File

@ -1,54 +0,0 @@
# Please, don't change the idx
*[idx] 0 [engl] PRESS ANY KEY TO START [trans]
*[idx] 1 [engl] Enter an event [trans]
*[idx] 2 [engl] Practice [trans]
*[idx] 3 [engl] Configuration [trans]
*[idx] 4 [engl] Credits [trans]
*[idx] 5 [engl] Quit [trans]
*[idx] 6 [engl] Select an event [trans]
*[idx] 7 [engl] Select a cup [trans]
*[idx] 8 [engl] Back [trans]
*[idx] 9 [engl] Continue [trans]
*[idx] 10 [engl] You cannot enter this cup yet
[trans]
*[idx] 11 [engl] Herring: [trans]
*[idx] 12 [engl] Time: [trans]
*[idx] 13 [engl] Race! [trans]
*[idx] 14 [engl] seconds [trans]
*[idx] 15 [engl] Ok [trans]
*[idx] 16 [engl] Congratulations! You won the cup!
[trans]
*[idx] 17 [engl] You have reached level [trans]
*[idx] 18 [engl] Sorry, you didn't advance [trans]
*[idx] 19 [engl] You don't have any lives left [trans]
*[idx] 20 [engl] Select a race [trans]
*[idx] 21 [engl] Failed, -1 Tuxlive [trans]
*[idx] 22 [engl] Success, +/- 0 Tuxlive [trans]
*[idx] 23 [engl] Success, +1 Tuxlive [trans]
*[idx] 24 [engl] Success, +2 Tuxlive [trans]
*[idx] 25 [engl] Race aborted [trans]
*[idx] 26 [engl] Score: [trans]
*[idx] 27 [engl] points [trans]
*[idx] 28 [engl] Cancel [trans]
*[idx] 29 [engl] Loading [trans]
*[idx] 30 [engl] Please wait... [trans]
*[idx] 31 [engl] Fullscreen: [trans]
*[idx] 32 [engl] Resolution: [trans]
*[idx] 33 [engl] Music volume: [trans]
*[idx] 34 [engl] Sound volume: [trans]
*[idx] 35 [engl] Language: [trans]
*[idx] 36 [engl] Level of detail: [trans]
*[idx] 37 [engl] Contributed by: [trans]
*[idx] 38 [engl] Event: [trans]
*[idx] 39 [engl] Cup: [trans]
*[idx] 40 [engl] Race Over [trans]
*[idx] 41 [engl] For more configuration options, please edit the
[trans]
*[idx] 42 [engl] file 'options.lst' and read the documentation.
[trans]

View File

@ -1,54 +0,0 @@
# Please, don't change the idx
*[idx] 0 [engl] PRESS ANY KEY TO START [trans]
*[idx] 1 [engl] Enter an event [trans]
*[idx] 2 [engl] Practice [trans]
*[idx] 3 [engl] Configuration [trans]
*[idx] 4 [engl] Credits [trans]
*[idx] 5 [engl] Quit [trans]
*[idx] 6 [engl] Select an event [trans]
*[idx] 7 [engl] Select a cup [trans]
*[idx] 8 [engl] Back [trans]
*[idx] 9 [engl] Continue [trans]
*[idx] 10 [engl] You cannot enter this cup yet
[trans]
*[idx] 11 [engl] Herring: [trans]
*[idx] 12 [engl] Time: [trans]
*[idx] 13 [engl] Race! [trans]
*[idx] 14 [engl] seconds [trans]
*[idx] 15 [engl] Ok [trans]
*[idx] 16 [engl] Congratulations! You won the cup!
[trans]
*[idx] 17 [engl] You have reached level [trans]
*[idx] 18 [engl] Sorry, you didn't advance [trans]
*[idx] 19 [engl] You don't have any lives left [trans]
*[idx] 20 [engl] Select a race [trans]
*[idx] 21 [engl] Failed, -1 Tuxlive [trans]
*[idx] 22 [engl] Success, +/- 0 Tuxlive [trans]
*[idx] 23 [engl] Success, +1 Tuxlive [trans]
*[idx] 24 [engl] Success, +2 Tuxlive [trans]
*[idx] 25 [engl] Race aborted [trans]
*[idx] 26 [engl] Score: [trans]
*[idx] 27 [engl] points [trans]
*[idx] 28 [engl] Cancel [trans]
*[idx] 29 [engl] Loading [trans]
*[idx] 30 [engl] Please wait... [trans]
*[idx] 31 [engl] Fullscreen: [trans]
*[idx] 32 [engl] Resolution: [trans]
*[idx] 33 [engl] Music volume: [trans]
*[idx] 34 [engl] Sound volume: [trans]
*[idx] 35 [engl] Language: [trans]
*[idx] 36 [engl] Level of detail: [trans]
*[idx] 37 [engl] Contributed by: [trans]
*[idx] 38 [engl] Event: [trans]
*[idx] 39 [engl] Cup: [trans]
*[idx] 40 [engl] Race Over [trans]
*[idx] 41 [engl] For more configuration options, please edit the
[trans]
*[idx] 42 [engl] file 'options.lst' and read the documentation.
[trans]

View File

@ -1,54 +0,0 @@
# Please, don't change the idx
*[idx] 0 [engl] PRESS ANY KEY TO START [trans]
*[idx] 1 [engl] Enter an event [trans]
*[idx] 2 [engl] Practice [trans]
*[idx] 3 [engl] Configuration [trans]
*[idx] 4 [engl] Credits [trans]
*[idx] 5 [engl] Quit [trans]
*[idx] 6 [engl] Select an event [trans]
*[idx] 7 [engl] Select a cup [trans]
*[idx] 8 [engl] Back [trans]
*[idx] 9 [engl] Continue [trans]
*[idx] 10 [engl] You cannot enter this cup yet
[trans]
*[idx] 11 [engl] Herring: [trans]
*[idx] 12 [engl] Time: [trans]
*[idx] 13 [engl] Race! [trans]
*[idx] 14 [engl] seconds [trans]
*[idx] 15 [engl] Ok [trans]
*[idx] 16 [engl] Congratulations! You won the cup!
[trans]
*[idx] 17 [engl] You have reached level [trans]
*[idx] 18 [engl] Sorry, you didn't advance [trans]
*[idx] 19 [engl] You don't have any lives left [trans]
*[idx] 20 [engl] Select a race [trans]
*[idx] 21 [engl] Failed, -1 Tuxlive [trans]
*[idx] 22 [engl] Success, +/- 0 Tuxlive [trans]
*[idx] 23 [engl] Success, +1 Tuxlive [trans]
*[idx] 24 [engl] Success, +2 Tuxlive [trans]
*[idx] 25 [engl] Race aborted [trans]
*[idx] 26 [engl] Score: [trans]
*[idx] 27 [engl] points [trans]
*[idx] 28 [engl] Cancel [trans]
*[idx] 29 [engl] Loading [trans]
*[idx] 30 [engl] Please wait... [trans]
*[idx] 31 [engl] Fullscreen: [trans]
*[idx] 32 [engl] Resolution: [trans]
*[idx] 33 [engl] Music volume: [trans]
*[idx] 34 [engl] Sound volume: [trans]
*[idx] 35 [engl] Language: [trans]
*[idx] 36 [engl] Level of detail: [trans]
*[idx] 37 [engl] Contributed by: [trans]
*[idx] 38 [engl] Event: [trans]
*[idx] 39 [engl] Cup: [trans]
*[idx] 40 [engl] Race Over [trans]
*[idx] 41 [engl] For more configuration options, please edit the
[trans]
*[idx] 42 [engl] file 'options.lst' and read the documentation.
[trans]

View File

@ -1,54 +0,0 @@
# Please, don't change the idx
*[idx] 0 [engl] PRESS ANY KEY TO START [trans]
*[idx] 1 [engl] Enter an event [trans]
*[idx] 2 [engl] Practice [trans]
*[idx] 3 [engl] Configuration [trans]
*[idx] 4 [engl] Credits [trans]
*[idx] 5 [engl] Quit [trans]
*[idx] 6 [engl] Select an event [trans]
*[idx] 7 [engl] Select a cup [trans]
*[idx] 8 [engl] Back [trans]
*[idx] 9 [engl] Continue [trans]
*[idx] 10 [engl] You cannot enter this cup yet
[trans]
*[idx] 11 [engl] Herring: [trans]
*[idx] 12 [engl] Time: [trans]
*[idx] 13 [engl] Race! [trans]
*[idx] 14 [engl] seconds [trans]
*[idx] 15 [engl] Ok [trans]
*[idx] 16 [engl] Congratulations! You won the cup!
[trans]
*[idx] 17 [engl] You have reached level [trans]
*[idx] 18 [engl] Sorry, you didn't advance [trans]
*[idx] 19 [engl] You don't have any lives left [trans]
*[idx] 20 [engl] Select a race [trans]
*[idx] 21 [engl] Failed, -1 Tuxlive [trans]
*[idx] 22 [engl] Success, +/- 0 Tuxlive [trans]
*[idx] 23 [engl] Success, +1 Tuxlive [trans]
*[idx] 24 [engl] Success, +2 Tuxlive [trans]
*[idx] 25 [engl] Race aborted [trans]
*[idx] 26 [engl] Score: [trans]
*[idx] 27 [engl] points [trans]
*[idx] 28 [engl] Cancel [trans]
*[idx] 29 [engl] Loading [trans]
*[idx] 30 [engl] Please wait... [trans]
*[idx] 31 [engl] Fullscreen: [trans]
*[idx] 32 [engl] Resolution: [trans]
*[idx] 33 [engl] Music volume: [trans]
*[idx] 34 [engl] Sound volume: [trans]
*[idx] 35 [engl] Language: [trans]
*[idx] 36 [engl] Level of detail: [trans]
*[idx] 37 [engl] Contributed by: [trans]
*[idx] 38 [engl] Event: [trans]
*[idx] 39 [engl] Cup: [trans]
*[idx] 40 [engl] Race Over [trans]
*[idx] 41 [engl] For more configuration options, please edit the
[trans]
*[idx] 42 [engl] file 'options.lst' and read the documentation.
[trans]

View File

@ -1,54 +0,0 @@
# Please, don't change the idx
*[idx] 0 [engl] PRESS ANY KEY TO START [trans]
*[idx] 1 [engl] Enter an event [trans]
*[idx] 2 [engl] Practice [trans]
*[idx] 3 [engl] Configuration [trans]
*[idx] 4 [engl] Credits [trans]
*[idx] 5 [engl] Quit [trans]
*[idx] 6 [engl] Select an event [trans]
*[idx] 7 [engl] Select a cup [trans]
*[idx] 8 [engl] Back [trans]
*[idx] 9 [engl] Continue [trans]
*[idx] 10 [engl] You cannot enter this cup yet
[trans]
*[idx] 11 [engl] Herring: [trans]
*[idx] 12 [engl] Time: [trans]
*[idx] 13 [engl] Race! [trans]
*[idx] 14 [engl] seconds [trans]
*[idx] 15 [engl] Ok [trans]
*[idx] 16 [engl] Congratulations! You won the cup!
[trans]
*[idx] 17 [engl] You have reached level [trans]
*[idx] 18 [engl] Sorry, you didn't advance [trans]
*[idx] 19 [engl] You don't have any lives left [trans]
*[idx] 20 [engl] Select a race [trans]
*[idx] 21 [engl] Failed, -1 Tuxlive [trans]
*[idx] 22 [engl] Success, +/- 0 Tuxlive [trans]
*[idx] 23 [engl] Success, +1 Tuxlive [trans]
*[idx] 24 [engl] Success, +2 Tuxlive [trans]
*[idx] 25 [engl] Race aborted [trans]
*[idx] 26 [engl] Score: [trans]
*[idx] 27 [engl] points [trans]
*[idx] 28 [engl] Cancel [trans]
*[idx] 29 [engl] Loading [trans]
*[idx] 30 [engl] Please wait... [trans]
*[idx] 31 [engl] Fullscreen: [trans]
*[idx] 32 [engl] Resolution: [trans]
*[idx] 33 [engl] Music volume: [trans]
*[idx] 34 [engl] Sound volume: [trans]
*[idx] 35 [engl] Language: [trans]
*[idx] 36 [engl] Level of detail: [trans]
*[idx] 37 [engl] Contributed by: [trans]
*[idx] 38 [engl] Event: [trans]
*[idx] 39 [engl] Cup: [trans]
*[idx] 40 [engl] Race Over [trans]
*[idx] 41 [engl] For more configuration options, please edit the
[trans]
*[idx] 42 [engl] file 'options.lst' and read the documentation.
[trans]

View File

@ -1,54 +0,0 @@
# Please, don't change the idx
*[idx] 0 [engl] PRESS ANY KEY TO START [trans]
*[idx] 1 [engl] Enter an event [trans]
*[idx] 2 [engl] Practice [trans]
*[idx] 3 [engl] Configuration [trans]
*[idx] 4 [engl] Credits [trans]
*[idx] 5 [engl] Quit [trans]
*[idx] 6 [engl] Select an event [trans]
*[idx] 7 [engl] Select a cup [trans]
*[idx] 8 [engl] Back [trans]
*[idx] 9 [engl] Continue [trans]
*[idx] 10 [engl] You cannot enter this cup yet
[trans]
*[idx] 11 [engl] Herring: [trans]
*[idx] 12 [engl] Time: [trans]
*[idx] 13 [engl] Race! [trans]
*[idx] 14 [engl] seconds [trans]
*[idx] 15 [engl] Ok [trans]
*[idx] 16 [engl] Congratulations! You won the cup!
[trans]
*[idx] 17 [engl] You have reached level [trans]
*[idx] 18 [engl] Sorry, you didn't advance [trans]
*[idx] 19 [engl] You don't have any lives left [trans]
*[idx] 20 [engl] Select a race [trans]
*[idx] 21 [engl] Failed, -1 Tuxlive [trans]
*[idx] 22 [engl] Success, +/- 0 Tuxlive [trans]
*[idx] 23 [engl] Success, +1 Tuxlive [trans]
*[idx] 24 [engl] Success, +2 Tuxlive [trans]
*[idx] 25 [engl] Race aborted [trans]
*[idx] 26 [engl] Score: [trans]
*[idx] 27 [engl] points [trans]
*[idx] 28 [engl] Cancel [trans]
*[idx] 29 [engl] Loading [trans]
*[idx] 30 [engl] Please wait... [trans]
*[idx] 31 [engl] Fullscreen: [trans]
*[idx] 32 [engl] Resolution: [trans]
*[idx] 33 [engl] Music volume: [trans]
*[idx] 34 [engl] Sound volume: [trans]
*[idx] 35 [engl] Language: [trans]
*[idx] 36 [engl] Level of detail: [trans]
*[idx] 37 [engl] Contributed by: [trans]
*[idx] 38 [engl] Event: [trans]
*[idx] 39 [engl] Cup: [trans]
*[idx] 40 [engl] Race Over [trans]
*[idx] 41 [engl] For more configuration options, please edit the
[trans]
*[idx] 42 [engl] file 'options.lst' and read the documentation.
[trans]

View File

@ -1,54 +0,0 @@
# Please, don't change the idx
*[idx] 0 [engl] PRESS ANY KEY TO START [trans]
*[idx] 1 [engl] Enter an event [trans]
*[idx] 2 [engl] Practice [trans]
*[idx] 3 [engl] Configuration [trans]
*[idx] 4 [engl] Credits [trans]
*[idx] 5 [engl] Quit [trans]
*[idx] 6 [engl] Select an event [trans]
*[idx] 7 [engl] Select a cup [trans]
*[idx] 8 [engl] Back [trans]
*[idx] 9 [engl] Continue [trans]
*[idx] 10 [engl] You cannot enter this cup yet
[trans]
*[idx] 11 [engl] Herring: [trans]
*[idx] 12 [engl] Time: [trans]
*[idx] 13 [engl] Race! [trans]
*[idx] 14 [engl] seconds [trans]
*[idx] 15 [engl] Ok [trans]
*[idx] 16 [engl] Congratulations! You won the cup!
[trans]
*[idx] 17 [engl] You have reached level [trans]
*[idx] 18 [engl] Sorry, you didn't advance [trans]
*[idx] 19 [engl] You don't have any lives left [trans]
*[idx] 20 [engl] Select a race [trans]
*[idx] 21 [engl] Failed, -1 Tuxlive [trans]
*[idx] 22 [engl] Success, +/- 0 Tuxlive [trans]
*[idx] 23 [engl] Success, +1 Tuxlive [trans]
*[idx] 24 [engl] Success, +2 Tuxlive [trans]
*[idx] 25 [engl] Race aborted [trans]
*[idx] 26 [engl] Score: [trans]
*[idx] 27 [engl] points [trans]
*[idx] 28 [engl] Cancel [trans]
*[idx] 29 [engl] Loading [trans]
*[idx] 30 [engl] Please wait... [trans]
*[idx] 31 [engl] Fullscreen: [trans]
*[idx] 32 [engl] Resolution: [trans]
*[idx] 33 [engl] Music volume: [trans]
*[idx] 34 [engl] Sound volume: [trans]
*[idx] 35 [engl] Language: [trans]
*[idx] 36 [engl] Level of detail: [trans]
*[idx] 37 [engl] Contributed by: [trans]
*[idx] 38 [engl] Event: [trans]
*[idx] 39 [engl] Cup: [trans]
*[idx] 40 [engl] Race Over [trans]
*[idx] 41 [engl] For more configuration options, please edit the
[trans]
*[idx] 42 [engl] file 'options.lst' and read the documentation.
[trans]

View File

@ -1,5 +1,4 @@
# Please, don't change the idx # Please, don't change the idx
# but you may change the order of the entries
*[idx] 0 [engl] PRESS ANY KEY TO START [trans] *[idx] 0 [engl] PRESS ANY KEY TO START [trans]
*[idx] 1 [engl] Enter an event [trans] *[idx] 1 [engl] Enter an event [trans]
@ -35,6 +34,7 @@
*[idx] 28 [engl] Cancel [trans] *[idx] 28 [engl] Cancel [trans]
*[idx] 29 [engl] Loading [trans] *[idx] 29 [engl] Loading [trans]
*[idx] 30 [engl] Please wait... [trans] *[idx] 30 [engl] Please wait... [trans]
*[idx] 31 [engl] Fullscreen: [trans] *[idx] 31 [engl] Fullscreen: [trans]
*[idx] 32 [engl] Resolution: [trans] *[idx] 32 [engl] Resolution: [trans]
*[idx] 33 [engl] Music volume: [trans] *[idx] 33 [engl] Music volume: [trans]
@ -48,7 +48,6 @@
*[idx] 41 [engl] For more configuration options, please edit the [trans] *[idx] 41 [engl] For more configuration options, please edit the [trans]
*[idx] 42 [engl] file 'options.lst' and read the documentation. [trans] *[idx] 42 [engl] file 'options.lst' and read the documentation. [trans]
*[idx] 43 [engl] Help [trans] *[idx] 43 [engl] Help [trans]
*[idx] 44 [engl] 1, 2, 3 - change view mode [trans] *[idx] 44 [engl] 1, 2, 3 - change view mode [trans]
*[idx] 45 [engl] F - hide/show fps display [trans] *[idx] 45 [engl] F - hide/show fps display [trans]
@ -63,4 +62,47 @@
*[idx] 54 [engl] CRSR Right - turn right [trans] *[idx] 54 [engl] CRSR Right - turn right [trans]
*[idx] 55 [engl] CRSR Up - accelerate [trans] *[idx] 55 [engl] CRSR Up - accelerate [trans]
*[idx] 56 [engl] CRSR down - brake [trans] *[idx] 56 [engl] CRSR down - brake [trans]
*[idx] 57 [engl] Keyboard Functions [trans] *[idx] 57 [engl] Keyboard Functions [trans]
*[idx] 65 [engl] Press any key to return to the main menu [trans]
*[idx] 58 [engl] Select your player name: [trans]
*[idx] 59 [engl] Select a character: [trans]
*[idx] 60 [engl] Enter [trans]
*[idx] 61 [engl] Register a new player [trans]
*[idx] 62 [engl] Highscore list [trans]
*[idx] 63 [engl] No entries for this race [trans]
*[idx] 64 [engl] Back [trans]
*[idx] 66 [engl] Enter a name for the new player and select an avatar: [trans]
*[idx] 67 [engl] Loading resources, [trans]
*[idx] 68 [engl] please wait [trans]
*[idx] 69 [engl] Mirror track: Off [trans]
*[idx] 70 [engl] Mirror track: On [trans]
*[idx] 71 [engl] Light: Sunny [trans]
*[idx] 72 [engl] Light: Cloudy [trans]
*[idx] 73 [engl] Light: Evening [trans]
*[idx] 74 [engl] Light: Night [trans]
*[idx] 75 [engl] Snow: No [trans]
*[idx] 76 [engl] Snow: A little [trans]
*[idx] 77 [engl] Snow: Some [trans]
*[idx] 78 [engl] Snow: A lot [trans]
*[idx] 79 [engl] Wind: No [trans]
*[idx] 80 [engl] Wind: Breeze [trans]
*[idx] 81 [engl] Wind: Strong [trans]
*[idx] 82 [engl] Wind: Blustery [trans]
*[idx] 83 [engl] Randomize settings [trans]
*[idx] 84 [engl] Score [trans]
*[idx] 85 [engl] Herring [trans]
*[idx] 86 [engl] Time [trans]
*[idx] 87 [engl] Path length [trans]
*[idx] 88 [engl] Average speed [trans]
*[idx] 89 [engl] Position [trans]
*[idx] 90 [engl] in highscore list [trans]

View File

@ -31,28 +31,28 @@ CSound Sound;
// class CAudio // class CAudio
// -------------------------------------------------------------------- // --------------------------------------------------------------------
CAudio::CAudio () { CAudio::CAudio() {
IsOpen = false; IsOpen = false;
} }
void CAudio::Open () { void CAudio::Open() {
// first initialize audio (SDL, not SDL_Mixer). // first initialize audio (SDL, not SDL_Mixer).
if (SDL_Init (SDL_INIT_AUDIO) < 0) { if (SDL_Init(SDL_INIT_AUDIO) < 0) {
Message ("Couldn't initialize SDL Audio", SDL_GetError()); Message("Couldn't initialize SDL Audio", SDL_GetError());
return; return;
} }
Uint16 format = AUDIO_S16SYS; Uint16 format = AUDIO_S16SYS;
int channels = 2; int channels = 2;
if (Mix_OpenAudio (param.audio_freq, format, channels, param.audio_buffer_size) < 0) if (Mix_OpenAudio(param.audio_freq, format, channels, param.audio_buffer_size) < 0)
Message ("Couldn't open SDL_mixer", Mix_GetError()); Message("Couldn't open SDL_mixer", Mix_GetError());
IsOpen = CheckOpen (); IsOpen = CheckOpen();
Mix_AllocateChannels (8); Mix_AllocateChannels(8);
} }
void CAudio::Close () { void CAudio::Close() {
if (IsOpen) { if (IsOpen) {
Music.FreeMusics (); Music.FreeMusics();
Sound.FreeSounds (); Sound.FreeSounds();
Mix_CloseAudio(); Mix_CloseAudio();
IsOpen = false; IsOpen = false;
} }
@ -62,7 +62,7 @@ bool CAudio::CheckOpen() {
int freq; int freq;
Uint16 format; Uint16 format;
int channels; int channels;
int ret = Mix_QuerySpec (&freq, &format, &channels); int ret = Mix_QuerySpec(&freq, &format, &channels);
return (ret > 0); return (ret > 0);
} }
@ -70,47 +70,47 @@ bool CAudio::CheckOpen() {
// class CSound // class CSound
// -------------------------------------------------------------------- // --------------------------------------------------------------------
bool CSound::LoadChunk (const std::string& name, const char *filename) { bool CSound::LoadChunk(const std::string& name, const char *filename) {
if (Audio.IsOpen == false) return false; if (Audio.IsOpen == false) return false;
sounds.push_back(TSound()); sounds.push_back(TSound());
sounds.back().chunk = Mix_LoadWAV (filename); sounds.back().chunk = Mix_LoadWAV(filename);
if (sounds.back().chunk == NULL) return false; if (sounds.back().chunk == NULL) return false;
sounds.back().channel = -1; // default: no channel sounds.back().channel = -1; // default: no channel
sounds.back().loop_count = 0; // default: playing once sounds.back().loop_count = 0; // default: playing once
Mix_VolumeChunk (sounds.back().chunk, param.sound_volume); Mix_VolumeChunk(sounds.back().chunk, param.sound_volume);
SoundIndex[name] = sounds.size()-1; SoundIndex[name] = sounds.size()-1;
return true; return true;
} }
// Load all soundfiles listed in "/sounds/sounds.lst" // Load all soundfiles listed in "/sounds/sounds.lst"
void CSound::LoadSoundList () { void CSound::LoadSoundList() {
if (!Audio.IsOpen) { if (!Audio.IsOpen) {
Message ("cannot load music, first open Audio"); Message("cannot load music, first open Audio");
return; return;
} }
CSPList list(200); CSPList list(200);
if (list.Load (param.sounds_dir, "sounds.lst")) { if (list.Load(param.sounds_dir, "sounds.lst")) {
for (size_t i=0; i<list.Count(); i++) { for (size_t i=0; i<list.Count(); i++) {
const string& line = list.Line(i); const string& line = list.Line(i);
string name = SPStrN (line, "name"); string name = SPStrN(line, "name");
string soundfile = SPStrN (line, "file"); string soundfile = SPStrN(line, "file");
string path = MakePathStr (param.sounds_dir, soundfile); string path = MakePathStr(param.sounds_dir, soundfile);
LoadChunk (name, path.c_str()); LoadChunk(name, path.c_str());
} }
} }
} }
void CSound::FreeSounds () { void CSound::FreeSounds() {
HaltAll (); HaltAll();
for (size_t i=0; i<sounds.size(); i++) for (size_t i=0; i<sounds.size(); i++)
if (sounds[i].chunk != NULL) if (sounds[i].chunk != NULL)
Mix_FreeChunk (sounds[i].chunk); Mix_FreeChunk(sounds[i].chunk);
sounds.clear(); sounds.clear();
SoundIndex.clear(); SoundIndex.clear();
} }
size_t CSound::GetSoundIdx (const string& name) const { size_t CSound::GetSoundIdx(const string& name) const {
if (Audio.IsOpen == false) return -1; if (Audio.IsOpen == false) return -1;
try { try {
return SoundIndex.at(name); return SoundIndex.at(name);
@ -119,17 +119,17 @@ size_t CSound::GetSoundIdx (const string& name) const {
} }
} }
void CSound::SetVolume (size_t soundid, int volume) { void CSound::SetVolume(size_t soundid, int volume) {
if (Audio.IsOpen == false) return; if (Audio.IsOpen == false) return;
if (soundid >= sounds.size()) return; if (soundid >= sounds.size()) return;
volume = clamp(0, volume, MIX_MAX_VOLUME); volume = clamp(0, volume, MIX_MAX_VOLUME);
if (sounds[soundid].chunk == NULL) return; if (sounds[soundid].chunk == NULL) return;
Mix_VolumeChunk (sounds[soundid].chunk, volume); Mix_VolumeChunk(sounds[soundid].chunk, volume);
} }
void CSound::SetVolume (const string& name, int volume) { void CSound::SetVolume(const string& name, int volume) {
SetVolume (GetSoundIdx (name), volume); SetVolume(GetSoundIdx(name), volume);
} }
// ------------------- play ------------------------------------------- // ------------------- play -------------------------------------------
@ -138,56 +138,56 @@ void TSound::Play(int loop) {
if (active == true) return; if (active == true) return;
if (chunk == NULL) return; if (chunk == NULL) return;
channel = Mix_PlayChannel (-1, chunk, loop); channel = Mix_PlayChannel(-1, chunk, loop);
loop_count = loop; loop_count = loop;
if (loop < 0) active = true; if (loop < 0) active = true;
} }
void CSound::Play (size_t soundid, int loop) { void CSound::Play(size_t soundid, int loop) {
if (!Audio.IsOpen) return; if (!Audio.IsOpen) return;
if (soundid >= sounds.size()) return; if (soundid >= sounds.size()) return;
sounds[soundid].Play(loop); sounds[soundid].Play(loop);
} }
void CSound::Play (const string& name, int loop) { void CSound::Play(const string& name, int loop) {
Play (GetSoundIdx (name), loop); Play(GetSoundIdx(name), loop);
} }
void CSound::Play (size_t soundid, int loop, int volume) { void CSound::Play(size_t soundid, int loop, int volume) {
if (!Audio.IsOpen) return; if (!Audio.IsOpen) return;
if (soundid >= sounds.size()) return; if (soundid >= sounds.size()) return;
volume = clamp(0, volume, MIX_MAX_VOLUME); volume = clamp(0, volume, MIX_MAX_VOLUME);
Mix_VolumeChunk (sounds[soundid].chunk, volume); Mix_VolumeChunk(sounds[soundid].chunk, volume);
sounds[soundid].Play(loop); sounds[soundid].Play(loop);
} }
void CSound::Play (const string& name, int loop, int volume) { void CSound::Play(const string& name, int loop, int volume) {
Play (GetSoundIdx (name), loop, volume); Play(GetSoundIdx(name), loop, volume);
} }
void CSound::Halt (size_t soundid) { void CSound::Halt(size_t soundid) {
if (!Audio.IsOpen) return; if (!Audio.IsOpen) return;
if (soundid >= sounds.size()) return; if (soundid >= sounds.size()) return;
if (sounds[soundid].chunk == NULL) return; if (sounds[soundid].chunk == NULL) return;
// loop_count must be -1 (endless loop) for halt // loop_count must be -1 (endless loop) for halt
if (sounds[soundid].loop_count < 0) { if (sounds[soundid].loop_count < 0) {
Mix_HaltChannel (sounds[soundid].channel); Mix_HaltChannel(sounds[soundid].channel);
sounds[soundid].loop_count = 0; sounds[soundid].loop_count = 0;
sounds[soundid].channel = -1; sounds[soundid].channel = -1;
sounds[soundid].active = false; sounds[soundid].active = false;
} }
} }
void CSound::Halt (const string& name) { void CSound::Halt(const string& name) {
Halt (GetSoundIdx (name)); Halt(GetSoundIdx(name));
} }
void CSound::HaltAll () { void CSound::HaltAll() {
if (!Audio.IsOpen) return; if (!Audio.IsOpen) return;
Mix_HaltChannel (-1); Mix_HaltChannel(-1);
for (size_t i=0; i<sounds.size(); i++) { for (size_t i=0; i<sounds.size(); i++) {
sounds[i].loop_count = 0; sounds[i].loop_count = 0;
sounds[i].channel = -1; sounds[i].channel = -1;
@ -199,23 +199,23 @@ void CSound::HaltAll () {
// class CMusic // class CMusic
// -------------------------------------------------------------------- // --------------------------------------------------------------------
void Hook () { void Hook() {
Mix_HaltMusic(); Mix_HaltMusic();
PrintStr ("halted"); PrintStr("halted");
} }
CMusic::CMusic () { CMusic::CMusic() {
curr_music = 0; curr_music = 0;
curr_volume = 10; curr_volume = 10;
loop_count = 0; loop_count = 0;
// Mix_HookMusicFinished (Hook); // Mix_HookMusicFinished (Hook);
} }
bool CMusic::LoadPiece (const string& name, const char *filename) { bool CMusic::LoadPiece(const string& name, const char *filename) {
if (!Audio.IsOpen) return -1; if (!Audio.IsOpen) return -1;
Mix_Music* m = Mix_LoadMUS (filename); Mix_Music* m = Mix_LoadMUS(filename);
if (m == NULL) { if (m == NULL) {
Message ("could not load music", filename); Message("could not load music", filename);
return false; return false;
} }
MusicIndex[name] = musics.size(); MusicIndex[name] = musics.size();
@ -223,50 +223,50 @@ bool CMusic::LoadPiece (const string& name, const char *filename) {
return true; return true;
} }
void CMusic::LoadMusicList () { void CMusic::LoadMusicList() {
if (!Audio.IsOpen) { if (!Audio.IsOpen) {
Message ("cannot load music, first open audio"); Message("cannot load music, first open audio");
return; return;
} }
// --- music --- // --- music ---
CSPList list(200); CSPList list(200);
if (list.Load (param.music_dir, "music.lst")) { if (list.Load(param.music_dir, "music.lst")) {
for (size_t i=0; i<list.Count(); i++) { for (size_t i=0; i<list.Count(); i++) {
const string& line = list.Line(i); const string& line = list.Line(i);
string name = SPStrN (line, "name"); string name = SPStrN(line, "name");
string musicfile = SPStrN (line, "file"); string musicfile = SPStrN(line, "file");
string path = MakePathStr (param.music_dir, musicfile); string path = MakePathStr(param.music_dir, musicfile);
LoadPiece (name, path.c_str()); LoadPiece(name, path.c_str());
} }
} else { } else {
Message ("could not load music.lst"); Message("could not load music.lst");
return; return;
} }
// --- racing themes --- // --- racing themes ---
list.Clear(); list.Clear();
ThemesIndex.clear(); ThemesIndex.clear();
if (list.Load (param.music_dir, "racing_themes.lst")) { if (list.Load(param.music_dir, "racing_themes.lst")) {
themes.resize(list.Count()); themes.resize(list.Count());
for (size_t i=0; i<list.Count(); i++) { for (size_t i=0; i<list.Count(); i++) {
const string& line = list.Line(i); const string& line = list.Line(i);
string name = SPStrN (line, "name"); string name = SPStrN(line, "name");
ThemesIndex[name] = i; ThemesIndex[name] = i;
string item = SPStrN (line, "race", "race_1"); string item = SPStrN(line, "race", "race_1");
themes[i].situation[0] = musics[MusicIndex[item]]; themes[i].situation[0] = musics[MusicIndex[item]];
item = SPStrN (line, "wonrace", "wonrace_1"); item = SPStrN(line, "wonrace", "wonrace_1");
themes[i].situation[1] = musics[MusicIndex[item]]; themes[i].situation[1] = musics[MusicIndex[item]];
item = SPStrN (line, "lostrace", "lostrace_1"); item = SPStrN(line, "lostrace", "lostrace_1");
themes[i].situation[2] = musics[MusicIndex[item]]; themes[i].situation[2] = musics[MusicIndex[item]];
} }
} else Message ("could not load racing_themes.lst"); } else Message("could not load racing_themes.lst");
} }
void CMusic::FreeMusics () { void CMusic::FreeMusics() {
Halt (); Halt();
for (size_t i=0; i<musics.size(); i++) for (size_t i=0; i<musics.size(); i++)
if (musics[i] != NULL) if (musics[i] != NULL)
Mix_FreeMusic (musics[i]); Mix_FreeMusic(musics[i]);
musics.clear(); musics.clear();
MusicIndex.clear(); MusicIndex.clear();
@ -277,7 +277,7 @@ void CMusic::FreeMusics () {
curr_volume = 10; curr_volume = 10;
} }
size_t CMusic::GetMusicIdx (const string& name) const { size_t CMusic::GetMusicIdx(const string& name) const {
if (Audio.IsOpen == false) return -1; if (Audio.IsOpen == false) return -1;
try { try {
return MusicIndex.at(name); return MusicIndex.at(name);
@ -286,7 +286,7 @@ size_t CMusic::GetMusicIdx (const string& name) const {
} }
} }
size_t CMusic::GetThemeIdx (const string& theme) const { size_t CMusic::GetThemeIdx(const string& theme) const {
if (Audio.IsOpen == false) return -1; if (Audio.IsOpen == false) return -1;
try { try {
return ThemesIndex.at(theme); return ThemesIndex.at(theme);
@ -295,9 +295,9 @@ size_t CMusic::GetThemeIdx (const string& theme) const {
} }
} }
void CMusic::SetVolume (int volume) { void CMusic::SetVolume(int volume) {
int vol = clamp(0, volume, MIX_MAX_VOLUME); int vol = clamp(0, volume, MIX_MAX_VOLUME);
Mix_VolumeMusic (vol); Mix_VolumeMusic(vol);
curr_volume = vol; curr_volume = vol;
} }
@ -305,56 +305,56 @@ void CMusic::SetVolume (int volume) {
// probably a bug in SDL_mixer. Help: we have to refresh the volume // probably a bug in SDL_mixer. Help: we have to refresh the volume
// in each (!) frame. // in each (!) frame.
void CMusic::Update () { void CMusic::Update() {
Mix_VolumeMusic (curr_volume); Mix_VolumeMusic(curr_volume);
} }
bool CMusic::Play (Mix_Music* music, int loop, int volume) { bool CMusic::Play(Mix_Music* music, int loop, int volume) {
if (!music) if (!music)
return false; return false;
int vol = clamp(0, volume, MIX_MAX_VOLUME); int vol = clamp(0, volume, MIX_MAX_VOLUME);
if (music != curr_music) { if (music != curr_music) {
Halt (); Halt();
Mix_PlayMusic (music, loop); Mix_PlayMusic(music, loop);
curr_music = music; curr_music = music;
loop_count = loop; loop_count = loop;
} }
Mix_VolumeMusic (vol); Mix_VolumeMusic(vol);
return true; return true;
} }
bool CMusic::Play (size_t musid, int loop) { bool CMusic::Play(size_t musid, int loop) {
if (!Audio.IsOpen) return false; if (!Audio.IsOpen) return false;
if (musid >= musics.size()) return false; if (musid >= musics.size()) return false;
Mix_Music *music = musics[musid]; Mix_Music *music = musics[musid];
return Play(music, loop, curr_volume); return Play(music, loop, curr_volume);
} }
bool CMusic::Play (const string& name, int loop) { bool CMusic::Play(const string& name, int loop) {
return Play (GetMusicIdx(name), loop); return Play(GetMusicIdx(name), loop);
} }
bool CMusic::Play (size_t musid, int loop, int volume) { bool CMusic::Play(size_t musid, int loop, int volume) {
if (!Audio.IsOpen) return false; if (!Audio.IsOpen) return false;
if (musid >= musics.size()) return false; if (musid >= musics.size()) return false;
Mix_Music *music = musics[musid]; Mix_Music *music = musics[musid];
return Play(music, loop, volume); return Play(music, loop, volume);
} }
bool CMusic::Play (const string& name, int loop, int volume) { bool CMusic::Play(const string& name, int loop, int volume) {
return Play (GetMusicIdx (name), loop, volume); return Play(GetMusicIdx(name), loop, volume);
} }
bool CMusic::PlayTheme (size_t theme, ESituation situation) { bool CMusic::PlayTheme(size_t theme, ESituation situation) {
if (theme >= themes.size()) return false; if (theme >= themes.size()) return false;
if (situation >= SITUATION_COUNT) return false; if (situation >= SITUATION_COUNT) return false;
Mix_Music *music = themes [theme].situation[situation]; Mix_Music *music = themes [theme].situation[situation];
return Play (music, -1, curr_volume); return Play(music, -1, curr_volume);
} }
void CMusic::Halt () { void CMusic::Halt() {
if (Mix_PlayingMusic ()) Mix_HaltMusic(); if (Mix_PlayingMusic()) Mix_HaltMusic();
loop_count = -1; loop_count = -1;
curr_music = 0; curr_music = 0;
} }

View File

@ -29,11 +29,11 @@ GNU General Public License for more details.
class CAudio { class CAudio {
private: private:
public: public:
CAudio (); CAudio();
void Open (); void Open();
void Close (); void Close();
static bool CheckOpen (); static bool CheckOpen();
bool IsOpen; bool IsOpen;
}; };
@ -47,7 +47,7 @@ struct TSound {
int loop_count; int loop_count;
bool active; bool active;
void Play (int loop); void Play(int loop);
}; };
class CSound { class CSound {
@ -55,23 +55,23 @@ private:
vector<TSound> sounds; vector<TSound> sounds;
map<string, size_t> SoundIndex; map<string, size_t> SoundIndex;
public: public:
bool LoadChunk (const std::string& name, const char *filename); bool LoadChunk(const std::string& name, const char *filename);
void LoadSoundList (); void LoadSoundList();
size_t GetSoundIdx (const string& name) const; size_t GetSoundIdx(const string& name) const;
void SetVolume (size_t soundid, int volume); void SetVolume(size_t soundid, int volume);
void SetVolume (const string& name, int volume); void SetVolume(const string& name, int volume);
void Play (size_t soundid, int loop); void Play(size_t soundid, int loop);
void Play (const string& name, int loop); // -1 infinite, 0 once, 1 twice ... void Play(const string& name, int loop); // -1 infinite, 0 once, 1 twice ...
void Play (size_t soundid, int loop, int volume); void Play(size_t soundid, int loop, int volume);
void Play (const string& name, int loop, int volume); void Play(const string& name, int loop, int volume);
void Halt (size_t soundid); void Halt(size_t soundid);
void Halt (const string& name); void Halt(const string& name);
void HaltAll (); void HaltAll();
void FreeSounds (); void FreeSounds();
}; };
// -------------------------------------------------------------------- // --------------------------------------------------------------------
@ -98,24 +98,24 @@ private:
Mix_Music* curr_music; // current music piece Mix_Music* curr_music; // current music piece
int curr_volume; int curr_volume;
bool Play (Mix_Music* music, int loop, int volume); bool Play(Mix_Music* music, int loop, int volume);
public: public:
CMusic (); CMusic();
bool LoadPiece (const string& name, const char *filename); bool LoadPiece(const string& name, const char *filename);
void LoadMusicList (); void LoadMusicList();
size_t GetMusicIdx (const string& name) const; size_t GetMusicIdx(const string& name) const;
size_t GetThemeIdx (const string& theme) const; size_t GetThemeIdx(const string& theme) const;
void SetVolume (int volume); void SetVolume(int volume);
void Update (); void Update();
bool Play (size_t musid, int loop); bool Play(size_t musid, int loop);
bool Play (const string& name, int loop); bool Play(const string& name, int loop);
bool Play (size_t musid, int loop, int volume); bool Play(size_t musid, int loop, int volume);
bool Play (const string& name, int loop, int volume); bool Play(const string& name, int loop, int volume);
bool PlayTheme (size_t theme, ESituation situation); bool PlayTheme(size_t theme, ESituation situation);
void Halt (); void Halt();
void FreeMusics (); void FreeMusics();
}; };
// -------------------------------------------------------------------- // --------------------------------------------------------------------

View File

@ -30,77 +30,77 @@ GNU General Public License for more details.
// color utils // color utils
// -------------------------------------------------------------------- // --------------------------------------------------------------------
const TColor colWhite (1.0, 1.0, 1.0, 1.0); const TColor colWhite(1.0, 1.0, 1.0, 1.0);
const TColor colDYell (1.0, 0.8, 0.0, 1.0); const TColor colDYell(1.0, 0.8, 0.0, 1.0);
const TColor colDDYell (0.8, 0.6, 0.0, 1.0); const TColor colDDYell(0.8, 0.6, 0.0, 1.0);
const TColor colYellow (1.0, 1.0, 0.0, 1.0); const TColor colYellow(1.0, 1.0, 0.0, 1.0);
const TColor colLYell (1.0, 1.0, 0.4, 1.0); const TColor colLYell(1.0, 1.0, 0.4, 1.0);
const TColor colOrange (1.0, 0.5, 0.0, 1.0); const TColor colOrange(1.0, 0.5, 0.0, 1.0);
const TColor colLRed (1.0, 0.3, 0.3, 1.0); const TColor colLRed(1.0, 0.3, 0.3, 1.0);
const TColor colRed (1.0, 0.0, 0.0, 1.0); const TColor colRed(1.0, 0.0, 0.0, 1.0);
const TColor colDRed (0.8, 0.0, 0.0, 1.0); const TColor colDRed(0.8, 0.0, 0.0, 1.0);
const TColor colGrey (0.5, 0.5, 0.5, 1.0); const TColor colGrey(0.5, 0.5, 0.5, 1.0);
const TColor colLGrey (0.7, 0.7, 0.7, 1.0); const TColor colLGrey(0.7, 0.7, 0.7, 1.0);
const TColor colDGrey (0.3, 0.3, 0.3, 1.0); const TColor colDGrey(0.3, 0.3, 0.3, 1.0);
const TColor colBlack (0.0, 0.0, 0.0, 1.0); const TColor colBlack(0.0, 0.0, 0.0, 1.0);
const TColor colBlue (0.0, 0.0, 1.0, 1.0); const TColor colBlue(0.0, 0.0, 1.0, 1.0);
const TColor colLBlue (0.5, 0.7, 1.0, 1.0); const TColor colLBlue(0.5, 0.7, 1.0, 1.0);
const TColor colDBlue (0.0, 0.0, 0.6, 1.0); const TColor colDBlue(0.0, 0.0, 0.6, 1.0);
const TColor colLBackgr (0.5, 0.7, 0.9, 1.0); const TColor colLBackgr(0.5, 0.7, 0.9, 1.0);
const TColor colBackgr (0.4, 0.6, 0.8, 1.0); const TColor colBackgr(0.4, 0.6, 0.8, 1.0);
const TColor colMBackgr (0.35, 0.5, 0.7, 1.0); const TColor colMBackgr(0.35, 0.5, 0.7, 1.0);
const TColor colDBackgr (0.2, 0.3, 0.6, 1.0); const TColor colDBackgr(0.2, 0.3, 0.6, 1.0);
const TColor colDDBackgr (0.13, 0.2, 0.4, 1.0); const TColor colDDBackgr(0.13, 0.2, 0.4, 1.0);
const TColor colMess (0.3, 0.3, 0.7, 1.0); const TColor colMess(0.3, 0.3, 0.7, 1.0);
const TColor colSky (0.82, 0.86, 0.88, 1.0); const TColor colSky(0.82, 0.86, 0.88, 1.0);
// -------------------------------------------------------------------- // --------------------------------------------------------------------
// print utils // print utils
// -------------------------------------------------------------------- // --------------------------------------------------------------------
void PrintInt (const int val) { void PrintInt(const int val) {
cout << "Integer: " << val << '\n'; cout << "Integer: " << val << '\n';
} }
void PrintInt (const string& s, const int val) { void PrintInt(const string& s, const int val) {
cout << s << val << endl; cout << s << val << endl;
} }
void PrintStr (const char *val) { void PrintStr(const char *val) {
cout << val << '\n'; cout << val << '\n';
} }
void PrintString (const string& s) { void PrintString(const string& s) {
cout << s << endl; cout << s << endl;
} }
void PrintDouble (const double val) { void PrintDouble(const double val) {
cout.precision(4); cout.precision(4);
cout << val << '\n'; cout << val << '\n';
} }
void PrintVector4 (const TVector4d& v) { void PrintVector4(const TVector4d& v) {
cout.precision(3); cout.precision(3);
cout << v.x << " " << v.y << " " << v.z << " " << v.w << '\n'; cout << v.x << " " << v.y << " " << v.z << " " << v.w << '\n';
} }
void PrintColor (const TColor& v) { void PrintColor(const TColor& v) {
cout.precision(3); cout.precision(3);
cout << v.r << " " << v.g << " " << v.b << '\n'; cout << v.r << " " << v.g << " " << v.b << '\n';
} }
void PrintVector2 (const TVector2d& v) { void PrintVector2(const TVector2d& v) {
cout.precision(3); cout.precision(3);
cout << v.x << " " << v.y << '\n'; cout << v.x << " " << v.y << '\n';
} }
void PrintVector (const TVector3d& v) { void PrintVector(const TVector3d& v) {
cout.precision(5); cout.precision(5);
cout << v.x << " " << v.y << " " << v.z << '\n'; cout << v.x << " " << v.y << " " << v.z << '\n';
} }
template<int x, int y> template<int x, int y>
void PrintMatrix (const TMatrix<x, y>& mat) { void PrintMatrix(const TMatrix<x, y>& mat) {
cout << '\n'; cout << '\n';
cout.precision(3); cout.precision(3);
for (int i=0; i<x; i++) { for (int i=0; i<x; i++) {
@ -115,7 +115,7 @@ void PrintMatrix (const TMatrix<x, y>& mat) {
template void PrintMatrix<4, 4>(const TMatrix<4, 4>& mat); template void PrintMatrix<4, 4>(const TMatrix<4, 4>& mat);
template void PrintMatrix<3, 3>(const TMatrix<3, 3>& mat); template void PrintMatrix<3, 3>(const TMatrix<3, 3>& mat);
void PrintQuaternion (const TQuaternion& q) { void PrintQuaternion(const TQuaternion& q) {
cout.precision(5); cout.precision(5);
cout << "Quaternion: " << q.x << " " << q.y << " " << q.z << " " << q.w << '\n'; cout << "Quaternion: " << q.x << " " << q.y << " " << q.z << " " << q.w << '\n';
} }
@ -124,13 +124,13 @@ void PrintQuaternion (const TQuaternion& q) {
// message utils // message utils
// -------------------------------------------------------------------- // --------------------------------------------------------------------
static CSPList msg_list (100); static CSPList msg_list(100);
void SaveMessages () { void SaveMessages() {
msg_list.Save (param.config_dir, "messages"); msg_list.Save(param.config_dir, "messages");
} }
void Message (const char *msg, const char *desc) { void Message(const char *msg, const char *desc) {
if (*msg == 0 && *desc == 0) { if (*msg == 0 && *desc == 0) {
cout << '\n'; cout << '\n';
return; return;
@ -139,55 +139,51 @@ void Message (const char *msg, const char *desc) {
string aa = msg; string aa = msg;
string bb = desc; string bb = desc;
cout << aa << " " << bb << '\n'; cout << aa << " " << bb << '\n';
msg_list.Add (aa + bb); msg_list.Add(aa + bb);
} }
void Message (const char *msg) { void Message(const char *msg) {
cout << msg << '\n'; cout << msg << '\n';
if (*msg != 0) if (*msg != 0)
msg_list.Add (msg); msg_list.Add(msg);
} }
void Message (const string& a, const string& b) { void Message(const string& a, const string& b) {
cout << a << ' ' << b << endl; cout << a << ' ' << b << endl;
msg_list.Add (a + b); msg_list.Add(a + b);
} }
void Message (const string& msg) { void Message(const string& msg) {
cout << msg << endl; cout << msg << endl;
msg_list.Add (msg); msg_list.Add(msg);
} }
// -------------------------------------------------------------------- // --------------------------------------------------------------------
// file utils // file utils
// -------------------------------------------------------------------- // --------------------------------------------------------------------
bool FileExists (const char *filename) { bool FileExists(const string& filename) {
struct stat stat_info; struct stat stat_info;
if (stat (filename, &stat_info) != 0) { if (stat(filename.c_str(), &stat_info) != 0) {
if (errno != ENOENT) Message ("couldn't stat ", filename); if (errno != ENOENT) Message("couldn't stat ", filename);
return false; return false;
} else return true; } else return true;
} }
bool FileExists (const string& filename) { bool FileExists(const string& dir, const string& filename) {
return FileExists (filename.c_str()); return FileExists(dir + SEP + filename);
}
bool FileExists (const string& dir, const string& filename) {
return FileExists (dir + SEP + filename);
} }
#ifndef OS_WIN32_MSC #ifndef OS_WIN32_MSC
bool DirExists (const char *dirname) { bool DirExists(const char *dirname) {
DIR *xdir; DIR *xdir;
if ((xdir = opendir (dirname)) == 0) if ((xdir = opendir(dirname)) == 0)
return ((errno != ENOENT) && (errno != ENOTDIR)); return ((errno != ENOENT) && (errno != ENOTDIR));
if (closedir (xdir) != 0) Message ("Couldn't close directory", dirname); if (closedir(xdir) != 0) Message("Couldn't close directory", dirname);
return true; return true;
} }
#else #else
bool DirExists (const char *dirname) { bool DirExists(const char *dirname) {
DWORD typ = GetFileAttributesA(dirname); DWORD typ = GetFileAttributesA(dirname);
if (typ == INVALID_FILE_ATTRIBUTES) if (typ == INVALID_FILE_ATTRIBUTES)
return false; // Doesn't exist return false; // Doesn't exist
@ -200,23 +196,23 @@ bool DirExists (const char *dirname) {
// date and time // date and time
// -------------------------------------------------------------------- // --------------------------------------------------------------------
void GetTimeComponents (double time, int *min, int *sec, int *hundr) { void GetTimeComponents(double time, int *min, int *sec, int *hundr) {
*min = (int) (time / 60); *min = (int)(time / 60);
*sec = ((int) time) % 60; *sec = ((int) time) % 60;
*hundr = ((int) (time * 100 + 0.5) ) % 100; *hundr = ((int)(time * 100 + 0.5)) % 100;
} }
string GetTimeString () { string GetTimeString() {
time_t rawtime; time_t rawtime;
struct tm * timeinfo; struct tm * timeinfo;
time (&rawtime); time(&rawtime);
timeinfo = localtime (&rawtime); timeinfo = localtime(&rawtime);
// line = Int_StrN (timeinfo->tm_year-100); // line = Int_StrN (timeinfo->tm_year-100);
string line = Int_StrN (timeinfo->tm_mon + 1); string line = Int_StrN(timeinfo->tm_mon + 1);
line += "_" + Int_StrN (timeinfo->tm_mday); line += "_" + Int_StrN(timeinfo->tm_mday);
line += "_" + Int_StrN (timeinfo->tm_hour); line += "_" + Int_StrN(timeinfo->tm_hour);
line += Int_StrN (timeinfo->tm_min); line += Int_StrN(timeinfo->tm_min);
line += Int_StrN (timeinfo->tm_sec); line += Int_StrN(timeinfo->tm_sec);
return line; return line;
} }

View File

@ -77,45 +77,44 @@ extern const TColor colSky;
// -------------------------------------------------------------------- // --------------------------------------------------------------------
// some simple functions to print out values on the // some simple functions to print out values on the
// terminal. Only used for development. // terminal. Only used for development.
void PrintInt (const int val); void PrintInt(const int val);
void PrintInt (const string& s, const int val); void PrintInt(const string& s, const int val);
void PrintStr (const char *val); void PrintStr(const char *val);
void PrintString (const string& s); void PrintString(const string& s);
void PrintDouble (const double val); void PrintDouble(const double val);
void PrintVector (const TVector3d& v); void PrintVector(const TVector3d& v);
void PrintVector4 (const TVector4d& v); void PrintVector4(const TVector4d& v);
void PrintColor (const TColor& c); void PrintColor(const TColor& c);
void PrintVector2 (const TVector2d& v); void PrintVector2(const TVector2d& v);
template<int x, int y> template<int x, int y>
void PrintMatrix (const TMatrix<x, y>& mat); void PrintMatrix(const TMatrix<x, y>& mat);
void PrintQuaternion (const TQuaternion& q); void PrintQuaternion(const TQuaternion& q);
// -------------------------------------------------------------------- // --------------------------------------------------------------------
// file utils // file utils
// -------------------------------------------------------------------- // --------------------------------------------------------------------
bool FileExists (const char *filename); bool FileExists(const string& filename);
bool FileExists (const string& filename); bool FileExists(const string& dir, const string& filename);
bool FileExists (const string& dir, const string& filename); bool DirExists(const char *dirname);
bool DirExists (const char *dirname);
// -------------------------------------------------------------------- // --------------------------------------------------------------------
// message utils // message utils
// -------------------------------------------------------------------- // --------------------------------------------------------------------
void Message (const char *msg, const char *desc); void Message(const char *msg, const char *desc);
void Message (const char *msg); void Message(const char *msg);
void Message (const string& a, const string& b); void Message(const string& a, const string& b);
void Message (const string& a); void Message(const string& a);
void SaveMessages (); void SaveMessages();
// -------------------------------------------------------------------- // --------------------------------------------------------------------
// date and time // date and time
// -------------------------------------------------------------------- // --------------------------------------------------------------------
void GetTimeComponents (double time, int *min, int *sec, int *hundr); void GetTimeComponents(double time, int *min, int *sec, int *hundr);
string GetTimeString (); string GetTimeString();
#endif #endif

View File

@ -48,9 +48,6 @@ Then edit the below functions:
#include "gui.h" #include "gui.h"
#include "textures.h" #include "textures.h"
#include "font.h" #include "font.h"
#include "translation.h"
#include "course.h"
#include "game_ctrl.h"
#include "winsys.h" #include "winsys.h"
CGameConfig GameConfig; CGameConfig GameConfig;
@ -64,8 +61,7 @@ static TUpDown* sound_vol;
static TUpDown* detail_level; static TUpDown* detail_level;
static TWidget* textbuttons[2]; static TWidget* textbuttons[2];
void SetConfig() {
void SetConfig () {
if (mus_vol->GetValue() != param.music_volume || if (mus_vol->GetValue() != param.music_volume ||
sound_vol->GetValue() != param.sound_volume || sound_vol->GetValue() != param.sound_volume ||
language->GetValue() != param.language || language->GetValue() != param.language ||
@ -89,20 +85,20 @@ void SetConfig () {
// the followind config params don't require a new VideoMode // the followind config params don't require a new VideoMode
// they only must stored in the param structure (and saved) // they only must stored in the param structure (and saved)
param.music_volume = mus_vol->GetValue(); param.music_volume = mus_vol->GetValue();
Music.SetVolume (param.music_volume); Music.SetVolume(param.music_volume);
param.sound_volume = sound_vol->GetValue(); param.sound_volume = sound_vol->GetValue();
param.perf_level = detail_level->GetValue(); param.perf_level = detail_level->GetValue();
Winsys.SetFonttype (); FT.SetFontFromSettings();
if (param.language != language->GetValue()) { if (param.language != language->GetValue()) {
param.language = language->GetValue(); param.language = language->GetValue();
Trans.LoadTranslations (param.language); Trans.LoadTranslations(param.language);
} }
SaveConfigFile (); SaveConfigFile();
} }
State::manager.RequestEnterState(*State::manager.PreviousState()); State::manager.RequestEnterState(*State::manager.PreviousState());
} }
void CGameConfig::Keyb (unsigned int key, bool special, bool release, int x, int y) { void CGameConfig::Keyb(unsigned int key, bool special, bool release, int x, int y) {
if (release) return; if (release) return;
if (key != SDLK_UP && key != SDLK_DOWN) if (key != SDLK_UP && key != SDLK_DOWN)
@ -112,13 +108,13 @@ void CGameConfig::Keyb (unsigned int key, bool special, bool release, int x, int
State::manager.RequestQuit(); State::manager.RequestQuit();
break; break;
case SDLK_ESCAPE: case SDLK_ESCAPE:
State::manager.RequestEnterState (*State::manager.PreviousState()); State::manager.RequestEnterState(*State::manager.PreviousState());
break; break;
case SDLK_RETURN: case SDLK_RETURN:
if (textbuttons[0]->focussed()) if (textbuttons[0]->focussed())
State::manager.RequestEnterState (*State::manager.PreviousState()); State::manager.RequestEnterState(*State::manager.PreviousState());
else if (textbuttons[1]->focussed()) else if (textbuttons[1]->focussed())
SetConfig (); SetConfig();
break; break;
case SDLK_UP: case SDLK_UP:
DecreaseFocus(); DecreaseFocus();
@ -129,21 +125,21 @@ void CGameConfig::Keyb (unsigned int key, bool special, bool release, int x, int
} }
} }
void CGameConfig::Mouse (int button, int state, int x, int y) { void CGameConfig::Mouse(int button, int state, int x, int y) {
if (state == 1) { if (state == 1) {
TWidget* focussed = ClickGUI(x, y); TWidget* focussed = ClickGUI(x, y);
if (focussed == textbuttons[0]) if (focussed == textbuttons[0])
State::manager.RequestEnterState (*State::manager.PreviousState()); State::manager.RequestEnterState(*State::manager.PreviousState());
else if (focussed == textbuttons[1]) else if (focussed == textbuttons[1])
SetConfig (); SetConfig();
} }
} }
void CGameConfig::Motion (int x, int y) { void CGameConfig::Motion(int x, int y) {
MouseMoveGUI(x, y); MouseMoveGUI(x, y);
if (param.ui_snow) push_ui_snow (cursor_pos); if (param.ui_snow) push_ui_snow(cursor_pos);
} }
// ------------------ Init -------------------------------------------- // ------------------ Init --------------------------------------------
@ -152,20 +148,20 @@ static TArea area;
static int dd; static int dd;
void CGameConfig::Enter() { void CGameConfig::Enter() {
Winsys.ShowCursor (!param.ice_cursor); Winsys.ShowCursor(!param.ice_cursor);
Winsys.KeyRepeat (true); Winsys.KeyRepeat(true);
for (int i=0; i<NUM_RESOLUTIONS; i++) res_names[i] = Winsys.GetResName (i); for (int i=0; i<NUM_RESOLUTIONS; i++) res_names[i] = Winsys.GetResName(i);
int framewidth = 550 * Winsys.scale; int framewidth = 550 * Winsys.scale;
area = AutoAreaN (30, 80, framewidth); area = AutoAreaN(30, 80, framewidth);
FT.AutoSizeN (4); FT.AutoSizeN(4);
dd = FT.AutoDistanceN (3); dd = FT.AutoDistanceN(3);
if (dd < 36) dd = 36; if (dd < 36) dd = 36;
int rightpos = area.right -48; int rightpos = area.right -48;
ResetGUI (); ResetGUI();
fullscreen = AddCheckbox (area.left, area.top, framewidth-16, Trans.Text(31)); fullscreen = AddCheckbox(area.left, area.top, framewidth-16, Trans.Text(31));
fullscreen->checked = param.fullscreen; fullscreen->checked = param.fullscreen;
resolution = AddUpDown(rightpos, area.top+dd*1, 0, NUM_RESOLUTIONS-1, (int)param.res_type); resolution = AddUpDown(rightpos, area.top+dd*1, 0, NUM_RESOLUTIONS-1, (int)param.res_type);
@ -174,90 +170,88 @@ void CGameConfig::Enter() {
detail_level = AddUpDown(rightpos, area.top+dd*4, 1, 4, param.perf_level); detail_level = AddUpDown(rightpos, area.top+dd*4, 1, 4, param.perf_level);
language = AddUpDown(rightpos, area.top+dd*5, 0, (int)Trans.languages.size() - 1, (int)param.language); language = AddUpDown(rightpos, area.top+dd*5, 0, (int)Trans.languages.size() - 1, (int)param.language);
int siz = FT.AutoSizeN (5); int siz = FT.AutoSizeN(5);
textbuttons[0] = AddTextButton (Trans.Text(28), area.left+50, AutoYPosN (80), siz); textbuttons[0] = AddTextButton(Trans.Text(28), area.left+50, AutoYPosN(80), siz);
double len = FT.GetTextWidth (Trans.Text(8)); double len = FT.GetTextWidth(Trans.Text(8));
textbuttons[1] = AddTextButton (Trans.Text(15), area.right-len-50, AutoYPosN (80), siz); textbuttons[1] = AddTextButton(Trans.Text(15), area.right-len-50, AutoYPosN(80), siz);
Music.Play (param.config_music, -1); Music.Play(param.config_music, -1);
} }
void CGameConfig::Loop (double time_step) { void CGameConfig::Loop(double time_step) {
int ww = Winsys.resolution.width; int ww = Winsys.resolution.width;
int hh = Winsys.resolution.height; int hh = Winsys.resolution.height;
Music.Update (); Music.Update();
check_gl_error();
Music.Update ();
ScopedRenderMode rm(GUI); ScopedRenderMode rm(GUI);
ClearRenderContext (); ClearRenderContext();
SetupGuiDisplay (); SetupGuiDisplay();
if (param.ui_snow) { if (param.ui_snow) {
update_ui_snow (time_step); update_ui_snow(time_step);
draw_ui_snow(); draw_ui_snow();
} }
Tex.Draw (T_TITLE_SMALL, CENTER, AutoYPosN (5), 1.0); Tex.Draw(T_TITLE_SMALL, CENTER, AutoYPosN(5), 1.0);
Tex.Draw (BOTTOM_LEFT, 0, hh-256, 1); Tex.Draw(BOTTOM_LEFT, 0, hh-256, 1);
Tex.Draw (BOTTOM_RIGHT, ww-256, hh-256, 1); Tex.Draw(BOTTOM_RIGHT, ww-256, hh-256, 1);
Tex.Draw (TOP_LEFT, 0, 0, 1); Tex.Draw(TOP_LEFT, 0, 0, 1);
Tex.Draw (TOP_RIGHT, ww-256, 0, 1); Tex.Draw(TOP_RIGHT, ww-256, 0, 1);
// DrawFrameX (area.left, area.top, area.right-area.left, area.bottom - area.top, // DrawFrameX (area.left, area.top, area.right-area.left, area.bottom - area.top,
// 0, colMBackgr, colBlack, 0.2); // 0, colMBackgr, colBlack, 0.2);
FT.AutoSizeN (4); FT.AutoSizeN(4);
if (resolution->focussed()) FT.SetColor (colDYell); if (resolution->focussed()) FT.SetColor(colDYell);
else FT.SetColor (colWhite); else FT.SetColor(colWhite);
FT.DrawString (area.left, area.top + dd, Trans.Text(32)); FT.DrawString(area.left, area.top + dd, Trans.Text(32));
if (mus_vol->focussed()) FT.SetColor (colDYell); if (mus_vol->focussed()) FT.SetColor(colDYell);
else FT.SetColor (colWhite); else FT.SetColor(colWhite);
FT.DrawString (area.left, area.top + dd*2, Trans.Text(33)); FT.DrawString(area.left, area.top + dd*2, Trans.Text(33));
if (sound_vol->focussed()) FT.SetColor (colDYell); if (sound_vol->focussed()) FT.SetColor(colDYell);
else FT.SetColor (colWhite); else FT.SetColor(colWhite);
FT.DrawString (area.left, area.top + dd*3, Trans.Text(34)); FT.DrawString(area.left, area.top + dd*3, Trans.Text(34));
if (detail_level->focussed()) FT.SetColor (colDYell); if (detail_level->focussed()) FT.SetColor(colDYell);
else FT.SetColor (colWhite); else FT.SetColor(colWhite);
FT.DrawString (area.left, area.top + dd*4, Trans.Text(36)); FT.DrawString(area.left, area.top + dd*4, Trans.Text(36));
if (language->focussed()) FT.SetColor (colDYell); if (language->focussed()) FT.SetColor(colDYell);
else FT.SetColor (colWhite); else FT.SetColor(colWhite);
FT.DrawString (area.left, area.top + dd*5, Trans.Text(35)); FT.DrawString(area.left, area.top + dd*5, Trans.Text(35));
FT.SetColor (colWhite); FT.SetColor(colWhite);
FT.DrawString (area.left+240, area.top + dd, res_names[resolution->GetValue()]); FT.DrawString(area.left+240, area.top + dd, res_names[resolution->GetValue()]);
FT.DrawString (area.left+240, area.top + dd*2, Int_StrN (mus_vol->GetValue())); FT.DrawString(area.left+240, area.top + dd*2, Int_StrN(mus_vol->GetValue()));
FT.DrawString (area.left+240, area.top + dd*3, Int_StrN (sound_vol->GetValue())); FT.DrawString(area.left+240, area.top + dd*3, Int_StrN(sound_vol->GetValue()));
FT.DrawString (area.left+240, area.top + dd*4, Int_StrN (detail_level->GetValue())); FT.DrawString(area.left+240, area.top + dd*4, Int_StrN(detail_level->GetValue()));
FT.DrawString (area.left+240, area.top + dd*5, Trans.languages[language->GetValue()].language); FT.DrawString(area.left+240, area.top + dd*5, Trans.languages[language->GetValue()].language);
#if defined (_WIN32) #if defined (_WIN32)
if (fullscreen->checked != param.fullscreen) { if (fullscreen->checked != param.fullscreen) {
FT.SetColor (colDYell); FT.SetColor(colDYell);
FT.AutoSizeN (4); FT.AutoSizeN(4);
FT.DrawString (CENTER, AutoYPosN (68), Trans.Text(84)); FT.DrawString(CENTER, AutoYPosN(68), Trans.Text(84));
FT.DrawString (CENTER, AutoYPosN (72), Trans.Text(85)); FT.DrawString(CENTER, AutoYPosN(72), Trans.Text(85));
} else { } else {
FT.SetColor (colLGrey); FT.SetColor(colLGrey);
FT.AutoSizeN (3); FT.AutoSizeN(3);
FT.DrawString (CENTER, AutoYPosN (68), Trans.Text(41)); FT.DrawString(CENTER, AutoYPosN(68), Trans.Text(41));
FT.DrawString (CENTER, AutoYPosN (72), Trans.Text(42)); FT.DrawString(CENTER, AutoYPosN(72), Trans.Text(42));
} }
#else #else
FT.SetColor (colWhite); FT.SetColor(colWhite);
FT.AutoSizeN (3); FT.AutoSizeN(3);
FT.DrawString (CENTER, AutoYPosN (68), Trans.Text(41)); FT.DrawString(CENTER, AutoYPosN(68), Trans.Text(41));
FT.DrawString (CENTER, AutoYPosN (72), Trans.Text(42)); FT.DrawString(CENTER, AutoYPosN(72), Trans.Text(42));
#endif #endif
DrawGUI(); DrawGUI();
Reshape (ww, hh); Reshape(ww, hh);
Winsys.SwapBuffers (); Winsys.SwapBuffers();
} }
void CGameConfig::Exit() { void CGameConfig::Exit() {
Winsys.KeyRepeat (false); Winsys.KeyRepeat(false);
} }

View File

@ -37,7 +37,7 @@ GNU General Public License for more details.
CCourse Course; CCourse Course;
CCourse::CCourse () { CCourse::CCourse() {
terrain = NULL; terrain = NULL;
elevation = NULL; elevation = NULL;
nmls = NULL; nmls = NULL;
@ -48,12 +48,12 @@ CCourse::CCourse () {
} }
CCourse::~CCourse() { CCourse::~CCourse() {
FreeCourseList (); FreeCourseList();
ResetCourse (); ResetCourse();
} }
double CCourse::GetBaseHeight (double distance) const { double CCourse::GetBaseHeight(double distance) const {
double slope = tan (ANGLES_TO_RADIANS (curr_course->angle)); double slope = tan(ANGLES_TO_RADIANS(curr_course->angle));
double base_height; double base_height;
base_height = -slope * distance - base_height = -slope * distance -
@ -61,16 +61,16 @@ double CCourse::GetBaseHeight (double distance) const {
return base_height; return base_height;
} }
double CCourse::GetMaxHeight (double distance) const { double CCourse::GetMaxHeight(double distance) const {
return GetBaseHeight (distance) + curr_course->scale; return GetBaseHeight(distance) + curr_course->scale;
} }
void CCourse::GetDivisions (int *x, int *y) const { void CCourse::GetDivisions(int *x, int *y) const {
*x = nx; *x = nx;
*y = ny; *y = ny;
} }
const TPolyhedron& CCourse::GetPoly (size_t type) const { const TPolyhedron& CCourse::GetPoly(size_t type) const {
return PolyArr[ObjTypes[type].poly]; return PolyArr[ObjTypes[type].poly];
} }
@ -79,17 +79,17 @@ TCourse* CCourse::GetCourse(const string& dir) {
} }
size_t CCourse::GetCourseIdx(const TCourse* course) const { size_t CCourse::GetCourseIdx(const TCourse* course) const {
size_t idx = (course - &CourseList[0]) / sizeof(TCourse); size_t idx = (course - &CourseList[0]);
if (idx >= CourseList.size()) if (idx >= CourseList.size())
return -1; return -1;
return idx; return idx;
} }
void CCourse::CalcNormals () { void CCourse::CalcNormals() {
for (int y=0; y<ny; y++) { for (int y=0; y<ny; y++) {
for (int x=0; x<nx; x++) { for (int x=0; x<nx; x++) {
TVector3d nml(0.0, 0.0, 0.0); TVector3d nml(0.0, 0.0, 0.0);
TVector3d p0 (XCD(x), ELEV(x,y), ZCD(y)); TVector3d p0(XCD(x), ELEV(x,y), ZCD(y));
if ((x + y) % 2 == 0) { if ((x + y) % 2 == 0) {
if (x > 0 && y > 0) { if (x > 0 && y > 0) {
@ -97,16 +97,16 @@ void CCourse::CalcNormals () {
TVector3d p2 = NMLPOINT(x-1,y-1); TVector3d p2 = NMLPOINT(x-1,y-1);
TVector3d v1 = p1 - p0; TVector3d v1 = p1 - p0;
TVector3d v2 = p2 - p0; TVector3d v2 = p2 - p0;
TVector3d n = CrossProduct (v2, v1); TVector3d n = CrossProduct(v2, v1);
n.Norm(); n.Norm();
nml += n; nml += n;
p1 = NMLPOINT (x-1, y-1); p1 = NMLPOINT(x-1, y-1);
p2 = NMLPOINT (x-1, y); p2 = NMLPOINT(x-1, y);
v1 = p1 - p0; v1 = p1 - p0;
v2 = p2 - p0; v2 = p2 - p0;
n = CrossProduct (v2, v1); n = CrossProduct(v2, v1);
n.Norm(); n.Norm();
nml += n; nml += n;
@ -116,7 +116,7 @@ void CCourse::CalcNormals () {
TVector3d p2 = NMLPOINT(x-1,y+1); TVector3d p2 = NMLPOINT(x-1,y+1);
TVector3d v1 = p1 - p0; TVector3d v1 = p1 - p0;
TVector3d v2 = p2 - p0; TVector3d v2 = p2 - p0;
TVector3d n = CrossProduct (v2, v1); TVector3d n = CrossProduct(v2, v1);
n.Norm(); n.Norm();
nml += n; nml += n;
@ -125,7 +125,7 @@ void CCourse::CalcNormals () {
p2 = NMLPOINT(x ,y+1); p2 = NMLPOINT(x ,y+1);
v1 = p1 - p0; v1 = p1 - p0;
v2 = p2 - p0; v2 = p2 - p0;
n = CrossProduct (v2, v1); n = CrossProduct(v2, v1);
n.Norm(); n.Norm();
nml += n; nml += n;
@ -135,7 +135,7 @@ void CCourse::CalcNormals () {
TVector3d p2 = NMLPOINT(x+1,y-1); TVector3d p2 = NMLPOINT(x+1,y-1);
TVector3d v1 = p1 - p0; TVector3d v1 = p1 - p0;
TVector3d v2 = p2 - p0; TVector3d v2 = p2 - p0;
TVector3d n = CrossProduct (v2, v1); TVector3d n = CrossProduct(v2, v1);
n.Norm(); n.Norm();
nml += n; nml += n;
@ -144,7 +144,7 @@ void CCourse::CalcNormals () {
p2 = NMLPOINT(x ,y-1); p2 = NMLPOINT(x ,y-1);
v1 = p1 - p0; v1 = p1 - p0;
v2 = p2 - p0; v2 = p2 - p0;
n = CrossProduct (v2, v1); n = CrossProduct(v2, v1);
n.Norm(); n.Norm();
nml += n; nml += n;
@ -154,7 +154,7 @@ void CCourse::CalcNormals () {
TVector3d p2 = NMLPOINT(x+1,y+1); TVector3d p2 = NMLPOINT(x+1,y+1);
TVector3d v1 = p1 - p0; TVector3d v1 = p1 - p0;
TVector3d v2 = p2 - p0; TVector3d v2 = p2 - p0;
TVector3d n = CrossProduct (v1, v2); TVector3d n = CrossProduct(v1, v2);
n.Norm(); n.Norm();
nml += n; nml += n;
@ -163,7 +163,7 @@ void CCourse::CalcNormals () {
p2 = NMLPOINT(x ,y+1); p2 = NMLPOINT(x ,y+1);
v1 = p1 - p0; v1 = p1 - p0;
v2 = p2 - p0; v2 = p2 - p0;
n = CrossProduct (v1, v2); n = CrossProduct(v1, v2);
n.Norm(); n.Norm();
nml += n; nml += n;
@ -174,7 +174,7 @@ void CCourse::CalcNormals () {
TVector3d p2 = NMLPOINT(x-1,y); TVector3d p2 = NMLPOINT(x-1,y);
TVector3d v1 = p1 - p0; TVector3d v1 = p1 - p0;
TVector3d v2 = p2 - p0; TVector3d v2 = p2 - p0;
TVector3d n = CrossProduct (v2, v1); TVector3d n = CrossProduct(v2, v1);
n.Norm(); n.Norm();
nml += n; nml += n;
@ -184,7 +184,7 @@ void CCourse::CalcNormals () {
TVector3d p2 = NMLPOINT(x ,y+1); TVector3d p2 = NMLPOINT(x ,y+1);
TVector3d v1 = p1 - p0; TVector3d v1 = p1 - p0;
TVector3d v2 = p2 - p0; TVector3d v2 = p2 - p0;
TVector3d n = CrossProduct (v2, v1); TVector3d n = CrossProduct(v2, v1);
n.Norm(); n.Norm();
nml += n; nml += n;
@ -194,7 +194,7 @@ void CCourse::CalcNormals () {
TVector3d p2 = NMLPOINT(x ,y-1); TVector3d p2 = NMLPOINT(x ,y-1);
TVector3d v1 = p1 - p0; TVector3d v1 = p1 - p0;
TVector3d v2 = p2 - p0; TVector3d v2 = p2 - p0;
TVector3d n = CrossProduct (v2, v1); TVector3d n = CrossProduct(v2, v1);
n.Norm(); n.Norm();
nml += n; nml += n;
@ -204,7 +204,7 @@ void CCourse::CalcNormals () {
TVector3d p2 = NMLPOINT(x ,y+1); TVector3d p2 = NMLPOINT(x ,y+1);
TVector3d v1 = p1 - p0; TVector3d v1 = p1 - p0;
TVector3d v2 = p2 - p0; TVector3d v2 = p2 - p0;
TVector3d n = CrossProduct (v1, v2); TVector3d n = CrossProduct(v1, v2);
n.Norm(); n.Norm();
nml += n; nml += n;
@ -218,15 +218,15 @@ void CCourse::CalcNormals () {
} }
} }
void CCourse::MakeCourseNormals () { void CCourse::MakeCourseNormals() {
if (nmls != NULL) delete[] nmls; if (nmls != NULL) delete[] nmls;
try { try {
nmls = new TVector3d[nx * ny]; nmls = new TVector3d[nx * ny];
} catch (...) { } catch (...) {
nmls = NULL; nmls = NULL;
Message ("Allocation failed in MakeCourseNormals"); Message("Allocation failed in MakeCourseNormals");
} }
CalcNormals (); CalcNormals();
} }
// -------------------------------------------------------------------- // --------------------------------------------------------------------
@ -261,7 +261,7 @@ void CCourse::FillGlArrays() {
} }
} }
void CCourse::MakeStandardPolyhedrons () { void CCourse::MakeStandardPolyhedrons() {
PolyArr.resize(2); PolyArr.resize(2);
// polyhedron "none" // polyhedron "none"
@ -312,14 +312,14 @@ void CCourse::MakeStandardPolyhedrons () {
PolyArr[1].polygons[7].vertices[2] = 3; PolyArr[1].polygons[7].vertices[2] = 3;
} }
void CCourse::FreeTerrainTextures () { void CCourse::FreeTerrainTextures() {
for (size_t i=0; i<TerrList.size(); i++) { for (size_t i=0; i<TerrList.size(); i++) {
delete TerrList[i].texture; delete TerrList[i].texture;
TerrList[i].texture = NULL; TerrList[i].texture = NULL;
} }
} }
void CCourse::FreeObjectTextures () { void CCourse::FreeObjectTextures() {
for (size_t i=0; i<ObjTypes.size(); i++) { for (size_t i=0; i<ObjTypes.size(); i++) {
delete ObjTypes[i].texture; delete ObjTypes[i].texture;
ObjTypes[i].texture = NULL; ObjTypes[i].texture = NULL;
@ -330,10 +330,11 @@ void CCourse::FreeObjectTextures () {
// LoadElevMap // LoadElevMap
// -------------------------------------------------------------------- // --------------------------------------------------------------------
bool CCourse::LoadElevMap () { bool CCourse::LoadElevMap() {
CImage img; CImage img;
if (!img.LoadPng (CourseDir.c_str(), "elev.png", true)) { Message ("unable to open elev.png"); if (!img.LoadPng(CourseDir.c_str(), "elev.png", true)) {
Message("unable to open elev.png");
return false; return false;
} }
@ -342,11 +343,11 @@ bool CCourse::LoadElevMap () {
try { try {
elevation = new double[nx * ny]; elevation = new double[nx * ny];
} catch (...) { } catch (...) {
Message ("Allocation failed in LoadElevMap"); Message("Allocation failed in LoadElevMap");
return false; return false;
} }
double slope = tan (ANGLES_TO_RADIANS (curr_course->angle)); double slope = tan(ANGLES_TO_RADIANS(curr_course->angle));
int pad = 0; int pad = 0;
for (int y=0; y<ny; y++) { for (int y=0; y<ny; y++) {
for (int x=0; x<nx; x++) { for (int x=0; x<nx; x++) {
@ -364,11 +365,11 @@ bool CCourse::LoadElevMap () {
// LoadItemList // LoadItemList
// ==================================================================== // ====================================================================
void CCourse::LoadItemList () { void CCourse::LoadItemList() {
CSPList list (16000); CSPList list(16000);
if (!list.Load (CourseDir, "items.lst")) { if (!list.Load(CourseDir, "items.lst")) {
Message ("could not load items list"); Message("could not load items list");
return; return;
} }
@ -376,14 +377,14 @@ void CCourse::LoadItemList () {
NocollArr.clear(); NocollArr.clear();
for (size_t i=0; i<list.Count(); i++) { for (size_t i=0; i<list.Count(); i++) {
const string& line = list.Line(i); const string& line = list.Line(i);
int x = SPIntN (line, "x", 0); int x = SPIntN(line, "x", 0);
int z = SPIntN (line, "z", 0); int z = SPIntN(line, "z", 0);
double height = SPFloatN (line, "height", 1); double height = SPFloatN(line, "height", 1);
double diam = SPFloatN (line, "diam", 1); double diam = SPFloatN(line, "diam", 1);
double xx = (nx - x) / (double)(nx - 1.0) * curr_course->size.x; double xx = (nx - x) / (double)(nx - 1.0) * curr_course->size.x;
double zz = -(ny - z) / (double)(ny - 1.0) * curr_course->size.y; double zz = -(ny - z) / (double)(ny - 1.0) * curr_course->size.y;
string name = SPStrN (line, "name"); string name = SPStrN(line, "name");
size_t type = ObjectIndex[name]; size_t type = ObjectIndex[name];
if (ObjTypes[type].texture == NULL && ObjTypes[type].drawable) { if (ObjTypes[type].texture == NULL && ObjTypes[type].drawable) {
string terrpath = param.obj_dir + SEP + ObjTypes[type].textureFile; string terrpath = param.obj_dir + SEP + ObjTypes[type].textureFile;
@ -401,7 +402,7 @@ void CCourse::LoadItemList () {
// -------------------- LoadObjectMap --------------------------------- // -------------------- LoadObjectMap ---------------------------------
static int GetObject (unsigned char pixel[]) { static int GetObject(unsigned char pixel[]) {
int r = pixel[0]; int r = pixel[0];
int g = pixel[1]; int g = pixel[1];
int b = pixel[2]; int b = pixel[2];
@ -428,32 +429,33 @@ const double sizefact[6] = {0.5, 0.5, 0.7, 1.0, 1.4, 2.0};
const double varfact[6] = {1.0, 1.0, 1.22, 1.41, 1.73, 2.0}; const double varfact[6] = {1.0, 1.0, 1.22, 1.41, 1.73, 2.0};
const double diamfact = 1.4; const double diamfact = 1.4;
static void CalcRandomTrees (double baseheight, double basediam, double &height, double &diam) { static void CalcRandomTrees(double baseheight, double basediam, double &height, double &diam) {
double hhh = baseheight * sizefact[g_game.treesize]; double hhh = baseheight * sizefact[g_game.treesize];
double minsiz = hhh / varfact[g_game.treevar]; double minsiz = hhh / varfact[g_game.treevar];
double maxsiz = hhh * varfact[g_game.treevar]; double maxsiz = hhh * varfact[g_game.treevar];
height = XRandom (minsiz, maxsiz); height = XRandom(minsiz, maxsiz);
diam = XRandom (height/diamfact, height); diam = XRandom(height/diamfact, height);
} }
bool CCourse::LoadAndConvertObjectMap () { bool CCourse::LoadAndConvertObjectMap() {
CImage treeImg; CImage treeImg;
if (!treeImg.LoadPng (CourseDir.c_str(), "trees.png", true)) { Message ("unable to open trees.png"); if (!treeImg.LoadPng(CourseDir.c_str(), "trees.png", true)) {
Message("unable to open trees.png");
return false; return false;
} }
int pad = 0; int pad = 0;
int cnt = 0; int cnt = 0;
double height, diam; double height, diam;
CSPList savelist (10000); CSPList savelist(10000);
CollArr.clear(); CollArr.clear();
NocollArr.clear(); NocollArr.clear();
for (int y=0; y<ny; y++) { for (int y=0; y<ny; y++) {
for (int x=0; x<nx; x++) { for (int x=0; x<nx; x++) {
int imgidx = (x + nx * y) * treeImg.depth + pad; int imgidx = (x + nx * y) * treeImg.depth + pad;
int type = GetObject (&treeImg.data[imgidx]); int type = GetObject(&treeImg.data[imgidx]);
if (type >= 0) { if (type >= 0) {
cnt++; cnt++;
double xx = (nx - x) / (double)(nx - 1.0) * curr_course->size.x; double xx = (nx - x) / (double)(nx - 1.0) * curr_course->size.x;
@ -467,13 +469,13 @@ bool CCourse::LoadAndConvertObjectMap () {
// set random height and diam - see constants above // set random height and diam - see constants above
switch (type) { switch (type) {
case 5: case 5:
CalcRandomTrees (2.5, 2.5, height, diam); CalcRandomTrees(2.5, 2.5, height, diam);
break; break;
case 6: case 6:
CalcRandomTrees (3, 3, height, diam); CalcRandomTrees(3, 3, height, diam);
break; break;
case 7: case 7:
CalcRandomTrees (1.2, 1.2, height, diam); CalcRandomTrees(1.2, 1.2, height, diam);
break; break;
case 2: case 2:
@ -495,17 +497,17 @@ bool CCourse::LoadAndConvertObjectMap () {
string line = "*[name]"; string line = "*[name]";
line += ObjTypes[type].name; line += ObjTypes[type].name;
SPSetIntN (line, "x", x); SPSetIntN(line, "x", x);
SPSetIntN (line, "z", y); SPSetIntN(line, "z", y);
SPSetFloatN (line, "height", height, 1); SPSetFloatN(line, "height", height, 1);
SPSetFloatN (line, "diam", diam, 1); SPSetFloatN(line, "diam", diam, 1);
savelist.Add (line); savelist.Add(line);
} }
} }
pad += (nx * treeImg.depth) % 4; pad += (nx * treeImg.depth) % 4;
} }
string itemfile = CourseDir + SEP "items.lst"; string itemfile = CourseDir + SEP "items.lst";
savelist.Save (itemfile); // Convert trees.png to items.lst savelist.Save(itemfile); // Convert trees.png to items.lst
return true; return true;
} }
@ -513,11 +515,11 @@ bool CCourse::LoadAndConvertObjectMap () {
// LoadObjectTypes // LoadObjectTypes
// -------------------------------------------------------------------- // --------------------------------------------------------------------
bool CCourse::LoadObjectTypes () { bool CCourse::LoadObjectTypes() {
CSPList list (MAX_OBJECT_TYPES+10); CSPList list(MAX_OBJECT_TYPES+10);
if (!list.Load (param.obj_dir, "object_types.lst")) { if (!list.Load(param.obj_dir, "object_types.lst")) {
Message ("could not load object types"); Message("could not load object types");
return false; return false;
} }
@ -525,22 +527,22 @@ bool CCourse::LoadObjectTypes () {
for (size_t i=0; i<list.Count(); i++) { for (size_t i=0; i<list.Count(); i++) {
const string& line = list.Line(i); const string& line = list.Line(i);
ObjTypes[i].name = SPStrN (line, "name"); ObjTypes[i].name = SPStrN(line, "name");
ObjTypes[i].textureFile = ObjTypes[i].name; ObjTypes[i].textureFile = ObjTypes[i].name;
ObjTypes[i].texture = NULL; ObjTypes[i].texture = NULL;
ObjTypes[i].drawable = SPBoolN (line, "draw", true); ObjTypes[i].drawable = SPBoolN(line, "draw", true);
if (ObjTypes[i].drawable) { if (ObjTypes[i].drawable) {
ObjTypes[i].textureFile = SPStrN (line, "texture"); ObjTypes[i].textureFile = SPStrN(line, "texture");
} }
ObjTypes[i].collectable = SPBoolN (line, "snap", -1) != 0; ObjTypes[i].collectable = SPBoolN(line, "snap", -1) != 0;
if (ObjTypes[i].collectable == 0) { if (ObjTypes[i].collectable == 0) {
ObjTypes[i].collectable = -1; ObjTypes[i].collectable = -1;
} }
ObjTypes[i].collidable = SPBoolN (line, "coll", false); ObjTypes[i].collidable = SPBoolN(line, "coll", false);
ObjTypes[i].reset_point = SPBoolN (line, "reset", false); ObjTypes[i].reset_point = SPBoolN(line, "reset", false);
ObjTypes[i].use_normal = SPBoolN (line, "usenorm", false); ObjTypes[i].use_normal = SPBoolN(line, "usenorm", false);
if (ObjTypes[i].use_normal) { if (ObjTypes[i].use_normal) {
ObjTypes[i].normal = SPVector3(line, "norm", TVector3d(0, 1, 0)); ObjTypes[i].normal = SPVector3(line, "norm", TVector3d(0, 1, 0));
@ -548,7 +550,7 @@ bool CCourse::LoadObjectTypes () {
} }
ObjTypes[i].poly = 1; ObjTypes[i].poly = 1;
} }
list.MakeIndex (ObjectIndex, "name"); list.MakeIndex(ObjectIndex, "name");
return true; return true;
} }
@ -556,7 +558,7 @@ bool CCourse::LoadObjectTypes () {
// Terrain // Terrain
// ==================================================================== // ====================================================================
int CCourse::GetTerrain (unsigned char pixel[]) const { int CCourse::GetTerrain(unsigned char pixel[]) const {
for (size_t i=0; i<TerrList.size(); i++) { for (size_t i=0; i<TerrList.size(); i++) {
if (abs(pixel[0]-(int)(TerrList[i].col.r)) < 30 if (abs(pixel[0]-(int)(TerrList[i].col.r)) < 30
&& abs(pixel[1]-(int)(TerrList[i].col.g)) < 30 && abs(pixel[1]-(int)(TerrList[i].col.g)) < 30
@ -571,30 +573,30 @@ int CCourse::GetTerrain (unsigned char pixel[]) const {
// LoadTerrainTypes // LoadTerrainTypes
// -------------------------------------------------------------------- // --------------------------------------------------------------------
bool CCourse::LoadTerrainTypes () { bool CCourse::LoadTerrainTypes() {
CSPList list(MAX_TERR_TYPES +10); CSPList list(MAX_TERR_TYPES +10);
if (!list.Load (param.terr_dir, "terrains.lst")) { if (!list.Load(param.terr_dir, "terrains.lst")) {
Message ("could not load terrain types"); Message("could not load terrain types");
return false; return false;
} }
TerrList.resize(list.Count()); TerrList.resize(list.Count());
for (size_t i=0; i<list.Count(); i++) { for (size_t i=0; i<list.Count(); i++) {
const string& line = list.Line(i); const string& line = list.Line(i);
TerrList[i].textureFile = SPStrN (line, "texture"); TerrList[i].textureFile = SPStrN(line, "texture");
TerrList[i].sound = Sound.GetSoundIdx (SPStrN (line, "sound")); TerrList[i].sound = Sound.GetSoundIdx(SPStrN(line, "sound"));
TerrList[i].starttex = SPIntN (line, "starttex", -1); TerrList[i].starttex = SPIntN(line, "starttex", -1);
TerrList[i].tracktex = SPIntN (line, "tracktex", -1); TerrList[i].tracktex = SPIntN(line, "tracktex", -1);
TerrList[i].stoptex = SPIntN (line, "stoptex", -1); TerrList[i].stoptex = SPIntN(line, "stoptex", -1);
TerrList[i].col = SPColor3N (line, "col", TColor3(1, 1, 1)); TerrList[i].col = SPColor3N(line, "col", TColor3(1, 1, 1));
TerrList[i].friction = SPFloatN (line, "friction", 0.5); TerrList[i].friction = SPFloatN(line, "friction", 0.5);
TerrList[i].depth = SPFloatN (line, "depth", 0.01); TerrList[i].depth = SPFloatN(line, "depth", 0.01);
TerrList[i].particles = SPBoolN (line, "part", false); TerrList[i].particles = SPBoolN(line, "part", false);
TerrList[i].trackmarks = SPBoolN (line, "trackmarks", false); TerrList[i].trackmarks = SPBoolN(line, "trackmarks", false);
TerrList[i].texture = NULL; TerrList[i].texture = NULL;
TerrList[i].shiny = SPBoolN(line, "shiny", false); TerrList[i].shiny = SPBoolN(line, "shiny", false);
TerrList[i].vol_type = SPIntN (line, "vol_type", 1); TerrList[i].vol_type = SPIntN(line, "vol_type", 1);
} }
return true; return true;
} }
@ -603,27 +605,28 @@ bool CCourse::LoadTerrainTypes () {
// LoadTerrainMap // LoadTerrainMap
// -------------------------------------------------------------------- // --------------------------------------------------------------------
bool CCourse::LoadTerrainMap () { bool CCourse::LoadTerrainMap() {
CImage terrImage; CImage terrImage;
if (!terrImage.LoadPng (CourseDir.c_str(), "terrain.png", true)) { Message ("unable to open terrain.png"); if (!terrImage.LoadPng(CourseDir.c_str(), "terrain.png", true)) {
Message("unable to open terrain.png");
return false; return false;
} }
if (nx != terrImage.nx || ny != terrImage.ny) { if (nx != terrImage.nx || ny != terrImage.ny) {
Message ("wrong terrain size"); Message("wrong terrain size");
} }
try { try {
terrain = new char[nx * ny]; terrain = new char[nx * ny];
} catch (...) { } catch (...) {
Message ("Allocation failed in LoadTerrainMap"); Message("Allocation failed in LoadTerrainMap");
} }
int pad = 0; int pad = 0;
for (int y=0; y<ny; y++) { for (int y=0; y<ny; y++) {
for (int x=0; x<nx; x++) { for (int x=0; x<nx; x++) {
int imgidx = (x+nx*y) * terrImage.depth + pad; int imgidx = (x+nx*y) * terrImage.depth + pad;
int arridx = (nx-1-x) + nx * (ny-1-y); int arridx = (nx-1-x) + nx * (ny-1-y);
int terr = GetTerrain (&terrImage.data[imgidx]); int terr = GetTerrain(&terrImage.data[imgidx]);
terrain[arridx] = terr; terrain[arridx] = terr;
if (TerrList[terr].texture == NULL) { if (TerrList[terr].texture == NULL) {
TerrList[terr].texture = new TTexture(); TerrList[terr].texture = new TTexture();
@ -639,25 +642,25 @@ bool CCourse::LoadTerrainMap () {
// LoadCourseList // LoadCourseList
// -------------------------------------------------------------------- // --------------------------------------------------------------------
bool CCourse::LoadCourseList () { bool CCourse::LoadCourseList() {
CSPList list (128); CSPList list(128);
if (!list.Load (param.common_course_dir, "courses.lst")) { if (!list.Load(param.common_course_dir, "courses.lst")) {
Message ("could not load courses.lst"); Message("could not load courses.lst");
return false; return false;
} }
CSPList paramlist (48); CSPList paramlist(48);
CourseList.resize(list.Count()); CourseList.resize(list.Count());
for (size_t i=0; i<list.Count(); i++) { for (size_t i=0; i<list.Count(); i++) {
const string& line1 = list.Line(i); const string& line1 = list.Line(i);
CourseList[i].name = SPStrN (line1, "name", "noname"); CourseList[i].name = SPStrN(line1, "name", "noname");
CourseList[i].dir = SPStrN (line1, "dir", "nodir"); CourseList[i].dir = SPStrN(line1, "dir", "nodir");
string desc = SPStrN (line1, "desc"); string desc = SPStrN(line1, "desc");
FT.AutoSizeN (2); FT.AutoSizeN(2);
vector<string> desclist = FT.MakeLineList (desc.c_str(), 335 * Winsys.scale - 16.0); vector<string> desclist = FT.MakeLineList(desc.c_str(), 335 * Winsys.scale - 16.0);
size_t cnt = min<size_t>(desclist.size(), MAX_DESCRIPTION_LINES); size_t cnt = min<size_t>(desclist.size(), MAX_DESCRIPTION_LINES);
CourseList[i].num_lines = cnt; CourseList[i].num_lines = cnt;
for (size_t ll=0; ll<cnt; ll++) { for (size_t ll=0; ll<cnt; ll++) {
@ -665,43 +668,43 @@ bool CCourse::LoadCourseList () {
} }
string coursepath = param.common_course_dir + SEP + CourseList[i].dir; string coursepath = param.common_course_dir + SEP + CourseList[i].dir;
if (DirExists (coursepath.c_str())) { if (DirExists(coursepath.c_str())) {
// preview // preview
string previewfile = coursepath + SEP "preview.png"; string previewfile = coursepath + SEP "preview.png";
CourseList[i].preview = new TTexture(); CourseList[i].preview = new TTexture();
if (!CourseList[i].preview->LoadMipmap(previewfile, false)) { if (!CourseList[i].preview->LoadMipmap(previewfile, false)) {
Message ("couldn't load previewfile"); Message("couldn't load previewfile");
// texid = Tex.TexID (NO_PREVIEW); // texid = Tex.TexID (NO_PREVIEW);
} }
// params // params
string paramfile = coursepath + SEP "course.dim"; string paramfile = coursepath + SEP "course.dim";
if (!paramlist.Load (paramfile)) { if (!paramlist.Load(paramfile)) {
Message ("could not load course.dim"); Message("could not load course.dim");
} }
const string& line2 = paramlist.Line (0); const string& line2 = paramlist.Line(0);
CourseList[i].author = SPStrN (line2, "author", "unknown"); CourseList[i].author = SPStrN(line2, "author", "unknown");
CourseList[i].size.x = SPFloatN (line2, "width", 100); CourseList[i].size.x = SPFloatN(line2, "width", 100);
CourseList[i].size.y = SPFloatN (line2, "length", 1000); CourseList[i].size.y = SPFloatN(line2, "length", 1000);
CourseList[i].play_size.x = SPFloatN (line2, "play_width", 90); CourseList[i].play_size.x = SPFloatN(line2, "play_width", 90);
CourseList[i].play_size.y = SPFloatN (line2, "play_length", 900); CourseList[i].play_size.y = SPFloatN(line2, "play_length", 900);
CourseList[i].angle = SPFloatN (line2, "angle", 10); CourseList[i].angle = SPFloatN(line2, "angle", 10);
CourseList[i].scale = SPFloatN (line2, "scale", 10); CourseList[i].scale = SPFloatN(line2, "scale", 10);
CourseList[i].start.x = SPFloatN (line2, "startx", 50); CourseList[i].start.x = SPFloatN(line2, "startx", 50);
CourseList[i].start.y = SPFloatN (line2, "starty", 5); CourseList[i].start.y = SPFloatN(line2, "starty", 5);
CourseList[i].env = Env.GetEnvIdx (SPStrN (line2, "env", "etr")); CourseList[i].env = Env.GetEnvIdx(SPStrN(line2, "env", "etr"));
CourseList[i].music_theme = Music.GetThemeIdx (SPStrN (line2, "theme", "normal")); CourseList[i].music_theme = Music.GetThemeIdx(SPStrN(line2, "theme", "normal"));
CourseList[i].use_keyframe = SPBoolN (line2, "use_keyframe", false); CourseList[i].use_keyframe = SPBoolN(line2, "use_keyframe", false);
CourseList[i].finish_brake = SPFloatN (line2, "finish_brake", 20); CourseList[i].finish_brake = SPFloatN(line2, "finish_brake", 20);
paramlist.Clear (); // the list is used several times paramlist.Clear(); // the list is used several times
} }
} }
list.MakeIndex (CourseIndex, "dir"); list.MakeIndex(CourseIndex, "dir");
return true; return true;
} }
void CCourse::FreeCourseList () { void CCourse::FreeCourseList() {
for (size_t i=0; i<CourseList.size(); i++) { for (size_t i=0; i<CourseList.size(); i++) {
delete CourseList[i].preview; delete CourseList[i].preview;
} }
@ -712,22 +715,22 @@ void CCourse::FreeCourseList () {
// LoadCourse // LoadCourse
// =================================================================== // ===================================================================
void CCourse::ResetCourse () { void CCourse::ResetCourse() {
if (nmls != NULL) {delete[] nmls; nmls = NULL;} if (nmls != NULL) {delete[] nmls; nmls = NULL;}
if (vnc_array != NULL) {delete[] vnc_array; vnc_array = NULL;} if (vnc_array != NULL) {delete[] vnc_array; vnc_array = NULL;}
if (elevation != NULL) {delete[] elevation; elevation = NULL;} if (elevation != NULL) {delete[] elevation; elevation = NULL;}
if (terrain != NULL) {delete[] terrain; terrain = NULL;} if (terrain != NULL) {delete[] terrain; terrain = NULL;}
FreeTerrainTextures (); FreeTerrainTextures();
FreeObjectTextures (); FreeObjectTextures();
ResetQuadtree (); ResetQuadtree();
curr_course = NULL; curr_course = NULL;
mirrored = false; mirrored = false;
} }
bool CCourse::LoadCourse (TCourse* course) { bool CCourse::LoadCourse(TCourse* course) {
if (course != curr_course || g_game.force_treemap) { if (course != curr_course || g_game.force_treemap) {
ResetCourse (); ResetCourse();
curr_course = course; curr_course = course;
CourseDir = param.common_course_dir + SEP + curr_course->dir; CourseDir = param.common_course_dir + SEP + curr_course->dir;
@ -738,33 +741,33 @@ bool CCourse::LoadCourse (TCourse* course) {
g_game.use_keyframe = course->use_keyframe; g_game.use_keyframe = course->use_keyframe;
g_game.finish_brake = course->finish_brake; g_game.finish_brake = course->finish_brake;
if (!LoadElevMap ()) { if (!LoadElevMap()) {
Message ("could not load course elev map"); Message("could not load course elev map");
return false; return false;
} }
MakeCourseNormals (); MakeCourseNormals();
FillGlArrays (); FillGlArrays();
if (!LoadTerrainMap ()) { if (!LoadTerrainMap()) {
Message ("could not load course terrain map"); Message("could not load course terrain map");
return false; return false;
} }
// ................................................................ // ................................................................
string itemfile = CourseDir + SEP "items.lst"; string itemfile = CourseDir + SEP "items.lst";
bool itemsexists = FileExists (itemfile); bool itemsexists = FileExists(itemfile);
const CControl *ctrl = g_game.player->ctrl; const CControl *ctrl = g_game.player->ctrl;
if (itemsexists && !g_game.force_treemap) if (itemsexists && !g_game.force_treemap)
LoadItemList (); LoadItemList();
else else
LoadAndConvertObjectMap (); LoadAndConvertObjectMap();
g_game.force_treemap = false; g_game.force_treemap = false;
// ................................................................ // ................................................................
init_track_marks (); init_track_marks();
InitQuadtree ( InitQuadtree(
elevation, nx, ny, elevation, nx, ny,
curr_course->size.x / (nx - 1.0), curr_course->size.x / (nx - 1.0),
-curr_course->size.y / (ny - 1.0), -curr_course->size.y / (ny - 1.0),
@ -773,13 +776,13 @@ bool CCourse::LoadCourse (TCourse* course) {
} }
if (g_game.mirrorred != mirrored) { if (g_game.mirrorred != mirrored) {
MirrorCourse (); MirrorCourse();
mirrored = g_game.mirrorred; mirrored = g_game.mirrorred;
} }
return true; return true;
} }
size_t CCourse::GetEnv () const { size_t CCourse::GetEnv() const {
return curr_course->env; return curr_course->env;
} }
@ -787,7 +790,7 @@ size_t CCourse::GetEnv () const {
// mirror course // mirror course
// -------------------------------------------------------------------- // --------------------------------------------------------------------
void CCourse::MirrorCourseData () { void CCourse::MirrorCourseData() {
for (int y=0; y<ny; y++) { for (int y=0; y<ny; y++) {
for (int x=0; x<nx/2; x++) { for (int x=0; x<nx/2; x++) {
double tmp = ELEV(x,y); double tmp = ELEV(x,y);
@ -808,29 +811,29 @@ void CCourse::MirrorCourseData () {
for (size_t i=0; i<CollArr.size(); i++) { for (size_t i=0; i<CollArr.size(); i++) {
CollArr[i].pt.x = curr_course->size.x - CollArr[i].pt.x; CollArr[i].pt.x = curr_course->size.x - CollArr[i].pt.x;
CollArr[i].pt.y = FindYCoord (CollArr[i].pt.x, CollArr[i].pt.z); CollArr[i].pt.y = FindYCoord(CollArr[i].pt.x, CollArr[i].pt.z);
} }
for (size_t i=0; i<NocollArr.size(); i++) { for (size_t i=0; i<NocollArr.size(); i++) {
NocollArr[i].pt.x = curr_course->size.x - NocollArr[i].pt.x; NocollArr[i].pt.x = curr_course->size.x - NocollArr[i].pt.x;
NocollArr[i].pt.y = FindYCoord (NocollArr[i].pt.x, NocollArr[i].pt.z); NocollArr[i].pt.y = FindYCoord(NocollArr[i].pt.x, NocollArr[i].pt.z);
} }
FillGlArrays(); FillGlArrays();
ResetQuadtree (); ResetQuadtree();
if (nx > 0 && ny > 0) { if (nx > 0 && ny > 0) {
const CControl *ctrl = g_game.player->ctrl; const CControl *ctrl = g_game.player->ctrl;
InitQuadtree (elevation, nx, ny, curr_course->size.x/(nx-1), InitQuadtree(elevation, nx, ny, curr_course->size.x/(nx-1),
- curr_course->size.y/(ny-1), ctrl->viewpos, param.course_detail_level); - curr_course->size.y/(ny-1), ctrl->viewpos, param.course_detail_level);
} }
start_pt.x = curr_course->size.x - start_pt.x; start_pt.x = curr_course->size.x - start_pt.x;
} }
void CCourse::MirrorCourse () { void CCourse::MirrorCourse() {
MirrorCourseData (); MirrorCourseData();
init_track_marks (); init_track_marks();
} }
// ******************************************************************** // ********************************************************************
@ -840,7 +843,7 @@ void CCourse::MirrorCourse () {
void CCourse::GetIndicesForPoint(double x, double z, int *x0, int *y0, int *x1, int *y1) const { void CCourse::GetIndicesForPoint(double x, double z, int *x0, int *y0, int *x1, int *y1) const {
double xidx = x / curr_course->size.x * ((double) nx - 1.); double xidx = x / curr_course->size.x * ((double) nx - 1.);
double yidx = -z / curr_course->size.y * ((double) ny - 1.); double yidx = -z / curr_course->size.y * ((double) ny - 1.);
if (xidx < 0) xidx = 0; if (xidx < 0) xidx = 0;
else if (xidx > nx-1) xidx = nx-1; else if (xidx > nx-1) xidx = nx-1;
@ -854,12 +857,12 @@ void CCourse::GetIndicesForPoint(double x, double z, int *x0, int *y0, int *x1,
*y1 = (int)(yidx + 0.9999); // ceil(yidx) *y1 = (int)(yidx + 0.9999); // ceil(yidx)
if (*x0 == *x1) { if (*x0 == *x1) {
if (*x1 < nx - 1) (*x1)++; if (*x1 < nx - 1)(*x1)++;
else (*x0)--; else (*x0)--;
} }
if (*y0 == *y1) { if (*y0 == *y1) {
if (*y1 < ny - 1) (*y1)++; if (*y1 < ny - 1)(*y1)++;
else (*y0)--; else (*y0)--;
} }
} }
@ -870,7 +873,7 @@ void CCourse::FindBarycentricCoords(double x, double z, TVector2i *idx0,
int x0, x1, y0, y1; int x0, x1, y0, y1;
double dx, ex, dz, ez, qx, qz, invdet; double dx, ex, dz, ez, qx, qz, invdet;
GetIndicesForPoint (x, z, &x0, &y0, &x1, &y1); GetIndicesForPoint(x, z, &x0, &y0, &x1, &y1);
xidx = x / curr_course->size.x * ((double) nx - 1.); xidx = x / curr_course->size.x * ((double) nx - 1.);
yidx = -z / curr_course->size.y * ((double) ny - 1.); yidx = -z / curr_course->size.y * ((double) ny - 1.);
@ -911,23 +914,23 @@ void CCourse::FindBarycentricCoords(double x, double z, TVector2i *idx0,
#define COURSE_VERTX(_x, _y) TVector3d ( (double)(_x)/(nx-1.)*curr_course->size.x, \ #define COURSE_VERTX(_x, _y) TVector3d ( (double)(_x)/(nx-1.)*curr_course->size.x, \
ELEV((_x),(_y)), -(double)(_y)/(ny-1.)*curr_course->size.y ) ELEV((_x),(_y)), -(double)(_y)/(ny-1.)*curr_course->size.y )
TVector3d CCourse::FindCourseNormal (double x, double z) const { TVector3d CCourse::FindCourseNormal(double x, double z) const {
double *elevation = Course.elevation; double *elevation = Course.elevation;
int x0, x1, y0, y1; int x0, x1, y0, y1;
GetIndicesForPoint (x, z, &x0, &y0, &x1, &y1); GetIndicesForPoint(x, z, &x0, &y0, &x1, &y1);
TVector2i idx0, idx1, idx2; TVector2i idx0, idx1, idx2;
double u, v; double u, v;
FindBarycentricCoords (x, z, &idx0, &idx1, &idx2, &u, &v); FindBarycentricCoords(x, z, &idx0, &idx1, &idx2, &u, &v);
const TVector3d& n0 = Course.nmls[ idx0.x + nx * idx0.y ]; const TVector3d& n0 = Course.nmls[ idx0.x + nx * idx0.y ];
const TVector3d& n1 = Course.nmls[ idx1.x + nx * idx1.y ]; const TVector3d& n1 = Course.nmls[ idx1.x + nx * idx1.y ];
const TVector3d& n2 = Course.nmls[ idx2.x + nx * idx2.y ]; const TVector3d& n2 = Course.nmls[ idx2.x + nx * idx2.y ];
TVector3d p0 = COURSE_VERTX (idx0.x, idx0.y); TVector3d p0 = COURSE_VERTX(idx0.x, idx0.y);
TVector3d p1 = COURSE_VERTX (idx1.x, idx1.y); TVector3d p1 = COURSE_VERTX(idx1.x, idx1.y);
TVector3d p2 = COURSE_VERTX (idx2.x, idx2.y); TVector3d p2 = COURSE_VERTX(idx2.x, idx2.y);
TVector3d smooth_nml = u * n0 + TVector3d smooth_nml = u * n0 +
v * n1 + v * n1 +
@ -936,8 +939,8 @@ TVector3d CCourse::FindCourseNormal (double x, double z) const {
TVector3d tri_nml = CrossProduct(p1 - p0, p2 - p0); TVector3d tri_nml = CrossProduct(p1 - p0, p2 - p0);
tri_nml.Norm(); tri_nml.Norm();
double min_bary = min (u, min (v, 1. - u - v)); double min_bary = min(u, min(v, 1. - u - v));
double interp_factor = min (min_bary / NORM_INTERPOL, 1.0); double interp_factor = min(min_bary / NORM_INTERPOL, 1.0);
TVector3d interp_nml = interp_factor * tri_nml + (1.-interp_factor) * smooth_nml; TVector3d interp_nml = interp_factor * tri_nml + (1.-interp_factor) * smooth_nml;
interp_nml.Norm(); interp_nml.Norm();
@ -945,7 +948,7 @@ TVector3d CCourse::FindCourseNormal (double x, double z) const {
return interp_nml; return interp_nml;
} }
double CCourse::FindYCoord (double x, double z) const { double CCourse::FindYCoord(double x, double z) const {
static double last_x, last_z, last_y; static double last_x, last_z, last_y;
static bool cache_full = false; static bool cache_full = false;
@ -954,13 +957,13 @@ double CCourse::FindYCoord (double x, double z) const {
TVector2i idx0, idx1, idx2; TVector2i idx0, idx1, idx2;
double u, v; double u, v;
FindBarycentricCoords (x, z, &idx0, &idx1, &idx2, &u, &v); FindBarycentricCoords(x, z, &idx0, &idx1, &idx2, &u, &v);
TVector3d p0 = COURSE_VERTX (idx0.x, idx0.y); TVector3d p0 = COURSE_VERTX(idx0.x, idx0.y);
TVector3d p1 = COURSE_VERTX (idx1.x, idx1.y); TVector3d p1 = COURSE_VERTX(idx1.x, idx1.y);
TVector3d p2 = COURSE_VERTX (idx2.x, idx2.y); TVector3d p2 = COURSE_VERTX(idx2.x, idx2.y);
double ycoord = u * p0.y + v * p1.y + (1. - u - v) * p2.y; double ycoord = u * p0.y + v * p1.y + (1. - u - v) * p2.y;
last_x = x; last_x = x;
last_z = z; last_z = z;
@ -970,10 +973,10 @@ double CCourse::FindYCoord (double x, double z) const {
return ycoord; return ycoord;
} }
void CCourse::GetSurfaceType (double x, double z, double weights[]) const { void CCourse::GetSurfaceType(double x, double z, double weights[]) const {
TVector2i idx0, idx1, idx2; TVector2i idx0, idx1, idx2;
double u, v; double u, v;
FindBarycentricCoords (x, z, &idx0, &idx1, &idx2, &u, &v); FindBarycentricCoords(x, z, &idx0, &idx1, &idx2, &u, &v);
char *terrain = Course.terrain; char *terrain = Course.terrain;
for (size_t i=0; i<Course.TerrList.size(); i++) { for (size_t i=0; i<Course.TerrList.size(); i++) {
@ -984,10 +987,10 @@ void CCourse::GetSurfaceType (double x, double z, double weights[]) const {
} }
} }
int CCourse::GetTerrainIdx (double x, double z, double level) const { int CCourse::GetTerrainIdx(double x, double z, double level) const {
TVector2i idx0, idx1, idx2; TVector2i idx0, idx1, idx2;
double u, v; double u, v;
FindBarycentricCoords (x, z, &idx0, &idx1, &idx2, &u, &v); FindBarycentricCoords(x, z, &idx0, &idx1, &idx2, &u, &v);
char *terrain = Course.terrain; char *terrain = Course.terrain;
for (size_t i=0; i<Course.TerrList.size(); i++) { for (size_t i=0; i<Course.TerrList.size(); i++) {
@ -1000,10 +1003,10 @@ int CCourse::GetTerrainIdx (double x, double z, double level) const {
return -1; return -1;
} }
TPlane CCourse::GetLocalCoursePlane (TVector3d pt) const { TPlane CCourse::GetLocalCoursePlane(TVector3d pt) const {
TPlane plane; TPlane plane;
pt.y = FindYCoord (pt.x, pt.z); pt.y = FindYCoord(pt.x, pt.z);
plane.nml = FindCourseNormal (pt.x, pt.z); plane.nml = FindCourseNormal(pt.x, pt.z);
plane.d = -DotProduct(plane.nml, pt); plane.d = -DotProduct(plane.nml, pt);
return plane; return plane;
} }

View File

@ -73,24 +73,27 @@ struct TObjectType {
int poly; int poly;
}; };
struct TCollidable { struct TObject {
TVector3d pt; TVector3d pt;
double height; double height;
double diam; double diam;
size_t tree_type; TObject(double x, double y, double z, double height_, double diam_)
TCollidable(double x, double y, double z, double height_, double diam_, size_t type) : pt(x, y, z), height(height_), diam(diam_)
: pt(x, y, z), height(height_), diam(diam_), tree_type(type)
{} {}
}; };
struct TItem { struct TCollidable : public TObject {
TVector3d pt; size_t tree_type;
double height; TCollidable(double x, double y, double z, double height_, double diam_, size_t type)
double diam; : TObject(x, y, z, height_, diam_), tree_type(type)
{}
};
struct TItem : public TObject {
int collectable; int collectable;
const TObjectType& type; const TObjectType& type;
TItem(double x, double y, double z, double height_, double diam_, const TObjectType& type_) TItem(double x, double y, double z, double height_, double diam_, const TObjectType& type_)
: pt(x, y, z), height(height_), diam(diam_), collectable(type_.collectable), type(type_) : TObject(x, y, z, height_, diam_), collectable(type_.collectable), type(type_)
{} {}
}; };
@ -125,19 +128,19 @@ private:
int base_height_value; int base_height_value;
bool mirrored; bool mirrored;
void FreeTerrainTextures (); void FreeTerrainTextures();
void FreeObjectTextures (); void FreeObjectTextures();
void CalcNormals (); void CalcNormals();
void MakeCourseNormals (); void MakeCourseNormals();
bool LoadElevMap (); bool LoadElevMap();
void LoadItemList (); void LoadItemList();
bool LoadAndConvertObjectMap (); bool LoadAndConvertObjectMap();
bool LoadTerrainMap (); bool LoadTerrainMap();
int GetTerrain (unsigned char pixel[]) const; int GetTerrain(unsigned char pixel[]) const;
void MirrorCourseData (); void MirrorCourseData();
public: public:
CCourse (); CCourse();
~CCourse(); ~CCourse();
vector<TCourse> CourseList; vector<TCourse> CourseList;
@ -152,37 +155,37 @@ public:
TVector3d *nmls; TVector3d *nmls;
GLubyte *vnc_array; GLubyte *vnc_array;
void ResetCourse (); void ResetCourse();
TCourse* GetCourse (const string& dir); TCourse* GetCourse(const string& dir);
size_t GetCourseIdx(const TCourse* course) const; size_t GetCourseIdx(const TCourse* course) const;
bool LoadCourseList (); bool LoadCourseList();
void FreeCourseList (); void FreeCourseList();
bool LoadCourse(TCourse* course); bool LoadCourse(TCourse* course);
bool LoadTerrainTypes (); bool LoadTerrainTypes();
bool LoadObjectTypes (); bool LoadObjectTypes();
void MakeStandardPolyhedrons (); void MakeStandardPolyhedrons();
GLubyte* GetGLArrays() const { return vnc_array; } GLubyte* GetGLArrays() const { return vnc_array; }
void FillGlArrays(); void FillGlArrays();
const TVector2d& GetDimensions() const { return curr_course->size; } const TVector2d& GetDimensions() const { return curr_course->size; }
const TVector2d& GetPlayDimensions() const { return curr_course->play_size; } const TVector2d& GetPlayDimensions() const { return curr_course->play_size; }
void GetDivisions (int *nx, int *ny) const; void GetDivisions(int *nx, int *ny) const;
double GetCourseAngle () const { return curr_course->angle; } double GetCourseAngle() const { return curr_course->angle; }
double GetBaseHeight (double distance) const; double GetBaseHeight(double distance) const;
double GetMaxHeight (double distance) const; double GetMaxHeight(double distance) const;
size_t GetEnv () const; size_t GetEnv() const;
const TVector2d& GetStartPoint () const { return start_pt; } const TVector2d& GetStartPoint() const { return start_pt; }
const TPolyhedron& GetPoly (size_t type) const; const TPolyhedron& GetPoly(size_t type) const;
void MirrorCourse (); void MirrorCourse();
void GetIndicesForPoint (double x, double z, int *x0, int *y0, int *x1, int *y1) const; void GetIndicesForPoint(double x, double z, int *x0, int *y0, int *x1, int *y1) const;
void FindBarycentricCoords (double x, double z, void FindBarycentricCoords(double x, double z,
TVector2i *idx0, TVector2i *idx1, TVector2i *idx2, double *u, double *v) const; TVector2i *idx0, TVector2i *idx1, TVector2i *idx2, double *u, double *v) const;
TVector3d FindCourseNormal (double x, double z) const; TVector3d FindCourseNormal(double x, double z) const;
double FindYCoord (double x, double z) const; double FindYCoord(double x, double z) const;
void GetSurfaceType (double x, double z, double weights[]) const; void GetSurfaceType(double x, double z, double weights[]) const;
int GetTerrainIdx (double x, double z, double level) const; int GetTerrainIdx(double x, double z, double level) const;
TPlane GetLocalCoursePlane (TVector3d pt) const; TPlane GetLocalCoursePlane(TVector3d pt) const;
}; };
extern CCourse Course; extern CCourse Course;

View File

@ -32,24 +32,24 @@ GNU General Public License for more details.
#define TEX_SCALE 6 #define TEX_SCALE 6
static const bool clip_course = true; static const bool clip_course = true;
void setup_course_tex_gen () { void setup_course_tex_gen() {
static const GLfloat xplane[4] = {1.0 / TEX_SCALE, 0.0, 0.0, 0.0 }; static const GLfloat xplane[4] = {1.0 / TEX_SCALE, 0.0, 0.0, 0.0 };
static const GLfloat zplane[4] = {0.0, 0.0, 1.0 / TEX_SCALE, 0.0 }; static const GLfloat zplane[4] = {0.0, 0.0, 1.0 / TEX_SCALE, 0.0 };
glTexGenfv (GL_S, GL_OBJECT_PLANE, xplane); glTexGenfv(GL_S, GL_OBJECT_PLANE, xplane);
glTexGenfv (GL_T, GL_OBJECT_PLANE, zplane); glTexGenfv(GL_T, GL_OBJECT_PLANE, zplane);
} }
// -------------------------------------------------------------------- // --------------------------------------------------------------------
// render course // render course
// -------------------------------------------------------------------- // --------------------------------------------------------------------
void RenderCourse () { void RenderCourse() {
ScopedRenderMode rm(COURSE); ScopedRenderMode rm(COURSE);
setup_course_tex_gen (); setup_course_tex_gen();
glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
set_material (colWhite, colBlack, 1.0); set_material(colWhite, colBlack, 1.0);
const CControl *ctrl = g_game.player->ctrl; const CControl *ctrl = g_game.player->ctrl;
UpdateQuadtree (ctrl->viewpos, param.course_detail_level); UpdateQuadtree(ctrl->viewpos, param.course_detail_level);
RenderQuadtree (); RenderQuadtree();
} }
// -------------------------------------------------------------------- // --------------------------------------------------------------------
@ -64,31 +64,28 @@ void DrawTrees() {
double fwd_clip_limit = param.forward_clip_distance; double fwd_clip_limit = param.forward_clip_distance;
double bwd_clip_limit = param.backward_clip_distance; double bwd_clip_limit = param.backward_clip_distance;
glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
set_material (colWhite, colBlack, 1.0); set_material(colWhite, colBlack, 1.0);
// -------------- trees ------------------------ // -------------- trees ------------------------
TCollidable* treeLocs = &Course.CollArr[0]; for (size_t i = 0; i< Course.CollArr.size(); i++) {
size_t numTrees = Course.CollArr.size();
for (size_t i = 0; i< numTrees; i++) {
if (clip_course) { if (clip_course) {
if (ctrl->viewpos.z - treeLocs[i].pt.z > fwd_clip_limit) continue; if (ctrl->viewpos.z - Course.CollArr[i].pt.z > fwd_clip_limit) continue;
if (treeLocs[i].pt.z - ctrl->viewpos.z > bwd_clip_limit) continue; if (Course.CollArr[i].pt.z - ctrl->viewpos.z > bwd_clip_limit) continue;
} }
if (treeLocs[i].tree_type != tree_type) { if (Course.CollArr[i].tree_type != tree_type) {
tree_type = treeLocs[i].tree_type; tree_type = Course.CollArr[i].tree_type;
object_types[tree_type].texture->Bind(); object_types[tree_type].texture->Bind();
} }
glPushMatrix(); glPushMatrix();
glTranslate(treeLocs[i].pt); glTranslate(Course.CollArr[i].pt);
if (param.perf_level > 1) glRotatef (1, 0, 1, 0); if (param.perf_level > 1) glRotatef(1, 0, 1, 0);
float treeRadius = treeLocs[i].diam / 2.0; float treeRadius = Course.CollArr[i].diam / 2.0;
float treeHeight = treeLocs[i].height; float treeHeight = Course.CollArr[i].height;
glNormal3i(0, 0, 1); glNormal3i(0, 0, 1);
static const GLshort tex[] = { static const GLshort tex[] = {
@ -127,32 +124,30 @@ void DrawTrees() {
} }
// items ----------------------------- // items -----------------------------
TItem* itemLocs = &Course.NocollArr[0];
size_t numItems = Course.NocollArr.size();
const TObjectType* item_type = NULL; const TObjectType* item_type = NULL;
for (size_t i = 0; i< numItems; i++) { for (size_t i = 0; i< Course.NocollArr.size(); i++) {
if (itemLocs[i].collectable == 0 || itemLocs[i].type.drawable == false) continue; if (Course.NocollArr[i].collectable == 0 || Course.NocollArr[i].type.drawable == false) continue;
if (clip_course) { if (clip_course) {
if (ctrl->viewpos.z - itemLocs[i].pt.z > fwd_clip_limit) continue; if (ctrl->viewpos.z - Course.NocollArr[i].pt.z > fwd_clip_limit) continue;
if (itemLocs[i].pt.z - ctrl->viewpos.z > bwd_clip_limit) continue; if (Course.NocollArr[i].pt.z - ctrl->viewpos.z > bwd_clip_limit) continue;
} }
if (&itemLocs[i].type != item_type) { if (&Course.NocollArr[i].type != item_type) {
item_type = &itemLocs[i].type; item_type = &Course.NocollArr[i].type;
item_type->texture->Bind(); item_type->texture->Bind();
} }
glPushMatrix(); glPushMatrix();
glTranslate(itemLocs[i].pt); glTranslate(Course.NocollArr[i].pt);
double itemRadius = itemLocs[i].diam / 2; double itemRadius = Course.NocollArr[i].diam / 2;
double itemHeight = itemLocs[i].height; double itemHeight = Course.NocollArr[i].height;
TVector3d normal; TVector3d normal;
if (item_type->use_normal) { if (item_type->use_normal) {
normal = item_type->normal; normal = item_type->normal;
} else { } else {
normal = ctrl->viewpos - itemLocs[i].pt; normal = ctrl->viewpos - Course.NocollArr[i].pt;
normal.Norm(); normal.Norm();
} }
glNormal3(normal); glNormal3(normal);

View File

@ -20,9 +20,9 @@ GNU General Public License for more details.
#include "bh.h" #include "bh.h"
void setup_course_tex_gen (); void setup_course_tex_gen();
void RenderCourse (); void RenderCourse();
void DrawTrees (); void DrawTrees();
#endif #endif

View File

@ -39,30 +39,30 @@ CCredits Credits;
static double y_offset = 0; static double y_offset = 0;
static bool moving = true; static bool moving = true;
void CCredits::LoadCreditList () { void CCredits::LoadCreditList() {
CSPList list(MAX_CREDITS); CSPList list(MAX_CREDITS);
if (!list.Load (param.data_dir, "credits.lst")) { if (!list.Load(param.data_dir, "credits.lst")) {
Message ("could not load credits list"); Message("could not load credits list");
return; return;
} }
for (size_t i=0; i<list.Count(); i++) { for (size_t i=0; i<list.Count(); i++) {
const string& line = list.Line(i); const string& line = list.Line(i);
TCredits credit; TCredits credit;
credit.text = SPStrN (line, "text"); credit.text = SPStrN(line, "text");
double offset = SPFloatN (line, "offs", 0) * OFFS_SCALE_FACTOR * Winsys.scale; double offset = SPFloatN(line, "offs", 0) * OFFS_SCALE_FACTOR * Winsys.scale;
if (i>0) credit.offs = CreditList.back().offs + (int)offset; if (i>0) credit.offs = CreditList.back().offs + (int)offset;
else credit.offs = offset; else credit.offs = offset;
credit.col = SPIntN (line, "col", 0); credit.col = SPIntN(line, "col", 0);
credit.size = SPFloatN (line, "size", 1.0); credit.size = SPFloatN(line, "size", 1.0);
CreditList.push_back(credit); CreditList.push_back(credit);
} }
} }
void CCredits::DrawCreditsText (double time_step) { void CCredits::DrawCreditsText(double time_step) {
int w = Winsys.resolution.width; int w = Winsys.resolution.width;
int h = Winsys.resolution.height; int h = Winsys.resolution.height;
double offs = 0.0; double offs = 0.0;
@ -75,19 +75,19 @@ void CCredits::DrawCreditsText (double time_step) {
continue; continue;
if (i->col == 0) if (i->col == 0)
FT.SetColor (colWhite); FT.SetColor(colWhite);
else else
FT.SetColor (colDYell); FT.SetColor(colDYell);
FT.AutoSizeN (i->size); FT.AutoSizeN(i->size);
FT.DrawString (-1, (int)offs, i->text); FT.DrawString(-1, (int)offs, i->text);
} }
glDisable (GL_TEXTURE_2D); glDisable(GL_TEXTURE_2D);
glColor(colBackgr); glColor(colBackgr);
glRecti (0, 0, w, BOTT_Y); glRecti(0, 0, w, BOTT_Y);
glBegin( GL_QUADS ); glBegin(GL_QUADS);
glVertex2i(0, BOTT_Y); glVertex2i(0, BOTT_Y);
glVertex2i(w, BOTT_Y); glVertex2i(w, BOTT_Y);
glColor(colBackgr, 0); glColor(colBackgr, 0);
@ -96,21 +96,21 @@ void CCredits::DrawCreditsText (double time_step) {
glEnd(); glEnd();
glColor(colBackgr); glColor(colBackgr);
glRecti (0, h - TOP_Y, w, h); glRecti(0, h - TOP_Y, w, h);
glBegin( GL_QUADS ); glBegin(GL_QUADS);
glVertex2i(w, h - TOP_Y); glVertex2i(w, h - TOP_Y);
glVertex2i(0, h - TOP_Y); glVertex2i(0, h - TOP_Y);
glColor(colBackgr, 0); glColor(colBackgr, 0);
glVertex2i(0, h - TOP_Y - 30); glVertex2i(0, h - TOP_Y - 30);
glVertex2i (w, h - TOP_Y - 30); glVertex2i(w, h - TOP_Y - 30);
glEnd(); glEnd();
glEnable (GL_TEXTURE_2D); glEnable(GL_TEXTURE_2D);
if (offs < TOP_Y) y_offset = 0; if (offs < TOP_Y) y_offset = 0;
} }
void CCredits::Keyb (unsigned int key, bool special, bool release, int x, int y) { void CCredits::Keyb(unsigned int key, bool special, bool release, int x, int y) {
if (release) return; if (release) return;
switch (key) { switch (key) {
case SDLK_m: case SDLK_m:
@ -120,46 +120,52 @@ void CCredits::Keyb (unsigned int key, bool special, bool release, int x, int y)
param.ui_snow = !param.ui_snow; param.ui_snow = !param.ui_snow;
break; break;
default: default:
State::manager.RequestEnterState (GameTypeSelect); State::manager.RequestEnterState(GameTypeSelect);
} }
} }
void CCredits::Mouse (int button, int state, int x, int y) { void CCredits::Mouse(int button, int state, int x, int y) {
if (state == 1) State::manager.RequestEnterState (GameTypeSelect); if (state == 1) State::manager.RequestEnterState(GameTypeSelect);
} }
void CCredits::Motion(int x, int y) { void CCredits::Motion(int x, int y) {
if (param.ui_snow) push_ui_snow (cursor_pos); if (param.ui_snow) push_ui_snow(cursor_pos);
} }
void CCredits::Enter() { void CCredits::Enter() {
Music.Play (param.credits_music, -1); LoadCreditList();
Music.Play(param.credits_music, -1);
y_offset = 0; y_offset = 0;
moving = true; moving = true;
} }
void CCredits::Exit() {
CreditList.clear();
}
void CCredits::Loop(double time_step) { void CCredits::Loop(double time_step) {
int ww = Winsys.resolution.width; int ww = Winsys.resolution.width;
int hh = Winsys.resolution.height; int hh = Winsys.resolution.height;
Music.Update (); Music.Update();
check_gl_error(); check_gl_error();
ClearRenderContext (); ClearRenderContext();
ScopedRenderMode rm(GUI); ScopedRenderMode rm(GUI);
SetupGuiDisplay (); SetupGuiDisplay();
DrawCreditsText (time_step); DrawCreditsText(time_step);
if (param.ui_snow) { if (param.ui_snow) {
update_ui_snow (time_step); update_ui_snow(time_step);
draw_ui_snow(); draw_ui_snow();
} }
Tex.Draw (BOTTOM_LEFT, 0, hh-256, 1); Tex.Draw(BOTTOM_LEFT, 0, hh-256, 1);
Tex.Draw (BOTTOM_RIGHT, ww-256, hh-256, 1); Tex.Draw(BOTTOM_RIGHT, ww-256, hh-256, 1);
Tex.Draw (TOP_LEFT, 0, 0, 1); Tex.Draw(TOP_LEFT, 0, 0, 1);
Tex.Draw (TOP_RIGHT, ww-256, 0, 1); Tex.Draw(TOP_RIGHT, ww-256, 0, 1);
Tex.Draw (T_TITLE_SMALL, CENTER, AutoYPosN (5), Winsys.scale); Tex.Draw(T_TITLE_SMALL, CENTER, AutoYPosN(5), Winsys.scale);
Reshape (ww, hh); Reshape(ww, hh);
Winsys.SwapBuffers(); Winsys.SwapBuffers();
} }

View File

@ -36,6 +36,7 @@ class CCredits : public State {
void DrawCreditsText(double time_step); void DrawCreditsText(double time_step);
void Enter(); void Enter();
void Exit();
void Loop(double time_step); void Loop(double time_step);
void Keyb(unsigned int key, bool special, bool release, int x, int y); void Keyb(unsigned int key, bool special, bool release, int x, int y);
void Mouse(int button, int state, int x, int y); void Mouse(int button, int state, int x, int y);

View File

@ -35,7 +35,7 @@ static const float def_diff[] = {1.0, 0.9, 1.0, 1.0};
static const float def_spec[] = {0.6, 0.6, 0.6, 1.0}; static const float def_spec[] = {0.6, 0.6, 0.6, 1.0};
static const float def_pos[] = {1, 2, 2, 0.0}; static const float def_pos[] = {1, 2, 2, 0.0};
static const float def_fogcol[] = {0.9, 0.9, 1.0, 0.0}; static const float def_fogcol[] = {0.9, 0.9, 1.0, 0.0};
static const TColor def_partcol (0.8, 0.8, 0.9, 0.0); static const TColor def_partcol(0.8, 0.8, 0.9, 0.0);
void TLight::Enable(GLenum num) const { void TLight::Enable(GLenum num) const {
glLightfv(num, GL_POSITION, position); glLightfv(num, GL_POSITION, position);
@ -47,7 +47,7 @@ void TLight::Enable(GLenum num) const {
CEnvironment Env; CEnvironment Env;
CEnvironment::CEnvironment () { CEnvironment::CEnvironment() {
EnvID = -1; EnvID = -1;
lightcond[0] = "sunny"; lightcond[0] = "sunny";
lightcond[1] = "cloudy"; lightcond[1] = "cloudy";
@ -75,12 +75,12 @@ CEnvironment::CEnvironment () {
default_fog.part_color = def_partcol; default_fog.part_color = def_partcol;
} }
void CEnvironment::ResetSkybox () { void CEnvironment::ResetSkybox() {
delete[] Skybox; delete[] Skybox;
Skybox = NULL; Skybox = NULL;
} }
void CEnvironment::SetupLight () { void CEnvironment::SetupLight() {
lights[0].Enable(GL_LIGHT0); lights[0].Enable(GL_LIGHT0);
if (lights[1].is_on) if (lights[1].is_on)
lights[1].Enable(GL_LIGHT1); lights[1].Enable(GL_LIGHT1);
@ -92,43 +92,43 @@ void CEnvironment::SetupLight () {
glEnable(GL_LIGHTING); glEnable(GL_LIGHTING);
} }
void CEnvironment::SetupFog () { void CEnvironment::SetupFog() {
glEnable (GL_FOG); glEnable(GL_FOG);
glFogi (GL_FOG_MODE, fog.mode); glFogi(GL_FOG_MODE, fog.mode);
glFogf (GL_FOG_START, fog.start); glFogf(GL_FOG_START, fog.start);
glFogf (GL_FOG_END, fog.end); glFogf(GL_FOG_END, fog.end);
glFogfv (GL_FOG_COLOR, fog.color); glFogfv(GL_FOG_COLOR, fog.color);
if (param.perf_level > 1) { if (param.perf_level > 1) {
glHint (GL_FOG_HINT, GL_NICEST); glHint(GL_FOG_HINT, GL_NICEST);
} else { } else {
glHint (GL_FOG_HINT, GL_FASTEST); glHint(GL_FOG_HINT, GL_FASTEST);
} }
} }
void CEnvironment::ResetLight () { void CEnvironment::ResetLight() {
lights[0] = default_light; lights[0] = default_light;
for (int i=1; i<4; i++) lights[i].is_on = false; for (int i=1; i<4; i++) lights[i].is_on = false;
glDisable (GL_LIGHT1); glDisable(GL_LIGHT1);
glDisable (GL_LIGHT2); glDisable(GL_LIGHT2);
glDisable (GL_LIGHT3); glDisable(GL_LIGHT3);
} }
void CEnvironment::ResetFog () { void CEnvironment::ResetFog() {
fog = default_fog; fog = default_fog;
} }
void CEnvironment::Reset () { void CEnvironment::Reset() {
EnvID = -1; EnvID = -1;
ResetSkybox (); ResetSkybox();
ResetLight (); ResetLight();
ResetFog (); ResetFog();
} }
bool CEnvironment::LoadEnvironmentList () { bool CEnvironment::LoadEnvironmentList() {
CSPList list (32, true); CSPList list(32, true);
if (!list.Load (param.env_dir2, "environment.lst")) { if (!list.Load(param.env_dir2, "environment.lst")) {
Message ("could not load environment.lst"); Message("could not load environment.lst");
return false; return false;
} }
@ -138,11 +138,11 @@ bool CEnvironment::LoadEnvironmentList () {
locs[i].name = SPStrN(line, "location"); locs[i].name = SPStrN(line, "location");
locs[i].high_res = SPBoolN(line, "high_res", false); locs[i].high_res = SPBoolN(line, "high_res", false);
} }
list.MakeIndex (EnvIndex, "location"); list.MakeIndex(EnvIndex, "location");
return true; return true;
} }
string CEnvironment::GetDir (size_t location, size_t light) const { string CEnvironment::GetDir(size_t location, size_t light) const {
if (location >= locs.size()) return ""; if (location >= locs.size()) return "";
if (light >= 4) return ""; if (light >= 4) return "";
string res = string res =
@ -160,7 +160,7 @@ void CEnvironment::LoadSkyboxSide(size_t index, const string& EnvDir, const stri
Skybox[index].Load(EnvDir, name + ".png"); Skybox[index].Load(EnvDir, name + ".png");
} }
void CEnvironment::LoadSkybox (const string& EnvDir, bool high_res) { void CEnvironment::LoadSkybox(const string& EnvDir, bool high_res) {
Skybox = new TTexture[param.full_skybox ? 6 : 3]; Skybox = new TTexture[param.full_skybox ? 6 : 3];
LoadSkyboxSide(0, EnvDir, "front", high_res); LoadSkyboxSide(0, EnvDir, "front", high_res);
LoadSkyboxSide(1, EnvDir, "left", high_res); LoadSkyboxSide(1, EnvDir, "left", high_res);
@ -172,37 +172,37 @@ void CEnvironment::LoadSkybox (const string& EnvDir, bool high_res) {
} }
} }
void CEnvironment::LoadLight (const string& EnvDir) { void CEnvironment::LoadLight(const string& EnvDir) {
static const string idxstr = "[fog]-1[0]0[1]1[2]2[3]3[4]4[5]5[6]6"; static const string idxstr = "[fog]-1[0]0[1]1[2]2[3]3[4]4[5]5[6]6";
CSPList list(24); CSPList list(24);
if (!list.Load (EnvDir, "light.lst")) { if (!list.Load(EnvDir, "light.lst")) {
Message ("could not load light file"); Message("could not load light file");
return; return;
} }
for (size_t i=0; i<list.Count(); i++) { for (size_t i=0; i<list.Count(); i++) {
const string& line = list.Line(i); const string& line = list.Line(i);
string item = SPStrN (line, "light", "none"); string item = SPStrN(line, "light", "none");
int idx = SPIntN (idxstr, item, -1); int idx = SPIntN(idxstr, item, -1);
if (idx < 0) { if (idx < 0) {
fog.is_on = SPBoolN (line, "fog", true); fog.is_on = SPBoolN(line, "fog", true);
fog.start = SPFloatN (line, "fogstart", 20); fog.start = SPFloatN(line, "fogstart", 20);
fog.end = SPFloatN (line, "fogend", param.forward_clip_distance); fog.end = SPFloatN(line, "fogend", param.forward_clip_distance);
fog.height = SPFloatN (line, "fogheight", 0); fog.height = SPFloatN(line, "fogheight", 0);
SPArrN (line, "fogcol", fog.color, 4, 1); SPArrN(line, "fogcol", fog.color, 4, 1);
fog.part_color = SPColorN (line, "partcol", def_partcol); fog.part_color = SPColorN(line, "partcol", def_partcol);
} else if (idx < 4) { } else if (idx < 4) {
lights[idx].is_on = true; lights[idx].is_on = true;
SPArrN (line, "amb", lights[idx].ambient, 4, 1); SPArrN(line, "amb", lights[idx].ambient, 4, 1);
SPArrN (line, "diff", lights[idx].diffuse, 4, 1); SPArrN(line, "diff", lights[idx].diffuse, 4, 1);
SPArrN (line, "spec", lights[idx].specular, 4, 1); SPArrN(line, "spec", lights[idx].specular, 4, 1);
SPArrN (line, "pos", lights[idx].position, 4, 1); SPArrN(line, "pos", lights[idx].position, 4, 1);
} }
} }
} }
void CEnvironment::DrawSkybox (const TVector3d& pos) { void CEnvironment::DrawSkybox(const TVector3d& pos) {
ScopedRenderMode rm(SKY); ScopedRenderMode rm(SKY);
#if defined (OS_LINUX) #if defined (OS_LINUX)
@ -213,8 +213,8 @@ void CEnvironment::DrawSkybox (const TVector3d& pos) {
static const float bb = 0.995f; static const float bb = 0.995f;
#endif #endif
glColor4f (1.0, 1.0, 1.0, 1.0); glColor4f(1.0, 1.0, 1.0, 1.0);
glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
glPushMatrix(); glPushMatrix();
glTranslate(pos); glTranslate(pos);
@ -308,7 +308,7 @@ void CEnvironment::DrawSkybox (const TVector3d& pos) {
glPopMatrix(); glPopMatrix();
} }
void CEnvironment::DrawFog () { void CEnvironment::DrawFog() {
if (!fog.is_on) if (!fog.is_on)
return; return;
@ -318,32 +318,32 @@ void CEnvironment::DrawFog () {
TVector3d bottomleft, bottomright; TVector3d bottomleft, bottomright;
// the clipping planes are calculated by view frustum (view.cpp) // the clipping planes are calculated by view frustum (view.cpp)
const TPlane& leftclip = get_left_clip_plane (); const TPlane& leftclip = get_left_clip_plane();
const TPlane& rightclip = get_right_clip_plane (); const TPlane& rightclip = get_right_clip_plane();
const TPlane& farclip = get_far_clip_plane (); const TPlane& farclip = get_far_clip_plane();
const TPlane& bottomclip = get_bottom_clip_plane (); const TPlane& bottomclip = get_bottom_clip_plane();
// --------------- calculate the planes --------------------------- // --------------- calculate the planes ---------------------------
double slope = tan (ANGLES_TO_RADIANS (Course.GetCourseAngle())); double slope = tan(ANGLES_TO_RADIANS(Course.GetCourseAngle()));
// TPlane left_edge_plane = MakePlane (1.0, 0.0, 0.0, 0.0); // TPlane left_edge_plane = MakePlane (1.0, 0.0, 0.0, 0.0);
// TPlane right_edge_plane = MakePlane (-1.0, 0.0, 0.0, Course.width); // TPlane right_edge_plane = MakePlane (-1.0, 0.0, 0.0, Course.width);
bottom_plane.nml = TVector3d(0.0, 1, -slope); bottom_plane.nml = TVector3d(0.0, 1, -slope);
float height = Course.GetBaseHeight (0); float height = Course.GetBaseHeight(0);
bottom_plane.d = -height * bottom_plane.nml.y; bottom_plane.d = -height * bottom_plane.nml.y;
top_plane.nml = bottom_plane.nml; top_plane.nml = bottom_plane.nml;
height = Course.GetMaxHeight (0) + fog.height; height = Course.GetMaxHeight(0) + fog.height;
top_plane.d = -height * top_plane.nml.y; top_plane.d = -height * top_plane.nml.y;
if (!IntersectPlanes (bottom_plane, farclip, leftclip, &left)) return; if (!IntersectPlanes(bottom_plane, farclip, leftclip, &left)) return;
if (!IntersectPlanes (bottom_plane, farclip, rightclip, &right)) return; if (!IntersectPlanes(bottom_plane, farclip, rightclip, &right)) return;
if (!IntersectPlanes (top_plane, farclip, leftclip, &topleft)) return; if (!IntersectPlanes(top_plane, farclip, leftclip, &topleft)) return;
if (!IntersectPlanes (top_plane, farclip, rightclip, &topright)) return; if (!IntersectPlanes(top_plane, farclip, rightclip, &topright)) return;
if (!IntersectPlanes (bottomclip, farclip, leftclip, &bottomleft)) return; if (!IntersectPlanes(bottomclip, farclip, leftclip, &bottomleft)) return;
if (!IntersectPlanes (bottomclip, farclip, rightclip, &bottomright)) return; if (!IntersectPlanes(bottomclip, farclip, rightclip, &bottomright)) return;
TVector3d leftvec = topleft - left; TVector3d leftvec = topleft - left;
TVector3d rightvec = topright - right; TVector3d rightvec = topright - right;
@ -351,7 +351,7 @@ void CEnvironment::DrawFog () {
// --------------- draw the fog plane ----------------------------- // --------------- draw the fog plane -----------------------------
ScopedRenderMode rm(FOG_PLANE); ScopedRenderMode rm(FOG_PLANE);
glEnable (GL_FOG); glEnable(GL_FOG);
// only the alpha channel is used // only the alpha channel is used
static const GLfloat bottom_dens[4] = {0, 0, 0, 1.0}; static const GLfloat bottom_dens[4] = {0, 0, 0, 1.0};
@ -359,24 +359,24 @@ void CEnvironment::DrawFog () {
static const GLfloat leftright_dens[4] = { 0, 0, 0, 0.3 }; static const GLfloat leftright_dens[4] = { 0, 0, 0, 0.3 };
static const GLfloat top_bottom_dens[4] = { 0, 0, 0, 0.0 }; static const GLfloat top_bottom_dens[4] = { 0, 0, 0, 0.0 };
glBegin (GL_QUAD_STRIP); glBegin(GL_QUAD_STRIP);
glColor4fv (bottom_dens); glColor4fv(bottom_dens);
glVertex3(bottomleft); glVertex3(bottomleft);
glVertex3(bottomright); glVertex3(bottomright);
glVertex3(left); glVertex3(left);
glVertex3(right); glVertex3(right);
glColor4fv (top_dens); glColor4fv(top_dens);
glVertex3(topleft); glVertex3(topleft);
glVertex3(topright); glVertex3(topright);
glColor4fv (leftright_dens); glColor4fv(leftright_dens);
vpoint = topleft + leftvec; vpoint = topleft + leftvec;
glVertex3(vpoint); glVertex3(vpoint);
vpoint = topright + rightvec; vpoint = topright + rightvec;
glVertex3(vpoint); glVertex3(vpoint);
glColor4fv (top_bottom_dens); glColor4fv(top_bottom_dens);
vpoint = topleft + 3.0 * leftvec; vpoint = topleft + 3.0 * leftvec;
glVertex3(vpoint); glVertex3(vpoint);
vpoint = topright + 3.0 * rightvec; vpoint = topright + 3.0 * rightvec;
@ -385,7 +385,7 @@ void CEnvironment::DrawFog () {
} }
void CEnvironment::LoadEnvironment (size_t loc, size_t light) { void CEnvironment::LoadEnvironment(size_t loc, size_t light) {
if (loc >= locs.size()) loc = 0; if (loc >= locs.size()) loc = 0;
if (light >= 4) light = 0; if (light >= 4) light = 0;
// remember: with (example) 3 locations and 4 lights there // remember: with (example) 3 locations and 4 lights there
@ -397,24 +397,24 @@ void CEnvironment::LoadEnvironment (size_t loc, size_t light) {
EnvID = env_id; EnvID = env_id;
// Set directory. The dir is used several times. // Set directory. The dir is used several times.
string EnvDir = GetDir (loc, light); string EnvDir = GetDir(loc, light);
// Load skybox. If the sky can't be loaded for any reason, the // Load skybox. If the sky can't be loaded for any reason, the
// texture id's are set to 0 and the sky will not be drawn. // texture id's are set to 0 and the sky will not be drawn.
// There is no error handling, you see the result on the screen. // There is no error handling, you see the result on the screen.
ResetSkybox (); ResetSkybox();
LoadSkybox(EnvDir, locs[loc].high_res); LoadSkybox(EnvDir, locs[loc].high_res);
// Load light conditions. // Load light conditions.
ResetFog (); ResetFog();
ResetLight (); ResetLight();
LoadLight (EnvDir); LoadLight(EnvDir);
} }
size_t CEnvironment::GetEnvIdx (const string& tag) const { size_t CEnvironment::GetEnvIdx(const string& tag) const {
return EnvIndex.at(tag); return EnvIndex.at(tag);
} }
size_t CEnvironment::GetLightIdx (const string& tag) const { size_t CEnvironment::GetLightIdx(const string& tag) const {
return LightIndex.at(tag); return LightIndex.at(tag);
} }

View File

@ -64,25 +64,25 @@ private:
map<string, size_t> EnvIndex; map<string, size_t> EnvIndex;
map<string, size_t> LightIndex; map<string, size_t> LightIndex;
void ResetSkybox (); void ResetSkybox();
void LoadSkybox(const string& EnvDir, bool high_res); void LoadSkybox(const string& EnvDir, bool high_res);
void LoadSkyboxSide(size_t index, const string& EnvDir, const string& name, bool high_res); void LoadSkyboxSide(size_t index, const string& EnvDir, const string& name, bool high_res);
void ResetLight (); void ResetLight();
void LoadLight (const string& EnvDir); void LoadLight(const string& EnvDir);
void ResetFog (); void ResetFog();
void Reset (); void Reset();
string GetDir (size_t location, size_t light) const; string GetDir(size_t location, size_t light) const;
public: public:
CEnvironment (); CEnvironment();
bool LoadEnvironmentList (); bool LoadEnvironmentList();
void LoadEnvironment (size_t loc, size_t light); void LoadEnvironment(size_t loc, size_t light);
void DrawSkybox (const TVector3d& pos); void DrawSkybox(const TVector3d& pos);
void SetupLight (); void SetupLight();
void SetupFog (); void SetupFog();
void DrawFog (); void DrawFog();
const TColor& ParticleColor () const { return fog.part_color; } const TColor& ParticleColor() const { return fog.part_color; }
size_t GetEnvIdx (const string& tag) const; size_t GetEnvIdx(const string& tag) const;
size_t GetLightIdx (const string& tag) const; size_t GetLightIdx(const string& tag) const;
}; };
extern CEnvironment Env; extern CEnvironment Env;

View File

@ -78,17 +78,17 @@ struct TGameData {
// course and race params // course and race params
TPlayer* player; TPlayer* player;
TCharacter* character;
size_t start_player; size_t start_player;
TCup* cup; TCup* cup;
bool mirrorred; TRace* race; // Only valid if not in practice mode
TCharacter* character;
TCourse* course; TCourse* course;
bool mirrorred;
size_t location_id; size_t location_id;
size_t light_id; size_t light_id;
int snow_id; int snow_id;
int wind_id; int wind_id;
size_t theme_id; size_t theme_id;
TRace* race; // Only valid if not in practice mode
// race results (better in player.ctrl ?) // race results (better in player.ctrl ?)
double time; // reached time double time; // reached time

View File

@ -46,9 +46,9 @@ static size_t curr_race = 0;
static size_t curr_bonus = 0; static size_t curr_bonus = 0;
static TWidget* textbuttons[3]; static TWidget* textbuttons[3];
void StartRace () { void StartRace() {
if (ready > 0) { if (ready > 0) {
State::manager.RequestEnterState (EventSelect); State::manager.RequestEnterState(EventSelect);
return; return;
} }
g_game.mirrorred = false; g_game.mirrorred = false;
@ -59,18 +59,18 @@ void StartRace () {
g_game.wind_id = ecup->races[curr_race]->wind; g_game.wind_id = ecup->races[curr_race]->wind;
g_game.race = ecup->races[curr_race]; g_game.race = ecup->races[curr_race];
g_game.game_type = CUPRACING; g_game.game_type = CUPRACING;
State::manager.RequestEnterState (Loading); State::manager.RequestEnterState(Loading);
} }
void CEvent::Keyb (unsigned int key, bool special, bool release, int x, int y) { void CEvent::Keyb(unsigned int key, bool special, bool release, int x, int y) {
if (release) return; if (release) return;
switch (key) { switch (key) {
case SDLK_RETURN: case SDLK_RETURN:
if (curr_focus == textbuttons[0] && ready < 1) StartRace (); if (curr_focus == textbuttons[0] && ready < 1) StartRace();
else State::manager.RequestEnterState (EventSelect); else State::manager.RequestEnterState(EventSelect);
break; break;
case SDLK_ESCAPE: case SDLK_ESCAPE:
State::manager.RequestEnterState (EventSelect); State::manager.RequestEnterState(EventSelect);
break; break;
case SDLK_TAB: case SDLK_TAB:
if (ready > 0) { if (ready > 0) {
@ -92,25 +92,25 @@ void CEvent::Keyb (unsigned int key, bool special, bool release, int x, int y) {
} }
} }
void CEvent::Mouse (int button, int state, int x, int y) { void CEvent::Mouse(int button, int state, int x, int y) {
if (state != 1) return; if (state != 1) return;
TWidget* clicked = ClickGUI(x, y); TWidget* clicked = ClickGUI(x, y);
if (clicked == textbuttons[0]) { if (clicked == textbuttons[0]) {
if (ready < 1) if (ready < 1)
StartRace (); StartRace();
} else if (clicked == textbuttons[1] || clicked == textbuttons[2]) } else if (clicked == textbuttons[1] || clicked == textbuttons[2])
State::manager.RequestEnterState (EventSelect); State::manager.RequestEnterState(EventSelect);
} }
void CEvent::Motion (int x, int y) { void CEvent::Motion(int x, int y) {
TWidget* foc = MouseMoveGUI(x, y); TWidget* foc = MouseMoveGUI(x, y);
if (foc != 0) curr_focus = foc; if (foc != 0) curr_focus = foc;
if (param.ui_snow) push_ui_snow (cursor_pos); if (param.ui_snow) push_ui_snow(cursor_pos);
} }
void InitCupRacing () { void InitCupRacing() {
ecup = g_game.cup; ecup = g_game.cup;
curr_race = 0; curr_race = 0;
curr_bonus = ecup->races.size(); curr_bonus = ecup->races.size();
@ -118,7 +118,7 @@ void InitCupRacing () {
curr_focus = 0; curr_focus = 0;
} }
void UpdateCupRacing () { void UpdateCupRacing() {
size_t lastrace = ecup->races.size() - 1; size_t lastrace = ecup->races.size() - 1;
curr_bonus += g_game.race_result; curr_bonus += g_game.race_result;
if (g_game.race_result >= 0) { if (g_game.race_result >= 0) {
@ -128,8 +128,8 @@ void UpdateCupRacing () {
if (curr_bonus == 0) ready = 2; if (curr_bonus == 0) ready = 2;
} }
if (ready == 1) { if (ready == 1) {
Players.AddPassedCup (ecup->cup); Players.AddPassedCup(ecup->cup);
Players.SavePlayers (); Players.SavePlayers();
} }
} }
@ -140,122 +140,121 @@ static int messtop, messtop2;
static int bonustop, framewidth, frametop, framebottom; static int bonustop, framewidth, frametop, framebottom;
static int dist, texsize; static int dist, texsize;
void CEvent::Enter () { void CEvent::Enter() {
Winsys.ShowCursor (!param.ice_cursor); Winsys.ShowCursor(!param.ice_cursor);
if (State::manager.PreviousState() == &GameOver) UpdateCupRacing (); if (State::manager.PreviousState() == &GameOver) UpdateCupRacing();
else InitCupRacing (); else InitCupRacing();
framewidth = 500; framewidth = 500;
frametop = AutoYPosN (45); frametop = AutoYPosN(45);
area = AutoAreaN (30, 80, framewidth); area = AutoAreaN(30, 80, framewidth);
messtop = AutoYPosN (50); messtop = AutoYPosN(50);
messtop2 = AutoYPosN (60); messtop2 = AutoYPosN(60);
bonustop = AutoYPosN (35); bonustop = AutoYPosN(35);
texsize = 32 * Winsys.scale; texsize = 32 * Winsys.scale;
if (texsize < 32) texsize = 32; if (texsize < 32) texsize = 32;
dist = texsize + 2 * 4; dist = texsize + 2 * 4;
framebottom = frametop + (int)ecup->races.size() * dist + 10; framebottom = frametop + (int)ecup->races.size() * dist + 10;
ResetGUI (); ResetGUI();
int siz = FT.AutoSizeN (5); int siz = FT.AutoSizeN(5);
textbuttons[1] = AddTextButton (Trans.Text(8), area.left + 100, AutoYPosN (80), siz); textbuttons[1] = AddTextButton(Trans.Text(8), area.left + 100, AutoYPosN(80), siz);
double len = FT.GetTextWidth (Trans.Text(13)); double len = FT.GetTextWidth(Trans.Text(13));
textbuttons[0] = AddTextButton (Trans.Text(13), area.right -len - 100, AutoYPosN (80), siz); textbuttons[0] = AddTextButton(Trans.Text(13), area.right -len - 100, AutoYPosN(80), siz);
textbuttons[2] = AddTextButton (Trans.Text(15), CENTER, AutoYPosN (80), siz); textbuttons[2] = AddTextButton(Trans.Text(15), CENTER, AutoYPosN(80), siz);
Music.Play (param.menu_music, -1); Music.Play(param.menu_music, -1);
if (ready < 1) curr_focus = textbuttons[0]; if (ready < 1) curr_focus = textbuttons[0];
else curr_focus = textbuttons[2]; else curr_focus = textbuttons[2];
} }
int resultlevel (size_t num, size_t numraces) { int resultlevel(size_t num, size_t numraces) {
if (num < 1) return 0; if (num < 1) return 0;
int q = (int)((num - 0.01) / numraces); int q = (int)((num - 0.01) / numraces);
return q + 1; return q + 1;
} }
void CEvent::Loop (double timestep) { void CEvent::Loop(double timestep) {
int ww = Winsys.resolution.width; int ww = Winsys.resolution.width;
int hh = Winsys.resolution.height; int hh = Winsys.resolution.height;
check_gl_error();
ScopedRenderMode rm(GUI); ScopedRenderMode rm(GUI);
Music.Update (); Music.Update();
ClearRenderContext (); ClearRenderContext();
SetupGuiDisplay (); SetupGuiDisplay();
if (param.ui_snow) { if (param.ui_snow) {
update_ui_snow (timestep); update_ui_snow(timestep);
draw_ui_snow (); draw_ui_snow();
} }
Tex.Draw (T_TITLE_SMALL, CENTER, AutoYPosN (5), Winsys.scale); Tex.Draw(T_TITLE_SMALL, CENTER, AutoYPosN(5), Winsys.scale);
Tex.Draw (BOTTOM_LEFT, 0, hh-256, 1); Tex.Draw(BOTTOM_LEFT, 0, hh-256, 1);
Tex.Draw (BOTTOM_RIGHT, ww-256, hh-256, 1); Tex.Draw(BOTTOM_RIGHT, ww-256, hh-256, 1);
Tex.Draw (TOP_LEFT, 0, 0, 1); Tex.Draw(TOP_LEFT, 0, 0, 1);
Tex.Draw (TOP_RIGHT, ww-256, 0, 1); Tex.Draw(TOP_RIGHT, ww-256, 0, 1);
// DrawFrameX (area.left, area.top, area.right-area.left, area.bottom - area.top, // DrawFrameX (area.left, area.top, area.right-area.left, area.bottom - area.top,
// 0, colMBackgr, colBlack, 0.2); // 0, colMBackgr, colBlack, 0.2);
if (ready == 0) { // cup not finished if (ready == 0) { // cup not finished
FT.AutoSizeN (6); FT.AutoSizeN(6);
FT.SetColor (colWhite); FT.SetColor(colWhite);
FT.DrawString (CENTER, AutoYPosN (25), ecup->name); FT.DrawString(CENTER, AutoYPosN(25), ecup->name);
DrawBonusExt (bonustop, (int)ecup->races.size(), curr_bonus); DrawBonusExt(bonustop, (int)ecup->races.size(), curr_bonus);
DrawFrameX (area.left, frametop, framewidth, DrawFrameX(area.left, frametop, framewidth,
(int)ecup->races.size() * dist + 20, 3, colBackgr, colWhite, 1); (int)ecup->races.size() * dist + 20, 3, colBackgr, colWhite, 1);
for (size_t i=0; i<ecup->races.size(); i++) { for (size_t i=0; i<ecup->races.size(); i++) {
FT.AutoSizeN (3); FT.AutoSizeN(3);
int y = frametop + 10 + (int)i * dist; int y = frametop + 10 + (int)i * dist;
if (i == curr_race) if (i == curr_race)
FT.SetColor (colDYell); FT.SetColor(colDYell);
else else
FT.SetColor (colWhite); FT.SetColor(colWhite);
FT.DrawString (area.left + 29, y, ecup->races[i]->course->name); FT.DrawString(area.left + 29, y, ecup->races[i]->course->name);
Tex.Draw (CHECKBOX, area.right -54, y, texsize, texsize); Tex.Draw(CHECKBOX, area.right -54, y, texsize, texsize);
if (curr_race > i) Tex.Draw (CHECKMARK_SMALL, area.right-50, y + 4, 0.8); if (curr_race > i) Tex.Draw(CHECKMARK_SMALL, area.right-50, y + 4, 0.8);
} }
FT.AutoSizeN (3); FT.AutoSizeN(3);
int ddd = FT.AutoDistanceN (1); int ddd = FT.AutoDistanceN(1);
FT.SetColor (colDBlue); FT.SetColor(colDBlue);
string info = Trans.Text(11); string info = Trans.Text(11);
info += " " + Int_StrN (ecup->races[curr_race]->herrings.x); info += " " + Int_StrN(ecup->races[curr_race]->herrings.x);
info += " " + Int_StrN (ecup->races[curr_race]->herrings.y); info += " " + Int_StrN(ecup->races[curr_race]->herrings.y);
info += " " + Int_StrN (ecup->races[curr_race]->herrings.z); info += " " + Int_StrN(ecup->races[curr_race]->herrings.z);
FT.DrawString (CENTER, framebottom+15, info); FT.DrawString(CENTER, framebottom+15, info);
info = Trans.Text(12); info = Trans.Text(12);
info += " " + Float_StrN (ecup->races[curr_race]->time.x, 0); info += " " + Float_StrN(ecup->races[curr_race]->time.x, 0);
info += " " + Float_StrN (ecup->races[curr_race]->time.y, 0); info += " " + Float_StrN(ecup->races[curr_race]->time.y, 0);
info += " " + Float_StrN (ecup->races[curr_race]->time.z, 0); info += " " + Float_StrN(ecup->races[curr_race]->time.z, 0);
info += " " + Trans.Text(14); info += " " + Trans.Text(14);
FT.DrawString (CENTER, framebottom+15+ddd, info); FT.DrawString(CENTER, framebottom+15+ddd, info);
} else if (ready == 1) { // cup successfully finished } else if (ready == 1) { // cup successfully finished
FT.AutoSizeN (5); FT.AutoSizeN(5);
FT.SetColor (colWhite); FT.SetColor(colWhite);
FT.DrawString (CENTER, messtop, Trans.Text(16)); FT.DrawString(CENTER, messtop, Trans.Text(16));
DrawBonusExt (bonustop, (int)ecup->races.size(), curr_bonus); DrawBonusExt(bonustop, (int)ecup->races.size(), curr_bonus);
int res = resultlevel(curr_bonus, ecup->races.size()); int res = resultlevel(curr_bonus, ecup->races.size());
FT.DrawString (CENTER, messtop2, Trans.Text(17) + " " + Int_StrN (res)); FT.DrawString(CENTER, messtop2, Trans.Text(17) + " " + Int_StrN(res));
} else if (ready == 2) { // cup finished but failed } else if (ready == 2) { // cup finished but failed
FT.AutoSizeN (5); FT.AutoSizeN(5);
FT.SetColor (colLRed); FT.SetColor(colLRed);
FT.DrawString (CENTER, messtop, Trans.Text(18)); FT.DrawString(CENTER, messtop, Trans.Text(18));
DrawBonusExt (bonustop, ecup->races.size(), curr_bonus); DrawBonusExt(bonustop, ecup->races.size(), curr_bonus);
FT.DrawString (CENTER, messtop2, Trans.Text(19)); FT.DrawString(CENTER, messtop2, Trans.Text(19));
} }
textbuttons[0]->SetVisible(ready < 1); textbuttons[0]->SetVisible(ready < 1);
textbuttons[1]->SetVisible(ready < 1); textbuttons[1]->SetVisible(ready < 1);
textbuttons[2]->SetVisible(!(ready < 1)); textbuttons[2]->SetVisible(!(ready < 1));
DrawGUI (); DrawGUI();
Winsys.SwapBuffers(); Winsys.SwapBuffers();
} }

View File

@ -39,24 +39,24 @@ static TUpDown* event;
static TUpDown* cup; static TUpDown* cup;
static TWidget* textbuttons[2]; static TWidget* textbuttons[2];
void EnterEvent () { void EnterEvent() {
g_game.game_type = CUPRACING; g_game.game_type = CUPRACING;
g_game.cup = EventList[event->GetValue()].cups[cup->GetValue()]; g_game.cup = EventList[event->GetValue()].cups[cup->GetValue()];
State::manager.RequestEnterState(Event); State::manager.RequestEnterState(Event);
} }
void CEventSelect::Keyb (unsigned int key, bool special, bool release, int x, int y) { void CEventSelect::Keyb(unsigned int key, bool special, bool release, int x, int y) {
if (release) return; if (release) return;
switch (key) { switch (key) {
case SDLK_ESCAPE: case SDLK_ESCAPE:
State::manager.RequestEnterState (GameTypeSelect); State::manager.RequestEnterState(GameTypeSelect);
break; break;
case SDLK_q: case SDLK_q:
State::manager.RequestQuit(); State::manager.RequestQuit();
break; break;
case SDLK_RETURN: case SDLK_RETURN:
if (textbuttons[1]->focussed()) State::manager.RequestEnterState (GameTypeSelect); if (textbuttons[1]->focussed()) State::manager.RequestEnterState(GameTypeSelect);
else if (Events.IsUnlocked (event->GetValue(), cup->GetValue())) EnterEvent(); else if (Events.IsUnlocked(event->GetValue(), cup->GetValue())) EnterEvent();
break; break;
case SDLK_u: case SDLK_u:
param.ui_snow = !param.ui_snow; param.ui_snow = !param.ui_snow;
@ -66,104 +66,103 @@ void CEventSelect::Keyb (unsigned int key, bool special, bool release, int x, in
} }
} }
void CEventSelect::Mouse (int button, int state, int x, int y) { void CEventSelect::Mouse(int button, int state, int x, int y) {
if (state == 1) { if (state == 1) {
TWidget* clicked = ClickGUI(x, y); TWidget* clicked = ClickGUI(x, y);
if (textbuttons[0] == clicked) { if (textbuttons[0] == clicked) {
if (Events.IsUnlocked (event->GetValue(), cup->GetValue())) if (Events.IsUnlocked(event->GetValue(), cup->GetValue()))
EnterEvent(); EnterEvent();
} else if (textbuttons[1] == clicked) } else if (textbuttons[1] == clicked)
State::manager.RequestEnterState (GameTypeSelect); State::manager.RequestEnterState(GameTypeSelect);
} }
} }
void CEventSelect::Motion (int x, int y) { void CEventSelect::Motion(int x, int y) {
MouseMoveGUI(x, y); MouseMoveGUI(x, y);
if (param.ui_snow) push_ui_snow (cursor_pos); if (param.ui_snow) push_ui_snow(cursor_pos);
} }
// -------------------------------------------------------------------- // --------------------------------------------------------------------
static TArea area; static TArea area;
static int framewidth, frameheight, frametop1, frametop2; static int framewidth, frameheight, frametop1, frametop2;
void CEventSelect::Enter () { void CEventSelect::Enter() {
Winsys.ShowCursor (!param.ice_cursor); Winsys.ShowCursor(!param.ice_cursor);
EventList = &Events.EventList[0]; EventList = &Events.EventList[0];
framewidth = 500 * Winsys.scale; framewidth = 500 * Winsys.scale;
frameheight = 50 * Winsys.scale; frameheight = 50 * Winsys.scale;
area = AutoAreaN (30, 80, framewidth); area = AutoAreaN(30, 80, framewidth);
frametop1 = AutoYPosN (35); frametop1 = AutoYPosN(35);
frametop2 = AutoYPosN (50); frametop2 = AutoYPosN(50);
ResetGUI(); ResetGUI();
event = AddUpDown(area.right+8, frametop1, 0, (int)Events.EventList.size() - 1, 0); event = AddUpDown(area.right+8, frametop1, 0, (int)Events.EventList.size() - 1, 0);
cup = AddUpDown(area.right + 8, frametop2, 0, (int)Events.EventList[0].cups.size() - 1, 0); cup = AddUpDown(area.right + 8, frametop2, 0, (int)Events.EventList[0].cups.size() - 1, 0);
int siz = FT.AutoSizeN (5); int siz = FT.AutoSizeN(5);
double len = FT.GetTextWidth (Trans.Text(9)); double len = FT.GetTextWidth(Trans.Text(9));
textbuttons[0] = AddTextButton (Trans.Text(9), area.right-len-50, AutoYPosN (70), siz); textbuttons[0] = AddTextButton(Trans.Text(9), area.right-len-50, AutoYPosN(70), siz);
textbuttons[1] = AddTextButton (Trans.Text(8), area.left+50, AutoYPosN (70), siz); textbuttons[1] = AddTextButton(Trans.Text(8), area.left+50, AutoYPosN(70), siz);
SetFocus(textbuttons[1]); SetFocus(textbuttons[1]);
Events.MakeUnlockList (g_game.player->funlocked); Events.MakeUnlockList(g_game.player->funlocked);
Music.Play (param.menu_music, -1); Music.Play(param.menu_music, -1);
} }
void CEventSelect::Loop (double timestep) { void CEventSelect::Loop(double timestep) {
int ww = Winsys.resolution.width; int ww = Winsys.resolution.width;
int hh = Winsys.resolution.height; int hh = Winsys.resolution.height;
TColor col; TColor col;
check_gl_error();
ScopedRenderMode rm(GUI); ScopedRenderMode rm(GUI);
Music.Update (); Music.Update();
ClearRenderContext (); ClearRenderContext();
SetupGuiDisplay (); SetupGuiDisplay();
if (param.ui_snow) { if (param.ui_snow) {
update_ui_snow (timestep); update_ui_snow(timestep);
draw_ui_snow (); draw_ui_snow();
} }
Tex.Draw (T_TITLE_SMALL, CENTER, AutoYPosN (5), Winsys.scale); Tex.Draw(T_TITLE_SMALL, CENTER, AutoYPosN(5), Winsys.scale);
Tex.Draw (BOTTOM_LEFT, 0, hh-256, 1); Tex.Draw(BOTTOM_LEFT, 0, hh-256, 1);
Tex.Draw (BOTTOM_RIGHT, ww-256, hh-256, 1); Tex.Draw(BOTTOM_RIGHT, ww-256, hh-256, 1);
Tex.Draw (TOP_LEFT, 0, 0, 1); Tex.Draw(TOP_LEFT, 0, 0, 1);
Tex.Draw (TOP_RIGHT, ww-256, 0, 1); Tex.Draw(TOP_RIGHT, ww-256, 0, 1);
// DrawFrameX (area.left, area.top, area.right-area.left, area.bottom - area.top, // DrawFrameX (area.left, area.top, area.right-area.left, area.bottom - area.top,
// 0, colMBackgr, colBlack, 0.2); // 0, colMBackgr, colBlack, 0.2);
FT.AutoSizeN (3); FT.AutoSizeN(3);
FT.SetColor (colWhite); FT.SetColor(colWhite);
FT.DrawString (area.left, AutoYPosN (30), Trans.Text (6)); FT.DrawString(area.left, AutoYPosN(30), Trans.Text(6));
FT.DrawString (area.left,AutoYPosN (45), Trans.Text (7)); FT.DrawString(area.left,AutoYPosN(45), Trans.Text(7));
if (Events.IsUnlocked (event->GetValue(), cup->GetValue()) == false) { if (Events.IsUnlocked(event->GetValue(), cup->GetValue()) == false) {
FT.SetColor (colLGrey); FT.SetColor(colLGrey);
FT.DrawString (CENTER, AutoYPosN (58), Trans.Text (10)); FT.DrawString(CENTER, AutoYPosN(58), Trans.Text(10));
} }
FT.AutoSizeN (4); FT.AutoSizeN(4);
if (event->focussed()) col = colDYell; if (event->focussed()) col = colDYell;
else col = colWhite; else col = colWhite;
DrawFrameX (area.left, frametop1, framewidth, frameheight, 3, colMBackgr, col, 1.0); DrawFrameX(area.left, frametop1, framewidth, frameheight, 3, colMBackgr, col, 1.0);
FT.SetColor (colDYell); FT.SetColor(colDYell);
FT.DrawString (area.left + 20, frametop1, EventList[event->GetValue()].name); FT.DrawString(area.left + 20, frametop1, EventList[event->GetValue()].name);
if (cup->focussed()) col = colDYell; if (cup->focussed()) col = colDYell;
else col = colWhite; else col = colWhite;
DrawFrameX (area.left, frametop2, framewidth, frameheight, 3, colMBackgr, col, 1.0); DrawFrameX(area.left, frametop2, framewidth, frameheight, 3, colMBackgr, col, 1.0);
if (Events.IsUnlocked (event->GetValue(), cup->GetValue())) if (Events.IsUnlocked(event->GetValue(), cup->GetValue()))
FT.SetColor (colDYell); FT.SetColor(colDYell);
else else
FT.SetColor (colLGrey); FT.SetColor(colLGrey);
FT.DrawString (area.left + 20, frametop2, Events.GetCupTrivialName (event->GetValue(), cup->GetValue())); FT.DrawString(area.left + 20, frametop2, Events.GetCupTrivialName(event->GetValue(), cup->GetValue()));
textbuttons[0]->SetActive(Events.IsUnlocked (event->GetValue(), cup->GetValue())); textbuttons[0]->SetActive(Events.IsUnlocked(event->GetValue(), cup->GetValue()));
DrawGUI(); DrawGUI();
Winsys.SwapBuffers(); Winsys.SwapBuffers();

View File

@ -33,7 +33,7 @@ GNU General Public License for more details.
// CFont::MakeLineList. This bundle of functions generates // CFont::MakeLineList. This bundle of functions generates
// a vector<string> from a textstring and adapts the lines to the textbox // a vector<string> from a textstring and adapts the lines to the textbox
static void MakeWordList (vector<string>& wordlist, const char *s) { static void MakeWordList(vector<string>& wordlist, const char *s) {
size_t start = 0; size_t start = 0;
for (size_t i = 0; s[i] != '\0'; i++) { for (size_t i = 0; s[i] != '\0'; i++) {
if (s[i] == ' ') { if (s[i] == ' ') {
@ -48,7 +48,7 @@ static void MakeWordList (vector<string>& wordlist, const char *s) {
wordlist.push_back(string(s+start)); wordlist.push_back(string(s+start));
} }
static size_t MakeLine (size_t first, const vector<string>& wordlist, vector<string>& linelist, float width) { static size_t MakeLine(size_t first, const vector<string>& wordlist, vector<string>& linelist, float width) {
if (first >= wordlist.size()) return wordlist.size()-1; if (first >= wordlist.size()) return wordlist.size()-1;
size_t last = first; size_t last = first;
@ -82,7 +82,7 @@ static size_t MakeLine (size_t first, const vector<string>& wordlist, vector<str
CFont FT; CFont FT;
CFont::CFont () { CFont::CFont() {
forientation = OR_TOP; forientation = OR_TOP;
// setting default values // setting default values
@ -99,7 +99,7 @@ CFont::~CFont() {
Clear(); Clear();
} }
void CFont::Clear () { void CFont::Clear() {
for (size_t i = 0; i < fonts.size(); i++) for (size_t i = 0; i < fonts.size(); i++)
delete fonts[i]; delete fonts[i];
fonts.clear(); fonts.clear();
@ -110,25 +110,25 @@ void CFont::Clear () {
// private // private
// -------------------------------------------------------------------- // --------------------------------------------------------------------
wstring CFont::UnicodeStr (const char *s) { wstring CFont::UnicodeStr(const char *s) {
size_t len = strlen (s); size_t len = strlen(s);
wstring res; wstring res;
res.resize(len); res.resize(len);
for (size_t i=0, j=0; i < len; ++i, ++j) { for (size_t i=0, j=0; i < len; ++i, ++j) {
wchar_t ch = ((const unsigned char *)s)[i]; wchar_t ch = ((const unsigned char *)s)[i];
if (ch >= 0xF0) { if (ch >= 0xF0) {
ch = (wchar_t) (s[i] & 0x07) << 18; ch = (wchar_t)(s[i] & 0x07) << 18;
ch |= (wchar_t) (s[++i] & 0x3F) << 12; ch |= (wchar_t)(s[++i] & 0x3F) << 12;
ch |= (wchar_t) (s[++i] & 0x3F) << 6; ch |= (wchar_t)(s[++i] & 0x3F) << 6;
ch |= (wchar_t) (s[++i] & 0x3F); ch |= (wchar_t)(s[++i] & 0x3F);
} else if (ch >= 0xE0) { } else if (ch >= 0xE0) {
ch = (wchar_t) (s[i] & 0x0F) << 12; ch = (wchar_t)(s[i] & 0x0F) << 12;
ch |= (wchar_t) (s[++i] & 0x3F) << 6; ch |= (wchar_t)(s[++i] & 0x3F) << 6;
ch |= (wchar_t) (s[++i] & 0x3F); ch |= (wchar_t)(s[++i] & 0x3F);
} else if (ch >= 0xC0) { } else if (ch >= 0xC0) {
ch = (wchar_t) (s[i] & 0x1F) << 6; ch = (wchar_t)(s[i] & 0x1F) << 6;
ch |= (wchar_t) (s[++i] & 0x3F); ch |= (wchar_t)(s[++i] & 0x3F);
} }
res[j] = ch; res[j] = ch;
} }
@ -139,14 +139,14 @@ wstring CFont::UnicodeStr (const char *s) {
// public // public
// -------------------------------------------------------------------- // --------------------------------------------------------------------
int CFont::LoadFont (const string& name, const char *path) { int CFont::LoadFont(const string& name, const char *path) {
fonts.push_back(new FTGLPixmapFont (path)); fonts.push_back(new FTGLPixmapFont(path));
if (fonts.back()->Error()) { if (fonts.back()->Error()) {
Message ("Failed to open font"); Message("Failed to open font");
return -1; return -1;
} }
fonts.back()->FaceSize (18); fonts.back()->FaceSize(18);
fonts.back()->CharMap (ft_encoding_unicode); fonts.back()->CharMap(ft_encoding_unicode);
fontindex[name] = fonts.size()-1; fontindex[name] = fonts.size()-1;
return (int)fonts.size()-1; return (int)fonts.size()-1;
@ -156,40 +156,40 @@ int CFont::LoadFont(const string& name, const string& dir, const string& filenam
string path = dir; string path = dir;
path += SEP; path += SEP;
path += filename; path += filename;
return LoadFont (name, path.c_str()); return LoadFont(name, path.c_str());
} }
bool CFont::LoadFontlist () { bool CFont::LoadFontlist() {
CSPList list(MAX_FONTS); CSPList list(MAX_FONTS);
if (!list.Load ( param.font_dir, "fonts.lst")) return false; if (!list.Load(param.font_dir, "fonts.lst")) return false;
for (size_t i=0; i<list.Count(); i++) { for (size_t i=0; i<list.Count(); i++) {
const string& line = list.Line(i); const string& line = list.Line(i);
string fontfile = SPStrN (line, "file"); string fontfile = SPStrN(line, "file");
string name = SPStrN (line, "name"); string name = SPStrN(line, "name");
int ftidx = LoadFont (name, param.font_dir, fontfile); int ftidx = LoadFont(name, param.font_dir, fontfile);
if (ftidx < 0) { if (ftidx < 0) {
Message ("couldn't load font", name); Message("couldn't load font", name);
} }
} }
return true; return true;
} }
size_t CFont::GetFontIdx (const string &name) const { size_t CFont::GetFontIdx(const string &name) const {
return fontindex.at(name); return fontindex.at(name);
} }
void CFont::SetProps (const string &fontname, float size, const TColor& col) { void CFont::SetProps(const string &fontname, float size, const TColor& col) {
SetProps(fontname, size); SetProps(fontname, size);
curr_col = col; curr_col = col;
} }
void CFont::SetProps (const string &fontname, float size) { void CFont::SetProps(const string &fontname, float size) {
curr_font = (int)GetFontIdx (fontname); curr_font = (int)GetFontIdx(fontname);
curr_size = size; curr_size = size;
} }
void CFont::SetFont (const string& fontname) { void CFont::SetFont(const string& fontname) {
try { try {
curr_font = (int)fontindex[fontname]; curr_font = (int)fontindex[fontname];
} catch (...) { } catch (...) {
@ -200,17 +200,24 @@ void CFont::SetFont (const string& fontname) {
else curr_fact = 1.0; else curr_fact = 1.0;
} }
void CFont::SetFontFromSettings() {
if (param.use_papercut_font > 0)
SetFont("pc20");
else
SetFont("bold");
}
// -------------------- auto ------------------------------------------ // -------------------- auto ------------------------------------------
int CFont::AutoSizeN (int rel_val) { int CFont::AutoSizeN(int rel_val) {
float size = (rel_val + 2) * 4; float size = (rel_val + 2) * 4;
size *= curr_fact; size *= curr_fact;
size *= Winsys.scale; size *= Winsys.scale;
SetSize (size); SetSize(size);
return (int)size; return (int)size;
} }
int CFont::AutoDistanceN (int rel_val) { int CFont::AutoDistanceN(int rel_val) {
float fact = (rel_val + 5) * 0.2; float fact = (rel_val + 5) * 0.2;
float dist = curr_size * fact; float dist = curr_size * fact;
return (int) dist; return (int) dist;
@ -232,9 +239,9 @@ void CFont::DrawText(float x, float y, const T* text, size_t font, float size) c
if (left < 0) left = 0; if (left < 0) left = 0;
if (forientation == OR_TOP) { if (forientation == OR_TOP) {
glRasterPos2i ((int)left, (int)(Winsys.resolution.height - curr_size - y)); glRasterPos2i((int)left, (int)(Winsys.resolution.height - curr_size - y));
} else { } else {
glRasterPos2i ((int)left, (int)y); glRasterPos2i((int)left, (int)y);
} }
fonts[font]->Render(text); fonts[font]->Render(text);
@ -243,7 +250,7 @@ void CFont::DrawText(float x, float y, const T* text, size_t font, float size) c
template void CFont::DrawText<char>(float x, float y, const char* text, size_t font, float size) const; // instanciate template void CFont::DrawText<char>(float x, float y, const char* text, size_t font, float size) const; // instanciate
template void CFont::DrawText<wchar_t>(float x, float y, const wchar_t* text, size_t font, float size) const; // instanciate template void CFont::DrawText<wchar_t>(float x, float y, const wchar_t* text, size_t font, float size) const; // instanciate
void CFont::DrawText (float x, float y, const char *text) const { void CFont::DrawText(float x, float y, const char *text) const {
#if USE_UNICODE #if USE_UNICODE
DrawString(x, y, UnicodeStr(text)); DrawString(x, y, UnicodeStr(text));
#else #else
@ -251,20 +258,20 @@ void CFont::DrawText (float x, float y, const char *text) const {
#endif #endif
} }
void CFont::DrawText (float x, float y, const wchar_t *text) const { void CFont::DrawText(float x, float y, const wchar_t *text) const {
DrawText(x, y, text, curr_font, curr_size); DrawText(x, y, text, curr_font, curr_size);
} }
void CFont::DrawString (float x, float y, const string &s) const { void CFont::DrawString(float x, float y, const string &s) const {
DrawText (x, y, s.c_str()); DrawText(x, y, s.c_str());
} }
void CFont::DrawString (float x, float y, const wstring &s) const { void CFont::DrawString(float x, float y, const wstring &s) const {
DrawText (x, y, s.c_str()); DrawText(x, y, s.c_str());
} }
void CFont::DrawText(float x, float y, const char *text, const string &fontname, float size) const { void CFont::DrawText(float x, float y, const char *text, const string &fontname, float size) const {
size_t temp_font = GetFontIdx (fontname); size_t temp_font = GetFontIdx(fontname);
#if USE_UNICODE #if USE_UNICODE
DrawText(x, y, UnicodeStr(text).c_str(), temp_font, size); DrawText(x, y, UnicodeStr(text).c_str(), temp_font, size);
#else #else
@ -274,90 +281,90 @@ void CFont::DrawText(float x, float y, const char *text, const string &fontname,
void CFont::DrawText void CFont::DrawText
(float x, float y, const wchar_t *text, const string &fontname, float size) const { (float x, float y, const wchar_t *text, const string &fontname, float size) const {
size_t temp_font = GetFontIdx (fontname); size_t temp_font = GetFontIdx(fontname);
DrawText(x, y, text, temp_font, size); DrawText(x, y, text, temp_font, size);
} }
void CFont::DrawString ( void CFont::DrawString(
float x, float y, const string &s, const string &fontname, float size) const { float x, float y, const string &s, const string &fontname, float size) const {
DrawText (x, y, s.c_str(), fontname, size); DrawText(x, y, s.c_str(), fontname, size);
} }
void CFont::DrawString ( void CFont::DrawString(
float x, float y, const wstring &s, const string &fontname, float size) const { float x, float y, const wstring &s, const string &fontname, float size) const {
DrawText (x, y, s.c_str(), fontname, size); DrawText(x, y, s.c_str(), fontname, size);
} }
// --------------------- metrics -------------------------------------- // --------------------- metrics --------------------------------------
void CFont::GetTextSize (const wchar_t *text, float &x, float &y, size_t font, float size) const { void CFont::GetTextSize(const wchar_t *text, float &x, float &y, size_t font, float size) const {
if (font >= fonts.size()) { x = 0; y = 0; return; } if (font >= fonts.size()) { x = 0; y = 0; return; }
float llx, lly, llz, urx, ury, urz; float llx, lly, llz, urx, ury, urz;
fonts[font]->FaceSize ((int)size); fonts[font]->FaceSize((int)size);
fonts[font]->BBox (text, llx, lly, llz, urx, ury, urz); fonts[font]->BBox(text, llx, lly, llz, urx, ury, urz);
x = urx - llx; x = urx - llx;
y = ury - lly; y = ury - lly;
} }
void CFont::GetTextSize (const char *text, float &x, float &y, size_t font, float size) const { void CFont::GetTextSize(const char *text, float &x, float &y, size_t font, float size) const {
#if USE_UNICODE #if USE_UNICODE
GetTextSize(UnicodeStr(text).c_str(), x, y, font, size); GetTextSize(UnicodeStr(text).c_str(), x, y, font, size);
#else #else
if (font >= fonts.size()) { x = 0; y = 0; return; } if (font >= fonts.size()) { x = 0; y = 0; return; }
float llx, lly, llz, urx, ury, urz; float llx, lly, llz, urx, ury, urz;
fonts[font]->FaceSize ((int)size); fonts[font]->FaceSize((int)size);
fonts[font]->BBox (text, llx, lly, llz, urx, ury, urz); fonts[font]->BBox(text, llx, lly, llz, urx, ury, urz);
x = urx - llx; x = urx - llx;
y = ury - lly; y = ury - lly;
#endif #endif
} }
void CFont::GetTextSize (const char *text, float &x, float &y) const { void CFont::GetTextSize(const char *text, float &x, float &y) const {
GetTextSize(text, x, y, curr_font, curr_size); GetTextSize(text, x, y, curr_font, curr_size);
} }
void CFont::GetTextSize (const char *text, float &x, float &y, const string &fontname, float size) const { void CFont::GetTextSize(const char *text, float &x, float &y, const string &fontname, float size) const {
size_t temp_font = GetFontIdx (fontname); size_t temp_font = GetFontIdx(fontname);
GetTextSize(text, x, y, temp_font, size); GetTextSize(text, x, y, temp_font, size);
} }
float CFont::GetTextWidth (const char *text) const { float CFont::GetTextWidth(const char *text) const {
float x, y; float x, y;
GetTextSize(text, x, y, curr_font, curr_size); GetTextSize(text, x, y, curr_font, curr_size);
return x; return x;
} }
float CFont::GetTextWidth (const string& text) const { float CFont::GetTextWidth(const string& text) const {
return GetTextWidth (text.c_str()); return GetTextWidth(text.c_str());
} }
float CFont::GetTextWidth (const wchar_t *text) const { float CFont::GetTextWidth(const wchar_t *text) const {
float x, y; float x, y;
GetTextSize(text, x, y, curr_font, curr_size); GetTextSize(text, x, y, curr_font, curr_size);
return x; return x;
} }
float CFont::GetTextWidth (const char *text, const string &fontname, float size) const { float CFont::GetTextWidth(const char *text, const string &fontname, float size) const {
size_t temp_font = GetFontIdx (fontname); size_t temp_font = GetFontIdx(fontname);
float x, y; float x, y;
GetTextSize(text, x, y, temp_font, size); GetTextSize(text, x, y, temp_font, size);
return x; return x;
} }
float CFont::GetTextWidth (const wchar_t *text, const string &fontname, float size) const { float CFont::GetTextWidth(const wchar_t *text, const string &fontname, float size) const {
size_t temp_font = GetFontIdx (fontname); size_t temp_font = GetFontIdx(fontname);
float x, y; float x, y;
GetTextSize(text, x, y, temp_font, size); GetTextSize(text, x, y, temp_font, size);
return x; return x;
} }
float CFont::CenterX (const char *text) const { float CFont::CenterX(const char *text) const {
return (Winsys.resolution.width - GetTextWidth (text)) / 2.0; return (Winsys.resolution.width - GetTextWidth(text)) / 2.0;
} }
vector<string> CFont::MakeLineList (const char *source, float width) { vector<string> CFont::MakeLineList(const char *source, float width) {
vector<string> wordlist; vector<string> wordlist;
MakeWordList(wordlist, source); MakeWordList(wordlist, source);
vector<string> linelist; vector<string> linelist;

View File

@ -50,51 +50,52 @@ private:
void GetTextSize(const wchar_t *text, float &x, float &y, size_t font, float size) const; void GetTextSize(const wchar_t *text, float &x, float &y, size_t font, float size) const;
public: public:
CFont (); CFont();
~CFont (); ~CFont();
void Clear (); void Clear();
int LoadFont(const string& name, const string& dir, const string& filename); int LoadFont(const string& name, const string& dir, const string& filename);
int LoadFont(const string& name, const char *path); int LoadFont(const string& name, const char *path);
bool LoadFontlist (); bool LoadFontlist();
size_t GetFontIdx (const string &name) const; size_t GetFontIdx(const string &name) const;
// properties // properties
void SetProps (const string &fontname, float size, const TColor& col); void SetProps(const string &fontname, float size, const TColor& col);
void SetProps (const string &fontname, float size); void SetProps(const string &fontname, float size);
void SetColor (const TColor& col) { curr_col = col; } void SetColor(const TColor& col) { curr_col = col; }
void SetSize (float size) { curr_size = size; } void SetSize(float size) { curr_size = size; }
void SetFont (const string& fontname); void SetFont(const string& fontname);
void SetFontFromSettings();
// auto // auto
int AutoSizeN (int rel_val); // rel_val = relative size, return: autosize int AutoSizeN(int rel_val); // rel_val = relative size, return: autosize
int AutoDistanceN (int rel_val); // rel_val = relative dist int AutoDistanceN(int rel_val); // rel_val = relative dist
// draw // draw
void DrawText (float x, float y, const char *text) const; // normal char* void DrawText(float x, float y, const char *text) const; // normal char*
void DrawText (float x, float y, const wchar_t *text) const; // wide char* void DrawText(float x, float y, const wchar_t *text) const; // wide char*
void DrawString (float x, float y, const string &s) const; // string class void DrawString(float x, float y, const string &s) const; // string class
void DrawString (float x, float y, const wstring &s) const; // wstring class void DrawString(float x, float y, const wstring &s) const; // wstring class
void DrawText (float x, float y, const char *text, const string &fontname, float size) const; void DrawText(float x, float y, const char *text, const string &fontname, float size) const;
void DrawText (float x, float y, const wchar_t *text, const string &fontname, float size) const; void DrawText(float x, float y, const wchar_t *text, const string &fontname, float size) const;
void DrawString (float x, float y, const string &s, const string &fontname, float size) const; void DrawString(float x, float y, const string &s, const string &fontname, float size) const;
void DrawString (float x, float y, const wstring &s, const string &fontname, float size) const; void DrawString(float x, float y, const wstring &s, const string &fontname, float size) const;
// metrics // metrics
void GetTextSize (const char *text, float &x, float &y) const; void GetTextSize(const char *text, float &x, float &y) const;
void GetTextSize (const char *text, float &x, float &y, const string &fontname, float size) const; void GetTextSize(const char *text, float &x, float &y, const string &fontname, float size) const;
float GetTextWidth (const char *text) const; float GetTextWidth(const char *text) const;
float GetTextWidth (const string& text) const; float GetTextWidth(const string& text) const;
float GetTextWidth (const wchar_t *text) const; float GetTextWidth(const wchar_t *text) const;
float GetTextWidth (const char *text, const string &fontname, float size) const; float GetTextWidth(const char *text, const string &fontname, float size) const;
float GetTextWidth (const wchar_t *text, const string &fontname, float size) const; float GetTextWidth(const wchar_t *text, const string &fontname, float size) const;
float CenterX (const char *text) const; float CenterX(const char *text) const;
void SetOrientation (Orientation orientation) { forientation = orientation; } void SetOrientation(Orientation orientation) { forientation = orientation; }
vector<string> MakeLineList (const char *source, float width); vector<string> MakeLineList(const char *source, float width);
}; };
extern CFont FT; extern CFont FT;

View File

@ -26,22 +26,22 @@ module.
// FTFont // FTFont
// -------------------------------------------------------------------- // --------------------------------------------------------------------
FTFont::FTFont (const char* fontFilePath) FTFont::FTFont(const char* fontFilePath)
: face (fontFilePath), glyphList(0) { : face(fontFilePath), glyphList(0) {
err = face.Error(); err = face.Error();
if (err == 0) glyphList = new FTGlyphContainer (&face); if (err == 0) glyphList = new FTGlyphContainer(&face);
} }
FTFont::FTFont (const unsigned char *pBufferBytes, size_t bufferSizeInBytes) FTFont::FTFont(const unsigned char *pBufferBytes, size_t bufferSizeInBytes)
: face (pBufferBytes, bufferSizeInBytes), glyphList(0) { : face(pBufferBytes, bufferSizeInBytes), glyphList(0) {
err = face.Error(); err = face.Error();
if (err == 0) glyphList = new FTGlyphContainer (&face); if (err == 0) glyphList = new FTGlyphContainer(&face);
} }
FTFont::~FTFont() {delete glyphList;} FTFont::~FTFont() {delete glyphList;}
bool FTFont::Attach (const char* fontFilePath) { bool FTFont::Attach(const char* fontFilePath) {
if (face.Attach (fontFilePath)) { if (face.Attach(fontFilePath)) {
err = 0; err = 0;
return true; return true;
} else { } else {
@ -50,8 +50,8 @@ bool FTFont::Attach (const char* fontFilePath) {
} }
} }
bool FTFont::Attach (const unsigned char *pBufferBytes, size_t bufferSizeInBytes) { bool FTFont::Attach(const unsigned char *pBufferBytes, size_t bufferSizeInBytes) {
if (face.Attach (pBufferBytes, bufferSizeInBytes)) { if (face.Attach(pBufferBytes, bufferSizeInBytes)) {
err = 0; err = 0;
return true; return true;
} else { } else {
@ -60,20 +60,20 @@ bool FTFont::Attach (const unsigned char *pBufferBytes, size_t bufferSizeInBytes
} }
} }
bool FTFont::FaceSize (const unsigned int size, const unsigned int res) { bool FTFont::FaceSize(const unsigned int size, const unsigned int res) {
charSize = face.Size (size, res); charSize = face.Size(size, res);
err = face.Error(); err = face.Error();
if (err != 0) return false; if (err != 0) return false;
if (glyphList != NULL) delete glyphList; if (glyphList != NULL) delete glyphList;
glyphList = new FTGlyphContainer (&face); glyphList = new FTGlyphContainer(&face);
return true; return true;
} }
unsigned int FTFont::FaceSize() const {return charSize.CharSize();} unsigned int FTFont::FaceSize() const {return charSize.CharSize();}
bool FTFont::CharMap (FT_Encoding encoding) { bool FTFont::CharMap(FT_Encoding encoding) {
bool result = glyphList->CharMap (encoding); bool result = glyphList->CharMap(encoding);
err = glyphList->Error(); err = glyphList->Error();
return result; return result;
} }
@ -84,25 +84,25 @@ float FTFont::Ascender() const {return charSize.Ascender();}
float FTFont::Descender() const {return charSize.Descender();} float FTFont::Descender() const {return charSize.Descender();}
float FTFont::LineHeight() const {return charSize.Height();} float FTFont::LineHeight() const {return charSize.Height();}
void FTFont::BBox (const char* string, float& llx, float& lly, float& llz, void FTFont::BBox(const char* string, float& llx, float& lly, float& llz,
float& urx, float& ury, float& urz) { float& urx, float& ury, float& urz) {
FTBBox totalBBox; FTBBox totalBBox;
if ((NULL != string) && ('\0' != *string)) { if ((NULL != string) && ('\0' != *string)) {
const unsigned char* c = (unsigned char*)string; const unsigned char* c = (unsigned char*)string;
float advance = 0; float advance = 0;
if (CheckGlyph (*c)) { if (CheckGlyph(*c)) {
totalBBox = glyphList->BBox (*c); totalBBox = glyphList->BBox(*c);
advance = glyphList->Advance (*c, *(c + 1)); advance = glyphList->Advance(*c, *(c + 1));
} }
while (*++c) { while (*++c) {
if (CheckGlyph (*c)) { if (CheckGlyph(*c)) {
FTBBox tempBBox = glyphList->BBox (*c); FTBBox tempBBox = glyphList->BBox(*c);
tempBBox.Move (FTPoint (advance, 0.0f, 0.0f)); tempBBox.Move(FTPoint(advance, 0.0f, 0.0f));
totalBBox += tempBBox; totalBBox += tempBBox;
advance += glyphList->Advance (*c, *(c + 1)); advance += glyphList->Advance(*c, *(c + 1));
} }
} }
} }
@ -115,25 +115,25 @@ void FTFont::BBox (const char* string, float& llx, float& lly, float& llz,
urz = totalBBox.upperZ; urz = totalBBox.upperZ;
} }
void FTFont::BBox (const wchar_t* string, float& llx, float& lly, float& llz, void FTFont::BBox(const wchar_t* string, float& llx, float& lly, float& llz,
float& urx, float& ury, float& urz) { float& urx, float& ury, float& urz) {
FTBBox totalBBox; FTBBox totalBBox;
if ((NULL != string) && ('\0' != *string)) { if ((NULL != string) && ('\0' != *string)) {
const wchar_t* c = string; const wchar_t* c = string;
float advance = 0; float advance = 0;
if (CheckGlyph (*c)) { if (CheckGlyph(*c)) {
totalBBox = glyphList->BBox (*c); totalBBox = glyphList->BBox(*c);
advance = glyphList->Advance (*c, *(c + 1)); advance = glyphList->Advance(*c, *(c + 1));
} }
while (*++c) { while (*++c) {
if (CheckGlyph (*c)) { if (CheckGlyph(*c)) {
FTBBox tempBBox = glyphList->BBox (*c); FTBBox tempBBox = glyphList->BBox(*c);
tempBBox.Move (FTPoint (advance, 0.0f, 0.0f)); tempBBox.Move(FTPoint(advance, 0.0f, 0.0f));
totalBBox += tempBBox; totalBBox += tempBBox;
advance += glyphList->Advance (*c, *(c + 1)); advance += glyphList->Advance(*c, *(c + 1));
} }
} }
} }
@ -146,59 +146,59 @@ void FTFont::BBox (const wchar_t* string, float& llx, float& lly, float& llz,
} }
float FTFont::Advance (const wchar_t* string) { float FTFont::Advance(const wchar_t* string) {
const wchar_t* c = string; const wchar_t* c = string;
float width = 0.0f; float width = 0.0f;
while (*c) { while (*c) {
if (CheckGlyph (*c)) width += glyphList->Advance (*c, *(c + 1)); if (CheckGlyph(*c)) width += glyphList->Advance(*c, *(c + 1));
++c; ++c;
} }
return width; return width;
} }
float FTFont::Advance (const char* string) { float FTFont::Advance(const char* string) {
const unsigned char* c = (unsigned char*)string; const unsigned char* c = (unsigned char*)string;
float width = 0.0f; float width = 0.0f;
while (*c) { while (*c) {
if (CheckGlyph (*c)) width += glyphList->Advance (*c, *(c + 1)); if (CheckGlyph(*c)) width += glyphList->Advance(*c, *(c + 1));
++c; ++c;
} }
return width; return width;
} }
void FTFont::Render (const char* string) { void FTFont::Render(const char* string) {
const unsigned char* c = (unsigned char*)string; const unsigned char* c = (unsigned char*)string;
pen.X(0); pen.X(0);
pen.Y(0); pen.Y(0);
while (*c) { while (*c) {
if (CheckGlyph (*c)) pen = glyphList->Render (*c, *(c + 1), pen); if (CheckGlyph(*c)) pen = glyphList->Render(*c, *(c + 1), pen);
++c; ++c;
} }
} }
void FTFont::Render (const wchar_t* string) { void FTFont::Render(const wchar_t* string) {
const wchar_t* c = string; const wchar_t* c = string;
pen.X(0); pen.X(0);
pen.Y(0); pen.Y(0);
while (*c) { while (*c) {
if (CheckGlyph (*c)) pen = glyphList->Render (*c, *(c + 1), pen); if (CheckGlyph(*c)) pen = glyphList->Render(*c, *(c + 1), pen);
++c; ++c;
} }
} }
bool FTFont::CheckGlyph (const unsigned int characterCode) { bool FTFont::CheckGlyph(const unsigned int characterCode) {
if (NULL == glyphList->Glyph (characterCode)) { if (NULL == glyphList->Glyph(characterCode)) {
unsigned int glyphIndex = glyphList->FontIndex (characterCode); unsigned int glyphIndex = glyphList->FontIndex(characterCode);
FTGlyph* tempGlyph = MakeGlyph (glyphIndex); FTGlyph* tempGlyph = MakeGlyph(glyphIndex);
if (NULL == tempGlyph) { if (NULL == tempGlyph) {
if (0 == err) err = 0x13; if (0 == err) err = 0x13;
return false; return false;
} }
glyphList->Add (tempGlyph, characterCode); glyphList->Add(tempGlyph, characterCode);
} }
return true; return true;
} }
@ -207,26 +207,26 @@ bool FTFont::CheckGlyph (const unsigned int characterCode) {
// FTLibrary // FTLibrary
// -------------------------------------------------------------------- // --------------------------------------------------------------------
const FTLibrary &FTLibrary::Instance () { const FTLibrary &FTLibrary::Instance() {
static FTLibrary ftlib; static FTLibrary ftlib;
return ftlib; return ftlib;
} }
FTLibrary::~FTLibrary () { FTLibrary::~FTLibrary() {
// PrintStr ("desctructor FTLibrary"); // PrintStr ("desctructor FTLibrary");
if (library != 0) { if (library != 0) {
FT_Done_FreeType (*library); FT_Done_FreeType(*library);
delete library; delete library;
library= 0; library= 0;
} }
} }
FTLibrary::FTLibrary () : library(0), err(0) {Initialise();} FTLibrary::FTLibrary() : library(0), err(0) {Initialise();}
bool FTLibrary::Initialise () { bool FTLibrary::Initialise() {
if (library != 0) return true; if (library != 0) return true;
library = new FT_Library; library = new FT_Library;
err = FT_Init_FreeType (library); err = FT_Init_FreeType(library);
if (err) { if (err) {
delete library; delete library;
library = 0; library = 0;
@ -239,14 +239,14 @@ bool FTLibrary::Initialise () {
// FTFace // FTFace
// -------------------------------------------------------------------- // --------------------------------------------------------------------
FTFace::FTFace (const char* fontFilePath) FTFace::FTFace(const char* fontFilePath)
: numGlyphs(0), fontEncodingList(0), err(0) { : numGlyphs(0), fontEncodingList(0), err(0) {
const FT_Long DEFAULT_FACE_INDEX = 0; const FT_Long DEFAULT_FACE_INDEX = 0;
ftFace = new FT_Face; ftFace = new FT_Face;
err = FT_New_Face (*FTLibrary::Instance().GetLibrary(), fontFilePath, DEFAULT_FACE_INDEX, ftFace); err = FT_New_Face(*FTLibrary::Instance().GetLibrary(), fontFilePath, DEFAULT_FACE_INDEX, ftFace);
if (err) { if (err) {
Message ("error FT_New_Face"); Message("error FT_New_Face");
delete ftFace; delete ftFace;
ftFace = 0; ftFace = 0;
} else { } else {
@ -255,12 +255,12 @@ FTFace::FTFace (const char* fontFilePath)
} }
} }
FTFace::FTFace (const unsigned char *pBufferBytes, size_t bufferSizeInBytes) FTFace::FTFace(const unsigned char *pBufferBytes, size_t bufferSizeInBytes)
: numGlyphs(0), err(0) { : numGlyphs(0), err(0) {
const FT_Long DEFAULT_FACE_INDEX = 0; const FT_Long DEFAULT_FACE_INDEX = 0;
ftFace = new FT_Face; ftFace = new FT_Face;
err = FT_New_Memory_Face ( err = FT_New_Memory_Face(
*FTLibrary::Instance().GetLibrary(), *FTLibrary::Instance().GetLibrary(),
(FT_Byte *)pBufferBytes, (FT_Byte *)pBufferBytes,
(FT_Long)bufferSizeInBytes, DEFAULT_FACE_INDEX, ftFace); (FT_Long)bufferSizeInBytes, DEFAULT_FACE_INDEX, ftFace);
@ -273,30 +273,30 @@ FTFace::FTFace (const unsigned char *pBufferBytes, size_t bufferSizeInBytes)
FTFace::~FTFace() { FTFace::~FTFace() {
if (ftFace) { if (ftFace) {
FT_Done_Face (*ftFace); FT_Done_Face(*ftFace);
delete ftFace; delete ftFace;
ftFace = 0; ftFace = 0;
} }
} }
bool FTFace::Attach (const char* fontFilePath) { bool FTFace::Attach(const char* fontFilePath) {
err = FT_Attach_File (*ftFace, fontFilePath); err = FT_Attach_File(*ftFace, fontFilePath);
return !err; return !err;
} }
bool FTFace::Attach (const unsigned char *pBufferBytes, size_t bufferSizeInBytes) { bool FTFace::Attach(const unsigned char *pBufferBytes, size_t bufferSizeInBytes) {
FT_Open_Args open; FT_Open_Args open;
open.flags = FT_OPEN_MEMORY; open.flags = FT_OPEN_MEMORY;
open.memory_base = (FT_Byte *)pBufferBytes; open.memory_base = (FT_Byte *)pBufferBytes;
open.memory_size = (FT_Long)bufferSizeInBytes; open.memory_size = (FT_Long)bufferSizeInBytes;
err = FT_Attach_Stream (*ftFace, &open); err = FT_Attach_Stream(*ftFace, &open);
return !err; return !err;
} }
const FTSize& FTFace::Size (const unsigned int size, const unsigned int res) { const FTSize& FTFace::Size(const unsigned int size, const unsigned int res) {
charSize.CharSize (ftFace, size, res, res); charSize.CharSize(ftFace, size, res, res);
err = charSize.Error(); err = charSize.Error();
return charSize; return charSize;
} }
@ -315,7 +315,7 @@ FT_Encoding* FTFace::CharMapList() {
return fontEncodingList; return fontEncodingList;
} }
FTPoint FTFace::KernAdvance (unsigned int index1, unsigned int index2) { FTPoint FTFace::KernAdvance(unsigned int index1, unsigned int index2) {
float x, y; float x, y;
x = y = 0.0f; x = y = 0.0f;
@ -323,17 +323,17 @@ FTPoint FTFace::KernAdvance (unsigned int index1, unsigned int index2) {
FT_Vector kernAdvance; FT_Vector kernAdvance;
kernAdvance.x = kernAdvance.y = 0; kernAdvance.x = kernAdvance.y = 0;
err = FT_Get_Kerning (*ftFace, index1, index2, ft_kerning_unfitted, &kernAdvance); err = FT_Get_Kerning(*ftFace, index1, index2, ft_kerning_unfitted, &kernAdvance);
if (!err) { if (!err) {
x = static_cast<float> (kernAdvance.x) / 64.0f; x = static_cast<float>(kernAdvance.x) / 64.0f;
y = static_cast<float> (kernAdvance.y) / 64.0f; y = static_cast<float>(kernAdvance.y) / 64.0f;
} }
} }
return FTPoint (x, y, 0.0); return FTPoint(x, y, 0.0);
} }
FT_GlyphSlot FTFace::Glyph (unsigned int index, FT_Int load_flags) { FT_GlyphSlot FTFace::Glyph(unsigned int index, FT_Int load_flags) {
err = FT_Load_Glyph (*ftFace, index, load_flags); err = FT_Load_Glyph(*ftFace, index, load_flags);
if (err) return NULL; if (err) return NULL;
return (*ftFace)->glyph; return (*ftFace)->glyph;
} }
@ -347,7 +347,7 @@ bool operator == (const FTPoint &a, const FTPoint &b) {
b.values[1]) && (a.values[2] == b.values[2])); b.values[1]) && (a.values[2] == b.values[2]));
} }
bool operator != (const FTPoint &a, const FTPoint &b) { bool operator != (const FTPoint &a, const FTPoint &b) {
return ((a.values[0] != b.values[0]) || (a.values[1] return ((a.values[0] != b.values[0]) || (a.values[1]
!= b.values[1]) || (a.values[2] != b.values[2])); != b.values[1]) || (a.values[2] != b.values[2]));
} }
@ -371,10 +371,10 @@ FTSize::FTSize()
FTSize::~FTSize() {} FTSize::~FTSize() {}
bool FTSize::CharSize (FT_Face* face, unsigned int pointSize, bool FTSize::CharSize(FT_Face* face, unsigned int pointSize,
unsigned int xRes, unsigned int yRes) { unsigned int xRes, unsigned int yRes) {
if (size != pointSize || xResolution != xRes || yResolution != yRes) { if (size != pointSize || xResolution != xRes || yResolution != yRes) {
err = FT_Set_Char_Size (*face, 0L, pointSize * 64, xResolution, yResolution); err = FT_Set_Char_Size(*face, 0L, pointSize * 64, xResolution, yResolution);
if (!err) { if (!err) {
ftFace = face; ftFace = face;
@ -398,29 +398,29 @@ unsigned int FTSize::CharSize() const {
} }
float FTSize::Ascender() const { float FTSize::Ascender() const {
return ftSize == 0 ? 0.0f : static_cast<float> (ftSize->metrics.ascender) / 64.0f; return ftSize == 0 ? 0.0f : static_cast<float>(ftSize->metrics.ascender) / 64.0f;
} }
float FTSize::Descender() const { float FTSize::Descender() const {
return ftSize == 0 ? 0.0f : static_cast<float> (ftSize->metrics.descender) / 64.0f; return ftSize == 0 ? 0.0f : static_cast<float>(ftSize->metrics.descender) / 64.0f;
} }
float FTSize::Height() const { float FTSize::Height() const {
if (0 == ftSize) return 0.0f; if (0 == ftSize) return 0.0f;
if (FT_IS_SCALABLE((*ftFace))) { if (FT_IS_SCALABLE((*ftFace))) {
return ((*ftFace)->bbox.yMax - (*ftFace)->bbox.yMin) * return ((*ftFace)->bbox.yMax - (*ftFace)->bbox.yMin) *
((float)ftSize->metrics.y_ppem / (float)(*ftFace)->units_per_EM); ((float)ftSize->metrics.y_ppem / (float)(*ftFace)->units_per_EM);
} else return static_cast<float> (ftSize->metrics.height) / 64.0f; } else return static_cast<float>(ftSize->metrics.height) / 64.0f;
} }
float FTSize::Width() const { float FTSize::Width() const {
if (0 == ftSize) return 0.0f; if (0 == ftSize) return 0.0f;
if (FT_IS_SCALABLE((*ftFace))) { if (FT_IS_SCALABLE((*ftFace))) {
return ((*ftFace)->bbox.xMax - (*ftFace)->bbox.xMin) * return ((*ftFace)->bbox.xMax - (*ftFace)->bbox.xMin) *
(static_cast<float>(ftSize->metrics.x_ppem) / (static_cast<float>(ftSize->metrics.x_ppem) /
static_cast<float>((*ftFace)->units_per_EM)); static_cast<float>((*ftFace)->units_per_EM));
} else return static_cast<float> (ftSize->metrics.max_advance) / 64.0f; } else return static_cast<float>(ftSize->metrics.max_advance) / 64.0f;
} }
float FTSize::Underline() const {return 0.0f;} float FTSize::Underline() const {return 0.0f;}
@ -429,20 +429,20 @@ float FTSize::Underline() const {return 0.0f;}
// FTGlyph // FTGlyph
// -------------------------------------------------------------------- // --------------------------------------------------------------------
FTGlyph::FTGlyph (FT_GlyphSlot glyph) FTGlyph::FTGlyph(FT_GlyphSlot glyph)
: err(0) { : err(0) {
if (glyph) { if (glyph) {
bBox = FTBBox (glyph); bBox = FTBBox(glyph);
advance = FTPoint (glyph->advance.x / 64.0f, glyph->advance.y / 64.0f, 0.0f); advance = FTPoint(glyph->advance.x / 64.0f, glyph->advance.y / 64.0f, 0.0f);
} }
} }
FTGlyph::~FTGlyph() {} FTGlyph::~FTGlyph() {}
FTGlyphContainer::FTGlyphContainer (FTFace* f) FTGlyphContainer::FTGlyphContainer(FTFace* f)
: face(f), err(0) { : face(f), err(0) {
glyphs.push_back (NULL); glyphs.push_back(NULL);
charMap = new FTCharmap (face); charMap = new FTCharmap(face);
} }
// -------------------------------------------------------------------- // --------------------------------------------------------------------
@ -458,51 +458,51 @@ FTGlyphContainer::~FTGlyphContainer() {
delete charMap; delete charMap;
} }
bool FTGlyphContainer::CharMap (FT_Encoding encoding) { bool FTGlyphContainer::CharMap(FT_Encoding encoding) {
bool result = charMap->CharMap (encoding); bool result = charMap->CharMap(encoding);
err = charMap->Error(); err = charMap->Error();
return result; return result;
} }
unsigned int FTGlyphContainer::FontIndex (const unsigned int characterCode) const { unsigned int FTGlyphContainer::FontIndex(const unsigned int characterCode) const {
return charMap->FontIndex (characterCode); return charMap->FontIndex(characterCode);
} }
void FTGlyphContainer::Add (FTGlyph* tempGlyph, const unsigned int characterCode) { void FTGlyphContainer::Add(FTGlyph* tempGlyph, const unsigned int characterCode) {
charMap->InsertIndex (characterCode, (unsigned int)glyphs.size()); charMap->InsertIndex(characterCode, (unsigned int)glyphs.size());
glyphs.push_back (tempGlyph); glyphs.push_back(tempGlyph);
} }
const FTGlyph* const FTGlyphContainer::Glyph (const unsigned int characterCode) const { const FTGlyph* const FTGlyphContainer::Glyph(const unsigned int characterCode) const {
signed int index = charMap->GlyphListIndex (characterCode); signed int index = charMap->GlyphListIndex(characterCode);
return glyphs[index]; return glyphs[index];
} }
FTBBox FTGlyphContainer::BBox (const unsigned int characterCode) const { FTBBox FTGlyphContainer::BBox(const unsigned int characterCode) const {
return glyphs[charMap->GlyphListIndex (characterCode)]->BBox(); return glyphs[charMap->GlyphListIndex(characterCode)]->BBox();
} }
float FTGlyphContainer::Advance (const unsigned int characterCode, float FTGlyphContainer::Advance(const unsigned int characterCode,
const unsigned int nextCharacterCode) { const unsigned int nextCharacterCode) {
unsigned int left = charMap->FontIndex (characterCode); unsigned int left = charMap->FontIndex(characterCode);
unsigned int right = charMap->FontIndex (nextCharacterCode); unsigned int right = charMap->FontIndex(nextCharacterCode);
float width = face->KernAdvance (left, right).X(); float width = face->KernAdvance(left, right).X();
width += glyphs[charMap->GlyphListIndex (characterCode)]->Advance().X(); width += glyphs[charMap->GlyphListIndex(characterCode)]->Advance().X();
return width; return width;
} }
FTPoint FTGlyphContainer::Render (const unsigned int characterCode, FTPoint FTGlyphContainer::Render(const unsigned int characterCode,
const unsigned int nextCharacterCode, FTPoint penPosition) { const unsigned int nextCharacterCode, FTPoint penPosition) {
FTPoint kernAdvance, advance; FTPoint kernAdvance, advance;
unsigned int left = charMap->FontIndex (characterCode); unsigned int left = charMap->FontIndex(characterCode);
unsigned int right = charMap->FontIndex (nextCharacterCode); unsigned int right = charMap->FontIndex(nextCharacterCode);
kernAdvance = face->KernAdvance (left, right); kernAdvance = face->KernAdvance(left, right);
if (!face->Error()) { if (!face->Error()) {
advance = glyphs[charMap->GlyphListIndex (characterCode)]->Render (penPosition); advance = glyphs[charMap->GlyphListIndex(characterCode)]->Render(penPosition);
} }
kernAdvance += advance; kernAdvance += advance;
@ -515,10 +515,10 @@ FTPoint FTGlyphContainer::Render (const unsigned int characterCode,
GLint FTTextureGlyph::activeTextureID = 0; GLint FTTextureGlyph::activeTextureID = 0;
FTTextureGlyph::FTTextureGlyph (FT_GlyphSlot glyph, int id, int xOffset, FTTextureGlyph::FTTextureGlyph(FT_GlyphSlot glyph, int id, int xOffset,
int yOffset, GLsizei width, GLsizei height) int yOffset, GLsizei width, GLsizei height)
: FTGlyph (glyph), destWidth(0), destHeight(0), glTextureID(id) { : FTGlyph(glyph), destWidth(0), destHeight(0), glTextureID(id) {
err = FT_Render_Glyph (glyph, FT_RENDER_MODE_NORMAL); err = FT_Render_Glyph(glyph, FT_RENDER_MODE_NORMAL);
if (err || glyph->format != ft_glyph_format_bitmap) return; if (err || glyph->format != ft_glyph_format_bitmap) return;
FT_Bitmap bitmap = glyph->bitmap; FT_Bitmap bitmap = glyph->bitmap;
@ -526,36 +526,36 @@ FTTextureGlyph::FTTextureGlyph (FT_GlyphSlot glyph, int id, int xOffset,
destHeight = bitmap.rows; destHeight = bitmap.rows;
if (destWidth && destHeight) { if (destWidth && destHeight) {
glPushClientAttrib (GL_CLIENT_PIXEL_STORE_BIT); glPushClientAttrib(GL_CLIENT_PIXEL_STORE_BIT);
glPixelStorei (GL_UNPACK_LSB_FIRST, GL_FALSE); glPixelStorei(GL_UNPACK_LSB_FIRST, GL_FALSE);
glPixelStorei (GL_UNPACK_ROW_LENGTH, 0); glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
glPixelStorei (GL_UNPACK_ALIGNMENT, 1); glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glBindTexture (GL_TEXTURE_2D, glTextureID); glBindTexture(GL_TEXTURE_2D, glTextureID);
glTexSubImage2D (GL_TEXTURE_2D, 0, xOffset, yOffset, glTexSubImage2D(GL_TEXTURE_2D, 0, xOffset, yOffset,
destWidth, destHeight, GL_ALPHA, GL_UNSIGNED_BYTE, bitmap.buffer); destWidth, destHeight, GL_ALPHA, GL_UNSIGNED_BYTE, bitmap.buffer);
glPopClientAttrib(); glPopClientAttrib();
} }
uv[0].X (static_cast<float>(xOffset) / static_cast<float>(width)); uv[0].X(static_cast<float>(xOffset) / static_cast<float>(width));
uv[0].Y (static_cast<float>(yOffset) / static_cast<float>(height)); uv[0].Y(static_cast<float>(yOffset) / static_cast<float>(height));
uv[1].X (static_cast<float> (xOffset + destWidth) / static_cast<float>(width)); uv[1].X(static_cast<float>(xOffset + destWidth) / static_cast<float>(width));
uv[1].Y (static_cast<float> (yOffset + destHeight) / static_cast<float>(height)); uv[1].Y(static_cast<float>(yOffset + destHeight) / static_cast<float>(height));
pos.X (glyph->bitmap_left); pos.X(glyph->bitmap_left);
pos.Y (glyph->bitmap_top); pos.Y(glyph->bitmap_top);
} }
FTTextureGlyph::~FTTextureGlyph() {} FTTextureGlyph::~FTTextureGlyph() {}
const FTPoint& FTTextureGlyph::Render (const FTPoint& pen) { const FTPoint& FTTextureGlyph::Render(const FTPoint& pen) {
if (activeTextureID != glTextureID) { if (activeTextureID != glTextureID) {
glBindTexture (GL_TEXTURE_2D, (GLuint)glTextureID); glBindTexture(GL_TEXTURE_2D, (GLuint)glTextureID);
activeTextureID = glTextureID; activeTextureID = glTextureID;
} }
glTranslatef (pen.X(), pen.Y(), 0.0f); glTranslatef(pen.X(), pen.Y(), 0.0f);
const GLfloat tex[] = { const GLfloat tex[] = {
uv[0].X(), uv[0].Y(), uv[0].X(), uv[0].Y(),
@ -581,7 +581,7 @@ const FTPoint& FTTextureGlyph::Render (const FTPoint& pen) {
return advance; return advance;
} }
inline GLuint NextPowerOf2 (GLuint in) { inline GLuint NextPowerOf2(GLuint in) {
in -= 1; in -= 1;
in |= in >> 16; in |= in >> 16;
@ -596,8 +596,8 @@ inline GLuint NextPowerOf2 (GLuint in) {
// FTGLTextureFont // FTGLTextureFont
// -------------------------------------------------------------------- // --------------------------------------------------------------------
FTGLTextureFont::FTGLTextureFont (const char* fontFilePath) FTGLTextureFont::FTGLTextureFont(const char* fontFilePath)
: FTFont (fontFilePath), : FTFont(fontFilePath),
maximumGLTextureSize(0), maximumGLTextureSize(0),
textureWidth(0), textureWidth(0),
textureHeight(0), textureHeight(0),
@ -609,8 +609,8 @@ FTGLTextureFont::FTGLTextureFont (const char* fontFilePath)
remGlyphs = numGlyphs = face.GlyphCount(); remGlyphs = numGlyphs = face.GlyphCount();
} }
FTGLTextureFont::FTGLTextureFont (const unsigned char *pBufferBytes, size_t bufferSizeInBytes) FTGLTextureFont::FTGLTextureFont(const unsigned char *pBufferBytes, size_t bufferSizeInBytes)
: FTFont (pBufferBytes, bufferSizeInBytes), : FTFont(pBufferBytes, bufferSizeInBytes),
maximumGLTextureSize(0), maximumGLTextureSize(0),
textureWidth(0), textureWidth(0),
textureHeight(0), textureHeight(0),
@ -623,34 +623,34 @@ FTGLTextureFont::FTGLTextureFont (const unsigned char *pBufferBytes, size_t buff
} }
FTGLTextureFont::~FTGLTextureFont() { FTGLTextureFont::~FTGLTextureFont() {
glDeleteTextures ((GLsizei)textureIDList.size(), (const GLuint*)&textureIDList[0]); glDeleteTextures((GLsizei)textureIDList.size(), (const GLuint*)&textureIDList[0]);
} }
FTGlyph* FTGLTextureFont::MakeGlyph (unsigned int glyphIndex) { FTGlyph* FTGLTextureFont::MakeGlyph(unsigned int glyphIndex) {
FT_GlyphSlot ftGlyph = face.Glyph (glyphIndex, FT_LOAD_NO_HINTING); FT_GlyphSlot ftGlyph = face.Glyph(glyphIndex, FT_LOAD_NO_HINTING);
if (ftGlyph) { if (ftGlyph) {
glyphHeight = static_cast<int> (charSize.Height()); glyphHeight = static_cast<int>(charSize.Height());
glyphWidth = static_cast<int> (charSize.Width()); glyphWidth = static_cast<int>(charSize.Width());
if (textureIDList.empty()) { if (textureIDList.empty()) {
textureIDList.push_back (CreateTexture()); textureIDList.push_back(CreateTexture());
xOffset = yOffset = padding; xOffset = yOffset = padding;
} }
if (xOffset > (textureWidth - glyphWidth)) { if (xOffset > (textureWidth - glyphWidth)) {
xOffset = padding; xOffset = padding;
yOffset += glyphHeight; yOffset += glyphHeight;
if (yOffset > (textureHeight - glyphHeight)) { if (yOffset > (textureHeight - glyphHeight)) {
textureIDList.push_back (CreateTexture()); textureIDList.push_back(CreateTexture());
yOffset = padding; yOffset = padding;
} }
} }
FTTextureGlyph* tempGlyph = FTTextureGlyph* tempGlyph =
new FTTextureGlyph (ftGlyph, textureIDList[textureIDList.size() - 1], new FTTextureGlyph(ftGlyph, textureIDList[textureIDList.size() - 1],
xOffset, yOffset, textureWidth, textureHeight); xOffset, yOffset, textureWidth, textureHeight);
xOffset += static_cast<int> (tempGlyph->BBox().upperX - tempGlyph->BBox().lowerX + padding); xOffset += static_cast<int>(tempGlyph->BBox().upperX - tempGlyph->BBox().lowerX + padding);
--remGlyphs; --remGlyphs;
return tempGlyph; return tempGlyph;
@ -661,13 +661,13 @@ FTGlyph* FTGLTextureFont::MakeGlyph (unsigned int glyphIndex) {
void FTGLTextureFont::CalculateTextureSize() { void FTGLTextureFont::CalculateTextureSize() {
if (!maximumGLTextureSize) { if (!maximumGLTextureSize) {
glGetIntegerv (GL_MAX_TEXTURE_SIZE, (GLint*)&maximumGLTextureSize); glGetIntegerv(GL_MAX_TEXTURE_SIZE, (GLint*)&maximumGLTextureSize);
} }
textureWidth = NextPowerOf2 ((remGlyphs * glyphWidth) + (padding * 2)); textureWidth = NextPowerOf2((remGlyphs * glyphWidth) + (padding * 2));
textureWidth = textureWidth > maximumGLTextureSize ? maximumGLTextureSize : textureWidth; textureWidth = textureWidth > maximumGLTextureSize ? maximumGLTextureSize : textureWidth;
int h = static_cast<int> ((textureWidth - (padding * 2)) / glyphWidth); int h = static_cast<int>((textureWidth - (padding * 2)) / glyphWidth);
textureHeight = NextPowerOf2 (( (numGlyphs / h) + 1) * glyphHeight); textureHeight = NextPowerOf2(((numGlyphs / h) + 1) * glyphHeight);
textureHeight = textureHeight > maximumGLTextureSize ? maximumGLTextureSize : textureHeight; textureHeight = textureHeight > maximumGLTextureSize ? maximumGLTextureSize : textureHeight;
} }
@ -676,48 +676,48 @@ GLuint FTGLTextureFont::CreateTexture() {
int totalMemory = textureWidth * textureHeight; int totalMemory = textureWidth * textureHeight;
unsigned char* textureMemory = new unsigned char[totalMemory]; unsigned char* textureMemory = new unsigned char[totalMemory];
memset (textureMemory, 0, totalMemory); memset(textureMemory, 0, totalMemory);
GLuint textID; GLuint textID;
glGenTextures (1, (GLuint*)&textID); glGenTextures(1, (GLuint*)&textID);
glBindTexture (GL_TEXTURE_2D, textID); glBindTexture(GL_TEXTURE_2D, textID);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexImage2D (GL_TEXTURE_2D, 0, GL_ALPHA, textureWidth, textureHeight, 0, glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, textureWidth, textureHeight, 0,
GL_ALPHA, GL_UNSIGNED_BYTE, textureMemory); GL_ALPHA, GL_UNSIGNED_BYTE, textureMemory);
delete [] textureMemory; delete [] textureMemory;
return textID; return textID;
} }
bool FTGLTextureFont::FaceSize (const unsigned int size, const unsigned int res) { bool FTGLTextureFont::FaceSize(const unsigned int size, const unsigned int res) {
if (!textureIDList.empty()) { if (!textureIDList.empty()) {
glDeleteTextures ((GLsizei)textureIDList.size(), (const GLuint*)&textureIDList[0]); glDeleteTextures((GLsizei)textureIDList.size(), (const GLuint*)&textureIDList[0]);
textureIDList.clear(); textureIDList.clear();
remGlyphs = numGlyphs = face.GlyphCount(); remGlyphs = numGlyphs = face.GlyphCount();
} }
return FTFont::FaceSize (size, res); return FTFont::FaceSize(size, res);
} }
void FTGLTextureFont::Render (const char* string) { void FTGLTextureFont::Render(const char* string) {
glPushAttrib (GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT); glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT);
glEnable(GL_BLEND); glEnable(GL_BLEND);
glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // GL_ONE glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // GL_ONE
FTTextureGlyph::ResetActiveTexture(); FTTextureGlyph::ResetActiveTexture();
FTFont::Render (string); FTFont::Render(string);
glPopAttrib(); glPopAttrib();
} }
void FTGLTextureFont::Render (const wchar_t* string) { void FTGLTextureFont::Render(const wchar_t* string) {
glPushAttrib (GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT); glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT);
glEnable(GL_BLEND); glEnable(GL_BLEND);
glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // GL_ONE glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // GL_ONE
FTTextureGlyph::ResetActiveTexture(); FTTextureGlyph::ResetActiveTexture();
FTFont::Render (string); FTFont::Render(string);
glPopAttrib(); glPopAttrib();
} }
@ -725,33 +725,33 @@ void FTGLTextureFont::Render (const wchar_t* string) {
// FTCharmap (character map) // FTCharmap (character map)
// -------------------------------------------------------------------- // --------------------------------------------------------------------
FTCharmap::FTCharmap (FTFace* face) FTCharmap::FTCharmap(FTFace* face)
: ftFace (*(face->Face())), err(0) { : ftFace(*(face->Face())), err(0) {
if (!ftFace->charmap) err = FT_Set_Charmap (ftFace, ftFace->charmaps[0]); if (!ftFace->charmap) err = FT_Set_Charmap(ftFace, ftFace->charmaps[0]);
ftEncoding = ftFace->charmap->encoding; ftEncoding = ftFace->charmap->encoding;
} }
FTCharmap::~FTCharmap() {charMap.clear();} FTCharmap::~FTCharmap() {charMap.clear();}
bool FTCharmap::CharMap (FT_Encoding encoding) { bool FTCharmap::CharMap(FT_Encoding encoding) {
if (ftEncoding == encoding) return true; if (ftEncoding == encoding) return true;
err = FT_Select_Charmap (ftFace, encoding); err = FT_Select_Charmap(ftFace, encoding);
if (!err) ftEncoding = encoding; if (!err) ftEncoding = encoding;
else ftEncoding = ft_encoding_none; else ftEncoding = ft_encoding_none;
charMap.clear(); charMap.clear();
return !err; return !err;
} }
unsigned int FTCharmap::GlyphListIndex (unsigned int characterCode) { unsigned int FTCharmap::GlyphListIndex(unsigned int characterCode) {
return charMap.find (characterCode); return charMap.find(characterCode);
} }
unsigned int FTCharmap::FontIndex (unsigned int characterCode) { unsigned int FTCharmap::FontIndex(unsigned int characterCode) {
return FT_Get_Char_Index (ftFace, characterCode); return FT_Get_Char_Index(ftFace, characterCode);
} }
void FTCharmap::InsertIndex (const unsigned int characterCode, const unsigned int containerIndex) { void FTCharmap::InsertIndex(const unsigned int characterCode, const unsigned int containerIndex) {
charMap.insert (characterCode, containerIndex); charMap.insert(characterCode, containerIndex);
} }
@ -759,13 +759,13 @@ void FTCharmap::InsertIndex (const unsigned int characterCode, const unsigned in
// FTPixmapGlyph // FTPixmapGlyph
// -------------------------------------------------------------------- // --------------------------------------------------------------------
FTPixmapGlyph::FTPixmapGlyph( FT_GlyphSlot glyph) FTPixmapGlyph::FTPixmapGlyph(FT_GlyphSlot glyph)
: FTGlyph( glyph), : FTGlyph(glyph),
destWidth(0), destWidth(0),
destHeight(0), destHeight(0),
data(0) { data(0) {
err = FT_Render_Glyph( glyph, FT_RENDER_MODE_NORMAL); err = FT_Render_Glyph(glyph, FT_RENDER_MODE_NORMAL);
if ( err || ft_glyph_format_bitmap != glyph->format) return; if (err || ft_glyph_format_bitmap != glyph->format) return;
FT_Bitmap bitmap = glyph->bitmap; FT_Bitmap bitmap = glyph->bitmap;
int srcWidth = bitmap.width; int srcWidth = bitmap.width;
@ -781,8 +781,8 @@ FTPixmapGlyph::FTPixmapGlyph( FT_GlyphSlot glyph)
unsigned char* dest = data + ((destHeight - 1) * destWidth * 2); unsigned char* dest = data + ((destHeight - 1) * destWidth * 2);
size_t destStep = destWidth * 2 * 2; size_t destStep = destWidth * 2 * 2;
for ( int y = 0; y < srcHeight; ++y) { for (int y = 0; y < srcHeight; ++y) {
for ( int x = 0; x < srcWidth; ++x) { for (int x = 0; x < srcWidth; ++x) {
*dest++ = static_cast<unsigned char>(255); *dest++ = static_cast<unsigned char>(255);
*dest++ = *src++; *dest++ = *src++;
} }
@ -797,16 +797,16 @@ FTPixmapGlyph::FTPixmapGlyph( FT_GlyphSlot glyph)
FTPixmapGlyph::~FTPixmapGlyph() {delete [] data;} FTPixmapGlyph::~FTPixmapGlyph() {delete [] data;}
const FTPoint& FTPixmapGlyph::Render( const FTPoint& pen) { const FTPoint& FTPixmapGlyph::Render(const FTPoint& pen) {
glBitmap( 0, 0, 0.0f, 0.0f, pen.X() + pos.X(), pen.Y() - pos.Y(), (const GLubyte*)0); glBitmap(0, 0, 0.0f, 0.0f, pen.X() + pos.X(), pen.Y() - pos.Y(), (const GLubyte*)0);
if ( data) { if (data) {
glPixelStorei( GL_UNPACK_ROW_LENGTH, 0); glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
glPixelStorei( GL_UNPACK_ALIGNMENT, 2); glPixelStorei(GL_UNPACK_ALIGNMENT, 2);
glDrawPixels( destWidth, destHeight, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, (const GLvoid*)data); glDrawPixels(destWidth, destHeight, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, (const GLvoid*)data);
} }
glBitmap( 0, 0, 0.0f, 0.0f, -pos.X(), pos.Y(), (const GLubyte*)0); glBitmap(0, 0, 0.0f, 0.0f, -pos.X(), pos.Y(), (const GLubyte*)0);
return advance; return advance;
} }
@ -815,13 +815,13 @@ const FTPoint& FTPixmapGlyph::Render( const FTPoint& pen) {
// FTPixmapFont // FTPixmapFont
// -------------------------------------------------------------------- // --------------------------------------------------------------------
FTGLPixmapFont::FTGLPixmapFont( const char* fontFilePath) FTGLPixmapFont::FTGLPixmapFont(const char* fontFilePath)
: FTFont( fontFilePath) : FTFont(fontFilePath)
{} {}
FTGLPixmapFont::FTGLPixmapFont( const unsigned char *pBufferBytes, size_t bufferSizeInBytes) FTGLPixmapFont::FTGLPixmapFont(const unsigned char *pBufferBytes, size_t bufferSizeInBytes)
: FTFont( pBufferBytes, bufferSizeInBytes) : FTFont(pBufferBytes, bufferSizeInBytes)
{} {}
@ -829,11 +829,11 @@ FTGLPixmapFont::~FTGLPixmapFont()
{} {}
FTGlyph* FTGLPixmapFont::MakeGlyph( unsigned int g) { FTGlyph* FTGLPixmapFont::MakeGlyph(unsigned int g) {
FT_GlyphSlot ftGlyph = face.Glyph( g, FT_LOAD_NO_HINTING); FT_GlyphSlot ftGlyph = face.Glyph(g, FT_LOAD_NO_HINTING);
if ( ftGlyph) { if (ftGlyph) {
FTPixmapGlyph* tempGlyph = new FTPixmapGlyph( ftGlyph); FTPixmapGlyph* tempGlyph = new FTPixmapGlyph(ftGlyph);
return tempGlyph; return tempGlyph;
} }
@ -842,48 +842,48 @@ FTGlyph* FTGLPixmapFont::MakeGlyph( unsigned int g) {
} }
void FTGLPixmapFont::Render( const char* string) { void FTGLPixmapFont::Render(const char* string) {
glPushAttrib( GL_ENABLE_BIT | GL_PIXEL_MODE_BIT | GL_COLOR_BUFFER_BIT); glPushAttrib(GL_ENABLE_BIT | GL_PIXEL_MODE_BIT | GL_COLOR_BUFFER_BIT);
glPushClientAttrib( GL_CLIENT_PIXEL_STORE_BIT); glPushClientAttrib(GL_CLIENT_PIXEL_STORE_BIT);
glEnable(GL_BLEND); glEnable(GL_BLEND);
glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDisable( GL_TEXTURE_2D); glDisable(GL_TEXTURE_2D);
GLfloat ftglColour[4]; GLfloat ftglColour[4];
glGetFloatv( GL_CURRENT_RASTER_COLOR, ftglColour); glGetFloatv(GL_CURRENT_RASTER_COLOR, ftglColour);
glPixelTransferf(GL_RED_SCALE, ftglColour[0]); glPixelTransferf(GL_RED_SCALE, ftglColour[0]);
glPixelTransferf(GL_GREEN_SCALE, ftglColour[1]); glPixelTransferf(GL_GREEN_SCALE, ftglColour[1]);
glPixelTransferf(GL_BLUE_SCALE, ftglColour[2]); glPixelTransferf(GL_BLUE_SCALE, ftglColour[2]);
glPixelTransferf(GL_ALPHA_SCALE, ftglColour[3]); glPixelTransferf(GL_ALPHA_SCALE, ftglColour[3]);
FTFont::Render( string); FTFont::Render(string);
glPopClientAttrib(); glPopClientAttrib();
glPopAttrib(); glPopAttrib();
} }
void FTGLPixmapFont::Render( const wchar_t* string) { void FTGLPixmapFont::Render(const wchar_t* string) {
glPushAttrib( GL_ENABLE_BIT | GL_PIXEL_MODE_BIT | GL_COLOR_BUFFER_BIT); glPushAttrib(GL_ENABLE_BIT | GL_PIXEL_MODE_BIT | GL_COLOR_BUFFER_BIT);
glPushClientAttrib( GL_CLIENT_PIXEL_STORE_BIT); glPushClientAttrib(GL_CLIENT_PIXEL_STORE_BIT);
glEnable(GL_BLEND); glEnable(GL_BLEND);
glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDisable( GL_TEXTURE_2D); glDisable(GL_TEXTURE_2D);
GLfloat ftglColour[4]; GLfloat ftglColour[4];
glGetFloatv( GL_CURRENT_RASTER_COLOR, ftglColour); glGetFloatv(GL_CURRENT_RASTER_COLOR, ftglColour);
glPixelTransferf(GL_RED_SCALE, ftglColour[0]); glPixelTransferf(GL_RED_SCALE, ftglColour[0]);
glPixelTransferf(GL_GREEN_SCALE, ftglColour[1]); glPixelTransferf(GL_GREEN_SCALE, ftglColour[1]);
glPixelTransferf(GL_BLUE_SCALE, ftglColour[2]); glPixelTransferf(GL_BLUE_SCALE, ftglColour[2]);
glPixelTransferf(GL_ALPHA_SCALE, ftglColour[3]); glPixelTransferf(GL_ALPHA_SCALE, ftglColour[3]);
FTFont::Render( string); FTFont::Render(string);
glPopClientAttrib(); glPopClientAttrib();
glPopAttrib(); glPopAttrib();

View File

@ -211,9 +211,9 @@ public:
typedef signed long GlyphIndex; typedef signed long GlyphIndex;
enum { enum {
NumberOfBuckets = 256, NumberOfBuckets = 256,
BucketSize = 256, BucketSize = 256,
IndexNotFound = -1 IndexNotFound = -1
}; };
FTCharToGlyphIndexMap() {this->Indices = 0;} FTCharToGlyphIndexMap() {this->Indices = 0;}
virtual ~FTCharToGlyphIndexMap() { virtual ~FTCharToGlyphIndexMap() {
@ -444,7 +444,7 @@ public:
upperY = static_cast<float>(bbox.yMax) / 64.0f; upperY = static_cast<float>(bbox.yMax) / 64.0f;
upperZ = 0.0f; upperZ = 0.0f;
} }
FTBBox &Move (FTPoint distance) { FTBBox &Move(FTPoint distance) {
lowerX += distance.X(); lowerX += distance.X();
lowerY += distance.Y(); lowerY += distance.Y();
lowerZ += distance.Z(); lowerZ += distance.Z();
@ -521,7 +521,7 @@ private:
class FTGL_EXPORT FTGlyphContainer { class FTGL_EXPORT FTGlyphContainer {
typedef FTVector<FTGlyph*> GlyphVector; typedef FTVector<FTGlyph*> GlyphVector;
public: public:
FTGlyphContainer (FTFace* face); FTGlyphContainer(FTFace* face);
~FTGlyphContainer(); ~FTGlyphContainer();
bool CharMap(FT_Encoding encoding); bool CharMap(FT_Encoding encoding);
unsigned int FontIndex(const unsigned int characterCode) const; unsigned int FontIndex(const unsigned int characterCode) const;
@ -566,13 +566,13 @@ private:
class FTGL_EXPORT FTFont { class FTGL_EXPORT FTFont {
public: public:
FTFont (const char* fontFilePath); FTFont(const char* fontFilePath);
FTFont (const unsigned char *pBufferBytes, size_t bufferSizeInBytes); FTFont(const unsigned char *pBufferBytes, size_t bufferSizeInBytes);
virtual ~FTFont(); virtual ~FTFont();
bool Attach (const char* fontFilePath); bool Attach(const char* fontFilePath);
bool Attach (const unsigned char *pBufferBytes, size_t bufferSizeInBytes); bool Attach(const unsigned char *pBufferBytes, size_t bufferSizeInBytes);
bool CharMap (FT_Encoding encoding); bool CharMap(FT_Encoding encoding);
unsigned int CharMapCount(); unsigned int CharMapCount();
FT_Encoding* CharMapList(); FT_Encoding* CharMapList();
virtual bool FaceSize(const unsigned int size, const unsigned int res = 72); virtual bool FaceSize(const unsigned int size, const unsigned int res = 72);
@ -583,12 +583,12 @@ public:
float LineHeight() const; float LineHeight() const;
void BBox(const char* string, float& llx, float& lly, void BBox(const char* string, float& llx, float& lly,
float& llz, float& urx, float& ury, float& urz); float& llz, float& urx, float& ury, float& urz);
void BBox (const wchar_t* string, float& llx, float& lly, void BBox(const wchar_t* string, float& llx, float& lly,
float& llz, float& urx, float& ury, float& urz); float& llz, float& urx, float& ury, float& urz);
float Advance (const wchar_t* string); float Advance(const wchar_t* string);
float Advance (const char* string); float Advance(const char* string);
virtual void Render (const char* string); virtual void Render(const char* string);
virtual void Render (const wchar_t* string); virtual void Render(const wchar_t* string);
FT_Error Error() const { return err;} FT_Error Error() const { return err;}
protected: protected:
@ -633,22 +633,22 @@ private:
class FTGL_EXPORT FTGLPixmapFont : public FTFont { class FTGL_EXPORT FTGLPixmapFont : public FTFont {
public: public:
FTGLPixmapFont( const char* fontFilePath); FTGLPixmapFont(const char* fontFilePath);
FTGLPixmapFont( const unsigned char *pBufferBytes, size_t bufferSizeInBytes); FTGLPixmapFont(const unsigned char *pBufferBytes, size_t bufferSizeInBytes);
~FTGLPixmapFont(); ~FTGLPixmapFont();
void Render( const char* string); void Render(const char* string);
void Render( const wchar_t* string); void Render(const wchar_t* string);
private: private:
inline virtual FTGlyph* MakeGlyph( unsigned int g); inline virtual FTGlyph* MakeGlyph(unsigned int g);
}; };
class FTGL_EXPORT FTPixmapGlyph : public FTGlyph { class FTGL_EXPORT FTPixmapGlyph : public FTGlyph {
public: public:
FTPixmapGlyph( FT_GlyphSlot glyph); FTPixmapGlyph(FT_GlyphSlot glyph);
virtual ~FTPixmapGlyph(); virtual ~FTPixmapGlyph();
virtual const FTPoint& Render( const FTPoint& pen); virtual const FTPoint& Render(const FTPoint& pen);
private: private:
int destWidth; int destWidth;
int destHeight; int destHeight;

View File

@ -50,47 +50,47 @@ Then edit the below functions:
TParam param; TParam param;
void LoadConfigFile () { void LoadConfigFile() {
CSPList list(4); CSPList list(4);
if (!list.Load (param.configfile)) { if (!list.Load(param.configfile)) {
Message ("Could not load 'options'"); Message("Could not load 'options'");
return; return;
} }
for (size_t i=0; i<list.Count(); i++) { for (size_t i=0; i<list.Count(); i++) {
const string& line = list.Line(i); const string& line = list.Line(i);
param.fullscreen = SPBoolN (line, "fullscreen", false); param.fullscreen = SPBoolN(line, "fullscreen", false);
param.res_type = SPIntN (line, "res_type", 0); param.res_type = SPIntN(line, "res_type", 0);
param.framerate = SPIntN (line, "framerate", 60); param.framerate = SPIntN(line, "framerate", 60);
param.perf_level = SPIntN (line, "detail_level", 3); param.perf_level = SPIntN(line, "detail_level", 3);
param.language = SPIntN (line, "language", 0); param.language = Trans.GetLangIdx(SPStrN(line, "language", "EN_en"));
param.sound_volume = SPIntN (line, "sound_volume", 100); param.sound_volume = SPIntN(line, "sound_volume", 100);
param.music_volume = SPIntN (line, "music_volume", 20); param.music_volume = SPIntN(line, "music_volume", 20);
param.forward_clip_distance = SPIntN (line, "forward_clip_distance", 75); param.forward_clip_distance = SPIntN(line, "forward_clip_distance", 75);
param.backward_clip_distance = SPIntN (line, "backward_clip_distance", 20); param.backward_clip_distance = SPIntN(line, "backward_clip_distance", 20);
param.fov = SPIntN (line, "fov", 60); param.fov = SPIntN(line, "fov", 60);
param.bpp_mode = SPIntN (line, "bpp_mode", 1); param.bpp_mode = SPIntN(line, "bpp_mode", 1);
param.tree_detail_distance = SPIntN (line, "tree_detail_distance", 20); param.tree_detail_distance = SPIntN(line, "tree_detail_distance", 20);
param.tux_sphere_divisions = SPIntN (line, "tux_sphere_divisions", 10); param.tux_sphere_divisions = SPIntN(line, "tux_sphere_divisions", 10);
param.tux_shadow_sphere_divisions = SPIntN (line, "tux_shadow_sphere_div", 3); param.tux_shadow_sphere_divisions = SPIntN(line, "tux_shadow_sphere_div", 3);
param.course_detail_level = SPIntN (line, "course_detail_level", 75); param.course_detail_level = SPIntN(line, "course_detail_level", 75);
param.use_papercut_font = SPIntN (line, "use_papercut_font", 1); param.use_papercut_font = SPIntN(line, "use_papercut_font", 1);
param.ice_cursor = SPBoolN (line, "ice_cursor", true); param.ice_cursor = SPBoolN(line, "ice_cursor", true);
param.full_skybox = SPBoolN (line, "full_skybox", false); param.full_skybox = SPBoolN(line, "full_skybox", false);
param.audio_freq = SPIntN (line, "audio_freq", 22050); param.audio_freq = SPIntN(line, "audio_freq", 22050);
param.audio_buffer_size = SPIntN (line, "audio_buffer_size", 512); param.audio_buffer_size = SPIntN(line, "audio_buffer_size", 512);
param.use_quad_scale = SPBoolN (line, "use_quad_scale", false); param.use_quad_scale = SPBoolN(line, "use_quad_scale", false);
param.menu_music = SPStrN (line, "menu_music", "start_1"); param.menu_music = SPStrN(line, "menu_music", "start_1");
param.credits_music = SPStrN (line, "credits_music", "credits_1"); param.credits_music = SPStrN(line, "credits_music", "credits_1");
param.config_music = SPStrN (line, "config_music", "options_1"); param.config_music = SPStrN(line, "config_music", "options_1");
} }
} }
void SetConfigDefaults () { void SetConfigDefaults() {
param.fullscreen = true; param.fullscreen = true;
param.res_type = 0; // 0=auto / 1=800x600 / 2=1024x768 ... param.res_type = 0; // 0=auto / 1=800x600 / 2=1024x768 ...
param.framerate = 60; param.framerate = 60;
@ -123,166 +123,166 @@ void SetConfigDefaults () {
} }
void AddItem (CSPList &list, const string& tag, const string& content) { void AddItem(CSPList &list, const string& tag, const string& content) {
string item = " [" +tag + "] " + content; string item = " [" +tag + "] " + content;
list.Add (item); list.Add(item);
} }
void AddIntItem (CSPList &list, const string& tag, int val) { void AddIntItem(CSPList &list, const string& tag, int val) {
string vs = Int_StrN (val); string vs = Int_StrN(val);
AddItem (list, tag, vs); AddItem(list, tag, vs);
} }
void AddComment (CSPList &list, const string& comment) { void AddComment(CSPList &list, const string& comment) {
string line = "# " + comment; string line = "# " + comment;
list.Add (line); list.Add(line);
} }
void SaveConfigFile () { void SaveConfigFile() {
CSPList liste (512); CSPList liste(512);
liste.Add ("# ------------------------------------------------------------------"); liste.Add("# ------------------------------------------------------------------");
liste.Add ("# The first group of params can be adjusted "); liste.Add("# The first group of params can be adjusted ");
liste.Add ("# on the configuration screen, too"); liste.Add("# on the configuration screen, too");
liste.Add ("# ------------------------------------------------------------------"); liste.Add("# ------------------------------------------------------------------");
liste.AddLine(); liste.AddLine();
AddComment (liste, "Full-screen mode [0...1]"); AddComment(liste, "Full-screen mode [0...1]");
AddIntItem (liste, "fullscreen", param.fullscreen); AddIntItem(liste, "fullscreen", param.fullscreen);
liste.AddLine(); liste.AddLine();
AddComment (liste, "Screen resolution [0...9]"); AddComment(liste, "Screen resolution [0...9]");
AddComment (liste, "0 = auto, 1 = 800x600, 2 = 1024x768"); AddComment(liste, "0 = auto, 1 = 800x600, 2 = 1024x768");
AddComment (liste, "3 = 1152x864, 4 = 1280x960, 5 = 1280x1024"); AddComment(liste, "3 = 1152x864, 4 = 1280x960, 5 = 1280x1024");
AddComment (liste, "6 = 1360x768, 7 = 1400x1050, 8 = 1440x900, 9=1680x1050"); AddComment(liste, "6 = 1360x768, 7 = 1400x1050, 8 = 1440x900, 9=1680x1050");
AddIntItem (liste, "res_type", (int)param.res_type); AddIntItem(liste, "res_type", (int)param.res_type);
liste.AddLine(); liste.AddLine();
AddComment (liste, "Framerate limit"); AddComment(liste, "Framerate limit");
AddComment (liste, "0 = unlimited, default: 60"); AddComment(liste, "0 = unlimited, default: 60");
AddIntItem (liste, "framerate", (int)param.framerate); AddIntItem(liste, "framerate", (int)param.framerate);
liste.AddLine(); liste.AddLine();
AddComment (liste, "Level of details [1...3]"); AddComment(liste, "Level of details [1...3]");
AddComment (liste, "1 = best performance, 3 = best appearance"); AddComment(liste, "1 = best performance, 3 = best appearance");
AddIntItem (liste, "detail_level", param.perf_level); AddIntItem(liste, "detail_level", param.perf_level);
liste.AddLine(); liste.AddLine();
AddComment (liste, "Language code [0...]"); AddComment(liste, "Language code");
AddComment (liste, "0 = English etc."); AddComment(liste, "en_GB = English etc.");
AddIntItem (liste, "language", (int)param.language); AddItem(liste, "language", Trans.languages[param.language].lang);
liste.AddLine(); liste.AddLine();
AddComment (liste, "Sound volume [0...120]"); AddComment(liste, "Sound volume [0...120]");
AddComment (liste, "Sounds are the terrain effects or the pickup noise."); AddComment(liste, "Sounds are the terrain effects or the pickup noise.");
AddIntItem (liste, "sound_volume", param.sound_volume); AddIntItem(liste, "sound_volume", param.sound_volume);
liste.AddLine(); liste.AddLine();
AddComment (liste, "Volume of the background music [0...120]"); AddComment(liste, "Volume of the background music [0...120]");
AddIntItem (liste, "music_volume", param.music_volume); AddIntItem(liste, "music_volume", param.music_volume);
liste.AddLine(); liste.AddLine();
liste.Add ("# ------------------------------------------------------------------"); liste.Add("# ------------------------------------------------------------------");
liste.Add ("# The second group of params must be adjusted in this file."); liste.Add("# The second group of params must be adjusted in this file.");
liste.Add ("# ------------------------------------------------------------------"); liste.Add("# ------------------------------------------------------------------");
liste.AddLine(); liste.AddLine();
AddComment (liste, "Forward clipping distance"); AddComment(liste, "Forward clipping distance");
AddComment (liste, "Controls how far ahead of the camera the course"); AddComment(liste, "Controls how far ahead of the camera the course");
AddComment (liste, "is rendered. Larger values mean that more of the course is"); AddComment(liste, "is rendered. Larger values mean that more of the course is");
AddComment (liste, "rendered, resulting in slower performance. Decreasing this "); AddComment(liste, "rendered, resulting in slower performance. Decreasing this ");
AddComment (liste, "value is an effective way to improve framerates."); AddComment(liste, "value is an effective way to improve framerates.");
AddIntItem (liste, "forward_clip_distance", param.forward_clip_distance); AddIntItem(liste, "forward_clip_distance", param.forward_clip_distance);
liste.AddLine(); liste.AddLine();
AddComment (liste, "Backward clipping distance"); AddComment(liste, "Backward clipping distance");
AddComment (liste, "Some objects aren't yet clipped to the view frustum, "); AddComment(liste, "Some objects aren't yet clipped to the view frustum, ");
AddComment (liste, "so this value is used to control how far up the course these "); AddComment(liste, "so this value is used to control how far up the course these ");
AddComment (liste, "objects are drawn."); AddComment(liste, "objects are drawn.");
AddIntItem (liste, "backward_clip_distance", param.backward_clip_distance); AddIntItem(liste, "backward_clip_distance", param.backward_clip_distance);
liste.AddLine(); liste.AddLine();
AddComment (liste, "Field of View of the camera"); AddComment(liste, "Field of View of the camera");
AddIntItem (liste, "fov", param.fov); AddIntItem(liste, "fov", param.fov);
liste.AddLine(); liste.AddLine();
AddComment (liste, "Bpp mode - bits per pixel [0...2]"); AddComment(liste, "Bpp mode - bits per pixel [0...2]");
AddComment (liste, "Controls the color depth of the OpenGL window"); AddComment(liste, "Controls the color depth of the OpenGL window");
AddComment (liste, "0 = use current bpp setting of operating system,"); AddComment(liste, "0 = use current bpp setting of operating system,");
AddComment (liste, "1 = 16 bpp, 2 = 32 bpp"); AddComment(liste, "1 = 16 bpp, 2 = 32 bpp");
AddIntItem (liste, "bpp_mode", param.bpp_mode); AddIntItem(liste, "bpp_mode", param.bpp_mode);
liste.AddLine(); liste.AddLine();
AddComment (liste, "Tree detail distance"); AddComment(liste, "Tree detail distance");
AddComment (liste, "Controls how far up the course the trees are drawn crosswise."); AddComment(liste, "Controls how far up the course the trees are drawn crosswise.");
AddIntItem (liste, "tree_detail_distance", param.tree_detail_distance); AddIntItem(liste, "tree_detail_distance", param.tree_detail_distance);
liste.AddLine(); liste.AddLine();
AddComment (liste, "Tux sphere divisions"); AddComment(liste, "Tux sphere divisions");
AddComment (liste, "Controls how detailled the character is drawn"); AddComment(liste, "Controls how detailled the character is drawn");
AddIntItem (liste, "tux_sphere_divisions", param.tux_sphere_divisions); AddIntItem(liste, "tux_sphere_divisions", param.tux_sphere_divisions);
liste.AddLine(); liste.AddLine();
AddComment (liste, "Tux shadow sphere divisions"); AddComment(liste, "Tux shadow sphere divisions");
AddComment (liste, "The same but for the shadow of the character"); AddComment(liste, "The same but for the shadow of the character");
AddIntItem (liste, "tux_shadow_sphere_div", param.tux_shadow_sphere_divisions); AddIntItem(liste, "tux_shadow_sphere_div", param.tux_shadow_sphere_divisions);
liste.AddLine(); liste.AddLine();
AddComment (liste, "Detail level of the course"); AddComment(liste, "Detail level of the course");
AddComment (liste, "This param is used for the quadtree and controls the"); AddComment(liste, "This param is used for the quadtree and controls the");
AddComment (liste, "LOD of the algorithm. "); AddComment(liste, "LOD of the algorithm. ");
AddIntItem (liste, "course_detail_level", param.course_detail_level); AddIntItem(liste, "course_detail_level", param.course_detail_level);
liste.AddLine(); liste.AddLine();
AddComment (liste, "Font type [0...2]"); AddComment(liste, "Font type [0...2]");
AddComment (liste, "0 = always arial-like font,"); AddComment(liste, "0 = always arial-like font,");
AddComment (liste, "1 = papercut font on the menu screens"); AddComment(liste, "1 = papercut font on the menu screens");
AddComment (liste, "2 = papercut font for the hud display, too"); AddComment(liste, "2 = papercut font for the hud display, too");
AddIntItem (liste, "use_papercut_font", param.use_papercut_font); AddIntItem(liste, "use_papercut_font", param.use_papercut_font);
liste.AddLine(); liste.AddLine();
AddComment (liste, "Cursor type [0...1]"); AddComment(liste, "Cursor type [0...1]");
AddComment (liste, "0 = normal cursor (arrow), 1 = icicle"); AddComment(liste, "0 = normal cursor (arrow), 1 = icicle");
AddIntItem (liste, "ice_cursor", param.ice_cursor); AddIntItem(liste, "ice_cursor", param.ice_cursor);
liste.AddLine(); liste.AddLine();
AddComment (liste, "Draw full skybox [0...1]"); AddComment(liste, "Draw full skybox [0...1]");
AddComment (liste, "A normal skybox consists of 6 textures. In Tuxracer"); AddComment(liste, "A normal skybox consists of 6 textures. In Tuxracer");
AddComment (liste, "3 textures are invisible (top, bottom and back)."); AddComment(liste, "3 textures are invisible (top, bottom and back).");
AddComment (liste, "These textures needn't be drawn."); AddComment(liste, "These textures needn't be drawn.");
AddIntItem (liste, "full_skybox", param.full_skybox); AddIntItem(liste, "full_skybox", param.full_skybox);
liste.AddLine(); liste.AddLine();
AddComment (liste, "Audio frequency"); AddComment(liste, "Audio frequency");
AddComment (liste, "Typical values are 11025, 22050 ..."); AddComment(liste, "Typical values are 11025, 22050 ...");
AddIntItem (liste, "audio_freq", param.audio_freq); AddIntItem(liste, "audio_freq", param.audio_freq);
liste.AddLine(); liste.AddLine();
AddComment (liste, "Size of audio buffer"); AddComment(liste, "Size of audio buffer");
AddComment (liste, "Typical values are 512, 1024, 2048 ..."); AddComment(liste, "Typical values are 512, 1024, 2048 ...");
AddIntItem (liste, "audio_buffer_size", param.audio_buffer_size); AddIntItem(liste, "audio_buffer_size", param.audio_buffer_size);
liste.AddLine(); liste.AddLine();
AddComment (liste, "Select the music:"); AddComment(liste, "Select the music:");
AddComment (liste, "(the racing music is defined by a music theme)"); AddComment(liste, "(the racing music is defined by a music theme)");
AddItem (liste, "menu_music", param.menu_music); AddItem(liste, "menu_music", param.menu_music);
AddItem (liste, "credits_music", param.credits_music); AddItem(liste, "credits_music", param.credits_music);
AddItem (liste, "config_music", param.config_music); AddItem(liste, "config_music", param.config_music);
liste.AddLine(); liste.AddLine();
AddComment (liste, "Use sqare root of scale factors for menu screens [0...1]"); AddComment(liste, "Use sqare root of scale factors for menu screens [0...1]");
AddComment (liste, "Exprimental: these factors reduce the effect of screen scaling."); AddComment(liste, "Exprimental: these factors reduce the effect of screen scaling.");
AddComment (liste, "The widgets are closer to their default sizes."); AddComment(liste, "The widgets are closer to their default sizes.");
AddIntItem (liste, "use_quad_scale", param.use_quad_scale); AddIntItem(liste, "use_quad_scale", param.use_quad_scale);
liste.AddLine(); liste.AddLine();
// --------------------------------------- // ---------------------------------------
liste.Save (param.configfile); liste.Save(param.configfile);
} }
// -------------------------------------------------------------------- // --------------------------------------------------------------------
void InitConfig (const char *arg0) { void InitConfig() {
#if defined (OS_WIN32_MINGW) || defined (OS_WIN32_MSC) #if defined (OS_WIN32_MINGW) || defined (OS_WIN32_MSC)
// the progdir is always the current dir // the progdir is always the current dir
param.config_dir = "config"; param.config_dir = "config";
@ -293,12 +293,12 @@ void InitConfig (const char *arg0) {
#if 0 #if 0
char buff[256]; char buff[256];
if (strcmp (arg0, "./etr") == 0) { // start from work directory if (strcmp(arg0, "./etr") == 0) { // start from work directory
char *s = getcwd (buff, 256); char *s = getcwd(buff, 256);
if (s==NULL) {}; if (s==NULL) {};
} else { // start with full path } else { // start with full path
strcpy (buff, arg0); strcpy(buff, arg0);
if (strlen (buff) > 5) { if (strlen(buff) > 5) {
buff[strlen(buff)-3] = 0; buff[strlen(buff)-3] = 0;
} }
} }
@ -306,13 +306,13 @@ void InitConfig (const char *arg0) {
param.prog_dir = buff; param.prog_dir = buff;
#endif /* 0 */ #endif /* 0 */
struct passwd *pwent = getpwuid (getuid ()); struct passwd *pwent = getpwuid(getuid());
param.config_dir = pwent->pw_dir; param.config_dir = pwent->pw_dir;
param.config_dir += SEP; param.config_dir += SEP;
param.config_dir += CONFIG_DIR; param.config_dir += ".etr";
// or: param.config_dir = param.prog_dir + SEP "config"; // or: param.config_dir = param.prog_dir + SEP "config";
if (!DirExists (param.config_dir.c_str())) if (!DirExists(param.config_dir.c_str()))
mkdir (param.config_dir.c_str(), 0775); mkdir(param.config_dir.c_str(), 0775);
param.data_dir = ETR_DATA_DIR; param.data_dir = ETR_DATA_DIR;
param.data_dir += SEP; param.data_dir += SEP;
param.data_dir += "etr"; param.data_dir += "etr";
@ -338,10 +338,12 @@ void InitConfig (const char *arg0) {
param.display_fps = false; param.display_fps = false;
param.show_hud = true; param.show_hud = true;
if (FileExists (param.configfile)) { Trans.LoadLanguages();
LoadConfigFile ();
if (FileExists(param.configfile)) {
LoadConfigFile();
} else { } else {
SetConfigDefaults (); SetConfigDefaults();
SaveConfigFile (); SaveConfigFile();
} }
} }

View File

@ -19,9 +19,6 @@ GNU General Public License for more details.
#include "bh.h" #include "bh.h"
#define CONFIG_DIR ".etr"
#define PLAYER_FILE "players"
struct TParam { struct TParam {
// defined at runtime: // defined at runtime:
// string prog_dir; // string prog_dir;
@ -78,8 +75,8 @@ struct TParam {
TViewMode view_mode; TViewMode view_mode;
}; };
void InitConfig (const char *arg0); void InitConfig();
void SaveConfigFile (); void SaveConfigFile();
extern TParam param; extern TParam param;

View File

@ -33,18 +33,18 @@ GNU General Public License for more details.
CEvents Events; CEvents Events;
bool CEvents::LoadEventList () { bool CEvents::LoadEventList() {
CSPList list(256); CSPList list(256);
if (!list.Load (param.common_course_dir, "events.lst")) { if (!list.Load(param.common_course_dir, "events.lst")) {
Message ("could not load events.lst"); Message("could not load events.lst");
return false; return false;
} }
// pass 1: races // pass 1: races
for (size_t i=0; i<list.Count(); i++) { for (size_t i=0; i<list.Count(); i++) {
const string& line = list.Line(i); const string& line = list.Line(i);
int type = SPIntN (line, "struct", -1); int type = SPIntN(line, "struct", -1);
if (type == 0) { if (type == 0) {
RaceList.push_back(TRace( RaceList.push_back(TRace(
Course.GetCourse(SPStrN(line, "course")), Course.GetCourse(SPStrN(line, "course")),
@ -56,71 +56,71 @@ bool CEvents::LoadEventList () {
Music.GetThemeIdx(SPStrN(line, "theme", "normal")))); Music.GetThemeIdx(SPStrN(line, "theme", "normal"))));
} }
} }
list.MakeIndex (RaceIndex, "race"); list.MakeIndex(RaceIndex, "race");
// pass 2: cups // pass 2: cups
for (size_t i=0; i<list.Count(); i++) { for (size_t i=0; i<list.Count(); i++) {
const string& line = list.Line(i); const string& line = list.Line(i);
int type = SPIntN (line, "struct", -1); int type = SPIntN(line, "struct", -1);
if (type == 1) { if (type == 1) {
CupList.push_back(TCup( CupList.push_back(TCup(
SPStrN(line, "cup", errorString), SPStrN(line, "cup", errorString),
SPStrN(line, "name", "unknown"), SPStrN(line, "name", "unknown"),
SPStrN(line, "desc", "unknown"))); SPStrN(line, "desc", "unknown")));
int num = SPIntN (line, "num", 0); int num = SPIntN(line, "num", 0);
CupList.back().races.resize(num); CupList.back().races.resize(num);
for (int ii=0; ii<num; ii++) { for (int ii=0; ii<num; ii++) {
string race = SPStrN (line, Int_StrN (ii+1)); string race = SPStrN(line, Int_StrN(ii+1));
CupList.back().races[ii] = &RaceList[GetRaceIdx(race)]; CupList.back().races[ii] = &RaceList[GetRaceIdx(race)];
} }
} }
} }
list.MakeIndex (CupIndex, "cup"); list.MakeIndex(CupIndex, "cup");
// pass 3: events // pass 3: events
for (size_t i=0; i<list.Count(); i++) { for (size_t i=0; i<list.Count(); i++) {
const string& line = list.Line(i); const string& line = list.Line(i);
int type = SPIntN (line, "struct", -1); int type = SPIntN(line, "struct", -1);
if (type == 2) { if (type == 2) {
EventList.push_back(TEvent(SPStrN(line, "name", "unknown"))); EventList.push_back(TEvent(SPStrN(line, "name", "unknown")));
int num = SPIntN (line, "num", 0); int num = SPIntN(line, "num", 0);
EventList.back().cups.resize(num); EventList.back().cups.resize(num);
for (int ii=0; ii<num; ii++) { for (int ii=0; ii<num; ii++) {
string cup = SPStrN (line, Int_StrN (ii+1)); string cup = SPStrN(line, Int_StrN(ii+1));
EventList.back().cups[ii] = &CupList[GetCupIdx(cup)]; EventList.back().cups[ii] = &CupList[GetCupIdx(cup)];
} }
} }
} }
list.MakeIndex (EventIndex, "event"); list.MakeIndex(EventIndex, "event");
return true; return true;
} }
size_t CEvents::GetRaceIdx (const string& race) const { size_t CEvents::GetRaceIdx(const string& race) const {
return RaceIndex.at(race); return RaceIndex.at(race);
} }
size_t CEvents::GetCupIdx (const string& cup) const { size_t CEvents::GetCupIdx(const string& cup) const {
return CupIndex.at(cup); return CupIndex.at(cup);
} }
size_t CEvents::GetEventIdx (const string& event) const { size_t CEvents::GetEventIdx(const string& event) const {
return EventIndex.at(event); return EventIndex.at(event);
} }
const string& CEvents::GetCup (size_t event, size_t cup) const { const string& CEvents::GetCup(size_t event, size_t cup) const {
if (event >= EventList.size()) return errorString; if (event >= EventList.size()) return errorString;
if (cup >= EventList[event].cups.size()) return errorString; if (cup >= EventList[event].cups.size()) return errorString;
return EventList[event].cups[cup]->cup; return EventList[event].cups[cup]->cup;
} }
const string& CEvents::GetCupTrivialName (size_t event, size_t cup) const { const string& CEvents::GetCupTrivialName(size_t event, size_t cup) const {
if (event >= EventList.size()) return errorString; if (event >= EventList.size()) return errorString;
if (cup >= EventList[event].cups.size()) return errorString; if (cup >= EventList[event].cups.size()) return errorString;
return EventList[event].cups[cup]->name; return EventList[event].cups[cup]->name;
} }
void CEvents::MakeUnlockList (const string& unlockstr) { void CEvents::MakeUnlockList(const string& unlockstr) {
for (size_t event=0; event<EventList.size(); event++) { for (size_t event=0; event<EventList.size(); event++) {
for (size_t cup=0; cup<EventList[event].cups.size(); cup++) { for (size_t cup=0; cup<EventList[event].cups.size(); cup++) {
EventList[event].cups[cup]->Unlocked = false; EventList[event].cups[cup]->Unlocked = false;
@ -128,8 +128,8 @@ void CEvents::MakeUnlockList (const string& unlockstr) {
} }
for (size_t event=0; event<EventList.size(); event++) { for (size_t event=0; event<EventList.size(); event++) {
for (size_t cup=0; cup<EventList[event].cups.size(); cup++) { for (size_t cup=0; cup<EventList[event].cups.size(); cup++) {
const string& cp = GetCup (event, cup); const string& cp = GetCup(event, cup);
bool passed = SPosN (unlockstr, cp) != string::npos; bool passed = SPosN(unlockstr, cp) != string::npos;
if (cup < 1) EventList[event].cups[0]->Unlocked = true; if (cup < 1) EventList[event].cups[0]->Unlocked = true;
if (passed) { if (passed) {
EventList[event].cups[cup]->Unlocked = true; EventList[event].cups[cup]->Unlocked = true;
@ -140,7 +140,7 @@ void CEvents::MakeUnlockList (const string& unlockstr) {
} }
} }
bool CEvents::IsUnlocked (size_t event, size_t cup) const { bool CEvents::IsUnlocked(size_t event, size_t cup) const {
if (event >= EventList.size()) return false; if (event >= EventList.size()) return false;
if (cup >= EventList[event].cups.size()) return false; if (cup >= EventList[event].cups.size()) return false;
return EventList[event].cups[cup]->Unlocked; return EventList[event].cups[cup]->Unlocked;
@ -158,26 +158,26 @@ CPlayers::~CPlayers() {
delete avatars[i].texture; delete avatars[i].texture;
} }
void CPlayers::AddPlayer (const string& name, const string& avatar) { void CPlayers::AddPlayer(const string& name, const string& avatar) {
plyr.push_back(TPlayer(name, FindAvatar(avatar))); plyr.push_back(TPlayer(name, FindAvatar(avatar)));
} }
void CPlayers::SetDefaultPlayers () { void CPlayers::SetDefaultPlayers() {
plyr.push_back(TPlayer("Racer", FindAvatar("avatar01.png"))); plyr.push_back(TPlayer("Racer", FindAvatar("avatar01.png")));
plyr.push_back(TPlayer("Bunny", FindAvatar("avatar02.png"))); plyr.push_back(TPlayer("Bunny", FindAvatar("avatar02.png")));
} }
bool CPlayers::LoadPlayers () { bool CPlayers::LoadPlayers() {
if (FileExists (param.config_dir, "players") == false) { if (FileExists(param.config_dir, "players") == false) {
SetDefaultPlayers (); SetDefaultPlayers();
Message ("file 'players' does not exist, set default players"); Message("file 'players' does not exist, set default players");
return false; return false;
} }
CSPList list(MAX_PLAYERS); CSPList list(MAX_PLAYERS);
if (list.Load (param.config_dir, "players") == false) { if (list.Load(param.config_dir, "players") == false) {
SetDefaultPlayers (); SetDefaultPlayers();
Message ("could not load players list, set default players"); Message("could not load players list, set default players");
return false; return false;
} }
@ -185,22 +185,22 @@ bool CPlayers::LoadPlayers () {
plyr.resize(list.Count()); plyr.resize(list.Count());
for (size_t i=0; i<list.Count(); i++) { for (size_t i=0; i<list.Count(); i++) {
const string& line = list.Line(i); const string& line = list.Line(i);
plyr[i].name = SPStrN (line, "name", "unknown"); plyr[i].name = SPStrN(line, "name", "unknown");
plyr[i].funlocked = SPStrN (line, "unlocked"); plyr[i].funlocked = SPStrN(line, "unlocked");
plyr[i].avatar = FindAvatar(SPStrN(line, "avatar")); plyr[i].avatar = FindAvatar(SPStrN(line, "avatar"));
plyr[i].ctrl = NULL; plyr[i].ctrl = NULL;
int active = SPIntN (line, "active", 0); int active = SPIntN(line, "active", 0);
if (active > 0) g_game.start_player = plyr.size()-1; if (active > 0) g_game.start_player = plyr.size()-1;
} }
if (plyr.empty()) { if (plyr.empty()) {
SetDefaultPlayers (); SetDefaultPlayers();
Message ("player file doesn't contain a player, set default players"); Message("player file doesn't contain a player, set default players");
return false; return false;
} }
return true; return true;
} }
void CPlayers::SavePlayers () const { void CPlayers::SavePlayers() const {
string playerfile = param.config_dir + SEP "players"; string playerfile = param.config_dir + SEP "players";
CSPList list(plyr.size()); CSPList list(plyr.size());
for (size_t i=0; i<plyr.size(); i++) { for (size_t i=0; i<plyr.size(); i++) {
@ -209,9 +209,9 @@ void CPlayers::SavePlayers () const {
item += "[unlocked]" + plyr[i].funlocked; item += "[unlocked]" + plyr[i].funlocked;
if (&plyr[i] == g_game.player) item += "[active]1"; if (&plyr[i] == g_game.player) item += "[active]1";
else item += "[active]0"; else item += "[active]0";
list.Add (item); list.Add(item);
} }
list.Save (playerfile); list.Save(playerfile);
} }
const TAvatar* CPlayers::FindAvatar(const string& name) { const TAvatar* CPlayers::FindAvatar(const string& name) {
@ -221,13 +221,13 @@ const TAvatar* CPlayers::FindAvatar(const string& name) {
return 0; return 0;
} }
void CPlayers::AddPassedCup (const string& cup) { void CPlayers::AddPassedCup(const string& cup) {
if (SPIntN (g_game.player->funlocked, cup, -1) > 0) return; if (SPIntN(g_game.player->funlocked, cup, -1) > 0) return;
g_game.player->funlocked += " "; g_game.player->funlocked += " ";
g_game.player->funlocked += cup; g_game.player->funlocked += cup;
} }
void CPlayers::ResetControls () { void CPlayers::ResetControls() {
for (size_t i=0; i<plyr.size(); i++) { for (size_t i=0; i<plyr.size(); i++) {
delete plyr[i].ctrl; delete plyr[i].ctrl;
plyr[i].ctrl = NULL; plyr[i].ctrl = NULL;
@ -235,7 +235,7 @@ void CPlayers::ResetControls () {
} }
// called in module regist.cpp: // called in module regist.cpp:
void CPlayers::AllocControl (size_t player) { void CPlayers::AllocControl(size_t player) {
if (player >= plyr.size()) return; if (player >= plyr.size()) return;
if (plyr[player].ctrl != NULL) return; if (plyr[player].ctrl != NULL) return;
plyr[player].ctrl = new CControl; plyr[player].ctrl = new CControl;
@ -243,17 +243,17 @@ void CPlayers::AllocControl (size_t player) {
// ----------------------- avatars ------------------------------------ // ----------------------- avatars ------------------------------------
void CPlayers::LoadAvatars () { void CPlayers::LoadAvatars() {
CSPList list (MAX_AVATARS); CSPList list(MAX_AVATARS);
if (!list.Load (param.player_dir, "avatars.lst")) { if (!list.Load(param.player_dir, "avatars.lst")) {
Message ("could not load avators.lst"); Message("could not load avators.lst");
return; return;
} }
for (size_t i=0; i<list.Count(); i++) { for (size_t i=0; i<list.Count(); i++) {
const string& line = list.Line(i); const string& line = list.Line(i);
string filename = SPStrN (line, "file", "unknown"); string filename = SPStrN(line, "file", "unknown");
TTexture* texture = new TTexture(); TTexture* texture = new TTexture();
if (texture && texture->Load(param.player_dir, filename)) { if (texture && texture->Load(param.player_dir, filename)) {
avatars.push_back(TAvatar(filename, texture)); avatars.push_back(TAvatar(filename, texture));
@ -262,12 +262,12 @@ void CPlayers::LoadAvatars () {
} }
} }
TTexture* CPlayers::GetAvatarTexture (size_t avatar) const { TTexture* CPlayers::GetAvatarTexture(size_t avatar) const {
if (avatar >= avatars.size()) return 0; if (avatar >= avatars.size()) return 0;
return avatars[avatar].texture; return avatars[avatar].texture;
} }
const string& CPlayers::GetDirectAvatarName (size_t avatar) const { const string& CPlayers::GetDirectAvatarName(size_t avatar) const {
if (avatar >= avatars.size()) return emptyString; if (avatar >= avatars.size()) return emptyString;
return avatars[avatar].filename; return avatars[avatar].filename;
} }
@ -293,48 +293,48 @@ CCharacter::~CCharacter() {
} }
} }
void CCharacter::LoadCharacterList () { void CCharacter::LoadCharacterList() {
CSPList list (MAX_CHARACTERS); CSPList list(MAX_CHARACTERS);
if (!list.Load (param.char_dir, "characters.lst")) { if (!list.Load(param.char_dir, "characters.lst")) {
Message ("could not load characters.lst"); Message("could not load characters.lst");
return; return;
} }
CharList.resize(list.Count()); CharList.resize(list.Count());
for (size_t i=0; i<list.Count(); i++) { for (size_t i=0; i<list.Count(); i++) {
const string& line = list.Line(i); const string& line = list.Line(i);
CharList[i].name = SPStrN (line, "name"); CharList[i].name = SPStrN(line, "name");
CharList[i].dir = SPStrN (line, "dir"); CharList[i].dir = SPStrN(line, "dir");
string typestr = SPStrN (line, "type", "unknown"); string typestr = SPStrN(line, "type", "unknown");
CharList[i].type = SPIntN (char_type_index, typestr, -1); CharList[i].type = SPIntN(char_type_index, typestr, -1);
string charpath = param.char_dir + SEP + CharList[i].dir; string charpath = param.char_dir + SEP + CharList[i].dir;
if (DirExists (charpath.c_str())) { if (DirExists(charpath.c_str())) {
string previewfile = charpath + SEP "preview.png"; string previewfile = charpath + SEP "preview.png";
TCharacter* ch = &CharList[i]; TCharacter* ch = &CharList[i];
ch->preview = new TTexture(); ch->preview = new TTexture();
if (!ch->preview->LoadMipmap(previewfile, false)) { if (!ch->preview->LoadMipmap(previewfile, false)) {
Message ("could not load previewfile of character"); Message("could not load previewfile of character");
// texid = Tex.TexID (NO_PREVIEW); // texid = Tex.TexID (NO_PREVIEW);
} }
ch->shape = new CCharShape; ch->shape = new CCharShape;
if (ch->shape->Load (charpath, "shape.lst", false) == false) { if (ch->shape->Load(charpath, "shape.lst", false) == false) {
delete ch->shape; delete ch->shape;
ch->shape = NULL; ch->shape = NULL;
Message ("could not load character shape"); Message("could not load character shape");
} }
ch->frames[0].Load (charpath, "start.lst"); ch->frames[0].Load(charpath, "start.lst");
ch->finishframesok = true; ch->finishframesok = true;
ch->frames[1].Load (charpath, "finish.lst"); ch->frames[1].Load(charpath, "finish.lst");
if (ch->frames[1].loaded == false) ch->finishframesok = false; if (ch->frames[1].loaded == false) ch->finishframesok = false;
ch->frames[2].Load (charpath, "wonrace.lst"); ch->frames[2].Load(charpath, "wonrace.lst");
if (ch->frames[2].loaded == false) ch->finishframesok = false; if (ch->frames[2].loaded == false) ch->finishframesok = false;
ch->frames[3].Load (charpath, "lostrace.lst"); ch->frames[3].Load(charpath, "lostrace.lst");
if (ch->frames[3].loaded == false) ch->finishframesok = false; if (ch->frames[3].loaded == false) ch->finishframesok = false;
} }
} }

View File

@ -78,15 +78,15 @@ public:
vector<TRace> RaceList; vector<TRace> RaceList;
vector<TCup> CupList; vector<TCup> CupList;
vector<TEvent> EventList; vector<TEvent> EventList;
bool LoadEventList (); bool LoadEventList();
size_t GetRaceIdx (const string& race) const; size_t GetRaceIdx(const string& race) const;
size_t GetCupIdx (const string& cup) const; size_t GetCupIdx(const string& cup) const;
size_t GetEventIdx (const string& event) const; size_t GetEventIdx(const string& event) const;
const string& GetCup (size_t event, size_t cup) const; const string& GetCup(size_t event, size_t cup) const;
const string& GetCupTrivialName (size_t event, size_t cup) const; const string& GetCupTrivialName(size_t event, size_t cup) const;
void MakeUnlockList (const string& unlockstr); void MakeUnlockList(const string& unlockstr);
bool IsUnlocked (size_t event, size_t cup) const; bool IsUnlocked(size_t event, size_t cup) const;
}; };
extern CEvents Events; extern CEvents Events;
@ -121,7 +121,7 @@ struct TPlayer {
class CPlayers { class CPlayers {
private: private:
vector<TPlayer> plyr; vector<TPlayer> plyr;
void SetDefaultPlayers (); void SetDefaultPlayers();
vector<TAvatar> avatars; vector<TAvatar> avatars;
const TAvatar* FindAvatar(const string& name); const TAvatar* FindAvatar(const string& name);
@ -129,17 +129,17 @@ public:
~CPlayers(); ~CPlayers();
TPlayer* GetPlayer(size_t index) { return &plyr[index]; } TPlayer* GetPlayer(size_t index) { return &plyr[index]; }
void AddPassedCup (const string& cup); void AddPassedCup(const string& cup);
void AddPlayer (const string& name, const string& avatar); void AddPlayer(const string& name, const string& avatar);
bool LoadPlayers (); bool LoadPlayers();
void SavePlayers () const; void SavePlayers() const;
void ResetControls (); void ResetControls();
void AllocControl (size_t player); void AllocControl(size_t player);
void LoadAvatars (); void LoadAvatars();
size_t numAvatars() const { return avatars.size(); } size_t numAvatars() const { return avatars.size(); }
size_t numPlayers() const { return plyr.size(); } size_t numPlayers() const { return plyr.size(); }
TTexture* GetAvatarTexture (size_t avatar) const; TTexture* GetAvatarTexture(size_t avatar) const;
const string& GetDirectAvatarName(size_t avatar) const; const string& GetDirectAvatarName(size_t avatar) const;
}; };
@ -166,8 +166,8 @@ public:
~CCharacter(); ~CCharacter();
void LoadCharacterList (); void LoadCharacterList();
void FreeCharacterPreviews (); void FreeCharacterPreviews();
}; };
extern CCharacter Char; extern CCharacter Char;

View File

@ -43,27 +43,27 @@ GNU General Public License for more details.
CGameOver GameOver; CGameOver GameOver;
static CKeyframe *final_frame; static CKeyframe *final_frame;
static int highscore_pos = 999; static int highscore_pos = MAX_SCORES;
void QuitGameOver () { void QuitGameOver() {
if (g_game.game_type == PRACTICING) { if (g_game.game_type == PRACTICING) {
State::manager.RequestEnterState (RaceSelect); State::manager.RequestEnterState(RaceSelect);
} else { } else {
State::manager.RequestEnterState (Event); State::manager.RequestEnterState(Event);
} }
} }
void CGameOver::Keyb (unsigned int key, bool special, bool release, int x, int y) { void CGameOver::Keyb(unsigned int key, bool special, bool release, int x, int y) {
if (release) return; if (release) return;
if (key == 13 || key == SDLK_ESCAPE) QuitGameOver (); if (key == 13 || key == SDLK_ESCAPE) QuitGameOver();
} }
void CGameOver::Mouse (int button, int state, int x, int y) { void CGameOver::Mouse(int button, int state, int x, int y) {
QuitGameOver (); QuitGameOver();
} }
void GameOverMessage (const CControl *ctrl) { void GameOverMessage(const CControl *ctrl) {
int fwidth = 500; int fwidth = 500;
int leftframe = (Winsys.resolution.width - fwidth) / 2; int leftframe = (Winsys.resolution.width - fwidth) / 2;
@ -72,82 +72,84 @@ void GameOverMessage (const CControl *ctrl) {
const TColor& backcol = colWhite; const TColor& backcol = colWhite;
static const TColor framecol(0.7, 0.7, 1, 1); static const TColor framecol(0.7, 0.7, 1, 1);
if (param.use_papercut_font > 0) FT.SetSize (28); if (param.use_papercut_font > 0) FT.SetSize(28);
else FT.SetSize (22); else FT.SetSize(22);
if (g_game.raceaborted) { if (g_game.raceaborted) {
DrawFrameX (leftframe, topframe, fwidth, 100, 4, backcol, framecol, 0.5); DrawFrameX(leftframe, topframe, fwidth, 100, 4, backcol, framecol, 0.5);
FT.SetColor (colDBlue); FT.SetColor(colDBlue);
FT.DrawString (CENTER, topframe+30, Trans.Text(25)); FT.DrawString(CENTER, topframe+30, Trans.Text(25));
} else { } else {
int firstMarker = leftframe + 60;
int secondMarker = leftframe + 310;
DrawFrameX(leftframe, topframe, fwidth, 210, 4, backcol, framecol, 0.5); DrawFrameX(leftframe, topframe, fwidth, 210, 4, backcol, framecol, 0.5);
if (param.use_papercut_font > 0) FT.SetSize (20); if (param.use_papercut_font > 0) FT.SetSize(20);
else FT.SetSize (14); else FT.SetSize(14);
if (g_game.race_result >= 0 || g_game.game_type != CUPRACING) FT.SetColor (colDBlue); if (g_game.race_result >= 0 || g_game.game_type != CUPRACING) FT.SetColor(colDBlue);
else FT.SetColor (colDRed); else FT.SetColor(colDRed);
string line = "Score: "; string line = Trans.Text(86) + ": ";
FT.DrawString (leftframe+80, topframe+15, line); FT.DrawString(firstMarker, topframe + 15, line);
line = Int_StrN (g_game.score); line = Int_StrN(g_game.score);
line += " pts"; line += " pts";
FT.DrawString (leftframe+240, topframe+15, line); FT.DrawString(secondMarker, topframe + 15, line);
line = "Herring: "; line = Trans.Text(87) + ": ";
FT.DrawString (leftframe+80, topframe+40, line); FT.DrawString(firstMarker, topframe + 40, line);
line = Int_StrN (g_game.herring); line = Int_StrN(g_game.herring);
if (g_game.game_type == CUPRACING) { if (g_game.game_type == CUPRACING) {
line += " ("; line += " (";
line += Int_StrN (g_game.race->herrings.x); line += Int_StrN(g_game.race->herrings.x);
line += ")"; line += ")";
} }
FT.DrawString (leftframe+240, topframe+40, line); FT.DrawString(secondMarker, topframe + 40, line);
line = "Time: "; line = Trans.Text(88) + ": ";
FT.DrawString (leftframe+80, topframe+65, line); FT.DrawString(firstMarker, topframe + 65, line);
line = Float_StrN (g_game.time, 2); line = Float_StrN(g_game.time, 2);
line += " s"; line += " s";
if (g_game.game_type == CUPRACING) { if (g_game.game_type == CUPRACING) {
line += " ("; line += " (";
line += Float_StrN (g_game.race->time.x, 2); line += Float_StrN(g_game.race->time.x, 2);
line += ")"; line += ")";
} }
FT.DrawString (leftframe+240, topframe+65, line); FT.DrawString(secondMarker, topframe + 65, line);
line = "Path length: "; line = Trans.Text(89) + ": ";
FT.DrawString (leftframe+80, topframe+90, line); FT.DrawString(firstMarker, topframe + 90, line);
line = Float_StrN (ctrl->way, 2); line = Float_StrN(ctrl->way, 2);
line += " m"; line += " m";
FT.DrawString (leftframe+240, topframe+90, line); FT.DrawString(secondMarker, topframe + 90, line);
line = "Average speed: "; line = Trans.Text(90) + ": ";
FT.DrawString (leftframe+80, topframe+115, line); FT.DrawString(firstMarker, topframe + 115, line);
line = Float_StrN (ctrl->way / g_game.time * 3.6, 2); line = Float_StrN(ctrl->way / g_game.time * 3.6, 2);
line += " km/h"; line += " km/h";
FT.DrawString (leftframe+240, topframe+115, line); FT.DrawString(secondMarker, topframe + 115, line);
if (param.use_papercut_font > 0) FT.SetSize (28); if (param.use_papercut_font > 0) FT.SetSize(28);
else FT.SetSize (22); else FT.SetSize(22);
if (g_game.game_type == CUPRACING) { if (g_game.game_type == CUPRACING) {
switch (g_game.race_result) { switch (g_game.race_result) {
case -1: case -1:
FT.DrawString (CENTER, topframe+150, Trans.Text(21)); FT.DrawString(CENTER, topframe+150, Trans.Text(21));
break; break;
case 0: case 0:
FT.DrawString (CENTER, topframe+150, Trans.Text(22)); FT.DrawString(CENTER, topframe+150, Trans.Text(22));
break; break;
case 1: case 1:
FT.DrawString (CENTER, topframe+150, Trans.Text(23)); FT.DrawString(CENTER, topframe+150, Trans.Text(23));
break; break;
case 2: case 2:
FT.DrawString (CENTER, topframe+150, Trans.Text(24)); FT.DrawString(CENTER, topframe+150, Trans.Text(24));
break; break;
} }
} else { } else {
if (highscore_pos < 5) { if (highscore_pos < MAX_SCORES) {
line = "Position "; line = Trans.Text(91) + ' ';
line += Int_StrN (highscore_pos + 1); line += Int_StrN(highscore_pos + 1);
line += " in highscore list"; line += ' ' + Trans.Text(92);
FT.DrawString (CENTER, topframe+150, line); FT.DrawString(CENTER, topframe+150, line);
} }
} }
} }
@ -155,21 +157,19 @@ void GameOverMessage (const CControl *ctrl) {
// ========================================================================= // =========================================================================
void CGameOver::Enter() { void CGameOver::Enter() {
Sound.HaltAll (); if (!g_game.raceaborted) highscore_pos = Score.CalcRaceResult();
if (!g_game.raceaborted) highscore_pos = Score.CalcRaceResult ();
if (g_game.game_type == CUPRACING) { if (g_game.game_type == CUPRACING) {
if (g_game.race_result >= 0) { if (g_game.race_result >= 0) {
Music.PlayTheme (g_game.theme_id, MUS_WONRACE); Music.PlayTheme(g_game.theme_id, MUS_WONRACE);
} else { } else {
Music.PlayTheme (g_game.theme_id, MUS_LOSTRACE); Music.PlayTheme(g_game.theme_id, MUS_LOSTRACE);
} }
} else { } else {
if (g_game.raceaborted) { if (g_game.raceaborted) {
Music.PlayTheme (g_game.theme_id, MUS_LOSTRACE); Music.PlayTheme(g_game.theme_id, MUS_LOSTRACE);
} else { } else {
Music.PlayTheme (g_game.theme_id, MUS_WONRACE); Music.PlayTheme(g_game.theme_id, MUS_WONRACE);
} }
} }
@ -181,14 +181,14 @@ void CGameOver::Enter() {
if (g_game.race_result < 0) if (g_game.race_result < 0)
final_frame = g_game.character->GetKeyframe(LOSTRACE); final_frame = g_game.character->GetKeyframe(LOSTRACE);
else final_frame = g_game.character->GetKeyframe(WONRACE); else final_frame = g_game.character->GetKeyframe(WONRACE);
} else final_frame = g_game.character->GetKeyframe( FINISH); } else final_frame = g_game.character->GetKeyframe(FINISH);
if (!g_game.raceaborted) { if (!g_game.raceaborted) {
const CControl *ctrl = g_game.player->ctrl; const CControl *ctrl = g_game.player->ctrl;
final_frame->Init (ctrl->cpos, -0.18); final_frame->Init(ctrl->cpos, -0.18);
} }
} }
SetStationaryCamera (true); SetStationaryCamera(true);
} }
@ -196,38 +196,37 @@ void CGameOver::Loop(double time_step) {
CControl *ctrl = g_game.player->ctrl; CControl *ctrl = g_game.player->ctrl;
int width = Winsys.resolution.width; int width = Winsys.resolution.width;
int height = Winsys.resolution.height; int height = Winsys.resolution.height;
check_gl_error();
Music.Update (); Music.Update();
ClearRenderContext (); ClearRenderContext();
Env.SetupFog (); Env.SetupFog();
update_view (ctrl, 0); update_view(ctrl, 0);
if (final_frame != NULL) final_frame->Update (time_step); if (final_frame != NULL) final_frame->Update(time_step);
SetupViewFrustum (ctrl); SetupViewFrustum(ctrl);
Env.DrawSkybox (ctrl->viewpos); Env.DrawSkybox(ctrl->viewpos);
Env.DrawFog (); Env.DrawFog();
Env.SetupLight (); Env.SetupLight();
RenderCourse (); RenderCourse();
DrawTrackmarks (); DrawTrackmarks();
DrawTrees (); DrawTrees();
UpdateWind (time_step); UpdateWind(time_step);
UpdateSnow (time_step, ctrl); UpdateSnow(time_step, ctrl);
DrawSnow (ctrl); DrawSnow(ctrl);
g_game.character->shape->Draw(); g_game.character->shape->Draw();
ScopedRenderMode rm(GUI); ScopedRenderMode rm(GUI);
SetupGuiDisplay (); SetupGuiDisplay();
if (final_frame != NULL) { if (final_frame != NULL) {
if (!final_frame->active) GameOverMessage (ctrl); if (!final_frame->active) GameOverMessage(ctrl);
} else GameOverMessage (ctrl); } else GameOverMessage(ctrl);
DrawHud (ctrl); DrawHud(ctrl);
Reshape (width, height); Reshape(width, height);
Winsys.SwapBuffers (); Winsys.SwapBuffers();
} }

View File

@ -39,36 +39,36 @@ CGameTypeSelect GameTypeSelect;
static TTextButton* textbuttons[7]; static TTextButton* textbuttons[7];
void EnterPractice () { void EnterPractice() {
g_game.game_type = PRACTICING; g_game.game_type = PRACTICING;
State::manager.RequestEnterState (RaceSelect); State::manager.RequestEnterState(RaceSelect);
} }
void QuitGameType () { void QuitGameType() {
if (textbuttons[0]->focussed()) if (textbuttons[0]->focussed())
State::manager.RequestEnterState (EventSelect); State::manager.RequestEnterState(EventSelect);
if (textbuttons[1]->focussed()) if (textbuttons[1]->focussed())
EnterPractice (); EnterPractice();
if (textbuttons[2]->focussed()) if (textbuttons[2]->focussed())
State::manager.RequestEnterState (GameConfig); State::manager.RequestEnterState(GameConfig);
if (textbuttons[3]->focussed()) if (textbuttons[3]->focussed())
State::manager.RequestEnterState (Score); State::manager.RequestEnterState(Score);
if (textbuttons[4]->focussed()) if (textbuttons[4]->focussed())
State::manager.RequestEnterState (Help); State::manager.RequestEnterState(Help);
if (textbuttons[5]->focussed()) if (textbuttons[5]->focussed())
State::manager.RequestEnterState (Credits); State::manager.RequestEnterState(Credits);
if (textbuttons[6]->focussed()) if (textbuttons[6]->focussed())
State::manager.RequestQuit(); State::manager.RequestQuit();
} }
void CGameTypeSelect::Mouse (int button, int state, int x, int y) { void CGameTypeSelect::Mouse(int button, int state, int x, int y) {
if (state == 1) { if (state == 1) {
ClickGUI(x, y); ClickGUI(x, y);
QuitGameType(); QuitGameType();
} }
} }
void CGameTypeSelect::Keyb (unsigned int key, bool special, bool release, int x, int y) { void CGameTypeSelect::Keyb(unsigned int key, bool special, bool release, int x, int y) {
if (release) return; if (release) return;
KeyGUI(key, 0, release); KeyGUI(key, 0, release);
@ -94,55 +94,54 @@ void CGameTypeSelect::Keyb (unsigned int key, bool special, bool release, int x,
} }
} }
void CGameTypeSelect::Motion (int x, int y) { void CGameTypeSelect::Motion(int x, int y) {
MouseMoveGUI(x, y); MouseMoveGUI(x, y);
if (param.ui_snow) push_ui_snow (cursor_pos); if (param.ui_snow) push_ui_snow(cursor_pos);
} }
// ==================================================================== // ====================================================================
void CGameTypeSelect::Enter () { void CGameTypeSelect::Enter() {
Winsys.ShowCursor (!param.ice_cursor); Winsys.ShowCursor(!param.ice_cursor);
ResetGUI (); ResetGUI();
int top = AutoYPosN (40); int top = AutoYPosN(40);
int siz = FT.AutoSizeN (6); int siz = FT.AutoSizeN(6);
int dist = FT.AutoDistanceN (2); int dist = FT.AutoDistanceN(2);
textbuttons[0] = AddTextButton (Trans.Text(1), CENTER, top, siz); textbuttons[0] = AddTextButton(Trans.Text(1), CENTER, top, siz);
textbuttons[1] = AddTextButton (Trans.Text(2), CENTER, top + dist, siz); textbuttons[1] = AddTextButton(Trans.Text(2), CENTER, top + dist, siz);
textbuttons[2] = AddTextButton (Trans.Text(3), CENTER, top + dist * 2, siz); textbuttons[2] = AddTextButton(Trans.Text(3), CENTER, top + dist * 2, siz);
textbuttons[3] = AddTextButton (Trans.Text(62), CENTER, top + dist * 3, siz); textbuttons[3] = AddTextButton(Trans.Text(62), CENTER, top + dist * 3, siz);
textbuttons[4] = AddTextButton (Trans.Text(43), CENTER, top + dist * 4, siz); textbuttons[4] = AddTextButton(Trans.Text(43), CENTER, top + dist * 4, siz);
textbuttons[5] = AddTextButton (Trans.Text(4), CENTER, top + dist * 5, siz); textbuttons[5] = AddTextButton(Trans.Text(4), CENTER, top + dist * 5, siz);
textbuttons[6] = AddTextButton (Trans.Text(5), CENTER, top + dist * 6, siz); textbuttons[6] = AddTextButton(Trans.Text(5), CENTER, top + dist * 6, siz);
Music.Play (param.menu_music, -1); Music.Play(param.menu_music, -1);
} }
void CGameTypeSelect::Loop (double time_step) { void CGameTypeSelect::Loop(double time_step) {
int ww = Winsys.resolution.width; int ww = Winsys.resolution.width;
int hh = Winsys.resolution.height; int hh = Winsys.resolution.height;
check_gl_error(); Music.Update();
Music.Update ();
ScopedRenderMode rm(GUI); ScopedRenderMode rm(GUI);
ClearRenderContext (); ClearRenderContext();
SetupGuiDisplay (); SetupGuiDisplay();
if (param.ui_snow) { if (param.ui_snow) {
update_ui_snow (time_step); update_ui_snow(time_step);
draw_ui_snow(); draw_ui_snow();
} }
Tex.Draw (T_TITLE, CENTER, AutoYPosN (5), Winsys.scale); Tex.Draw(T_TITLE, CENTER, AutoYPosN(5), Winsys.scale);
Tex.Draw (BOTTOM_LEFT, 0, hh-256, 1); Tex.Draw(BOTTOM_LEFT, 0, hh-256, 1);
Tex.Draw (BOTTOM_RIGHT, ww-256, hh-256, 1); Tex.Draw(BOTTOM_RIGHT, ww-256, hh-256, 1);
Tex.Draw (TOP_LEFT, 0, 0, 1); Tex.Draw(TOP_LEFT, 0, 0, 1);
Tex.Draw (TOP_RIGHT, ww-256, 0, 1); Tex.Draw(TOP_RIGHT, ww-256, 0, 1);
DrawGUI(); DrawGUI();
Reshape (ww, hh); Reshape(ww, hh);
Winsys.SwapBuffers (); Winsys.SwapBuffers();
} }

View File

@ -32,7 +32,7 @@ GNU General Public License for more details.
static vector<TWidget*> Widgets; static vector<TWidget*> Widgets;
static bool Inside (int x, int y, const TRect& Rect) { static bool Inside(int x, int y, const TRect& Rect) {
return (x >= Rect.left return (x >= Rect.left
&& x <= Rect.left + Rect.width && x <= Rect.left + Rect.width
&& y >= Rect.top && y >= Rect.top
@ -63,9 +63,9 @@ TTextButton::TTextButton(int x, int y, const string& text_, double ftsize_)
: TWidget(x, y, 0, 0) : TWidget(x, y, 0, 0)
, text(text_) , text(text_)
, ftsize(ftsize_) { , ftsize(ftsize_) {
if (ftsize < 0) ftsize = FT.AutoSizeN (4); if (ftsize < 0) ftsize = FT.AutoSizeN(4);
double len = FT.GetTextWidth (text); double len = FT.GetTextWidth(text);
if (x == CENTER) position.x = (int)((Winsys.resolution.width - len) / 2); if (x == CENTER) position.x = (int)((Winsys.resolution.width - len) / 2);
int offs = (int)(ftsize / 5); int offs = (int)(ftsize / 5);
mouseRect.left = position.x-20; mouseRect.left = position.x-20;
@ -76,21 +76,21 @@ TTextButton::TTextButton(int x, int y, const string& text_, double ftsize_)
void TTextButton::Draw() const { void TTextButton::Draw() const {
if (focus) if (focus)
FT.SetColor (colDYell); FT.SetColor(colDYell);
else else
FT.SetColor (colWhite); FT.SetColor(colWhite);
FT.SetSize (ftsize); FT.SetSize(ftsize);
FT.DrawString (position.x, position.y, text); FT.DrawString(position.x, position.y, text);
} }
TTextButton* AddTextButton (const string& text, int x, int y, double ftsize) { TTextButton* AddTextButton(const string& text, int x, int y, double ftsize) {
Widgets.push_back(new TTextButton(x, y, text, ftsize)); Widgets.push_back(new TTextButton(x, y, text, ftsize));
return static_cast<TTextButton*>(Widgets.back()); return static_cast<TTextButton*>(Widgets.back());
} }
TTextButton* AddTextButtonN (const string& text, int x, int y, int rel_ftsize) { TTextButton* AddTextButtonN(const string& text, int x, int y, int rel_ftsize) {
double siz = FT.AutoSizeN (rel_ftsize); double siz = FT.AutoSizeN(rel_ftsize);
return AddTextButton (text, x, y, siz); return AddTextButton(text, x, y, siz);
} }
@ -105,22 +105,22 @@ TTextField::TTextField(int x, int y, int width, int height, const string& text_)
void TTextField::Draw() const { void TTextField::Draw() const {
const TColor& col = focus?colDYell:colWhite; const TColor& col = focus?colDYell:colWhite;
FT.SetColor (col); FT.SetColor(col);
DrawFrameX (mouseRect.left, mouseRect.top, mouseRect.width, mouseRect.height, 3, colMBackgr, col, 1.0); DrawFrameX(mouseRect.left, mouseRect.top, mouseRect.width, mouseRect.height, 3, colMBackgr, col, 1.0);
FT.AutoSizeN (5); FT.AutoSizeN(5);
FT.DrawString (mouseRect.left+20, mouseRect.top, text); FT.DrawString(mouseRect.left+20, mouseRect.top, text);
if (cursor && focus) { if (cursor && focus) {
int x = mouseRect.left + 20 + 1; int x = mouseRect.left + 20 + 1;
if (cursorPos != 0) { if (cursorPos != 0) {
string temp = text.substr (0, cursorPos); string temp = text.substr(0, cursorPos);
x += FT.GetTextWidth (temp); x += FT.GetTextWidth(temp);
} }
int w = 3; int w = 3;
int h = 26 * Winsys.scale; int h = 26 * Winsys.scale;
int scrheight = Winsys.resolution.height; int scrheight = Winsys.resolution.height;
glDisable (GL_TEXTURE_2D); glDisable(GL_TEXTURE_2D);
glColor(colYellow); glColor(colYellow);
const GLshort vtx[] = { const GLshort vtx[] = {
x, scrheight - mouseRect.top - h - 9, x, scrheight - mouseRect.top - h - 9,
@ -132,18 +132,18 @@ void TTextField::Draw() const {
glVertexPointer(2, GL_SHORT, 0, vtx); glVertexPointer(2, GL_SHORT, 0, vtx);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4); glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_VERTEX_ARRAY);
glEnable (GL_TEXTURE_2D); glEnable(GL_TEXTURE_2D);
} }
} }
void TTextField::Key(unsigned int key, unsigned int mod, bool released) { void TTextField::Key(unsigned int key, unsigned int mod, bool released) {
if (islower (key)) { if (islower(key)) {
if (text.size() < maxLng) { if (text.size() < maxLng) {
if (mod & KMOD_SHIFT) text.insert(cursorPos, 1, toupper(key)); if (mod & KMOD_SHIFT) text.insert(cursorPos, 1, toupper(key));
else text.insert(cursorPos, 1, key); else text.insert(cursorPos, 1, key);
cursorPos++; cursorPos++;
} }
} else if (isdigit (key)) { } else if (isdigit(key)) {
if (text.size() < maxLng) { if (text.size() < maxLng) {
text.insert(cursorPos, 1, key); text.insert(cursorPos, 1, key);
cursorPos++; cursorPos++;
@ -151,10 +151,10 @@ void TTextField::Key(unsigned int key, unsigned int mod, bool released) {
} else { } else {
switch (key) { switch (key) {
case SDLK_DELETE: case SDLK_DELETE:
if (cursorPos < text.size()) text.erase (cursorPos, 1); if (cursorPos < text.size()) text.erase(cursorPos, 1);
break; break;
case SDLK_BACKSPACE: case SDLK_BACKSPACE:
if (cursorPos > 0) { text.erase (cursorPos-1, 1); cursorPos--; } if (cursorPos > 0) { text.erase(cursorPos-1, 1); cursorPos--; }
break; break;
case SDLK_RIGHT: case SDLK_RIGHT:
if (cursorPos < text.size()) cursorPos++; if (cursorPos < text.size()) cursorPos++;
@ -189,15 +189,15 @@ TTextField* AddTextField(const string& text, int x, int y, int width, int height
return static_cast<TTextField*>(Widgets.back()); return static_cast<TTextField*>(Widgets.back());
} }
void TCheckbox::Draw () const { void TCheckbox::Draw() const {
Tex.Draw (CHECKBOX, position.x + width - 32, position.y, 1.0); Tex.Draw(CHECKBOX, position.x + width - 32, position.y, 1.0);
if (checked) if (checked)
Tex.Draw (CHECKMARK_SMALL, position.x + width - 32, position.y, 1.0); Tex.Draw(CHECKMARK_SMALL, position.x + width - 32, position.y, 1.0);
if (focus) if (focus)
FT.SetColor (colDYell); FT.SetColor(colDYell);
else else
FT.SetColor (colWhite); FT.SetColor(colWhite);
FT.DrawString (position.x, position.y, tag); FT.DrawString(position.x, position.y, tag);
} }
bool TCheckbox::Click(int x, int y) { bool TCheckbox::Click(int x, int y) {
@ -216,18 +216,18 @@ void TCheckbox::Key(unsigned int key, unsigned int mod, bool released) {
} }
} }
TCheckbox* AddCheckbox (int x, int y, int width, const string& tag) { TCheckbox* AddCheckbox(int x, int y, int width, const string& tag) {
Widgets.push_back(new TCheckbox(x, y, width, tag)); Widgets.push_back(new TCheckbox(x, y, width, tag));
return static_cast<TCheckbox*>(Widgets.back()); return static_cast<TCheckbox*>(Widgets.back());
} }
void TIconButton::SetValue (int _value) { void TIconButton::SetValue(int _value) {
value = _value; value = _value;
if (value > maximum) if (value > maximum)
value = maximum; value = maximum;
} }
void TIconButton::Draw () const { void TIconButton::Draw() const {
TColor framecol = colWhite; TColor framecol = colWhite;
if (focus) framecol = colDYell; if (focus) framecol = colDYell;
@ -238,13 +238,13 @@ void TIconButton::Draw () const {
int x = position.x; int x = position.x;
int r = x + size; int r = x + size;
DrawFrameX (position.x-line, position.y-line, DrawFrameX(position.x-line, position.y-line,
framesize, framesize, line, colBlack, framecol, 1.0); framesize, framesize, line, colBlack, framecol, 1.0);
glEnable (GL_TEXTURE_2D); glEnable(GL_TEXTURE_2D);
glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
texture->Bind(); texture->Bind();
glColor4f (1.0, 1.0, 1.0, 1.0); glColor4f(1.0, 1.0, 1.0, 1.0);
const GLshort vtx[] = { const GLshort vtx[] = {
x, y, x, y,
@ -329,10 +329,10 @@ void TArrow::Draw() const {
if (down) if (down)
type += 3; type += 3;
glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable (GL_TEXTURE_2D); glEnable(GL_TEXTURE_2D);
Tex.BindTex (LB_ARROWS); Tex.BindTex(LB_ARROWS);
glColor4f (1.0, 1.0, 1.0, 1.0); glColor4f(1.0, 1.0, 1.0, 1.0);
const GLfloat tex[] = { const GLfloat tex[] = {
textl[type], texbl[type], textl[type], texbl[type],
@ -448,7 +448,7 @@ TUpDown* AddUpDown(int x, int y, int minimum, int maximum, int value, int distan
// ------------------ Elementary drawing --------------------------------------------- // ------------------ Elementary drawing ---------------------------------------------
void DrawFrameX (int x, int y, int w, int h, int line, const TColor& backcol, const TColor& framecol, double transp) { void DrawFrameX(int x, int y, int w, int h, int line, const TColor& backcol, const TColor& framecol, double transp) {
float yy = Winsys.resolution.height - y - h; float yy = Winsys.resolution.height - y - h;
if (x < 0) x = (Winsys.resolution.width -w) / 2; if (x < 0) x = (Winsys.resolution.width -w) / 2;
@ -478,11 +478,11 @@ void DrawFrameX (int x, int y, int w, int h, int line, const TColor& backcol, co
glDrawArrays(GL_TRIANGLE_FAN, 0, 4); glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_VERTEX_ARRAY);
glEnable (GL_TEXTURE_2D); glEnable(GL_TEXTURE_2D);
glPopMatrix(); glPopMatrix();
} }
void DrawBonusExt (int y, size_t numraces, size_t num) { void DrawBonusExt(int y, size_t numraces, size_t num) {
size_t maxtux = numraces * 3; size_t maxtux = numraces * 3;
if (num > maxtux) return; if (num > maxtux) return;
@ -502,18 +502,18 @@ void DrawBonusExt (int y, size_t numraces, size_t num) {
lleft[1] = xleft + framewidth + 4; lleft[1] = xleft + framewidth + 4;
lleft[2] = xleft + framewidth + framewidth + 8; lleft[2] = xleft + framewidth + framewidth + 8;
DrawFrameX (lleft[0], y, framewidth, 40, 1, col2, colBlack, 1); DrawFrameX(lleft[0], y, framewidth, 40, 1, col2, colBlack, 1);
DrawFrameX (lleft[1], y, framewidth, 40, 1, col2, colBlack, 1); DrawFrameX(lleft[1], y, framewidth, 40, 1, col2, colBlack, 1);
DrawFrameX (lleft[2], y, framewidth, 40, 1, col2, colBlack, 1); DrawFrameX(lleft[2], y, framewidth, 40, 1, col2, colBlack, 1);
if (param.use_papercut_font > 0) FT.SetSize (20); if (param.use_papercut_font > 0) FT.SetSize(20);
else FT.SetSize (15); else FT.SetSize(15);
bl.y = Winsys.resolution.height - y - 32 -4; bl.y = Winsys.resolution.height - y - 32 -4;
tr.y = Winsys.resolution.height - y - 0 -4; tr.y = Winsys.resolution.height - y - 0 -4;
glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable (GL_TEXTURE_2D); glEnable(GL_TEXTURE_2D);
Tex.BindTex (TUXBONUS); Tex.BindTex(TUXBONUS);
glColor4f (1.0, 1.0, 1.0, 1.0); glColor4f(1.0, 1.0, 1.0, 1.0);
glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY);
@ -552,9 +552,9 @@ void DrawBonusExt (int y, size_t numraces, size_t num) {
glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_VERTEX_ARRAY);
} }
void DrawCursor () { void DrawCursor() {
Tex.Draw (MOUSECURSOR, cursor_pos.x, cursor_pos.y, Tex.Draw(MOUSECURSOR, cursor_pos.x, cursor_pos.y,
CURSOR_SIZE * (double)Winsys.resolution.width / 14000); CURSOR_SIZE * (double)Winsys.resolution.width / 14000);
} }
@ -565,7 +565,7 @@ void DrawGUI() {
if (Widgets[i]->GetVisible()) if (Widgets[i]->GetVisible())
Widgets[i]->Draw(); Widgets[i]->Draw();
if (param.ice_cursor) if (param.ice_cursor)
DrawCursor (); DrawCursor();
} }
TWidget* ClickGUI(int x, int y) { TWidget* ClickGUI(int x, int y) {
@ -664,7 +664,7 @@ void DecreaseFocus() {
Widgets[focussed]->focus = true; Widgets[focussed]->focus = true;
} }
void ResetGUI () { void ResetGUI() {
for (size_t i = 0; i < Widgets.size(); i++) for (size_t i = 0; i < Widgets.size(); i++)
delete Widgets[i]; delete Widgets[i];
Widgets.clear(); Widgets.clear();
@ -673,16 +673,16 @@ void ResetGUI () {
// ------------------ new --------------------------------------------- // ------------------ new ---------------------------------------------
int AutoYPosN (double percent) { int AutoYPosN(double percent) {
double hh = (double)Winsys.resolution.height; double hh = (double)Winsys.resolution.height;
double po = hh * percent / 100; double po = hh * percent / 100;
return (int)(po); return (int)(po);
} }
TArea AutoAreaN (double top_perc, double bott_perc, int w) { TArea AutoAreaN(double top_perc, double bott_perc, int w) {
TArea res; TArea res;
res.top = AutoYPosN (top_perc); res.top = AutoYPosN(top_perc);
res.bottom = AutoYPosN (bott_perc); res.bottom = AutoYPosN(bott_perc);
if (w > Winsys.resolution.width) w = Winsys.resolution.width; if (w > Winsys.resolution.width) w = Winsys.resolution.width;
res.left = (Winsys.resolution.width - w) / 2; res.left = (Winsys.resolution.width - w) / 2;
res.right = Winsys.resolution.width - res.left; res.right = Winsys.resolution.width - res.left;

View File

@ -70,8 +70,8 @@ public:
TTextButton(int x, int y, const string& text_, double ftsize_); TTextButton(int x, int y, const string& text_, double ftsize_);
void Draw() const; void Draw() const;
}; };
TTextButton* AddTextButton (const string& text, int x, int y, double ftsize); TTextButton* AddTextButton(const string& text, int x, int y, double ftsize);
TTextButton* AddTextButtonN (const string& text, int x, int y, int rel_ftsize); TTextButton* AddTextButtonN(const string& text, int x, int y, int rel_ftsize);
class TTextField : public TWidget { class TTextField : public TWidget {
string text; string text;
@ -105,7 +105,7 @@ public:
bool Click(int x, int y); bool Click(int x, int y);
void Key(unsigned int key, unsigned int mod, bool released); void Key(unsigned int key, unsigned int mod, bool released);
}; };
TCheckbox* AddCheckbox (int x, int y, int width, const string& tag); TCheckbox* AddCheckbox(int x, int y, int width, const string& tag);
class TIconButton : public TWidget { class TIconButton : public TWidget {
double size; double size;
@ -126,7 +126,7 @@ public:
bool Click(int x, int y); bool Click(int x, int y);
void Key(unsigned int key, unsigned int mod, bool released); void Key(unsigned int key, unsigned int mod, bool released);
}; };
TIconButton* AddIconButton (int x, int y, TTexture* texture, double size, int maximum, int value); TIconButton* AddIconButton(int x, int y, TTexture* texture, double size, int maximum, int value);
class TArrow : public TWidget { class TArrow : public TWidget {
public: public:
@ -171,14 +171,14 @@ void ResetGUI();
// -------------------------------------------------------------------- // --------------------------------------------------------------------
void DrawFrameX (int x, int y, int w, int h, int line, void DrawFrameX(int x, int y, int w, int h, int line,
const TColor& backcol, const TColor& framecol, double transp); const TColor& backcol, const TColor& framecol, double transp);
void DrawBonusExt (int y, size_t numraces, size_t num); void DrawBonusExt(int y, size_t numraces, size_t num);
void DrawCursor (); void DrawCursor();
// -------------------------------------------------------------------- // --------------------------------------------------------------------
int AutoYPosN (double percent); int AutoYPosN(double percent);
TArea AutoAreaN (double top_perc, double bott_perc, int w); TArea AutoAreaN(double top_perc, double bott_perc, int w);
#endif #endif

View File

@ -34,58 +34,57 @@ CHelp Help;
static int ytop; static int ytop;
void CHelp::Keyb(unsigned int key, bool special, bool release, int x, int y) { void CHelp::Keyb(unsigned int key, bool special, bool release, int x, int y) {
State::manager.RequestEnterState (GameTypeSelect); State::manager.RequestEnterState(GameTypeSelect);
} }
void CHelp::Mouse(int button, int state, int x, int y) { void CHelp::Mouse(int button, int state, int x, int y) {
if (state == 1) State::manager.RequestEnterState (GameTypeSelect); if (state == 1) State::manager.RequestEnterState(GameTypeSelect);
} }
void CHelp::Motion(int x, int y) { void CHelp::Motion(int x, int y) {
if (param.ui_snow) push_ui_snow (cursor_pos); if (param.ui_snow) push_ui_snow(cursor_pos);
} }
void CHelp::Enter() { void CHelp::Enter() {
Winsys.ShowCursor (false); Winsys.ShowCursor(false);
Music.Play (param.credits_music, -1); Music.Play(param.credits_music, -1);
ytop = AutoYPosN (15); ytop = AutoYPosN(15);
} }
void CHelp::Loop(double timestep) { void CHelp::Loop(double timestep) {
Music.Update (); Music.Update();
check_gl_error(); ClearRenderContext();
ClearRenderContext ();
ScopedRenderMode rm(GUI); ScopedRenderMode rm(GUI);
SetupGuiDisplay (); SetupGuiDisplay();
if (param.ui_snow) { if (param.ui_snow) {
update_ui_snow (timestep); update_ui_snow(timestep);
draw_ui_snow(); draw_ui_snow();
} }
FT.AutoSizeN (4); FT.AutoSizeN(4);
FT.SetColor(colWhite); FT.SetColor(colWhite);
const int xleft1 = 40; const int xleft1 = 40;
FT.DrawString (xleft1, AutoYPosN (5), Trans.Text (57)); FT.DrawString(xleft1, AutoYPosN(5), Trans.Text(57));
FT.AutoSizeN (3); FT.AutoSizeN(3);
int offs = FT.AutoDistanceN (2); int offs = FT.AutoDistanceN(2);
FT.DrawString (xleft1, ytop, Trans.Text(44)); FT.DrawString(xleft1, ytop, Trans.Text(44));
FT.DrawString (xleft1, ytop + offs, Trans.Text(45)); FT.DrawString(xleft1, ytop + offs, Trans.Text(45));
FT.DrawString (xleft1, ytop + offs * 2, Trans.Text(46)); FT.DrawString(xleft1, ytop + offs * 2, Trans.Text(46));
FT.DrawString (xleft1, ytop + offs * 3, Trans.Text(47)); FT.DrawString(xleft1, ytop + offs * 3, Trans.Text(47));
FT.DrawString (xleft1, ytop + offs * 4, Trans.Text(48)); FT.DrawString(xleft1, ytop + offs * 4, Trans.Text(48));
FT.DrawString (xleft1, ytop + offs * 5, Trans.Text(49)); FT.DrawString(xleft1, ytop + offs * 5, Trans.Text(49));
FT.DrawString (xleft1, ytop + offs * 6, Trans.Text(50)); FT.DrawString(xleft1, ytop + offs * 6, Trans.Text(50));
FT.DrawString (xleft1, ytop + offs * 7, Trans.Text(51)); FT.DrawString(xleft1, ytop + offs * 7, Trans.Text(51));
FT.DrawString (xleft1, ytop + offs * 8,Trans.Text(52)); FT.DrawString(xleft1, ytop + offs * 8,Trans.Text(52));
FT.DrawString (xleft1, ytop + offs * 9, Trans.Text(53)); FT.DrawString(xleft1, ytop + offs * 9, Trans.Text(53));
FT.DrawString (xleft1, ytop + offs * 10, Trans.Text(54)); FT.DrawString(xleft1, ytop + offs * 10, Trans.Text(54));
FT.DrawString (xleft1, ytop + offs * 11, Trans.Text(55)); FT.DrawString(xleft1, ytop + offs * 11, Trans.Text(55));
FT.DrawString (xleft1, ytop + offs * 12, Trans.Text(56)); FT.DrawString(xleft1, ytop + offs * 12, Trans.Text(56));
FT.DrawString (CENTER, AutoYPosN (90), Trans.Text(65)); FT.DrawString(CENTER, AutoYPosN(90), Trans.Text(65));
Winsys.SwapBuffers(); Winsys.SwapBuffers();
} }

View File

@ -56,17 +56,17 @@ static const TColor text_colour(0, 0, 0, 1);
static void draw_time() { static void draw_time() {
int min, sec, hundr; int min, sec, hundr;
GetTimeComponents (g_game.time, &min, &sec, &hundr); GetTimeComponents(g_game.time, &min, &sec, &hundr);
string timestr = Int_StrN (min, 2); string timestr = Int_StrN(min, 2);
string secstr = Int_StrN (sec, 2); string secstr = Int_StrN(sec, 2);
string hundrstr = Int_StrN (hundr, 2); string hundrstr = Int_StrN(hundr, 2);
timestr += ":"; timestr += ":";
timestr += secstr; timestr += secstr;
if (param.use_papercut_font < 2) { if (param.use_papercut_font < 2) {
Tex.DrawNumStr (timestr, 20, 10, 1, colWhite); Tex.DrawNumStr(timestr, 50, 12, 1, colWhite);
Tex.DrawNumStr (hundrstr, 136, 10, 0.7, colWhite); Tex.DrawNumStr(hundrstr, 170, 12, 0.7, colWhite);
} else { } else {
/* /*
@ -76,45 +76,45 @@ static void draw_time() {
glHint (GL_LINE_SMOOTH_HINT, GL_DONT_CARE); glHint (GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
glLineWidth (1.5); glLineWidth (1.5);
*/ */
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
Tex.Draw (T_TIME, 16, 20, 1); Tex.Draw(T_TIME, 16, 20, 1);
FT.SetColor (colDYell); FT.SetColor(colDYell);
FT.SetSize (32); FT.SetSize(32);
FT.DrawString (160, 6, hundrstr); FT.DrawString(160, 6, hundrstr);
FT.SetSize (42); FT.SetSize(42);
FT.DrawString (70, 10, timestr); FT.DrawString(70, 10, timestr);
} }
} }
static void draw_herring_count (int herring_count) { static void draw_herring_count(int herring_count) {
string hcountstr = Int_StrN (herring_count, 3); string hcountstr = Int_StrN(herring_count, 3);
if (param.use_papercut_font < 2) { if (param.use_papercut_font < 2) {
Tex.DrawNumStr (hcountstr, Winsys.resolution.width - 90, 10, 1, colWhite); Tex.DrawNumStr(hcountstr, Winsys.resolution.width - 90, 10, 1, colWhite);
Tex.Draw (HERRING_ICON, Winsys.resolution.width-160, -20, 1); Tex.Draw(HERRING_ICON, Winsys.resolution.width-160, -20, 1);
} else { } else {
FT.SetColor (colDYell); FT.SetColor(colDYell);
FT.DrawString ( Winsys.resolution.width - 90, 10, hcountstr); FT.DrawString(Winsys.resolution.width - 90, 10, hcountstr);
Tex.Draw (T_YELLHERRING, Winsys.resolution.width-160, 12, 1); Tex.Draw(T_YELLHERRING, Winsys.resolution.width-160, 12, 1);
} }
} }
TVector2d calc_new_fan_pt (double angle) { TVector2d calc_new_fan_pt(double angle) {
TVector2d pt; TVector2d pt;
pt.x = ENERGY_GAUGE_CENTER_X + cos (ANGLES_TO_RADIANS (angle)) * SPEEDBAR_OUTER_RADIUS; pt.x = ENERGY_GAUGE_CENTER_X + cos(ANGLES_TO_RADIANS(angle)) * SPEEDBAR_OUTER_RADIUS;
pt.y = ENERGY_GAUGE_CENTER_Y + sin (ANGLES_TO_RADIANS (angle)) * SPEEDBAR_OUTER_RADIUS; pt.y = ENERGY_GAUGE_CENTER_Y + sin(ANGLES_TO_RADIANS(angle)) * SPEEDBAR_OUTER_RADIUS;
return pt; return pt;
} }
void start_tri_fan() { void start_tri_fan() {
glBegin (GL_TRIANGLE_FAN); glBegin(GL_TRIANGLE_FAN);
glVertex2f (ENERGY_GAUGE_CENTER_X, glVertex2f(ENERGY_GAUGE_CENTER_X,
ENERGY_GAUGE_CENTER_Y); ENERGY_GAUGE_CENTER_Y);
TVector2d pt = calc_new_fan_pt (SPEEDBAR_BASE_ANGLE); TVector2d pt = calc_new_fan_pt(SPEEDBAR_BASE_ANGLE);
glVertex2f (pt.x, pt.y); glVertex2f(pt.x, pt.y);
} }
void draw_partial_tri_fan (double fraction) { void draw_partial_tri_fan(double fraction) {
bool trifan = false; bool trifan = false;
double angle = SPEEDBAR_BASE_ANGLE + double angle = SPEEDBAR_BASE_ANGLE +
@ -130,8 +130,8 @@ void draw_partial_tri_fan (double fraction) {
trifan = true; trifan = true;
} }
cur_angle -= angle_incr; cur_angle -= angle_incr;
TVector2d pt = calc_new_fan_pt (cur_angle); TVector2d pt = calc_new_fan_pt(cur_angle);
glVertex2f (pt.x, pt.y); glVertex2f(pt.x, pt.y);
} }
if (cur_angle > angle + EPS) { if (cur_angle > angle + EPS) {
@ -140,8 +140,8 @@ void draw_partial_tri_fan (double fraction) {
start_tri_fan(); start_tri_fan();
trifan = true; trifan = true;
} }
TVector2d pt = calc_new_fan_pt (cur_angle); TVector2d pt = calc_new_fan_pt(cur_angle);
glVertex2f (pt.x, pt.y); glVertex2f(pt.x, pt.y);
} }
if (trifan) { if (trifan) {
@ -149,23 +149,23 @@ void draw_partial_tri_fan (double fraction) {
} }
} }
void draw_gauge (double speed, double energy) { void draw_gauge(double speed, double energy) {
static const GLfloat xplane[4] = {1.0 / GAUGE_IMG_SIZE, 0.0, 0.0, 0.0 }; static const GLfloat xplane[4] = {1.0 / GAUGE_IMG_SIZE, 0.0, 0.0, 0.0 };
static const GLfloat yplane[4] = {0.0, 1.0 / GAUGE_IMG_SIZE, 0.0, 0.0 }; static const GLfloat yplane[4] = {0.0, 1.0 / GAUGE_IMG_SIZE, 0.0, 0.0 };
ScopedRenderMode rm(GAUGE_BARS); ScopedRenderMode rm(GAUGE_BARS);
if (Tex.GetTexture (GAUGE_ENERGY) == NULL) return; if (Tex.GetTexture(GAUGE_ENERGY) == NULL) return;
if (Tex.GetTexture (GAUGE_SPEED) == NULL) return; if (Tex.GetTexture(GAUGE_SPEED) == NULL) return;
if (Tex.GetTexture (GAUGE_OUTLINE) == NULL) return; if (Tex.GetTexture(GAUGE_OUTLINE) == NULL) return;
Tex.BindTex (GAUGE_ENERGY); Tex.BindTex(GAUGE_ENERGY);
glTexGenfv (GL_S, GL_OBJECT_PLANE, xplane); glTexGenfv(GL_S, GL_OBJECT_PLANE, xplane);
glTexGenfv (GL_T, GL_OBJECT_PLANE, yplane); glTexGenfv(GL_T, GL_OBJECT_PLANE, yplane);
glPushMatrix(); glPushMatrix();
glTranslatef (Winsys.resolution.width - GAUGE_WIDTH, 0, 0); glTranslatef(Winsys.resolution.width - GAUGE_WIDTH, 0, 0);
Tex.BindTex (GAUGE_ENERGY); Tex.BindTex(GAUGE_ENERGY);
double y = ENERGY_GAUGE_BOTTOM + energy * ENERGY_GAUGE_HEIGHT; double y = ENERGY_GAUGE_BOTTOM + energy * ENERGY_GAUGE_HEIGHT;
const GLfloat vtx1 [] = { const GLfloat vtx1 [] = {
@ -213,13 +213,13 @@ void draw_gauge (double speed, double energy) {
speedbar_frac += speed/SPEEDBAR_GREEN_MAX_SPEED * SPEEDBAR_GREEN_FRACTION; speedbar_frac += speed/SPEEDBAR_GREEN_MAX_SPEED * SPEEDBAR_GREEN_FRACTION;
} }
glColor4fv (speedbar_background_color); glColor4fv(speedbar_background_color);
Tex.BindTex (GAUGE_SPEED); Tex.BindTex(GAUGE_SPEED);
draw_partial_tri_fan (1.0); draw_partial_tri_fan(1.0);
glColor4fv (hud_white); glColor4fv(hud_white);
draw_partial_tri_fan (min (1.0, speedbar_frac)); draw_partial_tri_fan(min(1.0, speedbar_frac));
glColor4fv (hud_white); glColor4fv(hud_white);
Tex.BindTex(GAUGE_OUTLINE); Tex.BindTex(GAUGE_OUTLINE);
static const GLshort vtx3 [] = { static const GLshort vtx3 [] = {
0, 0, 0, 0,
@ -236,22 +236,22 @@ void draw_gauge (double speed, double energy) {
glPopMatrix(); glPopMatrix();
} }
void DrawSpeed (double speed) { void DrawSpeed(double speed) {
string speedstr = Int_StrN ((int)speed, 3); string speedstr = Int_StrN((int)speed, 3);
if (param.use_papercut_font < 2) { if (param.use_papercut_font < 2) {
Tex.DrawNumStr (speedstr, Tex.DrawNumStr(speedstr,
Winsys.resolution.width - 85, Winsys.resolution.height-74, 1, colWhite); Winsys.resolution.width - 85, Winsys.resolution.height-74, 1, colWhite);
} else { } else {
FT.SetColor (colDDYell); FT.SetColor(colDDYell);
FT.DrawString (Winsys.resolution.width-82, Winsys.resolution.height-80, speedstr); FT.DrawString(Winsys.resolution.width-82, Winsys.resolution.height-80, speedstr);
} }
} }
void DrawWind(float dir, float speed, const CControl *ctrl) { void DrawWind(float dir, float speed, const CControl *ctrl) {
if (g_game.wind_id < 1) return; if (g_game.wind_id < 1) return;
Tex.Draw (SPEEDMETER, 0, Winsys.resolution.height-140, 1.0); Tex.Draw(SPEEDMETER, 0, Winsys.resolution.height-140, 1.0);
glDisable (GL_TEXTURE_2D); glDisable(GL_TEXTURE_2D);
float alpha, red, blue; float alpha, red, blue;
@ -264,9 +264,9 @@ void DrawWind(float dir, float speed, const CControl *ctrl) {
} }
blue = 1.0 - red; blue = 1.0 - red;
glPushMatrix (); glPushMatrix();
glColor4f (red, 0, blue, alpha); glColor4f(red, 0, blue, alpha);
glTranslatef (72, 66, 0); glTranslatef(72, 66, 0);
glRotatef(dir, 0, 0, 1); glRotatef(dir, 0, 0, 1);
glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_VERTEX_ARRAY);
static const int len = 45; static const int len = 45;
@ -282,8 +282,8 @@ void DrawWind(float dir, float speed, const CControl *ctrl) {
// direction indicator // direction indicator
float dir_angle = RADIANS_TO_ANGLES(atan2(ctrl->cvel.x, ctrl->cvel.z)); float dir_angle = RADIANS_TO_ANGLES(atan2(ctrl->cvel.x, ctrl->cvel.z));
glColor4f (0, 0.5, 0, 1.0); glColor4f(0, 0.5, 0, 1.0);
glRotatef (dir_angle - dir, 0, 0, 1); glRotatef(dir_angle - dir, 0, 0, 1);
static const GLshort vtx2 [] = { static const GLshort vtx2 [] = {
-2, 0, -2, 0,
2, 0, 2, 0,
@ -293,17 +293,17 @@ void DrawWind(float dir, float speed, const CControl *ctrl) {
glVertexPointer(2, GL_SHORT, 0, vtx2); glVertexPointer(2, GL_SHORT, 0, vtx2);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4); glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_VERTEX_ARRAY);
glPopMatrix (); glPopMatrix();
glEnable (GL_TEXTURE_2D); glEnable(GL_TEXTURE_2D);
Tex.Draw (SPEED_KNOB, 64, Winsys.resolution.height - 74, 1.0); Tex.Draw(SPEED_KNOB, 64, Winsys.resolution.height - 74, 1.0);
string windstr = Int_StrN ((int)speed, 3); string windstr = Int_StrN((int)speed, 3);
if (param.use_papercut_font < 2) { if (param.use_papercut_font < 2) {
Tex.DrawNumStr (windstr, 130, Winsys.resolution.height - 55, 1, colWhite); Tex.DrawNumStr(windstr, 130, Winsys.resolution.height - 55, 1, colWhite);
} else { } else {
FT.SetColor (colBlue); FT.SetColor(colBlue);
FT.DrawString (130, Winsys.resolution.height - 55, windstr); FT.DrawString(130, Winsys.resolution.height - 55, windstr);
} }
} }
@ -328,19 +328,19 @@ void DrawFps() {
string fpsstr = Int_StrN((int)averagefps); string fpsstr = Int_StrN((int)averagefps);
if (param.use_papercut_font < 2) { if (param.use_papercut_font < 2) {
Tex.DrawNumStr (fpsstr, (Winsys.resolution.width - 60) / 2, 10, 1, colWhite); Tex.DrawNumStr(fpsstr, (Winsys.resolution.width - 60) / 2, 10, 1, colWhite);
} else { } else {
if (averagefps >= 35) if (averagefps >= 35)
FT.SetColor (colWhite); FT.SetColor(colWhite);
else else
FT.SetColor (colRed); FT.SetColor(colRed);
FT.DrawString ((Winsys.resolution.width - 60) / 2, 10, fpsstr); FT.DrawString((Winsys.resolution.width - 60) / 2, 10, fpsstr);
} }
} }
void DrawPercentBar (float fact, float x, float y) { void DrawPercentBar(float fact, float x, float y) {
Tex.BindTex (T_ENERGY_MASK); Tex.BindTex(T_ENERGY_MASK);
glColor4f (1.0, 1.0, 1.0, 1.0); glColor4f(1.0, 1.0, 1.0, 1.0);
const GLfloat tex[] = { const GLfloat tex[] = {
0, 0, 0, 0,
@ -366,28 +366,28 @@ void DrawPercentBar (float fact, float x, float y) {
glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_VERTEX_ARRAY);
} }
void DrawCoursePosition (const CControl *ctrl) { void DrawCoursePosition(const CControl *ctrl) {
double fact = ctrl->cpos.z / Course.GetPlayDimensions().y; double fact = ctrl->cpos.z / Course.GetPlayDimensions().y;
if (fact > 1.0) fact = 1.0; if (fact > 1.0) fact = 1.0;
glEnable (GL_TEXTURE_2D); glEnable(GL_TEXTURE_2D);
DrawPercentBar (-fact, Winsys.resolution.width - 48, 280-128); DrawPercentBar(-fact, Winsys.resolution.width - 48, 280-128);
Tex.Draw (T_MASK_OUTLINE, Winsys.resolution.width - 48, Winsys.resolution.height - 280, 1.0); Tex.Draw(T_MASK_OUTLINE, Winsys.resolution.width - 48, Winsys.resolution.height - 280, 1.0);
} }
// ------------------------------------------------------- // -------------------------------------------------------
void DrawHud (const CControl *ctrl) { void DrawHud(const CControl *ctrl) {
if (!param.show_hud) if (!param.show_hud)
return; return;
double speed = ctrl->cvel.Length(); double speed = ctrl->cvel.Length();
SetupGuiDisplay (); SetupGuiDisplay();
draw_gauge (speed * 3.6, ctrl->jump_amt); draw_gauge(speed * 3.6, ctrl->jump_amt);
ScopedRenderMode rm(TEXFONT); ScopedRenderMode rm(TEXFONT);
draw_time(); draw_time();
draw_herring_count (g_game.herring); draw_herring_count(g_game.herring);
DrawSpeed (speed * 3.6); DrawSpeed(speed * 3.6);
DrawFps (); DrawFps();
DrawCoursePosition (ctrl); DrawCoursePosition(ctrl);
DrawWind (Wind.Angle (), Wind.Speed (), ctrl); DrawWind(Wind.Angle(), Wind.Speed(), ctrl);
} }

View File

@ -20,6 +20,6 @@ GNU General Public License for more details.
#include "bh.h" #include "bh.h"
void DrawHud (const CControl *ctrl); void DrawHud(const CControl *ctrl);
#endif #endif

View File

@ -38,9 +38,9 @@ GNU General Public License for more details.
CIntro Intro; CIntro Intro;
static CKeyframe *startframe; static CKeyframe *startframe;
void abort_intro (CControl *ctrl) { void abort_intro(CControl *ctrl) {
TVector2d start_pt = Course.GetStartPoint (); TVector2d start_pt = Course.GetStartPoint();
State::manager.RequestEnterState (Racing); State::manager.RequestEnterState(Racing);
ctrl->orientation_initialized = false; ctrl->orientation_initialized = false;
ctrl->view_init = false; ctrl->view_init = false;
ctrl->cpos.x = start_pt.x; ctrl->cpos.x = start_pt.x;
@ -50,7 +50,7 @@ void abort_intro (CControl *ctrl) {
// ================================================================= // =================================================================
void CIntro::Enter() { void CIntro::Enter() {
CControl *ctrl = g_game.player->ctrl; CControl *ctrl = g_game.player->ctrl;
TVector2d start_pt = Course.GetStartPoint (); TVector2d start_pt = Course.GetStartPoint();
ctrl->orientation_initialized = false; ctrl->orientation_initialized = false;
ctrl->view_init = false; ctrl->view_init = false;
ctrl->cpos.x = start_pt.x; ctrl->cpos.x = start_pt.x;
@ -68,14 +68,14 @@ void CIntro::Enter() {
g_game.race_result = -1; g_game.race_result = -1;
g_game.raceaborted = false; g_game.raceaborted = false;
ctrl->Init (); ctrl->Init();
ctrl->cvel = TVector3d(0, 0, 0); ctrl->cvel = TVector3d(0, 0, 0);
clear_particles(); clear_particles();
set_view_mode (ctrl, ABOVE); set_view_mode(ctrl, ABOVE);
SetCameraDistance (4.0); SetCameraDistance(4.0);
SetStationaryCamera (false); SetStationaryCamera(false);
update_view (ctrl, EPS); update_view(ctrl, EPS);
size_t num_items = Course.NocollArr.size(); size_t num_items = Course.NocollArr.size();
TItem* item_locs = &Course.NocollArr[0]; TItem* item_locs = &Course.NocollArr[0];
for (size_t i = 0; i < num_items; i++) { for (size_t i = 0; i < num_items; i++) {
@ -84,53 +84,52 @@ void CIntro::Enter() {
} }
} }
InitSnow (ctrl); InitSnow(ctrl);
InitWind (); InitWind();
Music.PlayTheme (g_game.theme_id, MUS_RACING); Music.PlayTheme(g_game.theme_id, MUS_RACING);
param.show_hud = true; param.show_hud = true;
} }
void CIntro::Loop (double time_step) { void CIntro::Loop(double time_step) {
CControl *ctrl = g_game.player->ctrl; CControl *ctrl = g_game.player->ctrl;
int width = Winsys.resolution.width; int width = Winsys.resolution.width;
int height = Winsys.resolution.height; int height = Winsys.resolution.height;
check_gl_error();
if (startframe->active) { if (startframe->active) {
startframe->Update (time_step); startframe->Update(time_step);
} else State::manager.RequestEnterState (Racing); } else State::manager.RequestEnterState(Racing);
ClearRenderContext (); ClearRenderContext();
Env.SetupFog (); Env.SetupFog();
update_view (ctrl, time_step); update_view(ctrl, time_step);
SetupViewFrustum (ctrl); SetupViewFrustum(ctrl);
Music.Update (); Music.Update();
Env.DrawSkybox (ctrl->viewpos); Env.DrawSkybox(ctrl->viewpos);
Env.DrawFog (); Env.DrawFog();
Env.SetupLight (); Env.SetupLight();
RenderCourse (); RenderCourse();
DrawTrackmarks (); DrawTrackmarks();
DrawTrees (); DrawTrees();
UpdateWind (time_step); UpdateWind(time_step);
UpdateSnow (time_step, ctrl); UpdateSnow(time_step, ctrl);
DrawSnow (ctrl); DrawSnow(ctrl);
g_game.character->shape->Draw(); g_game.character->shape->Draw();
DrawHud (ctrl); DrawHud(ctrl);
Reshape (width, height); Reshape(width, height);
Winsys.SwapBuffers (); Winsys.SwapBuffers();
} }
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
void CIntro::Keyb (unsigned int key, bool special, bool release, int x, int y) { void CIntro::Keyb(unsigned int key, bool special, bool release, int x, int y) {
CControl *ctrl = g_game.player->ctrl; CControl *ctrl = g_game.player->ctrl;
if (release) return; if (release) return;
abort_intro (ctrl); abort_intro(ctrl);
} }

View File

@ -52,7 +52,7 @@ static const string highlightnames[numJoints] = {
CKeyframe TestFrame; CKeyframe TestFrame;
CKeyframe::CKeyframe () { CKeyframe::CKeyframe() {
keytime = 0; keytime = 0;
active = false; active = false;
loaded = false; loaded = false;
@ -60,11 +60,11 @@ CKeyframe::CKeyframe () {
keyidx = 0; keyidx = 0;
} }
double CKeyframe::interp (double frac, double v1, double v2) { double CKeyframe::interp(double frac, double v1, double v2) {
return frac * v1 + (1.0 - frac) * v2; return frac * v1 + (1.0 - frac) * v2;
} }
void CKeyframe::Init (const TVector3d& ref_position, double height_correction) { void CKeyframe::Init(const TVector3d& ref_position, double height_correction) {
if (!loaded) return; if (!loaded) return;
g_game.character->shape->ResetNode("head"); g_game.character->shape->ResetNode("head");
g_game.character->shape->ResetNode("neck"); g_game.character->shape->ResetNode("neck");
@ -75,10 +75,10 @@ void CKeyframe::Init (const TVector3d& ref_position, double height_correction) {
keytime = 0; keytime = 0;
} }
void CKeyframe::Init (const TVector3d& ref_position, double height_correction, CCharShape *shape) { void CKeyframe::Init(const TVector3d& ref_position, double height_correction, CCharShape *shape) {
if (!loaded) return; if (!loaded) return;
shape->ResetNode ("head"); shape->ResetNode("head");
shape->ResetNode ("neck"); shape->ResetNode("neck");
refpos = ref_position; refpos = ref_position;
heightcorr = height_correction; heightcorr = height_correction;
active = true; active = true;
@ -87,10 +87,10 @@ void CKeyframe::Init (const TVector3d& ref_position, double height_correction, C
} }
void CKeyframe::InitTest (const TVector3d& ref_position, CCharShape *shape) { void CKeyframe::InitTest(const TVector3d& ref_position, CCharShape *shape) {
if (!loaded) return; if (!loaded) return;
shape->ResetNode ("head"); shape->ResetNode("head");
shape->ResetNode ("neck"); shape->ResetNode("neck");
refpos = ref_position; refpos = ref_position;
heightcorr = 0.0; heightcorr = 0.0;
active = true; active = true;
@ -98,7 +98,7 @@ void CKeyframe::InitTest (const TVector3d& ref_position, CCharShape *shape) {
keytime = 0; keytime = 0;
} }
void CKeyframe::Reset () { void CKeyframe::Reset() {
loaded = false; loaded = false;
active = false; active = false;
loadedfile = ""; loadedfile = "";
@ -106,24 +106,24 @@ void CKeyframe::Reset () {
frames.clear(); frames.clear();
} }
bool CKeyframe::Load (const string& dir, const string& filename) { bool CKeyframe::Load(const string& dir, const string& filename) {
if (loaded && loadedfile == filename) return true; if (loaded && loadedfile == filename) return true;
CSPList list (1000); CSPList list(1000);
if (list.Load (dir, filename)) { if (list.Load(dir, filename)) {
frames.resize(list.Count()); frames.resize(list.Count());
for (size_t i=0; i<list.Count(); i++) { for (size_t i=0; i<list.Count(); i++) {
const string& line = list.Line(i); const string& line = list.Line(i);
frames[i].val[0] = SPFloatN (line, "time", 0); frames[i].val[0] = SPFloatN(line, "time", 0);
TVector3d posit = SPVector3d(line, "pos"); TVector3d posit = SPVector3d(line, "pos");
frames[i].val[1] = posit.x; frames[i].val[1] = posit.x;
frames[i].val[2] = posit.y; frames[i].val[2] = posit.y;
frames[i].val[3] = posit.z; frames[i].val[3] = posit.z;
frames[i].val[4] = SPFloatN (line, "yaw", 0); frames[i].val[4] = SPFloatN(line, "yaw", 0);
frames[i].val[5] = SPFloatN (line, "pitch", 0); frames[i].val[5] = SPFloatN(line, "pitch", 0);
frames[i].val[6] = SPFloatN (line, "roll", 0); frames[i].val[6] = SPFloatN(line, "roll", 0);
frames[i].val[7] = SPFloatN (line, "neck", 0); frames[i].val[7] = SPFloatN(line, "neck", 0);
frames[i].val[8] = SPFloatN (line, "head", 0); frames[i].val[8] = SPFloatN(line, "head", 0);
TVector2d pp = SPVector2d(line, "sh"); TVector2d pp = SPVector2d(line, "sh");
frames[i].val[9] = pp.x; frames[i].val[9] = pp.x;
frames[i].val[10] = pp.y; frames[i].val[10] = pp.y;
@ -144,7 +144,7 @@ bool CKeyframe::Load (const string& dir, const string& filename) {
loadedfile = filename; loadedfile = filename;
return true; return true;
} else { } else {
Message ("keyframe not found:", filename); Message("keyframe not found:", filename);
loaded = false; loaded = false;
return false; return false;
} }
@ -153,55 +153,55 @@ bool CKeyframe::Load (const string& dir, const string& filename) {
// there are more possibilities for rotating the parts of the body, // there are more possibilities for rotating the parts of the body,
// that will be implemented later // that will be implemented later
void CKeyframe::InterpolateKeyframe (size_t idx, double frac, CCharShape *shape) { void CKeyframe::InterpolateKeyframe(size_t idx, double frac, CCharShape *shape) {
double vv; double vv;
vv = interp (frac, frames[idx].val[4], frames[idx+1].val[4]); vv = interp(frac, frames[idx].val[4], frames[idx+1].val[4]);
shape->RotateNode ("root", 2, vv); shape->RotateNode("root", 2, vv);
vv = interp (frac, frames[idx].val[5], frames[idx+1].val[5]); vv = interp(frac, frames[idx].val[5], frames[idx+1].val[5]);
shape->RotateNode ("root", 1, vv); shape->RotateNode("root", 1, vv);
vv = interp (frac, frames[idx].val[6], frames[idx+1].val[6]); vv = interp(frac, frames[idx].val[6], frames[idx+1].val[6]);
shape->RotateNode ("root", 3, vv); shape->RotateNode("root", 3, vv);
vv = interp (frac, frames[idx].val[7], frames[idx+1].val[7]); vv = interp(frac, frames[idx].val[7], frames[idx+1].val[7]);
shape->RotateNode ("neck", 3, vv); shape->RotateNode("neck", 3, vv);
vv = interp (frac, frames[idx].val[8], frames[idx+1].val[8]); vv = interp(frac, frames[idx].val[8], frames[idx+1].val[8]);
shape->RotateNode ("head", 2, vv); shape->RotateNode("head", 2, vv);
vv = interp (frac, frames[idx].val[9], frames[idx+1].val[9]); vv = interp(frac, frames[idx].val[9], frames[idx+1].val[9]);
shape->RotateNode ("left_shldr", 3, vv); shape->RotateNode("left_shldr", 3, vv);
vv = interp (frac, frames[idx].val[10], frames[idx+1].val[10]); vv = interp(frac, frames[idx].val[10], frames[idx+1].val[10]);
shape->RotateNode ("right_shldr", 3, vv); shape->RotateNode("right_shldr", 3, vv);
vv = interp (frac, frames[idx].val[11], frames[idx+1].val[11]); vv = interp(frac, frames[idx].val[11], frames[idx+1].val[11]);
shape->RotateNode ("left_shldr", 2, vv); shape->RotateNode("left_shldr", 2, vv);
vv = interp (frac, frames[idx].val[12], frames[idx+1].val[12]); vv = interp(frac, frames[idx].val[12], frames[idx+1].val[12]);
shape->RotateNode ("right_shldr", 2, vv); shape->RotateNode("right_shldr", 2, vv);
vv = interp (frac, frames[idx].val[13], frames[idx+1].val[13]); vv = interp(frac, frames[idx].val[13], frames[idx+1].val[13]);
shape->RotateNode ("left_hip", 3, vv); shape->RotateNode("left_hip", 3, vv);
vv = interp (frac, frames[idx].val[14], frames[idx+1].val[14]); vv = interp(frac, frames[idx].val[14], frames[idx+1].val[14]);
shape->RotateNode ("right_hip", 3, vv); shape->RotateNode("right_hip", 3, vv);
vv = interp (frac, frames[idx].val[15], frames[idx+1].val[15]); vv = interp(frac, frames[idx].val[15], frames[idx+1].val[15]);
shape->RotateNode ("left_knee", 3, vv); shape->RotateNode("left_knee", 3, vv);
vv = interp (frac, frames[idx].val[16], frames[idx+1].val[16]); vv = interp(frac, frames[idx].val[16], frames[idx+1].val[16]);
shape->RotateNode ("right_knee", 3, vv); shape->RotateNode("right_knee", 3, vv);
vv = interp (frac, frames[idx].val[17], frames[idx+1].val[17]); vv = interp(frac, frames[idx].val[17], frames[idx+1].val[17]);
shape->RotateNode ("left_ankle", 3, vv); shape->RotateNode("left_ankle", 3, vv);
vv = interp (frac, frames[idx].val[18], frames[idx+1].val[18]); vv = interp(frac, frames[idx].val[18], frames[idx+1].val[18]);
shape->RotateNode ("right_ankle", 3, vv); shape->RotateNode("right_ankle", 3, vv);
} }
void CKeyframe::CalcKeyframe (size_t idx, CCharShape *shape, const TVector3d& refpos) { void CKeyframe::CalcKeyframe(size_t idx, CCharShape *shape, const TVector3d& refpos) {
double vv; double vv;
TVector3d pos; TVector3d pos;
@ -209,57 +209,57 @@ void CKeyframe::CalcKeyframe (size_t idx, CCharShape *shape, const TVector3d& re
pos.z = frames[idx].val[3] + refpos.z; pos.z = frames[idx].val[3] + refpos.z;
pos.y = refpos.y; pos.y = refpos.y;
shape->ResetRoot (); shape->ResetRoot();
shape->ResetJoints (); shape->ResetJoints();
shape->TranslateNode (0, pos); shape->TranslateNode(0, pos);
vv = frames[idx].val[4]; vv = frames[idx].val[4];
shape->RotateNode ("root", 2, vv); shape->RotateNode("root", 2, vv);
vv = frames[idx].val[5]; vv = frames[idx].val[5];
shape->RotateNode ("root", 1, vv); shape->RotateNode("root", 1, vv);
vv = frames[idx].val[6]; vv = frames[idx].val[6];
shape->RotateNode ("root", 3, vv); shape->RotateNode("root", 3, vv);
vv = frames[idx].val[7]; vv = frames[idx].val[7];
shape->RotateNode ("neck", 3, vv); shape->RotateNode("neck", 3, vv);
vv = frames[idx].val[8]; vv = frames[idx].val[8];
shape->RotateNode ("head", 2, vv); shape->RotateNode("head", 2, vv);
vv = frames[idx].val[9]; vv = frames[idx].val[9];
shape->RotateNode ("left_shldr", 3, vv); shape->RotateNode("left_shldr", 3, vv);
vv = frames[idx].val[10]; vv = frames[idx].val[10];
shape->RotateNode ("right_shldr", 3, vv); shape->RotateNode("right_shldr", 3, vv);
vv = frames[idx].val[11]; vv = frames[idx].val[11];
shape->RotateNode ("left_shldr", 2, vv); shape->RotateNode("left_shldr", 2, vv);
vv = frames[idx].val[12]; vv = frames[idx].val[12];
shape->RotateNode ("right_shldr", 2, vv); shape->RotateNode("right_shldr", 2, vv);
vv = frames[idx].val[13]; vv = frames[idx].val[13];
shape->RotateNode ("left_hip", 3, vv); shape->RotateNode("left_hip", 3, vv);
vv = frames[idx].val[14]; vv = frames[idx].val[14];
shape->RotateNode ("right_hip", 3, vv); shape->RotateNode("right_hip", 3, vv);
vv = frames[idx].val[15]; vv = frames[idx].val[15];
shape->RotateNode ("left_knee", 3, vv); shape->RotateNode("left_knee", 3, vv);
vv = frames[idx].val[16]; vv = frames[idx].val[16];
shape->RotateNode ("right_knee", 3, vv); shape->RotateNode("right_knee", 3, vv);
vv = frames[idx].val[17]; vv = frames[idx].val[17];
shape->RotateNode ("left_ankle", 3, vv); shape->RotateNode("left_ankle", 3, vv);
vv = frames[idx].val[18]; vv = frames[idx].val[18];
shape->RotateNode ("right_ankle", 3, vv); shape->RotateNode("right_ankle", 3, vv);
} }
void CKeyframe::Update (double timestep) { void CKeyframe::Update(double timestep) {
if (!loaded) return; if (!loaded) return;
if (!active) return; if (!active) return;
@ -278,25 +278,25 @@ void CKeyframe::Update (double timestep) {
TVector3d pos; TVector3d pos;
CCharShape *shape = g_game.character->shape; CCharShape *shape = g_game.character->shape;
if (fabs (frames[keyidx].val[0]) < 0.0001) frac = 1.0; if (fabs(frames[keyidx].val[0]) < 0.0001) frac = 1.0;
else frac = (frames[keyidx].val[0] - keytime) / frames[keyidx].val[0]; else frac = (frames[keyidx].val[0] - keytime) / frames[keyidx].val[0];
pos.x = interp (frac, frames[keyidx].val[1], frames[keyidx+1].val[1]) + refpos.x; pos.x = interp(frac, frames[keyidx].val[1], frames[keyidx+1].val[1]) + refpos.x;
pos.z = interp (frac, frames[keyidx].val[3], frames[keyidx+1].val[3]) + refpos.z; pos.z = interp(frac, frames[keyidx].val[3], frames[keyidx+1].val[3]) + refpos.z;
pos.y = interp (frac, frames[keyidx].val[2], frames[keyidx+1].val[2]); pos.y = interp(frac, frames[keyidx].val[2], frames[keyidx+1].val[2]);
pos.y += Course.FindYCoord (pos.x, pos.z); pos.y += Course.FindYCoord(pos.x, pos.z);
shape->ResetRoot (); shape->ResetRoot();
shape->ResetJoints (); shape->ResetJoints();
g_game.player->ctrl->cpos = pos; g_game.player->ctrl->cpos = pos;
double disp_y = pos.y + TUX_Y_CORR + heightcorr; double disp_y = pos.y + TUX_Y_CORR + heightcorr;
shape->ResetNode (0); shape->ResetNode(0);
shape->TranslateNode (0, TVector3d(pos.x, disp_y, pos.z)); shape->TranslateNode(0, TVector3d(pos.x, disp_y, pos.z));
InterpolateKeyframe (keyidx, frac, shape); InterpolateKeyframe(keyidx, frac, shape);
} }
void CKeyframe::UpdateTest (double timestep, CCharShape *shape) { void CKeyframe::UpdateTest(double timestep, CCharShape *shape) {
if (!active) return; if (!active) return;
keytime += timestep; keytime += timestep;
@ -313,52 +313,52 @@ void CKeyframe::UpdateTest (double timestep, CCharShape *shape) {
double frac; double frac;
TVector3d pos; TVector3d pos;
if (fabs (frames[keyidx].val[0]) < 0.0001) frac = 1.0; if (fabs(frames[keyidx].val[0]) < 0.0001) frac = 1.0;
else frac = (frames[keyidx].val[0] - keytime) / frames[keyidx].val[0]; else frac = (frames[keyidx].val[0] - keytime) / frames[keyidx].val[0];
pos.x = interp (frac, frames[keyidx].val[1], frames[keyidx+1].val[1]) + refpos.x; pos.x = interp(frac, frames[keyidx].val[1], frames[keyidx+1].val[1]) + refpos.x;
pos.z = interp (frac, frames[keyidx].val[3], frames[keyidx+1].val[3]) + refpos.z; pos.z = interp(frac, frames[keyidx].val[3], frames[keyidx+1].val[3]) + refpos.z;
pos.y = interp (frac, frames[keyidx].val[2], frames[keyidx+1].val[2]); pos.y = interp(frac, frames[keyidx].val[2], frames[keyidx+1].val[2]);
shape->ResetRoot (); shape->ResetRoot();
shape->ResetJoints (); shape->ResetJoints();
shape->TranslateNode (0, pos); shape->TranslateNode(0, pos);
InterpolateKeyframe (keyidx, frac, shape); InterpolateKeyframe(keyidx, frac, shape);
} }
void CKeyframe::ResetFrame2 (TKeyframe *frame) { void CKeyframe::ResetFrame2(TKeyframe *frame) {
for (int i=1; i<32; i++) frame->val[i] = 0.0; for (int i=1; i<32; i++) frame->val[i] = 0.0;
frame->val[0] = 0.5; // time frame->val[0] = 0.5; // time
} }
TKeyframe *CKeyframe::GetFrame (size_t idx) { TKeyframe *CKeyframe::GetFrame(size_t idx) {
if (idx >= frames.size()) return NULL; if (idx >= frames.size()) return NULL;
return &frames[idx]; return &frames[idx];
} }
const string& CKeyframe::GetJointName (size_t idx) { const string& CKeyframe::GetJointName(size_t idx) {
if (idx >= numJoints) return emptyString; if (idx >= numJoints) return emptyString;
return jointnames[idx]; return jointnames[idx];
} }
const string& CKeyframe::GetHighlightName (size_t idx) { const string& CKeyframe::GetHighlightName(size_t idx) {
if (idx >= numJoints) return emptyString; if (idx >= numJoints) return emptyString;
return highlightnames[idx]; return highlightnames[idx];
} }
int CKeyframe::GetNumJoints () { int CKeyframe::GetNumJoints() {
return numJoints; return numJoints;
} }
void CKeyframe::SaveTest (const string& dir, const string& filename) { void CKeyframe::SaveTest(const string& dir, const string& filename) {
CSPList list (100); CSPList list(100);
for (size_t i=0; i<frames.size(); i++) { for (size_t i=0; i<frames.size(); i++) {
TKeyframe* frame = &frames[i]; TKeyframe* frame = &frames[i];
string line = "*[time] " + Float_StrN (frame->val[0], 1); string line = "*[time] " + Float_StrN(frame->val[0], 1);
line += " [pos] " + Float_StrN (frame->val[1], 2); line += " [pos] " + Float_StrN(frame->val[1], 2);
line += " " + Float_StrN (frame->val[2], 2); line += " " + Float_StrN(frame->val[2], 2);
line += " " + Float_StrN (frame->val[3], 2); line += " " + Float_StrN(frame->val[3], 2);
if (frame->val[4] != 0) line += " [yaw] " + Int_StrN((int)frame->val[4]); if (frame->val[4] != 0) line += " [yaw] " + Int_StrN((int)frame->val[4]);
if (frame->val[5] != 0) line += " [pitch] " + Int_StrN((int)frame->val[5]); if (frame->val[5] != 0) line += " [pitch] " + Int_StrN((int)frame->val[5]);
if (frame->val[6] != 0) line += " [roll] " + Int_StrN((int)frame->val[6]); if (frame->val[6] != 0) line += " [roll] " + Int_StrN((int)frame->val[6]);
@ -390,23 +390,23 @@ void CKeyframe::SaveTest (const string& dir, const string& filename) {
if (ll != 0 || rr != 0) if (ll != 0 || rr != 0)
line += " [ankle] " + Int_StrN((int)ll) + " " + Int_StrN((int)rr); line += " [ankle] " + Int_StrN((int)ll) + " " + Int_StrN((int)rr);
list.Add (line); list.Add(line);
} }
list.Save (dir, filename); list.Save(dir, filename);
} }
void CKeyframe::CopyFrame (size_t prim_idx, size_t sec_idx) { void CKeyframe::CopyFrame(size_t prim_idx, size_t sec_idx) {
TKeyframe *ppp = &frames[prim_idx]; TKeyframe *ppp = &frames[prim_idx];
TKeyframe *sss = &frames[sec_idx]; TKeyframe *sss = &frames[sec_idx];
memcpy(sss->val, ppp->val, MAX_FRAME_VALUES*sizeof(*sss->val)); memcpy(sss->val, ppp->val, MAX_FRAME_VALUES*sizeof(*sss->val));
} }
void CKeyframe::AddFrame () { void CKeyframe::AddFrame() {
frames.push_back(TKeyframe()); frames.push_back(TKeyframe());
ResetFrame2 (&frames.back()); ResetFrame2(&frames.back());
} }
size_t CKeyframe::DeleteFrame (size_t idx) { size_t CKeyframe::DeleteFrame(size_t idx) {
if (frames.size() < 2) return idx; if (frames.size() < 2) return idx;
size_t lastframe = frames.size()-1; size_t lastframe = frames.size()-1;
if (idx > lastframe) return 0; if (idx > lastframe) return 0;
@ -416,33 +416,33 @@ size_t CKeyframe::DeleteFrame (size_t idx) {
return frames.size()-1; return frames.size()-1;
} else { } else {
for (size_t i=idx; i<lastframe-1; i++) CopyFrame (i+1, i); for (size_t i=idx; i<lastframe-1; i++) CopyFrame(i+1, i);
frames.pop_back(); frames.pop_back();
return idx; return idx;
} }
} }
void CKeyframe::InsertFrame (size_t idx) { void CKeyframe::InsertFrame(size_t idx) {
size_t lastframe = frames.size()-1; size_t lastframe = frames.size()-1;
if (idx > lastframe) return; if (idx > lastframe) return;
frames.push_back(TKeyframe()); frames.push_back(TKeyframe());
for (size_t i=frames.size()-1; i>idx; i--) CopyFrame (i-1, i); for (size_t i=frames.size()-1; i>idx; i--) CopyFrame(i-1, i);
ResetFrame2 (&frames[idx]); ResetFrame2(&frames[idx]);
} }
void CKeyframe::CopyToClipboard (size_t idx) { void CKeyframe::CopyToClipboard(size_t idx) {
if (idx >= frames.size()) return; if (idx >= frames.size()) return;
memcpy(clipboard.val, frames[idx].val, MAX_FRAME_VALUES*sizeof(*frames[idx].val)); memcpy(clipboard.val, frames[idx].val, MAX_FRAME_VALUES*sizeof(*frames[idx].val));
} }
void CKeyframe::PasteFromClipboard (size_t idx) { void CKeyframe::PasteFromClipboard(size_t idx) {
if (idx >= frames.size()) return; if (idx >= frames.size()) return;
memcpy(frames[idx].val, clipboard.val, MAX_FRAME_VALUES*sizeof(*frames[idx].val)); memcpy(frames[idx].val, clipboard.val, MAX_FRAME_VALUES*sizeof(*frames[idx].val));
} }
void CKeyframe::ClearFrame (size_t idx) { void CKeyframe::ClearFrame(size_t idx) {
if (idx >= frames.size()) return; if (idx >= frames.size()) return;
ResetFrame2 (&frames[idx]); ResetFrame2(&frames[idx]);
} }

View File

@ -39,38 +39,38 @@ private:
double heightcorr; double heightcorr;
size_t keyidx; size_t keyidx;
double interp (double frac, double v1, double v2); double interp(double frac, double v1, double v2);
void InterpolateKeyframe (size_t idx, double frac, CCharShape *shape); void InterpolateKeyframe(size_t idx, double frac, CCharShape *shape);
// test and editing // test and editing
void ResetFrame2 (TKeyframe *frame); void ResetFrame2(TKeyframe *frame);
public: public:
CKeyframe (); CKeyframe();
bool loaded; bool loaded;
bool active; bool active;
void Init (const TVector3d& ref_position, double height_correction); void Init(const TVector3d& ref_position, double height_correction);
void Init (const TVector3d& ref_position, double height_correction, CCharShape *shape); void Init(const TVector3d& ref_position, double height_correction, CCharShape *shape);
void InitTest (const TVector3d& ref_position, CCharShape *shape); void InitTest(const TVector3d& ref_position, CCharShape *shape);
void Reset (); void Reset();
void Update (double timestep); void Update(double timestep);
void UpdateTest (double timestep, CCharShape *shape); void UpdateTest(double timestep, CCharShape *shape);
bool Load (const string& dir, const string& filename); bool Load(const string& dir, const string& filename);
void CalcKeyframe (size_t idx, CCharShape *shape, const TVector3d& refpos); void CalcKeyframe(size_t idx, CCharShape *shape, const TVector3d& refpos);
// test and editing // test and editing
TKeyframe *GetFrame (size_t idx); TKeyframe *GetFrame(size_t idx);
static const string& GetHighlightName (size_t idx); static const string& GetHighlightName(size_t idx);
static const string& GetJointName (size_t idx); static const string& GetJointName(size_t idx);
static int GetNumJoints (); static int GetNumJoints();
void SaveTest (const string& dir, const string& filename); void SaveTest(const string& dir, const string& filename);
void CopyFrame (size_t prim_idx, size_t sec_idx); void CopyFrame(size_t prim_idx, size_t sec_idx);
void AddFrame (); void AddFrame();
size_t DeleteFrame (size_t idx); size_t DeleteFrame(size_t idx);
void InsertFrame (size_t idx); void InsertFrame(size_t idx);
void CopyToClipboard (size_t idx); void CopyToClipboard(size_t idx);
void PasteFromClipboard (size_t idx); void PasteFromClipboard(size_t idx);
void ClearFrame (size_t idx); void ClearFrame(size_t idx);
size_t numFrames() const { return frames.size(); } size_t numFrames() const { return frames.size(); }
}; };

View File

@ -36,8 +36,8 @@ CLoading Loading;
// ==================================================================== // ====================================================================
void CLoading::Enter() { void CLoading::Enter() {
Winsys.ShowCursor (false); Winsys.ShowCursor(false);
Music.Play ("loading", -1); Music.Play("loading", -1);
} }
void CLoading::Loop(double time_step) { void CLoading::Loop(double time_step) {
@ -46,35 +46,34 @@ void CLoading::Loop(double time_step) {
int ww = Winsys.resolution.width; int ww = Winsys.resolution.width;
int hh = Winsys.resolution.height; int hh = Winsys.resolution.height;
string msg = Trans.Text(29) + " " + g_game.course->name; string msg = Trans.Text(29) + " " + g_game.course->name;
check_gl_error ();
ScopedRenderMode rm(GUI); ScopedRenderMode rm(GUI);
ClearRenderContext (); ClearRenderContext();
SetupGuiDisplay (); SetupGuiDisplay();
if (param.ui_snow) { if (param.ui_snow) {
update_ui_snow (time_step); update_ui_snow(time_step);
draw_ui_snow (); draw_ui_snow();
} }
Tex.Draw (TEXLOGO, CENTER, 40, 0.7); Tex.Draw(TEXLOGO, CENTER, 40, 0.6);
Tex.Draw (BOTTOM_LEFT, 0, hh-256, 1); Tex.Draw(BOTTOM_LEFT, 0, hh-256, 1);
Tex.Draw (BOTTOM_RIGHT, ww-256, hh-256, 1); Tex.Draw(BOTTOM_RIGHT, ww-256, hh-256, 1);
Tex.Draw (TOP_LEFT, 0, 0, 1); Tex.Draw(TOP_LEFT, 0, 0, 1);
Tex.Draw (TOP_RIGHT, ww-256, 0, 1); Tex.Draw(TOP_RIGHT, ww-256, 0, 1);
FT.SetColor (colDYell); FT.SetColor(colDYell);
FT.AutoSizeN (5); FT.AutoSizeN(5);
FT.DrawString (CENTER, AutoYPosN (60), msg); FT.DrawString(CENTER, AutoYPosN(60), msg);
FT.SetColor (colWhite); FT.SetColor(colWhite);
FT.DrawString (CENTER, AutoYPosN (70), Trans.Text (30)); FT.DrawString(CENTER, AutoYPosN(70), Trans.Text(30));
Winsys.SwapBuffers (); Winsys.SwapBuffers();
Course.LoadCourse (g_game.course); Course.LoadCourse(g_game.course);
g_game.location_id = Course.GetEnv (); g_game.location_id = Course.GetEnv();
Env.LoadEnvironment (g_game.location_id, g_game.light_id); Env.LoadEnvironment(g_game.location_id, g_game.light_id);
State::manager.RequestEnterState (Intro); State::manager.RequestEnterState(Intro);
} }
void CLoading::Exit() { void CLoading::Exit() {
Music.Halt (); Music.Halt();
} }

View File

@ -33,7 +33,7 @@ GNU General Public License for more details.
TGameData g_game; TGameData g_game;
void InitGame (int argc, char **argv) { void InitGame(int argc, char **argv) {
g_game.toolmode = NONE; g_game.toolmode = NONE;
g_game.argument = 0; g_game.argument = 0;
if (argc == 4) { if (argc == 4) {
@ -55,7 +55,7 @@ void InitGame (int argc, char **argv) {
g_game.snow_id = 0; g_game.snow_id = 0;
g_game.cup = 0; g_game.cup = 0;
g_game.theme_id = 0; g_game.theme_id = 0;
g_game.force_treemap = 0; g_game.force_treemap = false;
g_game.treesize = 3; g_game.treesize = 3;
g_game.treevar = 3; g_game.treevar = 3;
} }
@ -68,28 +68,28 @@ void InitGame (int argc, char **argv) {
#undef main #undef main
#endif #endif
int main( int argc, char **argv ) { int main(int argc, char **argv) {
// **************************************************************** // ****************************************************************
cout << "\n----------- Extreme Tux Racer " ETR_VERSION_STRING " ----------------"; cout << "\n----------- Extreme Tux Racer " ETR_VERSION_STRING " ----------------";
cout << "\n----------- (C) 2010-2013 Extreme Tuxracer Team --------\n\n"; cout << "\n----------- (C) 2010-2013 Extreme Tuxracer Team --------\n\n";
srand (time (NULL)); srand(time(NULL));
InitConfig (argv[0]); InitConfig();
InitGame (argc, argv); InitGame(argc, argv);
Winsys.Init (); Winsys.Init();
InitOpenglExtensions (); InitOpenglExtensions();
// for checking the joystick and the OpgenGL version (the info is // for checking the joystick and the OpgenGL version (the info is
// written on the console): // written on the console):
// Winsys.PrintJoystickInfo (); // Winsys.PrintJoystickInfo ();
// PrintGLInfo (); // PrintGLInfo ();
// theses resources must or should be loaded before splashscreen starts // theses resources must or should be loaded before splashscreen starts
Tex.LoadTextureList (); Tex.LoadTextureList();
FT.LoadFontlist (); FT.LoadFontlist();
Winsys.SetFonttype (); FT.SetFontFromSettings();
Audio.Open (); Audio.Open();
Music.LoadMusicList (); Music.LoadMusicList();
Music.SetVolume (param.music_volume); Music.SetVolume(param.music_volume);
switch (g_game.argument) { switch (g_game.argument) {
case 0: case 0:

View File

@ -25,8 +25,8 @@ GNU General Public License for more details.
#include <algorithm> #include <algorithm>
TVector3d ProjectToPlane (const TVector3d& nml, const TVector3d& v) { TVector3d ProjectToPlane(const TVector3d& nml, const TVector3d& v) {
double dotProd = DotProduct (nml, v); double dotProd = DotProduct(nml, v);
TVector3d nmlComp = dotProd * nml; TVector3d nmlComp = dotProd * nml;
return v - nmlComp; return v - nmlComp;
@ -60,7 +60,7 @@ TVector3d TransformPoint(const TMatrix<4, 4>& mat, const TVector3d& p) {
return r; return r;
} }
bool IntersectPlanes (const TPlane& s1, const TPlane& s2, const TPlane& s3, TVector3d *p) { bool IntersectPlanes(const TPlane& s1, const TPlane& s2, const TPlane& s3, TVector3d *p) {
double A[3][4]; double A[3][4];
double x[3]; double x[3];
double retval; double retval;
@ -80,7 +80,7 @@ bool IntersectPlanes (const TPlane& s1, const TPlane& s2, const TPlane& s3, TVec
A[2][2] = s3.nml.z; A[2][2] = s3.nml.z;
A[2][3] = -s3.d; A[2][3] = -s3.d;
retval = Gauss ((double*) A, 3, x); retval = Gauss((double*) A, 3, x);
if (retval != 0) { if (retval != 0) {
return false; return false;
@ -92,7 +92,7 @@ bool IntersectPlanes (const TPlane& s1, const TPlane& s2, const TPlane& s3, TVec
} }
} }
double DistanceToPlane (const TPlane& plane, const TVector3d& pt) { double DistanceToPlane(const TPlane& plane, const TVector3d& pt) {
return return
DotProduct(plane.nml, pt) + DotProduct(plane.nml, pt) +
plane.d; plane.d;
@ -107,7 +107,7 @@ TMatrix<4, 4> RotateAboutVectorMatrix(const TVector3d& u, double angle) {
double b = u.y; double b = u.y;
double c = u.z; double c = u.z;
double d = sqrt (b*b + c*c); double d = sqrt(b*b + c*c);
if (d < EPS) { if (d < EPS) {
if (a < 0) if (a < 0)
@ -151,7 +151,7 @@ TMatrix<4, 4> RotateAboutVectorMatrix(const TVector3d& u, double angle) {
return mat; return mat;
} }
TQuaternion MultiplyQuaternions (const TQuaternion& q, const TQuaternion& r) { TQuaternion MultiplyQuaternions(const TQuaternion& q, const TQuaternion& r) {
TQuaternion res; TQuaternion res;
res.x = q.y * r.z - q.z * r.y + r.w * q.x + q.w * r.x; res.x = q.y * r.z - q.z * r.y + r.w * q.x + q.w * r.x;
res.y = q.z * r.x - q.x * r.z + r.w * q.y + q.w * r.y; res.y = q.z * r.x - q.x * r.z + r.w * q.y + q.w * r.y;
@ -160,7 +160,7 @@ TQuaternion MultiplyQuaternions (const TQuaternion& q, const TQuaternion& r) {
return res; return res;
} }
TQuaternion ConjugateQuaternion (const TQuaternion& q) { TQuaternion ConjugateQuaternion(const TQuaternion& q) {
TQuaternion res( TQuaternion res(
-1 * q.x, -1 * q.x,
-1 * q.y, -1 * q.y,
@ -172,17 +172,17 @@ TQuaternion ConjugateQuaternion (const TQuaternion& q) {
TMatrix<4, 4> MakeMatrixFromQuaternion(const TQuaternion& q) { TMatrix<4, 4> MakeMatrixFromQuaternion(const TQuaternion& q) {
TMatrix<4, 4> mat; TMatrix<4, 4> mat;
mat[0][0] = 1.0 - 2.0 * (q.y * q.y + q.z * q.z); mat[0][0] = 1.0 - 2.0 * (q.y * q.y + q.z * q.z);
mat[1][0] = 2.0 * (q.x * q.y - q.w * q.z); mat[1][0] = 2.0 * (q.x * q.y - q.w * q.z);
mat[2][0] = 2.0 * (q.x * q.z + q.w * q.y); mat[2][0] = 2.0 * (q.x * q.z + q.w * q.y);
mat[0][1] = 2.0 * (q.x * q.y + q.w * q.z); mat[0][1] = 2.0 * (q.x * q.y + q.w * q.z);
mat[1][1] = 1.0 - 2.0 * (q.x * q.x + q.z * q.z); mat[1][1] = 1.0 - 2.0 * (q.x * q.x + q.z * q.z);
mat[2][1] = 2.0 * (q.y * q.z - q.w * q.x); mat[2][1] = 2.0 * (q.y * q.z - q.w * q.x);
mat[0][2] = 2.0 * (q.x * q.z - q.w * q.y); mat[0][2] = 2.0 * (q.x * q.z - q.w * q.y);
mat[1][2] = 2.0 * (q.y * q.z + q.w * q.x); mat[1][2] = 2.0 * (q.y * q.z + q.w * q.x);
mat[2][2] = 1.0 - 2.0 * (q.x * q.x + q.y * q.y); mat[2][2] = 1.0 - 2.0 * (q.x * q.x + q.y * q.y);
mat[3][0] = mat[3][1] = mat[3][2] = 0.0; mat[3][0] = mat[3][1] = mat[3][2] = 0.0;
mat[0][3] = mat[1][3] = mat[2][3] = 0.0; mat[0][3] = mat[1][3] = mat[2][3] = 0.0;
@ -199,7 +199,7 @@ TQuaternion MakeQuaternionFromMatrix(const TMatrix<4, 4>& m) {
tr = m[0][0] + m[1][1] + m[2][2]; tr = m[0][0] + m[1][1] + m[2][2];
if (tr > 0.0) { if (tr > 0.0) {
s = sqrt (tr + 1.0); s = sqrt(tr + 1.0);
res.w = 0.5 * s; res.w = 0.5 * s;
s = 0.5 / s; s = 0.5 / s;
res.x = (m[1][2] - m[2][1]) * s; res.x = (m[1][2] - m[2][1]) * s;
@ -212,7 +212,7 @@ TQuaternion MakeQuaternionFromMatrix(const TMatrix<4, 4>& m) {
int j = nxt[i]; int j = nxt[i];
int k = nxt[j]; int k = nxt[j];
s = sqrt (m[i][i] - m[j][j] - m[k][k] + 1.0); s = sqrt(m[i][i] - m[j][j] - m[k][k] + 1.0);
q[i] = s * 0.5; q[i] = s * 0.5;
@ -231,17 +231,17 @@ TQuaternion MakeQuaternionFromMatrix(const TMatrix<4, 4>& m) {
return res; return res;
} }
TQuaternion MakeRotationQuaternion (const TVector3d& s, const TVector3d& t) { TQuaternion MakeRotationQuaternion(const TVector3d& s, const TVector3d& t) {
TVector3d u = CrossProduct (s, t); TVector3d u = CrossProduct(s, t);
double sin2phi = u.Norm(); double sin2phi = u.Norm();
if (sin2phi < EPS) { if (sin2phi < EPS) {
return TQuaternion (0., 0., 0., 1.); return TQuaternion(0., 0., 0., 1.);
} else { } else {
double cos2phi = DotProduct (s, t); double cos2phi = DotProduct(s, t);
double sinphi = sqrt ( (1 - cos2phi) / 2.0); double sinphi = sqrt((1 - cos2phi) / 2.0);
double cosphi = sqrt ( (1 + cos2phi) / 2.0); double cosphi = sqrt((1 + cos2phi) / 2.0);
return TQuaternion( return TQuaternion(
sinphi * u.x, sinphi * u.x,
@ -251,7 +251,7 @@ TQuaternion MakeRotationQuaternion (const TVector3d& s, const TVector3d& t) {
} }
} }
TQuaternion InterpolateQuaternions (const TQuaternion& q, TQuaternion r, double t) { TQuaternion InterpolateQuaternions(const TQuaternion& q, TQuaternion r, double t) {
double cosphi = q.x * r.x + q.y * r.y + q.z * r.z + q.w * r.w; double cosphi = q.x * r.x + q.y * r.y + q.z * r.z + q.w * r.w;
if (cosphi < 0.0) { if (cosphi < 0.0) {
@ -264,10 +264,10 @@ TQuaternion InterpolateQuaternions (const TQuaternion& q, TQuaternion r, double
double scale0, scale1; double scale0, scale1;
if (1.0 - cosphi > EPS) { if (1.0 - cosphi > EPS) {
double phi = acos (cosphi); double phi = acos(cosphi);
double sinphi = sin (phi); double sinphi = sin(phi);
scale0 = sin (phi * (1.0 - t)) / sinphi; scale0 = sin(phi * (1.0 - t)) / sinphi;
scale1 = sin (phi * t) / sinphi; scale1 = sin(phi * t) / sinphi;
} else { } else {
scale0 = 1.0 - t; scale0 = 1.0 - t;
scale1 = t; scale1 = t;
@ -276,12 +276,12 @@ TQuaternion InterpolateQuaternions (const TQuaternion& q, TQuaternion r, double
return scale0 * q + scale1 * r; return scale0 * q + scale1 * r;
} }
TVector3d RotateVector (const TQuaternion& q, const TVector3d& v) { TVector3d RotateVector(const TQuaternion& q, const TVector3d& v) {
TQuaternion p(v.x, v.y, v.z, 1.0); TQuaternion p(v.x, v.y, v.z, 1.0);
TQuaternion qs(-q.x, -q.y, -q.z, q.w); TQuaternion qs(-q.x, -q.y, -q.z, q.w);
TQuaternion res_q = MultiplyQuaternions (q, MultiplyQuaternions (p, qs)); TQuaternion res_q = MultiplyQuaternions(q, MultiplyQuaternions(p, qs));
return res_q; return res_q;
} }
@ -290,9 +290,9 @@ TVector3d RotateVector (const TQuaternion& q, const TVector3d& v) {
// Gauss // Gauss
// -------------------------------------------------------------------- // --------------------------------------------------------------------
bool order (double *matrix, int n, int pivot); bool order(double *matrix, int n, int pivot);
void elim (double *matrix, int n, int pivot); void elim(double *matrix, int n, int pivot);
void backsb (double *matrix, int n, double *soln); void backsb(double *matrix, int n, double *soln);
int Gauss(double *matrix, int n, double *soln) { int Gauss(double *matrix, int n, double *soln) {
int pivot = 0; int pivot = 0;
@ -312,7 +312,7 @@ int Gauss(double *matrix, int n, double *soln) {
return 0; return 0;
} }
bool order (double *matrix, int n, int pivot) { bool order(double *matrix, int n, int pivot) {
bool error = false; bool error = false;
int rmax = pivot; int rmax = pivot;
@ -334,7 +334,7 @@ bool order (double *matrix, int n, int pivot) {
return error; return error;
} }
void elim (double *matrix, int n, int pivot) { void elim(double *matrix, int n, int pivot) {
for (int row = pivot+1; row < n; row++) { for (int row = pivot+1; row < n; row++) {
double factor = (*(matrix+row*(n+1)+pivot))/(*(matrix+pivot*(n+1)+pivot)); double factor = (*(matrix+row*(n+1)+pivot))/(*(matrix+pivot*(n+1)+pivot));
*(matrix+row*(n+1)+pivot)=0.0; *(matrix+row*(n+1)+pivot)=0.0;
@ -346,7 +346,7 @@ void elim (double *matrix, int n, int pivot) {
} }
void backsb (double *matrix, int n, double *soln) { void backsb(double *matrix, int n, double *soln) {
for (int row = n-1; row >=0; row--) { for (int row = n-1; row >=0; row--) {
for (int col = n-1; col >= row+1; col--) { for (int col = n-1; col >= row+1; col--) {
*(matrix+row*(n+1)+(n)) = *(matrix+row*(n+1)+n) - *(matrix+row*(n+1)+(n)) = *(matrix+row*(n+1)+n) -
@ -364,17 +364,17 @@ bool IntersectPolygon(const TPolygon& p, vector<TVector3d>& v) {
double d, s, nuDotProd; double d, s, nuDotProd;
double distsq; double distsq;
TVector3d nml = MakeNormal (p, &v[0]); TVector3d nml = MakeNormal(p, &v[0]);
ray.pt = TVector3d(0., 0., 0.); ray.pt = TVector3d(0., 0., 0.);
ray.vec = nml; ray.vec = nml;
nuDotProd = DotProduct (nml, ray.vec); nuDotProd = DotProduct(nml, ray.vec);
if (fabs(nuDotProd) < EPS) if (fabs(nuDotProd) < EPS)
return false; return false;
d = - DotProduct(nml, v[p.vertices[0]]); d = - DotProduct(nml, v[p.vertices[0]]);
if (fabs (d) > 1) return false; if (fabs(d) > 1) return false;
for (size_t i=0; i < p.vertices.size(); i++) { for (size_t i=0; i < p.vertices.size(); i++) {
TVector3d *v0, *v1; TVector3d *v0, *v1;
@ -385,28 +385,28 @@ bool IntersectPolygon(const TPolygon& p, vector<TVector3d>& v) {
TVector3d edge_vec = *v1 - *v0; TVector3d edge_vec = *v1 - *v0;
double edge_len = edge_vec.Norm(); double edge_len = edge_vec.Norm();
double t = - DotProduct (*v0, edge_vec); double t = - DotProduct(*v0, edge_vec);
if (t < 0) { if (t < 0) {
distsq = MAG_SQD (*v0); distsq = MAG_SQD(*v0);
} else if (t > edge_len) { } else if (t > edge_len) {
distsq = MAG_SQD (*v1); distsq = MAG_SQD(*v1);
} else { } else {
*v0 += t * edge_vec; *v0 += t * edge_vec;
distsq = MAG_SQD (*v0); distsq = MAG_SQD(*v0);
} }
if (distsq <= 1) return true; if (distsq <= 1) return true;
} }
s = - (d + DotProduct (nml, ray.pt)) / nuDotProd; s = - (d + DotProduct(nml, ray.pt)) / nuDotProd;
TVector3d pt = ray.pt + s * ray.vec; TVector3d pt = ray.pt + s * ray.vec;
for (size_t i = 0; i < p.vertices.size(); i++) { for (size_t i = 0; i < p.vertices.size(); i++) {
TVector3d edge_nml = CrossProduct (nml, TVector3d edge_nml = CrossProduct(nml,
v[p.vertices[(i + 1) % p.vertices.size()]] - v[p.vertices[i]]); v[p.vertices[(i + 1) % p.vertices.size()]] - v[p.vertices[i]]);
double wec = DotProduct (pt - v[p.vertices[i]], edge_nml); double wec = DotProduct(pt - v[p.vertices[i]], edge_nml);
if (wec < 0) return false; if (wec < 0) return false;
} }
return true; return true;
@ -415,25 +415,25 @@ bool IntersectPolygon(const TPolygon& p, vector<TVector3d>& v) {
bool IntersectPolyhedron(TPolyhedron& p) { bool IntersectPolyhedron(TPolyhedron& p) {
bool hit = false; bool hit = false;
for (size_t i = 0; i < p.polygons.size(); i++) { for (size_t i = 0; i < p.polygons.size(); i++) {
hit = IntersectPolygon (p.polygons[i], p.vertices); hit = IntersectPolygon(p.polygons[i], p.vertices);
if (hit == true) break; if (hit == true) break;
} }
return hit; return hit;
} }
TVector3d MakeNormal (const TPolygon& p, const TVector3d *v) { TVector3d MakeNormal(const TPolygon& p, const TVector3d *v) {
TVector3d v1 = v[p.vertices[1]] - v[p.vertices[0]]; TVector3d v1 = v[p.vertices[1]] - v[p.vertices[0]];
TVector3d v2 = v[p.vertices[p.vertices.size() - 1]] - v[p.vertices[0]]; TVector3d v2 = v[p.vertices[p.vertices.size() - 1]] - v[p.vertices[0]];
TVector3d normal = CrossProduct (v1, v2); TVector3d normal = CrossProduct(v1, v2);
normal.Norm(); normal.Norm();
return normal; return normal;
} }
void TransPolyhedron (const TMatrix<4, 4>& mat, TPolyhedron& ph) { void TransPolyhedron(const TMatrix<4, 4>& mat, TPolyhedron& ph) {
for (size_t i = 0; i < ph.vertices.size(); i++) for (size_t i = 0; i < ph.vertices.size(); i++)
ph.vertices[i] = TransformPoint (mat, ph.vertices[i]); ph.vertices[i] = TransformPoint(mat, ph.vertices[i]);
} }
// -------------------------------------------------------------------- // --------------------------------------------------------------------
@ -453,7 +453,7 @@ const double ode23_time_step_exp = 1./3.;
int ode23_NumEstimates() {return 4; } int ode23_NumEstimates() {return 4; }
void ode23_InitOdeData (TOdeData *data, double init_val, double h) { void ode23_InitOdeData(TOdeData *data, double init_val, double h) {
data->init_val = init_val; data->init_val = init_val;
data->h = h; data->h = h;
} }
@ -462,7 +462,7 @@ double ode23_NextTime(TOdeData *data, int step) {
return ode23_time_step_mat[step] * data->h; return ode23_time_step_mat[step] * data->h;
} }
double ode23_NextValue (TOdeData *data, int step) { double ode23_NextValue(TOdeData *data, int step) {
double val = data->init_val; double val = data->init_val;
for (int i=0; i<step; i++) for (int i=0; i<step; i++)
@ -505,7 +505,7 @@ TOdeSolver::TOdeSolver() {
TimestepExponent = ode23_TimestepExponent; TimestepExponent = ode23_TimestepExponent;
} }
double LinearInterp (const double x[], const double y[], double val, int n) { double LinearInterp(const double x[], const double y[], double val, int n) {
int i; int i;
double m, b; double m, b;
@ -519,22 +519,22 @@ double LinearInterp (const double x[], const double y[], double val, int n) {
return m * val + b; return m * val + b;
} }
double XRandom (float min, float max) { double XRandom(float min, float max) {
return (double)rand () / RAND_MAX * (max - min) + min; return (double)rand() / RAND_MAX * (max - min) + min;
} }
double FRandom () { double FRandom() {
return (double)rand () / RAND_MAX; return (double)rand() / RAND_MAX;
} }
int IRandom (int min, int max) { int IRandom(int min, int max) {
return min + rand()%(max-min+1); return min + rand()%(max-min+1);
} }
int ITrunc (int val, int base) { int ITrunc(int val, int base) {
return (int)(val / base); return (int)(val / base);
} }
int IFrac (int val, int base) { int IFrac(int val, int base) {
return val - ITrunc (val, base) * base; return val - ITrunc(val, base) * base;
} }

View File

@ -50,22 +50,22 @@ TVector3d ProjectToPlane(const TVector3d& nml, const TVector3d& v);
TVector3d TransformVector(const TMatrix<4, 4>& mat, const TVector3d& v); TVector3d TransformVector(const TMatrix<4, 4>& mat, const TVector3d& v);
TVector3d TransformNormal(const TVector3d& n, const TMatrix<4, 4>& mat); // not used ? TVector3d TransformNormal(const TVector3d& n, const TMatrix<4, 4>& mat); // not used ?
TVector3d TransformPoint(const TMatrix<4, 4>& mat, const TVector3d& p); TVector3d TransformPoint(const TMatrix<4, 4>& mat, const TVector3d& p);
bool IntersectPlanes (const TPlane& s1, const TPlane& s2, const TPlane& s3, TVector3d *p); bool IntersectPlanes(const TPlane& s1, const TPlane& s2, const TPlane& s3, TVector3d *p);
double DistanceToPlane (const TPlane& plane, const TVector3d& pt); double DistanceToPlane(const TPlane& plane, const TVector3d& pt);
TMatrix<4, 4> RotateAboutVectorMatrix(const TVector3d& u, double angle); TMatrix<4, 4> RotateAboutVectorMatrix(const TVector3d& u, double angle);
TQuaternion MultiplyQuaternions (const TQuaternion& q, const TQuaternion& r); TQuaternion MultiplyQuaternions(const TQuaternion& q, const TQuaternion& r);
TQuaternion ConjugateQuaternion (const TQuaternion& q); TQuaternion ConjugateQuaternion(const TQuaternion& q);
TMatrix<4, 4> MakeMatrixFromQuaternion(const TQuaternion& q); TMatrix<4, 4> MakeMatrixFromQuaternion(const TQuaternion& q);
TQuaternion MakeQuaternionFromMatrix(const TMatrix<4, 4>& mat); TQuaternion MakeQuaternionFromMatrix(const TMatrix<4, 4>& mat);
TQuaternion MakeRotationQuaternion (const TVector3d& s, const TVector3d& t); TQuaternion MakeRotationQuaternion(const TVector3d& s, const TVector3d& t);
TQuaternion InterpolateQuaternions (const TQuaternion& q, TQuaternion r, double t); TQuaternion InterpolateQuaternions(const TQuaternion& q, TQuaternion r, double t);
TVector3d RotateVector (const TQuaternion& q, const TVector3d& v); TVector3d RotateVector(const TQuaternion& q, const TVector3d& v);
bool IntersectPolygon (const TPolygon& p, vector<TVector3d>& v); bool IntersectPolygon(const TPolygon& p, vector<TVector3d>& v);
bool IntersectPolyhedron (TPolyhedron& p); bool IntersectPolyhedron(TPolyhedron& p);
TVector3d MakeNormal (const TPolygon& p, const TVector3d *v); TVector3d MakeNormal(const TPolygon& p, const TVector3d *v);
void TransPolyhedron(const TMatrix<4, 4>& mat, TPolyhedron& ph); void TransPolyhedron(const TMatrix<4, 4>& mat, TPolyhedron& ph);
// -------------------------------------------------------------------- // --------------------------------------------------------------------
@ -78,14 +78,14 @@ struct TOdeData {
double h; double h;
}; };
typedef int (*PNumEstimates) (); typedef int (*PNumEstimates)();
typedef void (*PInitOdeData) (TOdeData *, double init_val, double h); typedef void (*PInitOdeData)(TOdeData *, double init_val, double h);
typedef double (*PNextTime) (TOdeData *, int step); typedef double(*PNextTime)(TOdeData *, int step);
typedef double (*PNextValue) (TOdeData *, int step); typedef double(*PNextValue)(TOdeData *, int step);
typedef void (*PUpdateEstimate) (TOdeData *, int step, double val); typedef void (*PUpdateEstimate)(TOdeData *, int step, double val);
typedef double (*PFinalEstimate) (TOdeData *); typedef double(*PFinalEstimate)(TOdeData *);
typedef double (*PEstimateError) (TOdeData *); typedef double(*PEstimateError)(TOdeData *);
typedef double (*PTimestepExponent) (); typedef double(*PTimestepExponent)();
struct TOdeSolver { struct TOdeSolver {
PNumEstimates NumEstimates; PNumEstimates NumEstimates;
@ -103,13 +103,13 @@ struct TOdeSolver {
// special // special
// -------------------------------------------------------------------- // --------------------------------------------------------------------
int Gauss (double *matrix, int n, double *soln); int Gauss(double *matrix, int n, double *soln);
double LinearInterp (const double x[], const double y[], double val, int n); double LinearInterp(const double x[], const double y[], double val, int n);
double XRandom (float min, float max); double XRandom(float min, float max);
double FRandom (); double FRandom();
int IRandom (int min, int max); int IRandom(int min, int max);
int ITrunc (int val, int base); int ITrunc(int val, int base);
int IFrac (int val, int base); int IFrac(int val, int base);
#endif #endif

View File

@ -39,69 +39,69 @@ static TUpDown* avatar;
static TWidget* textbuttons[2]; static TWidget* textbuttons[2];
static TTextField* textfield; static TTextField* textfield;
void QuitAndAddPlayer () { void QuitAndAddPlayer() {
if (textfield->Text().size () > 0) if (textfield->Text().size() > 0)
Players.AddPlayer (textfield->Text(), Players.GetDirectAvatarName(avatar->GetValue())); Players.AddPlayer(textfield->Text(), Players.GetDirectAvatarName(avatar->GetValue()));
State::manager.RequestEnterState (Regist); State::manager.RequestEnterState(Regist);
} }
void CNewPlayer::Keyb_spec (SDL_keysym sym, bool release) { void CNewPlayer::Keyb_spec(SDL_keysym sym, bool release) {
if (release) return; if (release) return;
KeyGUI(sym.sym, sym.mod, release); KeyGUI(sym.sym, sym.mod, release);
switch (sym.sym) { switch (sym.sym) {
case SDLK_ESCAPE: case SDLK_ESCAPE:
State::manager.RequestEnterState (Regist); State::manager.RequestEnterState(Regist);
break; break;
case SDLK_RETURN: case SDLK_RETURN:
if (textbuttons[0]->focussed()) State::manager.RequestEnterState (Regist); if (textbuttons[0]->focussed()) State::manager.RequestEnterState(Regist);
else QuitAndAddPlayer (); else QuitAndAddPlayer();
break; break;
default: default:
break; break;
} }
} }
void CNewPlayer::Mouse (int button, int state, int x, int y) { void CNewPlayer::Mouse(int button, int state, int x, int y) {
if (state == 1) { if (state == 1) {
TWidget* clicked = ClickGUI(x, y); TWidget* clicked = ClickGUI(x, y);
if (clicked == textbuttons[0]) if (clicked == textbuttons[0])
State::manager.RequestEnterState (Regist); State::manager.RequestEnterState(Regist);
else if (clicked == textbuttons[1]) else if (clicked == textbuttons[1])
QuitAndAddPlayer(); QuitAndAddPlayer();
} }
} }
void CNewPlayer::Motion (int x, int y) { void CNewPlayer::Motion(int x, int y) {
MouseMoveGUI(x, y); MouseMoveGUI(x, y);
if (param.ui_snow) push_ui_snow (cursor_pos); if (param.ui_snow) push_ui_snow(cursor_pos);
} }
static int prevleft, prevtop, prevwidth; static int prevleft, prevtop, prevwidth;
void CNewPlayer::Enter() { void CNewPlayer::Enter() {
Winsys.KeyRepeat (true); Winsys.KeyRepeat(true);
Winsys.ShowCursor (!param.ice_cursor); Winsys.ShowCursor(!param.ice_cursor);
Music.Play (param.menu_music, -1); Music.Play(param.menu_music, -1);
int framewidth = 400 * Winsys.scale; int framewidth = 400 * Winsys.scale;
int frameheight = 50 * Winsys.scale; int frameheight = 50 * Winsys.scale;
int frametop = AutoYPosN (38); int frametop = AutoYPosN(38);
TArea area = AutoAreaN(30, 80, framewidth); TArea area = AutoAreaN(30, 80, framewidth);
int prevoffs = 80; int prevoffs = 80;
prevleft = area.left + prevoffs; prevleft = area.left + prevoffs;
prevtop = AutoYPosN (52); prevtop = AutoYPosN(52);
prevwidth = 75 * Winsys.scale; prevwidth = 75 * Winsys.scale;
ResetGUI(); ResetGUI();
avatar = AddUpDown (area.left + prevwidth + prevoffs + 8, prevtop, 0, (int)Players.numAvatars() - 1, 0, prevwidth - 34); avatar = AddUpDown(area.left + prevwidth + prevoffs + 8, prevtop, 0, (int)Players.numAvatars() - 1, 0, prevwidth - 34);
int siz = FT.AutoSizeN (5); int siz = FT.AutoSizeN(5);
textbuttons[0] = AddTextButton (Trans.Text(8), area.left+50, AutoYPosN (70), siz); textbuttons[0] = AddTextButton(Trans.Text(8), area.left+50, AutoYPosN(70), siz);
double len = FT.GetTextWidth (Trans.Text(15)); double len = FT.GetTextWidth(Trans.Text(15));
textbuttons[1] = AddTextButton (Trans.Text(15), area.right-len-50, AutoYPosN (70), siz); textbuttons[1] = AddTextButton(Trans.Text(15), area.right-len-50, AutoYPosN(70), siz);
textfield = AddTextField(emptyString, area.left, frametop, framewidth, frameheight); textfield = AddTextField(emptyString, area.left, frametop, framewidth, frameheight);
} }
@ -111,14 +111,13 @@ void CNewPlayer::Loop(double timestep) {
int hh = Winsys.resolution.height; int hh = Winsys.resolution.height;
TColor col; TColor col;
Music.Update (); Music.Update();
check_gl_error(); ClearRenderContext();
ClearRenderContext ();
ScopedRenderMode rm(GUI); ScopedRenderMode rm(GUI);
SetupGuiDisplay (); SetupGuiDisplay();
if (param.ui_snow) { if (param.ui_snow) {
update_ui_snow (timestep); update_ui_snow(timestep);
draw_ui_snow(); draw_ui_snow();
} }
@ -127,15 +126,15 @@ void CNewPlayer::Loop(double timestep) {
// DrawFrameX (area.left, area.top, area.right-area.left, area.bottom - area.top, // DrawFrameX (area.left, area.top, area.right-area.left, area.bottom - area.top,
// 0, colMBackgr, col, 0.2); // 0, colMBackgr, col, 0.2);
Tex.Draw (BOTTOM_LEFT, 0, hh - 256, 1); Tex.Draw(BOTTOM_LEFT, 0, hh - 256, 1);
Tex.Draw (BOTTOM_RIGHT, ww-256, hh-256, 1); Tex.Draw(BOTTOM_RIGHT, ww-256, hh-256, 1);
Tex.Draw (TOP_LEFT, 0, 0, 1); Tex.Draw(TOP_LEFT, 0, 0, 1);
Tex.Draw (TOP_RIGHT, ww-256, 0, 1); Tex.Draw(TOP_RIGHT, ww-256, 0, 1);
Tex.Draw (T_TITLE_SMALL, CENTER, AutoYPosN (5), Winsys.scale); Tex.Draw(T_TITLE_SMALL, CENTER, AutoYPosN(5), Winsys.scale);
FT.SetColor (colWhite); FT.SetColor(colWhite);
FT.AutoSizeN (4); FT.AutoSizeN(4);
FT.DrawString (CENTER, AutoYPosN (30), Trans.Text(66)); FT.DrawString(CENTER, AutoYPosN(30), Trans.Text(66));
if (avatar->focussed()) col = colDYell; if (avatar->focussed()) col = colDYell;
else col = colWhite; else col = colWhite;

View File

@ -47,7 +47,7 @@ void check_gl_error() {
GLenum error = glGetError(); GLenum error = glGetError();
if (error != GL_NO_ERROR) { if (error != GL_NO_ERROR) {
const char* errstr = (const char*)gluErrorString(error); const char* errstr = (const char*)gluErrorString(error);
Message ("OpenGL Error: ", errstr ? errstr : ""); Message("OpenGL Error: ", errstr ? errstr : "");
} }
} }
@ -55,7 +55,7 @@ PFNGLLOCKARRAYSEXTPROC glLockArraysEXT_p = NULL;
PFNGLUNLOCKARRAYSEXTPROC glUnlockArraysEXT_p = NULL; PFNGLUNLOCKARRAYSEXTPROC glUnlockArraysEXT_p = NULL;
typedef void (*(*get_gl_proc_fptr_t)(const GLubyte *))(); typedef void (*(*get_gl_proc_fptr_t)(const GLubyte *))();
void InitOpenglExtensions () { void InitOpenglExtensions() {
get_gl_proc_fptr_t get_gl_proc; get_gl_proc_fptr_t get_gl_proc;
get_gl_proc = (get_gl_proc_fptr_t) SDL_GL_GetProcAddress; get_gl_proc = (get_gl_proc_fptr_t) SDL_GL_GetProcAddress;
@ -69,24 +69,24 @@ void InitOpenglExtensions () {
if (glLockArraysEXT_p != NULL && glUnlockArraysEXT_p != NULL) { if (glLockArraysEXT_p != NULL && glUnlockArraysEXT_p != NULL) {
} else { } else {
Message ("GL_EXT_compiled_vertex_array extension NOT supported"); Message("GL_EXT_compiled_vertex_array extension NOT supported");
glLockArraysEXT_p = NULL; glLockArraysEXT_p = NULL;
glUnlockArraysEXT_p = NULL; glUnlockArraysEXT_p = NULL;
} }
} else { } else {
Message ("No function available for obtaining GL proc addresses"); Message("No function available for obtaining GL proc addresses");
} }
} }
void PrintGLInfo () { void PrintGLInfo() {
Message ("Gl vendor: ", (char*)glGetString (GL_VENDOR)); Message("Gl vendor: ", (char*)glGetString(GL_VENDOR));
Message ("Gl renderer: ", (char*)glGetString (GL_RENDERER)); Message("Gl renderer: ", (char*)glGetString(GL_RENDERER));
Message ("Gl version: ", (char*)glGetString (GL_VERSION)); Message("Gl version: ", (char*)glGetString(GL_VERSION));
string extensions = (char*)glGetString (GL_EXTENSIONS); string extensions = (char*)glGetString(GL_EXTENSIONS);
Message (""); Message("");
Message ("Gl extensions:"); Message("Gl extensions:");
Message (""); Message("");
size_t oldpos = 0; size_t oldpos = 0;
size_t pos; size_t pos;
@ -97,44 +97,44 @@ void PrintGLInfo () {
} }
Message(extensions.substr(oldpos)); Message(extensions.substr(oldpos));
Message (""); Message("");
for (int i=0; i<(int)(sizeof(gl_values)/sizeof(gl_values[0])); i++) { for (int i=0; i<(int)(sizeof(gl_values)/sizeof(gl_values[0])); i++) {
switch (gl_values[i].type) { switch (gl_values[i].type) {
case GL_INT: { case GL_INT: {
GLint int_val; GLint int_val;
glGetIntegerv (gl_values[i].value, &int_val); glGetIntegerv(gl_values[i].value, &int_val);
string ss = Int_StrN (int_val); string ss = Int_StrN(int_val);
Message (gl_values[i].name, ss); Message(gl_values[i].name, ss);
break; break;
} }
case GL_FLOAT: { case GL_FLOAT: {
GLfloat float_val; GLfloat float_val;
glGetFloatv (gl_values[i].value, &float_val); glGetFloatv(gl_values[i].value, &float_val);
string ss = Float_StrN (float_val, 2); string ss = Float_StrN(float_val, 2);
Message (gl_values[i].name, ss); Message(gl_values[i].name, ss);
break; break;
} }
case GL_UNSIGNED_BYTE: { case GL_UNSIGNED_BYTE: {
GLboolean boolean_val; GLboolean boolean_val;
glGetBooleanv (gl_values[i].value, &boolean_val); glGetBooleanv(gl_values[i].value, &boolean_val);
string ss = Int_StrN (boolean_val); string ss = Int_StrN(boolean_val);
Message (gl_values[i].name, ss); Message(gl_values[i].name, ss);
break; break;
} }
default: default:
Message (""); Message("");
} }
} }
} }
void set_material (const TColor& diffuse_colour, const TColor& specular_colour, float specular_exp) { void set_material(const TColor& diffuse_colour, const TColor& specular_colour, float specular_exp) {
GLfloat mat_amb_diff[4] = { GLfloat mat_amb_diff[4] = {
static_cast<GLfloat>(diffuse_colour.r), static_cast<GLfloat>(diffuse_colour.r),
static_cast<GLfloat>(diffuse_colour.g), static_cast<GLfloat>(diffuse_colour.g),
static_cast<GLfloat>(diffuse_colour.b), static_cast<GLfloat>(diffuse_colour.b),
static_cast<GLfloat>(diffuse_colour.a) static_cast<GLfloat>(diffuse_colour.a)
}; };
glMaterialfv (GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, mat_amb_diff); glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, mat_amb_diff);
GLfloat mat_specular[4] = { GLfloat mat_specular[4] = {
static_cast<GLfloat>(specular_colour.r), static_cast<GLfloat>(specular_colour.r),
@ -142,261 +142,261 @@ void set_material (const TColor& diffuse_colour, const TColor& specular_colour,
static_cast<GLfloat>(specular_colour.b), static_cast<GLfloat>(specular_colour.b),
static_cast<GLfloat>(specular_colour.a) static_cast<GLfloat>(specular_colour.a)
}; };
glMaterialfv (GL_FRONT_AND_BACK, GL_SPECULAR, mat_specular); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, mat_specular);
glMaterialf (GL_FRONT_AND_BACK, GL_SHININESS, specular_exp); glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, specular_exp);
glColor(diffuse_colour); glColor(diffuse_colour);
} }
void ClearRenderContext () { void ClearRenderContext() {
glDepthMask (GL_TRUE); glDepthMask(GL_TRUE);
glClearColor (colBackgr.r, colBackgr.g, colBackgr.b, colBackgr.a); glClearColor(colBackgr.r, colBackgr.g, colBackgr.b, colBackgr.a);
glClearStencil (0); glClearStencil(0);
glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
} }
void ClearRenderContext (const TColor& col) { void ClearRenderContext(const TColor& col) {
glDepthMask (GL_TRUE); glDepthMask(GL_TRUE);
glClearColor (col.r, col.g, col.b, col.a); glClearColor(col.r, col.g, col.b, col.a);
glClearStencil (0); glClearStencil(0);
glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
} }
void SetupGuiDisplay () { void SetupGuiDisplay() {
static const float offset = 0.f; static const float offset = 0.f;
glMatrixMode (GL_PROJECTION); glMatrixMode(GL_PROJECTION);
glLoadIdentity (); glLoadIdentity();
glOrtho (0, Winsys.resolution.width, 0, Winsys.resolution.height, -1.0, 1.0); glOrtho(0, Winsys.resolution.width, 0, Winsys.resolution.height, -1.0, 1.0);
glMatrixMode (GL_MODELVIEW); glMatrixMode(GL_MODELVIEW);
glLoadIdentity (); glLoadIdentity();
glTranslatef (offset, offset, -1.0); glTranslatef(offset, offset, -1.0);
glColor4f (1.0, 1.0, 1.0, 1.0); glColor4f(1.0, 1.0, 1.0, 1.0);
} }
void Reshape (int w, int h) { void Reshape(int w, int h) {
glViewport (0, 0, (GLint) w, (GLint) h ); glViewport(0, 0, (GLint) w, (GLint) h);
glMatrixMode (GL_PROJECTION); glMatrixMode(GL_PROJECTION);
glLoadIdentity (); glLoadIdentity();
double far_clip_dist = param.forward_clip_distance + FAR_CLIP_FUDGE_AMOUNT; double far_clip_dist = param.forward_clip_distance + FAR_CLIP_FUDGE_AMOUNT;
gluPerspective (param.fov, (double)w/h, NEAR_CLIP_DIST, far_clip_dist ); gluPerspective(param.fov, (double)w/h, NEAR_CLIP_DIST, far_clip_dist);
glMatrixMode (GL_MODELVIEW); glMatrixMode(GL_MODELVIEW);
} }
// ==================================================================== // ====================================================================
// GL options // GL options
// ==================================================================== // ====================================================================
TRenderMode currentMode = RM_UNINITIALIZED; TRenderMode currentMode = RM_UNINITIALIZED;
void set_gl_options (TRenderMode mode) { void set_gl_options(TRenderMode mode) {
currentMode = mode; currentMode = mode;
switch (mode) { switch (mode) {
case GUI: case GUI:
glEnable (GL_TEXTURE_2D); glEnable(GL_TEXTURE_2D);
glDisable (GL_DEPTH_TEST); glDisable(GL_DEPTH_TEST);
glDisable (GL_CULL_FACE); glDisable(GL_CULL_FACE);
glDisable (GL_LIGHTING); glDisable(GL_LIGHTING);
glDisable (GL_NORMALIZE); glDisable(GL_NORMALIZE);
glDisable (GL_ALPHA_TEST); glDisable(GL_ALPHA_TEST);
glEnable (GL_BLEND); glEnable(GL_BLEND);
glDisable (GL_STENCIL_TEST); glDisable(GL_STENCIL_TEST);
glDisable (GL_TEXTURE_GEN_S); glDisable(GL_TEXTURE_GEN_S);
glDisable (GL_TEXTURE_GEN_T); glDisable(GL_TEXTURE_GEN_T);
glDisable (GL_COLOR_MATERIAL); glDisable(GL_COLOR_MATERIAL);
glDepthMask (GL_TRUE); glDepthMask(GL_TRUE);
glShadeModel (GL_SMOOTH); glShadeModel(GL_SMOOTH);
glDepthFunc (GL_LESS); glDepthFunc(GL_LESS);
glDisable (GL_FOG); glDisable(GL_FOG);
break; break;
case GAUGE_BARS: case GAUGE_BARS:
glEnable (GL_TEXTURE_2D); glEnable(GL_TEXTURE_2D);
glDisable (GL_DEPTH_TEST); glDisable(GL_DEPTH_TEST);
glDisable (GL_CULL_FACE); glDisable(GL_CULL_FACE);
glDisable (GL_LIGHTING); glDisable(GL_LIGHTING);
glDisable (GL_NORMALIZE); glDisable(GL_NORMALIZE);
glDisable (GL_ALPHA_TEST); glDisable(GL_ALPHA_TEST);
glEnable (GL_BLEND); glEnable(GL_BLEND);
glDisable (GL_STENCIL_TEST); glDisable(GL_STENCIL_TEST);
glEnable (GL_TEXTURE_GEN_S); glEnable(GL_TEXTURE_GEN_S);
glEnable (GL_TEXTURE_GEN_T); glEnable(GL_TEXTURE_GEN_T);
glDisable (GL_COLOR_MATERIAL); glDisable(GL_COLOR_MATERIAL);
glDepthMask (GL_TRUE); glDepthMask(GL_TRUE);
glShadeModel (GL_SMOOTH); glShadeModel(GL_SMOOTH);
glDepthFunc (GL_LESS); glDepthFunc(GL_LESS);
glTexGeni (GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
glTexGeni (GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
break; break;
case TEXFONT: case TEXFONT:
glEnable (GL_TEXTURE_2D); glEnable(GL_TEXTURE_2D);
glDisable (GL_DEPTH_TEST); glDisable(GL_DEPTH_TEST);
glDisable (GL_CULL_FACE); glDisable(GL_CULL_FACE);
glDisable (GL_LIGHTING); glDisable(GL_LIGHTING);
glDisable (GL_NORMALIZE); glDisable(GL_NORMALIZE);
glDisable (GL_ALPHA_TEST); glDisable(GL_ALPHA_TEST);
glEnable (GL_BLEND); glEnable(GL_BLEND);
glDisable (GL_STENCIL_TEST); glDisable(GL_STENCIL_TEST);
glDisable (GL_TEXTURE_GEN_S); glDisable(GL_TEXTURE_GEN_S);
glDisable (GL_TEXTURE_GEN_T); glDisable(GL_TEXTURE_GEN_T);
glDisable (GL_COLOR_MATERIAL); glDisable(GL_COLOR_MATERIAL);
glDepthMask (GL_TRUE); glDepthMask(GL_TRUE);
glShadeModel (GL_SMOOTH); glShadeModel(GL_SMOOTH);
glDepthFunc (GL_LESS); glDepthFunc(GL_LESS);
break; break;
case COURSE: case COURSE:
glEnable (GL_TEXTURE_2D); glEnable(GL_TEXTURE_2D);
glEnable (GL_DEPTH_TEST); glEnable(GL_DEPTH_TEST);
glEnable (GL_CULL_FACE); glEnable(GL_CULL_FACE);
glEnable (GL_LIGHTING); glEnable(GL_LIGHTING);
glDisable (GL_NORMALIZE); glDisable(GL_NORMALIZE);
glDisable (GL_ALPHA_TEST); glDisable(GL_ALPHA_TEST);
glEnable (GL_BLEND); glEnable(GL_BLEND);
glDisable (GL_STENCIL_TEST); glDisable(GL_STENCIL_TEST);
glEnable (GL_TEXTURE_GEN_S); glEnable(GL_TEXTURE_GEN_S);
glEnable (GL_TEXTURE_GEN_T); glEnable(GL_TEXTURE_GEN_T);
glEnable (GL_COLOR_MATERIAL); glEnable(GL_COLOR_MATERIAL);
glDepthMask (GL_TRUE); glDepthMask(GL_TRUE);
glShadeModel (GL_SMOOTH); glShadeModel(GL_SMOOTH);
glDepthFunc (GL_LEQUAL); glDepthFunc(GL_LEQUAL);
glTexGeni (GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
glTexGeni (GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
break; break;
case TREES: case TREES:
glEnable (GL_TEXTURE_2D); glEnable(GL_TEXTURE_2D);
glEnable (GL_DEPTH_TEST); glEnable(GL_DEPTH_TEST);
glDisable (GL_CULL_FACE); glDisable(GL_CULL_FACE);
glEnable (GL_LIGHTING); glEnable(GL_LIGHTING);
glDisable (GL_NORMALIZE); glDisable(GL_NORMALIZE);
glEnable (GL_ALPHA_TEST); glEnable(GL_ALPHA_TEST);
glEnable (GL_BLEND); glEnable(GL_BLEND);
glDisable (GL_STENCIL_TEST); glDisable(GL_STENCIL_TEST);
glDisable (GL_TEXTURE_GEN_S); glDisable(GL_TEXTURE_GEN_S);
glDisable (GL_TEXTURE_GEN_T); glDisable(GL_TEXTURE_GEN_T);
glDisable (GL_COLOR_MATERIAL); glDisable(GL_COLOR_MATERIAL);
glDepthMask (GL_TRUE); glDepthMask(GL_TRUE);
glShadeModel (GL_SMOOTH); glShadeModel(GL_SMOOTH);
glDepthFunc (GL_LESS); glDepthFunc(GL_LESS);
glAlphaFunc (GL_GEQUAL, 0.5); glAlphaFunc(GL_GEQUAL, 0.5);
break; break;
case PARTICLES: case PARTICLES:
glEnable (GL_TEXTURE_2D); glEnable(GL_TEXTURE_2D);
glEnable (GL_DEPTH_TEST); glEnable(GL_DEPTH_TEST);
glDisable (GL_CULL_FACE); glDisable(GL_CULL_FACE);
glDisable (GL_LIGHTING); glDisable(GL_LIGHTING);
glDisable (GL_NORMALIZE); glDisable(GL_NORMALIZE);
glEnable (GL_ALPHA_TEST); glEnable(GL_ALPHA_TEST);
glEnable (GL_BLEND); glEnable(GL_BLEND);
glDisable (GL_STENCIL_TEST); glDisable(GL_STENCIL_TEST);
glDisable (GL_TEXTURE_GEN_S); glDisable(GL_TEXTURE_GEN_S);
glDisable (GL_TEXTURE_GEN_T); glDisable(GL_TEXTURE_GEN_T);
glDisable (GL_COLOR_MATERIAL); glDisable(GL_COLOR_MATERIAL);
glDepthMask (GL_TRUE); glDepthMask(GL_TRUE);
glShadeModel (GL_SMOOTH); glShadeModel(GL_SMOOTH);
glDepthFunc (GL_LESS); glDepthFunc(GL_LESS);
glAlphaFunc (GL_GEQUAL, 0.5); glAlphaFunc(GL_GEQUAL, 0.5);
break; break;
case SKY: case SKY:
glEnable (GL_TEXTURE_2D); glEnable(GL_TEXTURE_2D);
glDisable (GL_DEPTH_TEST); glDisable(GL_DEPTH_TEST);
glDisable (GL_CULL_FACE); glDisable(GL_CULL_FACE);
glDisable (GL_LIGHTING); glDisable(GL_LIGHTING);
glDisable (GL_NORMALIZE); glDisable(GL_NORMALIZE);
glDisable (GL_ALPHA_TEST); glDisable(GL_ALPHA_TEST);
glEnable (GL_BLEND); glEnable(GL_BLEND);
glDisable (GL_STENCIL_TEST); glDisable(GL_STENCIL_TEST);
glDisable (GL_TEXTURE_GEN_S); glDisable(GL_TEXTURE_GEN_S);
glDisable (GL_TEXTURE_GEN_T); glDisable(GL_TEXTURE_GEN_T);
glDisable (GL_COLOR_MATERIAL); glDisable(GL_COLOR_MATERIAL);
glDepthMask (GL_FALSE); glDepthMask(GL_FALSE);
glShadeModel (GL_SMOOTH); glShadeModel(GL_SMOOTH);
glDepthFunc (GL_LESS); glDepthFunc(GL_LESS);
break; break;
case FOG_PLANE: case FOG_PLANE:
glDisable (GL_TEXTURE_2D); glDisable(GL_TEXTURE_2D);
glEnable (GL_DEPTH_TEST); glEnable(GL_DEPTH_TEST);
glDisable (GL_CULL_FACE); glDisable(GL_CULL_FACE);
glDisable (GL_LIGHTING); glDisable(GL_LIGHTING);
glDisable (GL_NORMALIZE); glDisable(GL_NORMALIZE);
glDisable (GL_ALPHA_TEST); glDisable(GL_ALPHA_TEST);
glEnable (GL_BLEND); glEnable(GL_BLEND);
glDisable (GL_STENCIL_TEST); glDisable(GL_STENCIL_TEST);
glDisable (GL_TEXTURE_GEN_S); glDisable(GL_TEXTURE_GEN_S);
glDisable (GL_TEXTURE_GEN_T); glDisable(GL_TEXTURE_GEN_T);
glDisable (GL_COLOR_MATERIAL); glDisable(GL_COLOR_MATERIAL);
glDepthMask (GL_TRUE); glDepthMask(GL_TRUE);
glShadeModel (GL_SMOOTH); glShadeModel(GL_SMOOTH);
glDepthFunc (GL_LESS); glDepthFunc(GL_LESS);
break; break;
case TUX: case TUX:
glDisable (GL_TEXTURE_2D); glDisable(GL_TEXTURE_2D);
glEnable (GL_DEPTH_TEST); glEnable(GL_DEPTH_TEST);
glEnable (GL_CULL_FACE); glEnable(GL_CULL_FACE);
glEnable (GL_LIGHTING); glEnable(GL_LIGHTING);
glEnable (GL_NORMALIZE); glEnable(GL_NORMALIZE);
glDisable (GL_ALPHA_TEST); glDisable(GL_ALPHA_TEST);
glEnable (GL_BLEND); glEnable(GL_BLEND);
glDisable (GL_STENCIL_TEST); glDisable(GL_STENCIL_TEST);
glDisable (GL_TEXTURE_GEN_S); glDisable(GL_TEXTURE_GEN_S);
glDisable (GL_TEXTURE_GEN_T); glDisable(GL_TEXTURE_GEN_T);
glDisable (GL_COLOR_MATERIAL); glDisable(GL_COLOR_MATERIAL);
glDepthMask (GL_TRUE); glDepthMask(GL_TRUE);
glShadeModel (GL_SMOOTH); glShadeModel(GL_SMOOTH);
glDepthFunc (GL_LESS); glDepthFunc(GL_LESS);
break; break;
case TUX_SHADOW: case TUX_SHADOW:
glDisable (GL_TEXTURE_2D); glDisable(GL_TEXTURE_2D);
glEnable (GL_DEPTH_TEST); glEnable(GL_DEPTH_TEST);
glDisable (GL_LIGHTING); glDisable(GL_LIGHTING);
glDisable (GL_NORMALIZE); glDisable(GL_NORMALIZE);
glDisable (GL_ALPHA_TEST); glDisable(GL_ALPHA_TEST);
glEnable (GL_BLEND); glEnable(GL_BLEND);
glDisable (GL_COLOR_MATERIAL); glDisable(GL_COLOR_MATERIAL);
glShadeModel (GL_SMOOTH); glShadeModel(GL_SMOOTH);
glDepthFunc (GL_LESS); glDepthFunc(GL_LESS);
#ifdef USE_STENCIL_BUFFER #ifdef USE_STENCIL_BUFFER
glDisable (GL_CULL_FACE); glDisable(GL_CULL_FACE);
glEnable (GL_STENCIL_TEST); glEnable(GL_STENCIL_TEST);
glDepthMask (GL_FALSE); glDepthMask(GL_FALSE);
glStencilFunc (GL_EQUAL, 0, ~0); glStencilFunc(GL_EQUAL, 0, ~0);
glStencilOp (GL_KEEP, GL_KEEP, GL_INCR); glStencilOp(GL_KEEP, GL_KEEP, GL_INCR);
#else #else
glEnable (GL_CULL_FACE); glEnable(GL_CULL_FACE);
glDisable (GL_STENCIL_TEST); glDisable(GL_STENCIL_TEST);
glDepthMask (GL_TRUE); glDepthMask(GL_TRUE);
#endif #endif
break; break;
case TRACK_MARKS: case TRACK_MARKS:
glEnable (GL_TEXTURE_2D); glEnable(GL_TEXTURE_2D);
glEnable (GL_DEPTH_TEST); glEnable(GL_DEPTH_TEST);
glDisable (GL_CULL_FACE); glDisable(GL_CULL_FACE);
glEnable (GL_LIGHTING); glEnable(GL_LIGHTING);
glDisable (GL_NORMALIZE); glDisable(GL_NORMALIZE);
glDisable (GL_ALPHA_TEST); glDisable(GL_ALPHA_TEST);
glEnable (GL_BLEND); glEnable(GL_BLEND);
glDisable (GL_STENCIL_TEST); glDisable(GL_STENCIL_TEST);
glDisable (GL_COLOR_MATERIAL); glDisable(GL_COLOR_MATERIAL);
glDisable (GL_TEXTURE_GEN_S); glDisable(GL_TEXTURE_GEN_S);
glDisable (GL_TEXTURE_GEN_T); glDisable(GL_TEXTURE_GEN_T);
glDepthMask (GL_FALSE); glDepthMask(GL_FALSE);
glShadeModel (GL_SMOOTH); glShadeModel(GL_SMOOTH);
glDepthFunc (GL_LEQUAL); glDepthFunc(GL_LEQUAL);
break; break;
default: default:
Message ("not a valid render mode"); Message("not a valid render mode");
} }
} }
/* defined but not used /* defined but not used
@ -509,6 +509,10 @@ void glTexCoord2(const TVector2d& vec) {
glTexCoord2d(vec.x, vec.y); glTexCoord2d(vec.x, vec.y);
} }
void glMultMatrix(const TMatrix<4, 4>& mat) { void glLoadMatrix(const TMatrix<4, 4>& mat) {
glMultMatrixd((const double*)mat.data()); glLoadMatrixd((const double*) mat.data());
}
void glMultMatrix(const TMatrix<4, 4>& mat) {
glMultMatrixd((const double*) mat.data());
} }

View File

@ -48,9 +48,9 @@ void check_gl_error();
void InitOpenglExtensions(); void InitOpenglExtensions();
void PrintGLInfo(); void PrintGLInfo();
void set_material (const TColor& diffuse_colour, void set_material(const TColor& diffuse_colour,
const TColor& specular_colour, const TColor& specular_colour,
float specular_exp); float specular_exp);
void PushRenderMode(TRenderMode mode); void PushRenderMode(TRenderMode mode);
@ -65,10 +65,10 @@ struct ScopedRenderMode {
} }
}; };
void ClearRenderContext (); void ClearRenderContext();
void ClearRenderContext (const TColor& col); void ClearRenderContext(const TColor& col);
void SetupGuiDisplay (); void SetupGuiDisplay();
void Reshape (int w, int h); void Reshape(int w, int h);
void glColor(const TColor& col); void glColor(const TColor& col);
void glColor(const TColor& col, double alpha); void glColor(const TColor& col, double alpha);
@ -79,6 +79,7 @@ void glNormal3(const TVector3d& vec);
void glVertex3(const TVector3d& vec); void glVertex3(const TVector3d& vec);
void glTexCoord2(const TVector2d& vec); void glTexCoord2(const TVector2d& vec);
void glLoadMatrix(const TMatrix<4, 4>& mat);
void glMultMatrix(const TMatrix<4, 4>& mat); void glMultMatrix(const TMatrix<4, 4>& mat);

View File

@ -37,7 +37,7 @@ static const TLight light = {
}; };
void SetTestLight () { void SetTestLight() {
light.Enable(GL_LIGHT0); light.Enable(GL_LIGHT0);
glEnable(GL_LIGHTING); glEnable(GL_LIGHTING);
} }
@ -53,19 +53,17 @@ void COglTest::Keyb(unsigned int key, bool special, bool release, int x, int y)
} }
void COglTest::Enter() { void COglTest::Enter() {
Winsys.KeyRepeat (true); Winsys.KeyRepeat(true);
} }
void COglTest::Loop(double timestep) { void COglTest::Loop(double timestep) {
check_gl_error();
// ------------- 3d scenery --------------------------------------- // ------------- 3d scenery ---------------------------------------
ScopedRenderMode rm(TUX); ScopedRenderMode rm(TUX);
ClearRenderContext (colDDBackgr); ClearRenderContext(colDDBackgr);
glLoadIdentity (); glLoadIdentity();
glPushMatrix (); glPushMatrix();
SetTestLight (); SetTestLight();
/* /*
glTranslatef (xposition, yposition, zposition); glTranslatef (xposition, yposition, zposition);
@ -73,13 +71,13 @@ void COglTest::Loop(double timestep) {
glRotatef (yrotation, 0, 1, 0); glRotatef (yrotation, 0, 1, 0);
glRotatef (zrotation, 0, 0, 1); glRotatef (zrotation, 0, 0, 1);
*/ */
glPopMatrix (); glPopMatrix();
// --------------- 2d screen -------------------------------------- // --------------- 2d screen --------------------------------------
SetupGuiDisplay (); SetupGuiDisplay();
ScopedRenderMode rm2(TEXFONT); ScopedRenderMode rm2(TEXFONT);
FT.SetProps("bold", 24, colWhite); FT.SetProps("bold", 24, colWhite);
FT.DrawString (CENTER, 10, "Test screen"); FT.DrawString(CENTER, 10, "Test screen");
Reshape (Winsys.resolution.width, Winsys.resolution.height); Reshape(Winsys.resolution.width, Winsys.resolution.height);
Winsys.SwapBuffers (); Winsys.SwapBuffers();
} }

View File

@ -37,7 +37,7 @@ GNU General Public License for more details.
// ==================================================================== // ====================================================================
#define MAX_num_snowparticles 4000 #define MAX_num_snowparticles 4000
#define BASE_num_snowparticles 1000 #define BASE_snowparticles 1000.0/1024 // This is intentionally not divided by height*width to make particle count increasing slower than screen size
#define GRAVITY_FACTOR 0.015 #define GRAVITY_FACTOR 0.015
#define BASE_VELOCITY 0.05 #define BASE_VELOCITY 0.05
#define VELOCITY_RANGE 0.02 #define VELOCITY_RANGE 0.02
@ -124,19 +124,19 @@ void TGuiParticle::Update(double time_step, double push_timestep, const TVector2
if (push_timestep > 0) { if (push_timestep > 0) {
f.x = PUSH_FACTOR * push_vector.x / push_timestep; f.x = PUSH_FACTOR * push_vector.x / push_timestep;
f.y = PUSH_FACTOR * push_vector.y / push_timestep; f.y = PUSH_FACTOR * push_vector.y / push_timestep;
f.x = clamp (-MAX_PUSH_FORCE, f.x, MAX_PUSH_FORCE); f.x = clamp(-MAX_PUSH_FORCE, f.x, MAX_PUSH_FORCE);
f.y = clamp (-MAX_PUSH_FORCE, f.y, MAX_PUSH_FORCE); f.y = clamp(-MAX_PUSH_FORCE, f.y, MAX_PUSH_FORCE);
f.x *= 1.0/(PUSH_DIST_DECAY*dist_from_push + 1) * f.x *= 1.0/(PUSH_DIST_DECAY*dist_from_push + 1) *
size/PARTICLE_SIZE_RANGE; size/PARTICLE_SIZE_RANGE;
f.y *= 1.0/(PUSH_DIST_DECAY*dist_from_push + 1) * f.y *= 1.0/(PUSH_DIST_DECAY*dist_from_push + 1) *
size/PARTICLE_SIZE_RANGE; size/PARTICLE_SIZE_RANGE;
} }
vel.x += (f.x - vel.x * AIR_DRAG) * time_step; vel.x += (f.x - vel.x * AIR_DRAG) * time_step;
vel.y += (f.y - GRAVITY_FACTOR - vel.y * AIR_DRAG) * time_step; vel.y += (f.y - GRAVITY_FACTOR - vel.y * AIR_DRAG) * time_step;
pt.x += vel.x * time_step * (size / PARTICLE_SIZE_RANGE); pt.x += vel.x * time_step * (size / PARTICLE_SIZE_RANGE);
pt.y += vel.y * time_step * (size / PARTICLE_SIZE_RANGE); pt.y += vel.y * time_step * (size / PARTICLE_SIZE_RANGE);
if (pt.x < 0) { if (pt.x < 0) {
pt.x = 1; pt.x = 1;
@ -145,14 +145,15 @@ void TGuiParticle::Update(double time_step, double push_timestep, const TVector2
} }
} }
void init_ui_snow () { void init_ui_snow() {
for (int i=0; i<BASE_num_snowparticles; i++) particles_2d.clear();
for (int i = 0; i < BASE_snowparticles * Winsys.resolution.width; i++)
particles_2d.push_back(TGuiParticle(FRandom(), FRandom())); particles_2d.push_back(TGuiParticle(FRandom(), FRandom()));
push_position = TVector2d(0.0, 0.0); push_position = TVector2d(0.0, 0.0);
} }
void update_ui_snow(double time_step) { void update_ui_snow(double time_step) {
double time = Winsys.ClockTime (); double time = Winsys.ClockTime();
TVector2d push_vector; TVector2d push_vector;
double push_timestep = 0; double push_timestep = 0;
@ -175,7 +176,7 @@ void update_ui_snow(double time_step) {
for (list<TGuiParticle>::iterator p = particles_2d.begin(); p != particles_2d.end();) { for (list<TGuiParticle>::iterator p = particles_2d.begin(); p != particles_2d.end();) {
if (p->pt.y < -0.05) { if (p->pt.y < -0.05) {
if (particles_2d.size() > BASE_num_snowparticles && FRandom() > 0.2) { if (particles_2d.size() > BASE_snowparticles * Winsys.resolution.width && FRandom() > 0.2) {
p = particles_2d.erase(p); p = particles_2d.erase(p);
} else { } else {
p->pt.x = FRandom(); p->pt.x = FRandom();
@ -198,12 +199,12 @@ void update_ui_snow(double time_step) {
push_vector.y = 0.0; push_vector.y = 0.0;
} }
} }
void draw_ui_snow () { void draw_ui_snow() {
double xres = Winsys.resolution.width; double xres = Winsys.resolution.width;
double yres = Winsys.resolution.height; double yres = Winsys.resolution.height;
glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
Tex.BindTex (SNOW_PART); Tex.BindTex(SNOW_PART);
glColor4f(1.f, 1.f, 1.f, 0.3f); glColor4f(1.f, 1.f, 1.f, 0.3f);
glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_VERTEX_ARRAY);
@ -215,7 +216,7 @@ void draw_ui_snow () {
glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_VERTEX_ARRAY);
} }
void push_ui_snow (const TVector2i& pos) { void push_ui_snow(const TVector2i& pos) {
push_position = TVector2d(pos.x/(double)Winsys.resolution.width, 1.0 - pos.y/(double)Winsys.resolution.height); push_position = TVector2d(pos.x/(double)Winsys.resolution.width, 1.0 - pos.y/(double)Winsys.resolution.height);
if (!push_position_initialized) last_push_position = push_position; if (!push_position_initialized) last_push_position = push_position;
push_position_initialized = true; push_position_initialized = true;
@ -288,13 +289,13 @@ void Particle::Draw(const CControl* ctrl) const {
} }
}; };
const TColor& particle_colour = Env.ParticleColor (); const TColor& particle_colour = Env.ParticleColor();
glColor(particle_colour, particle_colour.a * alpha); glColor(particle_colour, particle_colour.a * alpha);
draw_billboard(ctrl, cur_size, cur_size, false, tex_coords[type]); draw_billboard(ctrl, cur_size, cur_size, false, tex_coords[type]);
} }
void Particle::draw_billboard (const CControl *ctrl, double width, double height, bool use_world_y_axis, const GLfloat* tex) const { void Particle::draw_billboard(const CControl *ctrl, double width, double height, bool use_world_y_axis, const GLfloat* tex) const {
TVector3d x_vec; TVector3d x_vec;
TVector3d y_vec; TVector3d y_vec;
TVector3d z_vec; TVector3d z_vec;
@ -305,9 +306,9 @@ void Particle::draw_billboard (const CControl *ctrl, double width, double height
if (use_world_y_axis) { if (use_world_y_axis) {
y_vec = TVector3d(0, 1, 0); y_vec = TVector3d(0, 1, 0);
x_vec = ProjectToPlane (y_vec, x_vec); x_vec = ProjectToPlane(y_vec, x_vec);
x_vec.Norm(); x_vec.Norm();
z_vec = CrossProduct (x_vec, y_vec); z_vec = CrossProduct(x_vec, y_vec);
} else { } else {
y_vec.x = ctrl->view_mat[1][0]; y_vec.x = ctrl->view_mat[1][0];
y_vec.y = ctrl->view_mat[1][1]; y_vec.y = ctrl->view_mat[1][1];
@ -340,11 +341,11 @@ void Particle::draw_billboard (const CControl *ctrl, double width, double height
glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_VERTEX_ARRAY);
} }
void create_new_particles (const TVector3d& loc, const TVector3d& vel, int num) { void create_new_particles(const TVector3d& loc, const TVector3d& vel, int num) {
double speed = vel.Length(); double speed = vel.Length();
if (particles.size() + num > MAX_PARTICLES) { if (particles.size() + num > MAX_PARTICLES) {
Message ("maximum number of particles exceeded"); Message("maximum number of particles exceeded");
} }
for (int i=0; i<num; i++) { for (int i=0; i<num; i++) {
particles.push_back(Particle()); particles.push_back(Particle());
@ -363,7 +364,7 @@ void create_new_particles (const TVector3d& loc, const TVector3d& vel, int num)
VARIANCE_FACTOR * (FRandom() - 0.5) * speed); VARIANCE_FACTOR * (FRandom() - 0.5) * speed);
} }
} }
void update_particles (double time_step) { void update_particles(double time_step) {
for (list<Particle>::iterator p = particles.begin(); p != particles.end();) { for (list<Particle>::iterator p = particles.begin(); p != particles.end();) {
p->age += time_step; p->age += time_step;
if (p->age < 0) { if (p->age < 0) {
@ -372,7 +373,7 @@ void update_particles (double time_step) {
} }
p->pt += time_step * p->vel; p->pt += time_step * p->vel;
double ycoord = Course.FindYCoord (p->pt.x, p->pt.z); double ycoord = Course.FindYCoord(p->pt.x, p->pt.z);
if (p->pt.y < ycoord - 3) {p->age = p->death + 1;} if (p->pt.y < ycoord - 3) {p->age = p->death + 1;}
if (p->age >= p->death) { if (p->age >= p->death) {
p = particles.erase(p); p = particles.erase(p);
@ -385,10 +386,10 @@ void update_particles (double time_step) {
++p; ++p;
} }
} }
void draw_particles (const CControl *ctrl) { void draw_particles(const CControl *ctrl) {
ScopedRenderMode rm(PARTICLES); ScopedRenderMode rm(PARTICLES);
Tex.BindTex (SNOW_PART); Tex.BindTex(SNOW_PART);
glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glColor4f(1.f, 1.f, 1.f, 0.8f); glColor4f(1.f, 1.f, 1.f, 0.8f);
for (list<Particle>::const_iterator p = particles.begin(); p != particles.end(); ++p) { for (list<Particle>::const_iterator p = particles.begin(); p != particles.end(); ++p) {
@ -400,21 +401,21 @@ void clear_particles() {
particles.clear(); particles.clear();
} }
double adjust_particle_count (double particles) { double adjust_particle_count(double particles) {
if (particles < 1) { if (particles < 1) {
if (((double) rand()) / RAND_MAX < particles) return 1.0; if (((double) rand()) / RAND_MAX < particles) return 1.0;
else return 0.0; else return 0.0;
} else return particles; } else return particles;
} }
void generate_particles (const CControl *ctrl, double dtime, const TVector3d& pos, double speed) { void generate_particles(const CControl *ctrl, double dtime, const TVector3d& pos, double speed) {
TTerrType *TerrList = &Course.TerrList[0]; TTerrType *TerrList = &Course.TerrList[0];
double surf_y = Course.FindYCoord (pos.x, pos.z); double surf_y = Course.FindYCoord(pos.x, pos.z);
int id = Course.GetTerrainIdx (pos.x, pos.z, 0.5); int id = Course.GetTerrainIdx(pos.x, pos.z, 0.5);
if (id >= 0 && TerrList[id].particles && pos.y < surf_y) { if (id >= 0 && TerrList[id].particles && pos.y < surf_y) {
TVector3d xvec = CrossProduct (ctrl->cdirection, ctrl->plane_nml); TVector3d xvec = CrossProduct(ctrl->cdirection, ctrl->plane_nml);
TVector3d right_part_pt = pos + TUX_WIDTH/2.0 * xvec; TVector3d right_part_pt = pos + TUX_WIDTH/2.0 * xvec;
@ -423,45 +424,45 @@ void generate_particles (const CControl *ctrl, double dtime, const TVector3d& po
right_part_pt.y = left_part_pt.y = surf_y; right_part_pt.y = left_part_pt.y = surf_y;
double brake_particles = dtime * double brake_particles = dtime *
BRAKE_PARTICLES * (ctrl->is_braking ? 1.0 : 0.0) BRAKE_PARTICLES * (ctrl->is_braking ? 1.0 : 0.0)
* min (speed / PARTICLE_SPEED_FACTOR, 1.0); * min(speed / PARTICLE_SPEED_FACTOR, 1.0);
double turn_particles = dtime * MAX_TURN_PARTICLES double turn_particles = dtime * MAX_TURN_PARTICLES
* min (speed / PARTICLE_SPEED_FACTOR, 1.0); * min(speed / PARTICLE_SPEED_FACTOR, 1.0);
double roll_particles = dtime * MAX_ROLL_PARTICLES double roll_particles = dtime * MAX_ROLL_PARTICLES
* min (speed / PARTICLE_SPEED_FACTOR, 1.0); * min(speed / PARTICLE_SPEED_FACTOR, 1.0);
double left_particles = turn_particles * double left_particles = turn_particles *
fabs (min(ctrl->turn_fact, 0.)) + fabs(min(ctrl->turn_fact, 0.)) +
brake_particles + brake_particles +
roll_particles * fabs (min(ctrl->turn_animation, 0.)); roll_particles * fabs(min(ctrl->turn_animation, 0.));
double right_particles = turn_particles * double right_particles = turn_particles *
fabs (max(ctrl->turn_fact, 0.)) + fabs(max(ctrl->turn_fact, 0.)) +
brake_particles + brake_particles +
roll_particles * fabs (max(ctrl->turn_animation, 0.)); roll_particles * fabs(max(ctrl->turn_animation, 0.));
left_particles = adjust_particle_count (left_particles); left_particles = adjust_particle_count(left_particles);
right_particles = adjust_particle_count (right_particles); right_particles = adjust_particle_count(right_particles);
TMatrix<4, 4> rot_mat = RotateAboutVectorMatrix( TMatrix<4, 4> rot_mat = RotateAboutVectorMatrix(
ctrl->cdirection, ctrl->cdirection,
max (-MAX_PARTICLE_ANGLE, max(-MAX_PARTICLE_ANGLE,
-MAX_PARTICLE_ANGLE * speed / MAX_PARTICLE_ANGLE_SPEED)); -MAX_PARTICLE_ANGLE * speed / MAX_PARTICLE_ANGLE_SPEED));
TVector3d left_part_vel = TransformVector (rot_mat, ctrl->plane_nml); TVector3d left_part_vel = TransformVector(rot_mat, ctrl->plane_nml);
left_part_vel = min(MAX_PARTICLE_SPEED, speed * PARTICLE_SPEED_MULTIPLIER); left_part_vel = min(MAX_PARTICLE_SPEED, speed * PARTICLE_SPEED_MULTIPLIER);
rot_mat = RotateAboutVectorMatrix( rot_mat = RotateAboutVectorMatrix(
ctrl->cdirection, ctrl->cdirection,
min (MAX_PARTICLE_ANGLE, min(MAX_PARTICLE_ANGLE,
MAX_PARTICLE_ANGLE * speed / MAX_PARTICLE_ANGLE_SPEED)); MAX_PARTICLE_ANGLE * speed / MAX_PARTICLE_ANGLE_SPEED));
TVector3d right_part_vel = TransformVector (rot_mat, ctrl->plane_nml); TVector3d right_part_vel = TransformVector(rot_mat, ctrl->plane_nml);
right_part_vel *= min(MAX_PARTICLE_SPEED, speed * PARTICLE_SPEED_MULTIPLIER); right_part_vel *= min(MAX_PARTICLE_SPEED, speed * PARTICLE_SPEED_MULTIPLIER);
create_new_particles (left_part_pt, left_part_vel, create_new_particles(left_part_pt, left_part_vel,
(int)left_particles); (int)left_particles);
create_new_particles (right_part_pt, right_part_vel, create_new_particles(right_part_pt, right_part_vel,
(int)right_particles); (int)right_particles);
} }
} }
@ -475,10 +476,10 @@ static CFlakes Flakes;
void TFlake::Draw(const TPlane& lp, const TPlane& rp, bool rotate_flake, float dir_angle) const { void TFlake::Draw(const TPlane& lp, const TPlane& rp, bool rotate_flake, float dir_angle) const {
if ((DistanceToPlane (lp, pt) < 0) && (DistanceToPlane (rp, pt) < 0)) { if ((DistanceToPlane(lp, pt) < 0) && (DistanceToPlane(rp, pt) < 0)) {
glPushMatrix(); glPushMatrix();
glTranslate(pt); glTranslate(pt);
if (rotate_flake) glRotatef (dir_angle, 0, 1, 0); if (rotate_flake) glRotatef(dir_angle, 0, 1, 0);
const GLfloat vtx[] = { const GLfloat vtx[] = {
0, 0, 0, 0, 0, 0,
@ -495,7 +496,7 @@ void TFlake::Draw(const TPlane& lp, const TPlane& rp, bool rotate_flake, float d
} }
TFlakeArea::TFlakeArea ( TFlakeArea::TFlakeArea(
int num_flakes, int num_flakes,
float _xrange, float _xrange,
float _ytop, float _ytop,
@ -519,17 +520,17 @@ TFlakeArea::TFlakeArea (
flakes.resize(num_flakes); flakes.resize(num_flakes);
} }
void TFlakeArea::Draw (const CControl *ctrl) const { void TFlakeArea::Draw(const CControl *ctrl) const {
if (g_game.snow_id < 1) return; if (g_game.snow_id < 1) return;
const TPlane& lp = get_left_clip_plane (); const TPlane& lp = get_left_clip_plane();
const TPlane& rp = get_right_clip_plane (); const TPlane& rp = get_right_clip_plane();
float dir_angle (atan (ctrl->viewdir.x / ctrl->viewdir.z) * 180 / 3.14159); float dir_angle(atan(ctrl->viewdir.x / ctrl->viewdir.z) * 180 / 3.14159);
ScopedRenderMode rm(PARTICLES); ScopedRenderMode rm(PARTICLES);
glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
Tex.BindTex(SNOW_PART); Tex.BindTex(SNOW_PART);
const TColor& particle_colour = Env.ParticleColor (); const TColor& particle_colour = Env.ParticleColor();
glColor(particle_colour); glColor(particle_colour);
glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_VERTEX_ARRAY);
@ -563,16 +564,16 @@ void TFlakeArea::Update(float timestep, float xcoeff, float ycoeff, float zcoeff
} }
} }
void CFlakes::Reset () { void CFlakes::Reset() {
areas.clear(); areas.clear();
} }
void CFlakes::MakeSnowFlake (size_t ar, size_t i) { void CFlakes::MakeSnowFlake(size_t ar, size_t i) {
areas[ar].flakes[i].pt.x = XRandom (areas[ar].left, areas[ar].right); areas[ar].flakes[i].pt.x = XRandom(areas[ar].left, areas[ar].right);
areas[ar].flakes[i].pt.y = -XRandom (areas[ar].top, areas[ar].bottom); areas[ar].flakes[i].pt.y = -XRandom(areas[ar].top, areas[ar].bottom);
areas[ar].flakes[i].pt.z = areas[ar].back - FRandom () * (areas[ar].back - areas[ar].front); areas[ar].flakes[i].pt.z = areas[ar].back - FRandom() * (areas[ar].back - areas[ar].front);
areas[ar].flakes[i].size = XRandom (areas[ar].minSize, areas[ar].maxSize); areas[ar].flakes[i].size = XRandom(areas[ar].minSize, areas[ar].maxSize);
areas[ar].flakes[i].vel.x = 0; areas[ar].flakes[i].vel.x = 0;
areas[ar].flakes[i].vel.z = 0; areas[ar].flakes[i].vel.z = 0;
areas[ar].flakes[i].vel.y = -areas[ar].flakes[i].size * areas[ar].speed; areas[ar].flakes[i].vel.y = -areas[ar].flakes[i].size * areas[ar].speed;
@ -606,15 +607,15 @@ void CFlakes::MakeSnowFlake (size_t ar, size_t i) {
areas[ar].flakes[i].tex = tex_coords[type]; areas[ar].flakes[i].tex = tex_coords[type];
} }
void CFlakes::GenerateSnowFlakes (const CControl *ctrl) { void CFlakes::GenerateSnowFlakes(const CControl *ctrl) {
if (g_game.snow_id < 1) return; if (g_game.snow_id < 1) return;
snow_lastpos = ctrl->cpos; snow_lastpos = ctrl->cpos;
for (size_t ar=0; ar<areas.size(); ar++) { for (size_t ar=0; ar<areas.size(); ar++) {
for (size_t i=0; i<areas[ar].flakes.size(); i++) MakeSnowFlake (ar, i); for (size_t i=0; i<areas[ar].flakes.size(); i++) MakeSnowFlake(ar, i);
} }
} }
void CFlakes::UpdateAreas (const CControl *ctrl) { void CFlakes::UpdateAreas(const CControl *ctrl) {
for (size_t ar=0; ar<areas.size(); ar++) { for (size_t ar=0; ar<areas.size(); ar++) {
areas[ar].left = ctrl->cpos.x - areas[ar].xrange / 2; areas[ar].left = ctrl->cpos.x - areas[ar].xrange / 2;
areas[ar].right = areas[ar].left + areas[ar].xrange; areas[ar].right = areas[ar].left + areas[ar].xrange;
@ -628,8 +629,8 @@ void CFlakes::UpdateAreas (const CControl *ctrl) {
#define YDRIFT 0.8 #define YDRIFT 0.8
#define ZDRIFT 0.6 #define ZDRIFT 0.6
void CFlakes::Init (int grade, const CControl *ctrl) { void CFlakes::Init(int grade, const CControl *ctrl) {
Reset (); Reset();
switch (grade) { switch (grade) {
case 1: case 1:
// areas.push_back(TFlakeArea(400, 5, 4, 4, -2, 4, 0.01, 0.02, 5, true)); // areas.push_back(TFlakeArea(400, 5, 4, 4, -2, 4, 0.01, 0.02, 5, true));
@ -668,15 +669,15 @@ void CFlakes::Init (int grade, const CControl *ctrl) {
break; break;
} }
UpdateAreas (ctrl); UpdateAreas(ctrl);
GenerateSnowFlakes (ctrl); GenerateSnowFlakes(ctrl);
} }
void CFlakes::Update (double timestep, const CControl *ctrl) { void CFlakes::Update(double timestep, const CControl *ctrl) {
if (g_game.snow_id < 1) if (g_game.snow_id < 1)
return; return;
UpdateAreas (ctrl); UpdateAreas(ctrl);
float zdiff = ctrl->cpos.z - snow_lastpos.z; float zdiff = ctrl->cpos.z - snow_lastpos.z;
float ydiff = 0.f; float ydiff = 0.f;
@ -684,7 +685,7 @@ void CFlakes::Update (double timestep, const CControl *ctrl) {
ydiff = ctrl->cpos.y - snow_lastpos.y; ydiff = ctrl->cpos.y - snow_lastpos.y;
} }
TVector3d winddrift = SNOW_WIND_DRIFT * Wind.WindDrift (); TVector3d winddrift = SNOW_WIND_DRIFT * Wind.WindDrift();
float xcoeff = winddrift.x * timestep; float xcoeff = winddrift.x * timestep;
float ycoeff = (ydiff * YDRIFT) + (winddrift.z * timestep); float ycoeff = (ydiff * YDRIFT) + (winddrift.z * timestep);
float zcoeff = (zdiff * ZDRIFT) + (winddrift.z * timestep); float zcoeff = (zdiff * ZDRIFT) + (winddrift.z * timestep);
@ -695,7 +696,7 @@ void CFlakes::Update (double timestep, const CControl *ctrl) {
snow_lastpos = ctrl->cpos; snow_lastpos = ctrl->cpos;
} }
void CFlakes::Draw (const CControl *ctrl) const { void CFlakes::Draw(const CControl *ctrl) const {
for (size_t ar=0; ar<areas.size(); ar++) for (size_t ar=0; ar<areas.size(); ar++)
areas[ar].Draw(ctrl); areas[ar].Draw(ctrl);
} }
@ -719,17 +720,17 @@ struct TChange {
TChange changes[NUM_CHANGES]; TChange changes[NUM_CHANGES];
void InitChanges () { void InitChanges() {
for (int i=0; i<NUM_CHANGES; i++) { for (int i=0; i<NUM_CHANGES; i++) {
changes[i].min = XRandom (-0.15, -0.05); changes[i].min = XRandom(-0.15, -0.05);
changes[i].max = XRandom (0.05, 0.15); changes[i].max = XRandom(0.05, 0.15);
changes[i].curr = (changes[i].min + changes[i].max) / 2; changes[i].curr = (changes[i].min + changes[i].max) / 2;
changes[i].step = CHANGE_SPEED; changes[i].step = CHANGE_SPEED;
changes[i].forward = true; changes[i].forward = true;
} }
} }
void UpdateChanges (double timestep) { void UpdateChanges(double timestep) {
for (int i=0; i<NUM_CHANGES; i++) { for (int i=0; i<NUM_CHANGES; i++) {
TChange* ch = &changes[i]; TChange* ch = &changes[i];
if (ch->forward) { if (ch->forward) {
@ -742,8 +743,8 @@ void UpdateChanges (double timestep) {
} }
} }
TCurtain::TCurtain (int num_rows, float z_dist, float tex_size, TCurtain::TCurtain(int num_rows, float z_dist, float tex_size,
float base_speed, float start_angle, float min_height, int dense) { float base_speed, float start_angle, float min_height, int dense) {
numRows = num_rows; numRows = num_rows;
zdist = z_dist; zdist = z_dist;
size = tex_size; size = tex_size;
@ -762,13 +763,13 @@ TCurtain::TCurtain (int num_rows, float z_dist, float tex_size,
break; break;
} }
angledist = atan (size / 2 / zdist) * 360 / 3.14159; angledist = atan(size / 2 / zdist) * 360 / 3.14159;
numCols = (unsigned int)(-2 * startangle / angledist) + 1; numCols = (unsigned int)(-2 * startangle / angledist) + 1;
if (numCols > MAX_CURTAIN_COLS) numCols = MAX_CURTAIN_COLS; if (numCols > MAX_CURTAIN_COLS) numCols = MAX_CURTAIN_COLS;
lastangle = startangle + (numCols-1) * angledist; lastangle = startangle + (numCols-1) * angledist;
for (unsigned int i=0; i<numRows; i++) for (unsigned int i=0; i<numRows; i++)
chg[i] = IRandom (0, 5); chg[i] = IRandom(0, 5);
} }
void TCurtain::SetStartParams(const CControl* ctrl) { void TCurtain::SetStartParams(const CControl* ctrl) {
@ -778,7 +779,7 @@ void TCurtain::SetStartParams(const CControl* ctrl) {
curt->height = minheight + row * size; curt->height = minheight + row * size;
float x, z; float x, z;
curt->angle = co * angledist + startangle; curt->angle = co * angledist + startangle;
CurtainVec (curt->angle, zdist, x, z); CurtainVec(curt->angle, zdist, x, z);
curt->pt.x = ctrl->cpos.x + x; curt->pt.x = ctrl->cpos.x + x;
curt->pt.z = ctrl->cpos.z + z; curt->pt.z = ctrl->cpos.z + z;
curt->pt.y = ctrl->cpos.y + curt->height; curt->pt.y = ctrl->cpos.y + curt->height;
@ -787,7 +788,7 @@ void TCurtain::SetStartParams(const CControl* ctrl) {
} }
void TCurtain::Draw() const { void TCurtain::Draw() const {
Tex.BindTex (texture); Tex.BindTex(texture);
float halfsize = size / 2.f; float halfsize = size / 2.f;
glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY);
@ -796,7 +797,7 @@ void TCurtain::Draw() const {
const TVector3d& pt = curtains[co][row].pt; const TVector3d& pt = curtains[co][row].pt;
glPushMatrix(); glPushMatrix();
glTranslate(pt); glTranslate(pt);
glRotatef (-curtains[co][row].angle, 0, 1, 0); glRotatef(-curtains[co][row].angle, 0, 1, 0);
static const GLshort tex[] = { static const GLshort tex[] = {
0, 0, 0, 0,
@ -832,7 +833,7 @@ void TCurtain::Update(float timestep, const TVector3d& drift, const CControl* ct
if (curt->angle > lastangle + angledist) curt->angle = startangle; if (curt->angle > lastangle + angledist) curt->angle = startangle;
if (curt->angle < startangle - angledist) curt->angle = lastangle; if (curt->angle < startangle - angledist) curt->angle = lastangle;
float x, z; float x, z;
CurtainVec (curt->angle, zdist, x, z); CurtainVec(curt->angle, zdist, x, z);
curt->pt.x = ctrl->cpos.x + x; curt->pt.x = ctrl->cpos.x + x;
curt->pt.z = ctrl->cpos.z + z; curt->pt.z = ctrl->cpos.z + z;
curt->pt.y = ctrl->cpos.y + curt->height; curt->pt.y = ctrl->cpos.y + curt->height;
@ -843,18 +844,18 @@ void TCurtain::Update(float timestep, const TVector3d& drift, const CControl* ct
static CCurtain Curtain; static CCurtain Curtain;
void TCurtain::CurtainVec (float angle, float zdist, float &x, float &z) { void TCurtain::CurtainVec(float angle, float zdist, float &x, float &z) {
x = zdist * sin (angle * 3.14159 / 180); x = zdist * sin(angle * 3.14159 / 180);
if (angle > 90 || angle < -90) z = sqrt (zdist * zdist - x * x); if (angle > 90 || angle < -90) z = sqrt(zdist * zdist - x * x);
else z = -sqrt (zdist * zdist - x * x); else z = -sqrt(zdist * zdist - x * x);
} }
void CCurtain::Draw () { void CCurtain::Draw() {
if (g_game.snow_id < 1) return; if (g_game.snow_id < 1) return;
ScopedRenderMode rm(PARTICLES); ScopedRenderMode rm(PARTICLES);
glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
const TColor& particle_colour = Env.ParticleColor (); const TColor& particle_colour = Env.ParticleColor();
glColor(particle_colour, 1.0); glColor(particle_colour, 1.0);
// glEnable (GL_NORMALIZE); // glEnable (GL_NORMALIZE);
@ -863,30 +864,30 @@ void CCurtain::Draw () {
} }
} }
void CCurtain::Update (float timestep, const CControl *ctrl) { void CCurtain::Update(float timestep, const CControl *ctrl) {
if (g_game.snow_id < 1) return; if (g_game.snow_id < 1) return;
const TVector3d& drift = Wind.WindDrift (); const TVector3d& drift = Wind.WindDrift();
UpdateChanges (timestep); UpdateChanges(timestep);
for (size_t i=0; i<curtains.size(); i++) { for (size_t i=0; i<curtains.size(); i++) {
curtains[i].Update(timestep, drift, ctrl); curtains[i].Update(timestep, drift, ctrl);
} }
Draw (); Draw();
} }
void CCurtain::Reset () { void CCurtain::Reset() {
curtains.clear(); curtains.clear();
} }
void CCurtain::SetStartParams (const CControl *ctrl) { void CCurtain::SetStartParams(const CControl *ctrl) {
for (size_t i=0; i<curtains.size(); i++) { for (size_t i=0; i<curtains.size(); i++) {
curtains[i].SetStartParams(ctrl); curtains[i].SetStartParams(ctrl);
} }
} }
void CCurtain::Init (const CControl *ctrl) { void CCurtain::Init(const CControl *ctrl) {
Reset (); Reset();
InitChanges (); InitChanges();
switch (g_game.snow_id) { switch (g_game.snow_id) {
case 1: case 1:
// curtains.push_back(TCurtain(3, 60, 10, 3, -100, -10, 1)); // curtains.push_back(TCurtain(3, 60, 10, 3, -100, -10, 1));
@ -924,7 +925,7 @@ void CCurtain::Init (const CControl *ctrl) {
default: default:
break; break;
} }
SetStartParams (ctrl); SetStartParams(ctrl);
} }
// -------------------------------------------------------------------- // --------------------------------------------------------------------
@ -935,7 +936,7 @@ void CCurtain::Init (const CControl *ctrl) {
CWind Wind; CWind Wind;
CWind::CWind () CWind::CWind()
: WVector(0, 0, 0) { : WVector(0, 0, 0) {
windy = false; windy = false;
CurrTime = 0.0; CurrTime = 0.0;
@ -950,7 +951,7 @@ CWind::CWind ()
AngleChange = 0; AngleChange = 0;
} }
void CWind::SetParams (int grade) { void CWind::SetParams(int grade) {
float min_base_speed = 0; float min_base_speed = 0;
float max_base_speed = 0; float max_base_speed = 0;
float min_speed_var = 0; float min_speed_var = 0;
@ -1022,46 +1023,46 @@ void CWind::SetParams (int grade) {
float speed, var, angle; float speed, var, angle;
speed = XRandom (min_base_speed, max_base_speed); speed = XRandom(min_base_speed, max_base_speed);
var = XRandom (min_speed_var, max_speed_var) / 2; var = XRandom(min_speed_var, max_speed_var) / 2;
params.minSpeed = speed - var; params.minSpeed = speed - var;
params.maxSpeed = speed + var; params.maxSpeed = speed + var;
if (params.minSpeed < 0) params.minSpeed = 0; if (params.minSpeed < 0) params.minSpeed = 0;
if (params.maxSpeed > 100) params.maxSpeed = 100; if (params.maxSpeed > 100) params.maxSpeed = 100;
angle = XRandom (min_base_angle, max_base_angle); angle = XRandom(min_base_angle, max_base_angle);
if (XRandom (0, 100) > 50) angle = angle + alt_angle; if (XRandom(0, 100) > 50) angle = angle + alt_angle;
var = XRandom (min_angle_var, max_angle_var) / 2; var = XRandom(min_angle_var, max_angle_var) / 2;
params.minAngle = angle - var; params.minAngle = angle - var;
params.maxAngle = angle + var; params.maxAngle = angle + var;
} }
void CWind::CalcDestSpeed () { void CWind::CalcDestSpeed() {
float rand = XRandom (0, 100); float rand = XRandom(0, 100);
if (rand > (100 - params.topProbability)) { if (rand > (100 - params.topProbability)) {
DestSpeed = XRandom (params.maxSpeed, params.topSpeed); DestSpeed = XRandom(params.maxSpeed, params.topSpeed);
WindChange = params.maxChange; WindChange = params.maxChange;
} else if (rand < params.nullProbability) { } else if (rand < params.nullProbability) {
DestSpeed = 0.0; DestSpeed = 0.0;
WindChange = XRandom (params.minChange, params.maxChange); WindChange = XRandom(params.minChange, params.maxChange);
} else { } else {
DestSpeed = XRandom (params.minSpeed, params.maxSpeed); DestSpeed = XRandom(params.minSpeed, params.maxSpeed);
WindChange = XRandom (params.minChange, params.maxChange); WindChange = XRandom(params.minChange, params.maxChange);
} }
if (DestSpeed > WSpeed) SpeedMode = 1; if (DestSpeed > WSpeed) SpeedMode = 1;
else SpeedMode = 0; else SpeedMode = 0;
} }
void CWind::CalcDestAngle () { void CWind::CalcDestAngle() {
DestAngle = XRandom (params.minAngle, params.maxAngle); DestAngle = XRandom(params.minAngle, params.maxAngle);
AngleChange = XRandom (params.minAngleChange, params.maxAngleChange); AngleChange = XRandom(params.minAngleChange, params.maxAngleChange);
if (DestAngle > WAngle) AngleMode = 1; if (DestAngle > WAngle) AngleMode = 1;
else AngleMode = 0; else AngleMode = 0;
} }
void CWind::Update (float timestep) { void CWind::Update(float timestep) {
if (!windy) return; if (!windy) return;
// the wind needn't be updated in each frame // the wind needn't be updated in each frame
@ -1072,11 +1073,11 @@ void CWind::Update (float timestep) {
if (SpeedMode == 1) { // current speed lesser than destination speed if (SpeedMode == 1) { // current speed lesser than destination speed
if (WSpeed < DestSpeed) { if (WSpeed < DestSpeed) {
WSpeed = WSpeed + WindChange; WSpeed = WSpeed + WindChange;
} else CalcDestSpeed (); } else CalcDestSpeed();
} else { } else {
if (WSpeed > DestSpeed) { if (WSpeed > DestSpeed) {
WSpeed = WSpeed - WindChange; WSpeed = WSpeed - WindChange;
} else CalcDestSpeed (); } else CalcDestSpeed();
} }
if (WSpeed > params.topSpeed) WSpeed = params.topSpeed; if (WSpeed > params.topSpeed) WSpeed = params.topSpeed;
if (WSpeed < 0) WSpeed = 0; if (WSpeed < 0) WSpeed = 0;
@ -1085,17 +1086,17 @@ void CWind::Update (float timestep) {
if (AngleMode == 1) { if (AngleMode == 1) {
if (WAngle < DestAngle) { if (WAngle < DestAngle) {
WAngle = WAngle + AngleChange; WAngle = WAngle + AngleChange;
} else CalcDestAngle (); } else CalcDestAngle();
} else { } else {
if (WAngle > DestAngle) { if (WAngle > DestAngle) {
WAngle = WAngle - AngleChange; WAngle = WAngle - AngleChange;
} else CalcDestAngle (); } else CalcDestAngle();
} }
if (WAngle > params.maxAngle) WAngle = params.maxAngle; if (WAngle > params.maxAngle) WAngle = params.maxAngle;
if (WAngle < params.minAngle) WAngle = params.minAngle; if (WAngle < params.minAngle) WAngle = params.minAngle;
float xx = sin (WAngle * 3.14159 / 180); float xx = sin(WAngle * 3.14159 / 180);
float zz = sqrt (1 - xx * xx); float zz = sqrt(1 - xx * xx);
if ((WAngle > 90 && WAngle < 270) || (WAngle > 450 && WAngle < 630)) { if ((WAngle > 90 && WAngle < 270) || (WAngle > 450 && WAngle < 630)) {
zz = -zz; zz = -zz;
} }
@ -1105,48 +1106,48 @@ void CWind::Update (float timestep) {
} }
} }
void CWind::Init (int wind_id) { void CWind::Init(int wind_id) {
if (wind_id < 1 || wind_id > 3) { if (wind_id < 1 || wind_id > 3) {
windy = false; windy = false;
WVector = TVector3d (0, 0, 0); WVector = TVector3d(0, 0, 0);
WAngle = 0; WAngle = 0;
WSpeed = 0; WSpeed = 0;
return; return;
} }
windy = true;; windy = true;;
SetParams (wind_id -1); SetParams(wind_id -1);
WSpeed = XRandom (params.minSpeed, (params.minSpeed + params.maxSpeed) / 2); WSpeed = XRandom(params.minSpeed, (params.minSpeed + params.maxSpeed) / 2);
WAngle = XRandom (params.minAngle, params.maxAngle); WAngle = XRandom(params.minAngle, params.maxAngle);
CalcDestSpeed (); CalcDestSpeed();
CalcDestAngle (); CalcDestAngle();
} }
// ==================================================================== // ====================================================================
// access functions // access functions
// ==================================================================== // ====================================================================
void InitSnow (const CControl *ctrl) { void InitSnow(const CControl *ctrl) {
if (g_game.snow_id < 1 || g_game.snow_id > 3) return; if (g_game.snow_id < 1 || g_game.snow_id > 3) return;
Flakes.Init (g_game.snow_id, ctrl); Flakes.Init(g_game.snow_id, ctrl);
Curtain.Init (ctrl); Curtain.Init(ctrl);
} }
void UpdateSnow (double timestep, const CControl *ctrl) { void UpdateSnow(double timestep, const CControl *ctrl) {
if (g_game.snow_id < 1 || g_game.snow_id > 3) return; if (g_game.snow_id < 1 || g_game.snow_id > 3) return;
Flakes.Update (timestep, ctrl); Flakes.Update(timestep, ctrl);
Curtain.Update (timestep, ctrl); Curtain.Update(timestep, ctrl);
} }
void DrawSnow (const CControl *ctrl) { void DrawSnow(const CControl *ctrl) {
if (g_game.snow_id < 1 || g_game.snow_id > 3) return; if (g_game.snow_id < 1 || g_game.snow_id > 3) return;
Flakes.Draw (ctrl); Flakes.Draw(ctrl);
Curtain.Draw (); Curtain.Draw();
} }
void InitWind () { void InitWind() {
Wind.Init (g_game.wind_id); Wind.Init(g_game.wind_id);
} }
void UpdateWind (double timestep) { void UpdateWind(double timestep) {
Wind.Update (timestep); Wind.Update(timestep);
} }

View File

@ -26,20 +26,20 @@ GNU General Public License for more details.
// snow for menu screens // snow for menu screens
// -------------------------------------------------------------------- // --------------------------------------------------------------------
void init_ui_snow (); void init_ui_snow();
void update_ui_snow (double time_step); void update_ui_snow(double time_step);
void push_ui_snow (const TVector2i& pos); void push_ui_snow(const TVector2i& pos);
void draw_ui_snow (); void draw_ui_snow();
// -------------------------------------------------------------------- // --------------------------------------------------------------------
// snow particles during race // snow particles during race
// -------------------------------------------------------------------- // --------------------------------------------------------------------
void create_new_particles (const TVector3d& loc, const TVector3d& vel, int num); void create_new_particles(const TVector3d& loc, const TVector3d& vel, int num);
void update_particles (double time_step); void update_particles(double time_step);
void clear_particles (); void clear_particles();
void draw_particles (const CControl *ctrl); void draw_particles(const CControl *ctrl);
void generate_particles (const CControl *ctrl, double dtime, const TVector3d& pos, double speed); void generate_particles(const CControl *ctrl, double dtime, const TVector3d& pos, double speed);
// -------------------------------------------------------------------- // --------------------------------------------------------------------
// snow flakes for short distances // snow flakes for short distances
@ -93,14 +93,14 @@ class CFlakes {
private: private:
TVector3d snow_lastpos; TVector3d snow_lastpos;
vector<TFlakeArea> areas; vector<TFlakeArea> areas;
void MakeSnowFlake (size_t ar, size_t i); void MakeSnowFlake(size_t ar, size_t i);
void GenerateSnowFlakes (const CControl *ctrl); void GenerateSnowFlakes(const CControl *ctrl);
void UpdateAreas (const CControl *ctrl); void UpdateAreas(const CControl *ctrl);
public: public:
void Init (int grade, const CControl *ctrl); void Init(int grade, const CControl *ctrl);
void Reset (); void Reset();
void Update (double timestep, const CControl *ctrl); void Update(double timestep, const CControl *ctrl);
void Draw (const CControl *ctrl) const; void Draw(const CControl *ctrl) const;
}; };
// -------------------------------------------------------------------- // --------------------------------------------------------------------
@ -150,19 +150,19 @@ struct TCurtain {
void Update(float timestep, const TVector3d& drift, const CControl* ctrl); void Update(float timestep, const TVector3d& drift, const CControl* ctrl);
private: private:
static void CurtainVec (float angle, float zdist, float &x, float &z); static void CurtainVec(float angle, float zdist, float &x, float &z);
}; };
class CCurtain { class CCurtain {
private: private:
vector<TCurtain> curtains; vector<TCurtain> curtains;
void SetStartParams (const CControl *ctrl); void SetStartParams(const CControl *ctrl);
public: public:
void Init (const CControl *ctrl); void Init(const CControl *ctrl);
void Update (float timestep, const CControl *ctrl); void Update(float timestep, const CControl *ctrl);
void Draw (); void Draw();
void Reset (); void Reset();
}; };
// -------------------------------------------------------------------- // --------------------------------------------------------------------
@ -203,18 +203,18 @@ private:
float WindChange; float WindChange;
float AngleChange; float AngleChange;
void SetParams (int grade); void SetParams(int grade);
void CalcDestSpeed (); void CalcDestSpeed();
void CalcDestAngle (); void CalcDestAngle();
public: public:
CWind (); CWind();
void Update (float timestep); void Update(float timestep);
void Init (int wind_id); void Init(int wind_id);
bool Windy () const { return windy; } bool Windy() const { return windy; }
float Angle () const { return WAngle; } float Angle() const { return WAngle; }
float Speed () const { return WSpeed; } float Speed() const { return WSpeed; }
const TVector3d& WindDrift () const { return WVector; } const TVector3d& WindDrift() const { return WVector; }
}; };
extern CWind Wind; extern CWind Wind;
@ -223,10 +223,10 @@ extern CWind Wind;
// Acess functions // Acess functions
// -------------------------------------------------------------------- // --------------------------------------------------------------------
void InitSnow (const CControl *ctrl); void InitSnow(const CControl *ctrl);
void UpdateSnow (double timestep, const CControl *ctrl); void UpdateSnow(double timestep, const CControl *ctrl);
void DrawSnow (const CControl *ctrl); void DrawSnow(const CControl *ctrl);
void InitWind (); void InitWind();
void UpdateWind (double timestep); void UpdateWind(double timestep);
#endif #endif

View File

@ -42,11 +42,11 @@ static bool fog = true;
static bool terr = true; static bool terr = true;
static bool trees = true; static bool trees = true;
void CPaused::Keyb (unsigned int key, bool special, bool release, int x, int y) { void CPaused::Keyb(unsigned int key, bool special, bool release, int x, int y) {
if (release) return; if (release) return;
switch (key) { switch (key) {
case SDLK_s: case SDLK_s:
ScreenshotN (); ScreenshotN();
break; break;
case SDLK_F5: case SDLK_F5:
sky = !sky; sky = !sky;
@ -61,41 +61,40 @@ void CPaused::Keyb (unsigned int key, bool special, bool release, int x, int y)
trees = !trees; trees = !trees;
break; break;
default: default:
State::manager.RequestEnterState (Racing); State::manager.RequestEnterState(Racing);
} }
} }
void CPaused::Mouse (int button, int state, int x, int y) { void CPaused::Mouse(int button, int state, int x, int y) {
State::manager.RequestEnterState (Racing); State::manager.RequestEnterState(Racing);
} }
// ==================================================================== // ====================================================================
void CPaused::Loop (double time_step) { void CPaused::Loop(double time_step) {
CControl *ctrl = g_game.player->ctrl; CControl *ctrl = g_game.player->ctrl;
int width = Winsys.resolution.width; int width = Winsys.resolution.width;
int height = Winsys.resolution.height; int height = Winsys.resolution.height;
check_gl_error();
Music.Update (); Music.Update();
ClearRenderContext (); ClearRenderContext();
Env.SetupFog (); Env.SetupFog();
update_view (ctrl, 0); update_view(ctrl, 0);
SetupViewFrustum (ctrl); SetupViewFrustum(ctrl);
if (sky) Env.DrawSkybox (ctrl->viewpos); if (sky) Env.DrawSkybox(ctrl->viewpos);
if (fog) Env.DrawFog (); if (fog) Env.DrawFog();
Env.SetupLight (); Env.SetupLight();
if (terr) RenderCourse(); if (terr) RenderCourse();
DrawTrackmarks (); DrawTrackmarks();
if (trees) DrawTrees(); if (trees) DrawTrees();
DrawSnow (ctrl); DrawSnow(ctrl);
if (param.perf_level > 2) draw_particles (ctrl); if (param.perf_level > 2) draw_particles(ctrl);
g_game.character->shape->Draw(); g_game.character->shape->Draw();
DrawHud (ctrl); DrawHud(ctrl);
Reshape (width, height); Reshape(width, height);
Winsys.SwapBuffers (); Winsys.SwapBuffers();
} }

View File

@ -28,7 +28,7 @@ GNU General Public License for more details.
#include "game_over.h" #include "game_over.h"
#include <algorithm> #include <algorithm>
CControl::CControl () : CControl::CControl() :
cnet_force(0, 0, 0) { cnet_force(0, 0, 0) {
minSpeed = 0; minSpeed = 0;
minFrictspeed = 0; minFrictspeed = 0;
@ -62,11 +62,11 @@ CControl::CControl () :
// init // init
// -------------------------------------------------------------------- // --------------------------------------------------------------------
void CControl::Init () { void CControl::Init() {
TVector3d nml = Course.FindCourseNormal (cpos.x, cpos.z); TVector3d nml = Course.FindCourseNormal(cpos.x, cpos.z);
TMatrix<4, 4> rotMat; TMatrix<4, 4> rotMat;
rotMat.SetRotationMatrix(-90.0, 'x'); rotMat.SetRotationMatrix(-90.0, 'x');
TVector3d init_vel = TransformVector (rotMat, nml); TVector3d init_vel = TransformVector(rotMat, nml);
init_vel *= INIT_TUX_SPEED; init_vel *= INIT_TUX_SPEED;
turn_fact = 0; turn_fact = 0;
@ -76,10 +76,10 @@ void CControl::Init () {
is_paddling = false; is_paddling = false;
jumping = false; jumping = false;
jump_charging = false; jump_charging = false;
cpos.y = Course.FindYCoord (cpos.x, cpos.z); cpos.y = Course.FindYCoord(cpos.x, cpos.z);
cvel = init_vel; cvel = init_vel;
last_pos = cpos; last_pos = cpos;
cnet_force = TVector3d (0, 0, 0); cnet_force = TVector3d(0, 0, 0);
orientation_initialized = false; orientation_initialized = false;
plane_nml = nml; plane_nml = nml;
cdirection = init_vel; cdirection = init_vel;
@ -100,36 +100,28 @@ void CControl::Init () {
// collision // collision
// -------------------------------------------------------------------- // --------------------------------------------------------------------
bool CControl::CheckTreeCollisions (const TVector3d& pos, TVector3d *tree_loc, double *tree_diam) { bool CControl::CheckTreeCollisions(const TVector3d& pos, TVector3d *tree_loc) {
// These variables are used to cache collision detection results // These variables are used to cache collision detection results
static bool last_collision = false; static bool last_collision = false;
static TVector3d last_collision_tree_loc(-999, -999, -999); static TVector3d last_collision_tree_loc(-999, -999, -999);
static double last_collision_tree_diam = 0;
static TVector3d last_collision_pos(-999, -999, -999); static TVector3d last_collision_pos(-999, -999, -999);
TVector3d dist_vec = pos - last_collision_pos; TVector3d dist_vec = pos - last_collision_pos;
if (MAG_SQD (dist_vec) < COLL_TOLERANCE) { if (MAG_SQD(dist_vec) < COLL_TOLERANCE) {
if (last_collision && !cairborne) { if (last_collision && !cairborne) {
if (tree_loc != NULL) *tree_loc = last_collision_tree_loc; if (tree_loc != NULL) *tree_loc = last_collision_tree_loc;
if (tree_diam != NULL) *tree_diam = last_collision_tree_diam;
return true; return true;
} else return false; } else return false;
} }
double diam = 0.0;
TVector3d loc(0, 0, 0); TVector3d loc(0, 0, 0);
bool hit = false; bool hit = false;
TMatrix<4, 4> mat; TMatrix<4, 4> mat;
TCollidable *trees = &Course.CollArr[0]; for (size_t i = 0; i<Course.CollArr.size(); i++) {
size_t num_trees = Course.CollArr.size(); double diam = Course.CollArr[i].diam;
size_t tree_type = trees[0].tree_type; double height = Course.CollArr[i].height;
const TPolyhedron* ph = &Course.GetPoly (tree_type); loc = Course.CollArr[i].pt;
for (size_t i=0; i<num_trees; i++) {
diam = trees[i].diam;
double height = trees[i].height;
loc = trees[i].pt;
TVector3d distvec(loc.x - pos.x, 0.0, loc.z - pos.z); TVector3d distvec(loc.x - pos.x, 0.0, loc.z - pos.z);
// check distance from tree; .6 is the radius of a bounding sphere // check distance from tree; .6 is the radius of a bounding sphere
@ -137,42 +129,31 @@ bool CControl::CheckTreeCollisions (const TVector3d& pos, TVector3d *tree_loc, d
squared_dist *= squared_dist; squared_dist *= squared_dist;
if (MAG_SQD(distvec) > squared_dist) continue; if (MAG_SQD(distvec) > squared_dist) continue;
// have to look at polyhedron - switch to correct one if necessary TPolyhedron ph2 = Course.GetPoly(Course.CollArr[i].tree_type);
if (tree_type != trees[i].tree_type) {
tree_type = trees[i].tree_type;
ph = &Course.GetPoly (tree_type);
}
TPolyhedron ph2 = *ph;
mat.SetScalingMatrix(diam, height, diam); mat.SetScalingMatrix(diam, height, diam);
TransPolyhedron (mat, ph2); TransPolyhedron(mat, ph2);
mat.SetTranslationMatrix(loc.x, loc.y, loc.z); mat.SetTranslationMatrix(loc.x, loc.y, loc.z);
TransPolyhedron (mat, ph2); TransPolyhedron(mat, ph2);
// hit = TuxCollision2 (pos, ph2);
hit = g_game.character->shape->Collision(pos, ph2);
hit = g_game.character->shape->Collision(pos, ph2);
if (hit == true) { if (hit == true) {
if (tree_loc != NULL) *tree_loc = loc; if (tree_loc != NULL) *tree_loc = loc;
if (tree_diam != NULL) *tree_diam = diam; Sound.Play("tree_hit", 0);
Sound.Play ("tree_hit", 0);
break; break;
} }
} }
last_collision_tree_loc = loc; last_collision_tree_loc = loc;
last_collision_tree_diam = diam;
last_collision_pos = pos; last_collision_pos = pos;
last_collision = hit;
if (hit) last_collision = true;
else last_collision = false;
return hit; return hit;
} }
void CControl::AdjustTreeCollision (const TVector3d& pos, TVector3d *vel) { void CControl::AdjustTreeCollision(const TVector3d& pos, TVector3d *vel) {
TVector3d treeLoc; TVector3d treeLoc;
double tree_diam;
if (CheckTreeCollisions (pos, &treeLoc, &tree_diam)) { if (CheckTreeCollisions(pos, &treeLoc)) {
TVector3d treeNml( TVector3d treeNml(
pos.x - treeLoc.x, pos.x - treeLoc.x,
0, 0,
@ -182,7 +163,7 @@ void CControl::AdjustTreeCollision (const TVector3d& pos, TVector3d *vel) {
double speed = vel->Norm(); double speed = vel->Norm();
speed *= 0.8; // original 0.7 speed *= 0.8; // original 0.7
double costheta = DotProduct (*vel, treeNml); double costheta = DotProduct(*vel, treeNml);
if (costheta < 0) { if (costheta < 0) {
double factor; double factor;
if (cairborne) factor = 0.5; if (cairborne) factor = 0.5;
@ -190,16 +171,12 @@ void CControl::AdjustTreeCollision (const TVector3d& pos, TVector3d *vel) {
*vel += (-factor * costheta) * treeNml; *vel += (-factor * costheta) * treeNml;
vel->Norm(); vel->Norm();
} }
speed = max (speed, minSpeed); speed = max(speed, minSpeed);
*vel *= speed; *vel *= speed;
} }
} }
void CControl::CheckItemCollection (const TVector3d& pos) { void CControl::CheckItemCollection(const TVector3d& pos) {
static TVector3d last_collision_pos(-999, -999, -999);
TVector3d dist_vec = pos - last_collision_pos;
if (MAG_SQD (dist_vec) < COLL_TOLERANCE) return;
TItem *items = &Course.NocollArr[0]; TItem *items = &Course.NocollArr[0];
size_t num_items = Course.NocollArr.size(); size_t num_items = Course.NocollArr.size();
@ -210,20 +187,15 @@ void CControl::CheckItemCollection (const TVector3d& pos) {
double height = items[i].height; double height = items[i].height;
const TVector3d& loc = items[i].pt; const TVector3d& loc = items[i].pt;
TVector3d distvec(loc.x - pos.x, 0.0, loc.z - pos.z); TVector3d distvec(loc.x - pos.x, loc.y - pos.y, loc.z - pos.z);
double squared_dist = (diam / 2. + 0.6); double squared_dist = (diam / 2. + 0.7);
squared_dist *= squared_dist; squared_dist *= squared_dist;
if (MAG_SQD (distvec) > squared_dist) continue; if (MAG_SQD(distvec) <= squared_dist) { // Check collision using a bounding sphere
if ((pos.y - 0.6 >= loc.y && pos.y - 0.6 <= loc.y + height) ||
(pos.y + 0.6 >= loc.y && pos.y + 0.6 <= loc.y + height) ||
(pos.y - 0.6 <= loc.y && pos.y + 0.6 >= loc.y + height)) {
items[i].collectable = 0; items[i].collectable = 0;
g_game.herring += 1; g_game.herring += 1;
Sound.HaltAll (); Sound.Play("pickup1", 0);
Sound.Play ("pickup1", 0); Sound.Play("pickup2", 0);
Sound.Play ("pickup2", 0); Sound.Play("pickup3", 0);
Sound.Play ("pickup3", 0);
} }
} }
} }
@ -231,26 +203,26 @@ void CControl::CheckItemCollection (const TVector3d& pos) {
// position and velocity *** // position and velocity ***
// -------------------------------------------------------------------- // --------------------------------------------------------------------
void CControl::AdjustVelocity (const TPlane& surf_plane) { void CControl::AdjustVelocity(const TPlane& surf_plane) {
double speed = cvel.Norm(); double speed = cvel.Norm();
speed = max (minSpeed, speed); speed = max(minSpeed, speed);
cvel *= speed; cvel *= speed;
if (g_game.finish == true) { if (g_game.finish == true) {
/// --------------- finish ------------------------------------ /// --------------- finish ------------------------------------
if (speed < 3) State::manager.RequestEnterState (GameOver); if (speed < 3) State::manager.RequestEnterState(GameOver);
/// ----------------------------------------------------------- /// -----------------------------------------------------------
} }
} }
void CControl::AdjustPosition (const TPlane& surf_plane, double dist_from_surface) { void CControl::AdjustPosition(const TPlane& surf_plane, double dist_from_surface) {
if (dist_from_surface < -MAX_SURF_PEN) { if (dist_from_surface < -MAX_SURF_PEN) {
double displace = -MAX_SURF_PEN - dist_from_surface; double displace = -MAX_SURF_PEN - dist_from_surface;
cpos += displace * surf_plane.nml; cpos += displace * surf_plane.nml;
} }
} }
void CControl::SetTuxPosition (double speed) { void CControl::SetTuxPosition(double speed) {
CCharShape *shape = g_game.character->shape; CCharShape *shape = g_game.character->shape;
TVector2d playSize = Course.GetPlayDimensions(); TVector2d playSize = Course.GetPlayDimensions();
@ -267,69 +239,69 @@ void CControl::SetTuxPosition (double speed) {
g_game.finish = true; g_game.finish = true;
finish_speed = speed; finish_speed = speed;
// SetStationaryCamera (true); // SetStationaryCamera (true);
} else State::manager.RequestEnterState (GameOver); } else State::manager.RequestEnterState(GameOver);
} }
/// ----------------------------------------------------------- /// -----------------------------------------------------------
} }
double disp_y = cpos.y + TUX_Y_CORR; double disp_y = cpos.y + TUX_Y_CORR;
shape->ResetNode (0); shape->ResetNode(0);
shape->TranslateNode (0, TVector3d (cpos.x, disp_y, cpos.z)); shape->TranslateNode(0, TVector3d(cpos.x, disp_y, cpos.z));
} }
// -------------------------------------------------------------------- // --------------------------------------------------------------------
// forces *** // forces ***
// -------------------------------------------------------------------- // --------------------------------------------------------------------
TVector3d CControl::CalcRollNormal (double speed) { TVector3d CControl::CalcRollNormal(double speed) {
TVector3d vel = ProjectToPlane (ff.surfnml, ff.vel); TVector3d vel = ProjectToPlane(ff.surfnml, ff.vel);
vel.Norm(); vel.Norm();
double roll_angle = MAX_ROLL_ANGLE; double roll_angle = MAX_ROLL_ANGLE;
if (is_braking) roll_angle = BRAKING_ROLL_ANGLE; if (is_braking) roll_angle = BRAKING_ROLL_ANGLE;
double angle = turn_fact * roll_angle * double angle = turn_fact * roll_angle *
min (1.0, max (0.0, ff.frict_coeff) / IDEAL_ROLL_FRIC) * min(1.0, max(0.0, ff.frict_coeff) / IDEAL_ROLL_FRIC) *
min (1.0, max (0.0, speed - minSpeed) / (IDEAL_ROLL_SPEED - minSpeed)); min(1.0, max(0.0, speed - minSpeed) / (IDEAL_ROLL_SPEED - minSpeed));
TMatrix<4, 4> rot_mat = RotateAboutVectorMatrix(vel, angle); TMatrix<4, 4> rot_mat = RotateAboutVectorMatrix(vel, angle);
return TransformVector (rot_mat, ff.surfnml); return TransformVector(rot_mat, ff.surfnml);
} }
const double airlog[] = {-1, 0, 1, 2, 3, 4, 5, 6}; const double airlog[] = {-1, 0, 1, 2, 3, 4, 5, 6};
const double airdrag[] = {2.25, 1.35, 0.6, 0, -0.35, -0.45, -0.33, -0.9}; const double airdrag[] = {2.25, 1.35, 0.6, 0, -0.35, -0.45, -0.33, -0.9};
TVector3d CControl::CalcAirForce () { TVector3d CControl::CalcAirForce() {
TVector3d windvec = -1.0 * ff.vel; TVector3d windvec = -1.0 * ff.vel;
if (g_game.wind_id > 0) if (g_game.wind_id > 0)
windvec += WIND_FACTOR * Wind.WindDrift(); windvec += WIND_FACTOR * Wind.WindDrift();
double windspeed = windvec.Length(); double windspeed = windvec.Length();
double re = 34600 * windspeed; double re = 34600 * windspeed;
int tablesize = sizeof (airdrag) / sizeof (airdrag[0]); int tablesize = sizeof(airdrag) / sizeof(airdrag[0]);
double interpol = LinearInterp (airlog, airdrag, log10 (re), tablesize); double interpol = LinearInterp(airlog, airdrag, log10(re), tablesize);
double dragcoeff = pow (10.0, interpol); double dragcoeff = pow(10.0, interpol);
double airfact = 0.104 * dragcoeff * windspeed; double airfact = 0.104 * dragcoeff * windspeed;
return airfact * windvec; return airfact * windvec;
} }
TVector3d CControl::CalcSpringForce () { TVector3d CControl::CalcSpringForce() {
double springvel = DotProduct (ff.vel, ff.rollnml); double springvel = DotProduct(ff.vel, ff.rollnml);
double springfact = min (ff.compression, 0.05) * 1500; double springfact = min(ff.compression, 0.05) * 1500;
springfact += clamp (0.0, ff.compression - 0.05, 0.12) * 3000; springfact += clamp(0.0, ff.compression - 0.05, 0.12) * 3000;
springfact += max (0.0, ff.compression - 0.12 - 0.05) * 10000; springfact += max(0.0, ff.compression - 0.12 - 0.05) * 10000;
springfact -= springvel * (ff.compression <= 0.05 ? 1500 : 500); springfact -= springvel * (ff.compression <= 0.05 ? 1500 : 500);
springfact = clamp (0.0, springfact, 3000.0); springfact = clamp(0.0, springfact, 3000.0);
return springfact * ff.rollnml; return springfact * ff.rollnml;
} }
TVector3d CControl::CalcNormalForce () { TVector3d CControl::CalcNormalForce() {
if (ff.surfdistance <= -ff.comp_depth) { if (ff.surfdistance <= -ff.comp_depth) {
ff.compression = -ff.surfdistance - ff.comp_depth; ff.compression = -ff.surfdistance - ff.comp_depth;
return CalcSpringForce (); return CalcSpringForce();
} }
return TVector3d(0, 0, 0); return TVector3d(0, 0, 0);
} }
TVector3d CControl::CalcJumpForce () { TVector3d CControl::CalcJumpForce() {
TVector3d jumpforce; TVector3d jumpforce;
if (begin_jump == true) { if (begin_jump == true) {
begin_jump = false; begin_jump = false;
@ -348,26 +320,26 @@ TVector3d CControl::CalcJumpForce () {
return jumpforce; // normally scaled with 1.0 return jumpforce; // normally scaled with 1.0
} }
TVector3d CControl::CalcFrictionForce (double speed, const TVector3d& nmlforce) { TVector3d CControl::CalcFrictionForce(double speed, const TVector3d& nmlforce) {
if ((cairborne == false && speed > minFrictspeed) || g_game.finish) { if ((cairborne == false && speed > minFrictspeed) || g_game.finish) {
double fric_f_mag = nmlforce.Length() * ff.frict_coeff; double fric_f_mag = nmlforce.Length() * ff.frict_coeff;
fric_f_mag = min (MAX_FRICT_FORCE, fric_f_mag); fric_f_mag = min(MAX_FRICT_FORCE, fric_f_mag);
TVector3d frictforce = fric_f_mag * ff.frictdir; TVector3d frictforce = fric_f_mag * ff.frictdir;
double steer_angle = turn_fact * MAX_TURN_ANGLE; double steer_angle = turn_fact * MAX_TURN_ANGLE;
if (fabs (fric_f_mag * sin (steer_angle * M_PI / 180)) > MAX_TURN_PERP) { if (fabs(fric_f_mag * sin(steer_angle * M_PI / 180)) > MAX_TURN_PERP) {
steer_angle = RADIANS_TO_ANGLES (asin (MAX_TURN_PERP / fric_f_mag)) * steer_angle = RADIANS_TO_ANGLES(asin(MAX_TURN_PERP / fric_f_mag)) *
turn_fact / fabs (turn_fact); turn_fact / fabs(turn_fact);
} }
TMatrix<4, 4> fric_rot_mat = RotateAboutVectorMatrix(ff.surfnml, steer_angle); TMatrix<4, 4> fric_rot_mat = RotateAboutVectorMatrix(ff.surfnml, steer_angle);
frictforce = TransformVector (fric_rot_mat, frictforce); frictforce = TransformVector(fric_rot_mat, frictforce);
return (1.0 + MAX_TURN_PEN) * frictforce; return (1.0 + MAX_TURN_PEN) * frictforce;
} }
return TVector3d (0, 0, 0); return TVector3d(0, 0, 0);
} }
TVector3d CControl::CalcBrakeForce (double speed) { TVector3d CControl::CalcBrakeForce(double speed) {
if (g_game.finish == false) { if (g_game.finish == false) {
if (cairborne == false && speed > minFrictspeed) { if (cairborne == false && speed > minFrictspeed) {
if (speed > minSpeed && is_braking) { if (speed > minSpeed && is_braking) {
@ -388,7 +360,7 @@ TVector3d CControl::CalcBrakeForce (double speed) {
return TVector3d(0, 0, 0); return TVector3d(0, 0, 0);
} }
TVector3d CControl::CalcPaddleForce (double speed) { TVector3d CControl::CalcPaddleForce(double speed) {
TVector3d paddleforce(0, 0, 0); TVector3d paddleforce(0, 0, 0);
if (is_paddling) if (is_paddling)
if (g_game.time - paddle_time >= PADDLING_DURATION) is_paddling = false; if (g_game.time - paddle_time >= PADDLING_DURATION) is_paddling = false;
@ -396,7 +368,7 @@ TVector3d CControl::CalcPaddleForce (double speed) {
if (is_paddling) { if (is_paddling) {
if (cairborne) { if (cairborne) {
paddleforce.z = -TUX_MASS * EARTH_GRAV / 4.0; paddleforce.z = -TUX_MASS * EARTH_GRAV / 4.0;
paddleforce = RotateVector (corientation, paddleforce); paddleforce = RotateVector(corientation, paddleforce);
} else { } else {
double factor = -1 * min(MAX_PADD_FORCE, MAX_PADD_FORCE double factor = -1 * min(MAX_PADD_FORCE, MAX_PADD_FORCE
* (MAX_PADDLING_SPEED - speed) / MAX_PADDLING_SPEED * (MAX_PADDLING_SPEED - speed) / MAX_PADDLING_SPEED
@ -407,18 +379,18 @@ TVector3d CControl::CalcPaddleForce (double speed) {
return PADDLE_FACT * paddleforce; return PADDLE_FACT * paddleforce;
} }
TVector3d CControl::CalcGravitationForce () { TVector3d CControl::CalcGravitationForce() {
if (g_game.finish == false) { if (g_game.finish == false) {
return TVector3d (0, -EARTH_GRAV * TUX_MASS, 0); return TVector3d(0, -EARTH_GRAV * TUX_MASS, 0);
} else { } else {
/// ---------------- finish ----------------------------------- /// ---------------- finish -----------------------------------
if (cairborne) return TVector3d (0, -FIN_AIR_GRAV, 0); if (cairborne) return TVector3d(0, -FIN_AIR_GRAV, 0);
else return TVector3d (0, -FIN_GRAV, 0); else return TVector3d(0, -FIN_GRAV, 0);
/// ----------------------------------------------------------- /// -----------------------------------------------------------
} }
} }
TVector3d CControl::CalcNetForce (const TVector3d& pos, const TVector3d& vel) { TVector3d CControl::CalcNetForce(const TVector3d& pos, const TVector3d& vel) {
// pos and vel are temporary, see ODE solver // pos and vel are temporary, see ODE solver
ff.pos = pos; ff.pos = pos;
@ -431,7 +403,7 @@ TVector3d CControl::CalcNetForce (const TVector3d& pos, const TVector3d& vel) {
static vector<double> surfweights; static vector<double> surfweights;
if (surfweights.size() != Course.TerrList.size()) if (surfweights.size() != Course.TerrList.size())
surfweights.resize(Course.TerrList.size()); surfweights.resize(Course.TerrList.size());
Course.GetSurfaceType (ff.pos.x, ff.pos.z, &surfweights[0]); Course.GetSurfaceType(ff.pos.x, ff.pos.z, &surfweights[0]);
TTerrType *TerrList = &Course.TerrList[0]; TTerrType *TerrList = &Course.TerrList[0];
ff.frict_coeff = ff.comp_depth = 0; ff.frict_coeff = ff.comp_depth = 0;
for (size_t i=0; i<Course.TerrList.size(); i++) { for (size_t i=0; i<Course.TerrList.size(); i++) {
@ -439,20 +411,20 @@ TVector3d CControl::CalcNetForce (const TVector3d& pos, const TVector3d& vel) {
ff.comp_depth += surfweights[i] * TerrList[i].depth; ff.comp_depth += surfweights[i] * TerrList[i].depth;
} }
TPlane surfplane = Course.GetLocalCoursePlane (ff.pos); TPlane surfplane = Course.GetLocalCoursePlane(ff.pos);
ff.surfnml = surfplane.nml; ff.surfnml = surfplane.nml;
ff.rollnml = CalcRollNormal (speed); ff.rollnml = CalcRollNormal(speed);
ff.surfdistance = DistanceToPlane (surfplane, ff.pos); ff.surfdistance = DistanceToPlane(surfplane, ff.pos);
cairborne = (bool)(ff.surfdistance > 0); cairborne = (bool)(ff.surfdistance > 0);
// don't change this order: // don't change this order:
TVector3d gravforce = CalcGravitationForce (); TVector3d gravforce = CalcGravitationForce();
TVector3d nmlforce = CalcNormalForce (); TVector3d nmlforce = CalcNormalForce();
TVector3d jumpforce = CalcJumpForce (); TVector3d jumpforce = CalcJumpForce();
TVector3d frictforce = CalcFrictionForce (speed, nmlforce); TVector3d frictforce = CalcFrictionForce(speed, nmlforce);
TVector3d brakeforce = CalcBrakeForce (speed); TVector3d brakeforce = CalcBrakeForce(speed);
TVector3d airforce = CalcAirForce (); TVector3d airforce = CalcAirForce();
TVector3d paddleforce = CalcPaddleForce (speed); TVector3d paddleforce = CalcPaddleForce(speed);
return jumpforce + gravforce + nmlforce + frictforce + airforce + brakeforce + paddleforce; return jumpforce + gravforce + nmlforce + frictforce + airforce + brakeforce + paddleforce;
} }
@ -461,21 +433,21 @@ TVector3d CControl::CalcNetForce (const TVector3d& pos, const TVector3d& vel) {
// ODE solver // ODE solver
// -------------------------------------------------------------------- // --------------------------------------------------------------------
double CControl::AdjustTimeStep (double h, const TVector3d& vel) { double CControl::AdjustTimeStep(double h, const TVector3d& vel) {
double speed = vel.Length(); double speed = vel.Length();
h = clamp (MIN_TIME_STEP, h, MAX_STEP_DIST / speed); h = clamp(MIN_TIME_STEP, h, MAX_STEP_DIST / speed);
h = min (h, MAX_TIME_STEP); h = min(h, MAX_TIME_STEP);
return h; return h;
} }
void CControl::SolveOdeSystem (double timestep) { void CControl::SolveOdeSystem(double timestep) {
double pos_err[3], vel_err[3], tot_pos_err, tot_vel_err; double pos_err[3], vel_err[3], tot_pos_err, tot_vel_err;
double err=0, tol=0; double err=0, tol=0;
static const TOdeSolver solver; static const TOdeSolver solver;
double h = ode_time_step; double h = ode_time_step;
if (h < 0 || solver.EstimateError == NULL) if (h < 0 || solver.EstimateError == NULL)
h = AdjustTimeStep (timestep, cvel); h = AdjustTimeStep(timestep, cvel);
double t = 0; double t = 0;
double tfinal = timestep; double tfinal = timestep;
@ -493,7 +465,7 @@ void CControl::SolveOdeSystem (double timestep) {
bool done = false; bool done = false;
while (!done) { while (!done) {
if (t >= tfinal) { if (t >= tfinal) {
Message ("t >= tfinal in ode_system()"); Message("t >= tfinal in ode_system()");
break; break;
} }
if (1.1 * h > tfinal - t) { if (1.1 * h > tfinal - t) {
@ -506,55 +478,55 @@ void CControl::SolveOdeSystem (double timestep) {
bool failed = false; bool failed = false;
for (;;) { for (;;) {
solver.InitOdeData (&x, new_pos.x, h); solver.InitOdeData(&x, new_pos.x, h);
solver.InitOdeData (&y, new_pos.y, h); solver.InitOdeData(&y, new_pos.y, h);
solver.InitOdeData (&z, new_pos.z, h); solver.InitOdeData(&z, new_pos.z, h);
solver.InitOdeData (&vx, new_vel.x, h); solver.InitOdeData(&vx, new_vel.x, h);
solver.InitOdeData (&vy, new_vel.y, h); solver.InitOdeData(&vy, new_vel.y, h);
solver.InitOdeData (&vz, new_vel.z, h); solver.InitOdeData(&vz, new_vel.z, h);
solver.UpdateEstimate (&x, 0, new_vel.x); solver.UpdateEstimate(&x, 0, new_vel.x);
solver.UpdateEstimate (&y, 0, new_vel.y); solver.UpdateEstimate(&y, 0, new_vel.y);
solver.UpdateEstimate (&z, 0, new_vel.z); solver.UpdateEstimate(&z, 0, new_vel.z);
solver.UpdateEstimate (&vx, 0, new_f.x / TUX_MASS); solver.UpdateEstimate(&vx, 0, new_f.x / TUX_MASS);
solver.UpdateEstimate (&vy, 0, new_f.y / TUX_MASS); solver.UpdateEstimate(&vy, 0, new_f.y / TUX_MASS);
solver.UpdateEstimate (&vz, 0, new_f.z / TUX_MASS); solver.UpdateEstimate(&vz, 0, new_f.z / TUX_MASS);
for (int i=1; i < solver.NumEstimates(); i++) { for (int i=1; i < solver.NumEstimates(); i++) {
new_pos.x = solver.NextValue (&x, i); new_pos.x = solver.NextValue(&x, i);
new_pos.y = solver.NextValue (&y, i); new_pos.y = solver.NextValue(&y, i);
new_pos.z = solver.NextValue (&z, i); new_pos.z = solver.NextValue(&z, i);
new_vel.x = solver.NextValue (&vx, i); new_vel.x = solver.NextValue(&vx, i);
new_vel.y = solver.NextValue (&vy, i); new_vel.y = solver.NextValue(&vy, i);
new_vel.z = solver.NextValue (&vz, i); new_vel.z = solver.NextValue(&vz, i);
solver.UpdateEstimate (&x, i, new_vel.x); solver.UpdateEstimate(&x, i, new_vel.x);
solver.UpdateEstimate (&y, i, new_vel.y); solver.UpdateEstimate(&y, i, new_vel.y);
solver.UpdateEstimate (&z, i, new_vel.z); solver.UpdateEstimate(&z, i, new_vel.z);
new_f = CalcNetForce (new_pos, new_vel); new_f = CalcNetForce(new_pos, new_vel);
solver.UpdateEstimate (&vx, i, new_f.x / TUX_MASS); solver.UpdateEstimate(&vx, i, new_f.x / TUX_MASS);
solver.UpdateEstimate (&vy, i, new_f.y / TUX_MASS); solver.UpdateEstimate(&vy, i, new_f.y / TUX_MASS);
solver.UpdateEstimate (&vz, i, new_f.z / TUX_MASS); solver.UpdateEstimate(&vz, i, new_f.z / TUX_MASS);
} }
new_pos.x = solver.FinalEstimate (&x); new_pos.x = solver.FinalEstimate(&x);
new_pos.y = solver.FinalEstimate (&y); new_pos.y = solver.FinalEstimate(&y);
new_pos.z = solver.FinalEstimate (&z); new_pos.z = solver.FinalEstimate(&z);
new_vel.x = solver.FinalEstimate (&vx); new_vel.x = solver.FinalEstimate(&vx);
new_vel.y = solver.FinalEstimate (&vy); new_vel.y = solver.FinalEstimate(&vy);
new_vel.z = solver.FinalEstimate (&vz); new_vel.z = solver.FinalEstimate(&vz);
if (solver.EstimateError != NULL) { if (solver.EstimateError != NULL) {
pos_err[0] = solver.EstimateError (&x); pos_err[0] = solver.EstimateError(&x);
pos_err[1] = solver.EstimateError (&y); pos_err[1] = solver.EstimateError(&y);
pos_err[2] = solver.EstimateError (&z); pos_err[2] = solver.EstimateError(&z);
vel_err[0] = solver.EstimateError (&vx); vel_err[0] = solver.EstimateError(&vx);
vel_err[1] = solver.EstimateError (&vy); vel_err[1] = solver.EstimateError(&vy);
vel_err[2] = solver.EstimateError (&vz); vel_err[2] = solver.EstimateError(&vz);
tot_pos_err = 0.; tot_pos_err = 0.;
tot_vel_err = 0.; tot_vel_err = 0.;
@ -565,8 +537,8 @@ void CControl::SolveOdeSystem (double timestep) {
vel_err[i] *= vel_err[i]; vel_err[i] *= vel_err[i];
tot_vel_err += vel_err[i]; tot_vel_err += vel_err[i];
} }
tot_pos_err = sqrt (tot_pos_err); tot_pos_err = sqrt(tot_pos_err);
tot_vel_err = sqrt (tot_vel_err); tot_vel_err = sqrt(tot_vel_err);
if (tot_pos_err / MAX_POS_ERR > tot_vel_err / MAX_VEL_ERR) { if (tot_pos_err / MAX_POS_ERR > tot_vel_err / MAX_VEL_ERR) {
err = tot_pos_err; err = tot_pos_err;
tol = MAX_POS_ERR; tol = MAX_POS_ERR;
@ -579,10 +551,10 @@ void CControl::SolveOdeSystem (double timestep) {
done = false; done = false;
if (!failed) { if (!failed) {
failed = true; failed = true;
h *= max (0.5, 0.8 * pow (tol/err, solver.TimestepExponent())); h *= max(0.5, 0.8 * pow(tol/err, solver.TimestepExponent()));
} else h *= 0.5; } else h *= 0.5;
h = AdjustTimeStep (h, saved_vel); h = AdjustTimeStep(h, saved_vel);
new_pos = saved_pos; new_pos = saved_pos;
new_vel = saved_vel; new_vel = saved_vel;
new_f = saved_f; new_f = saved_f;
@ -592,19 +564,19 @@ void CControl::SolveOdeSystem (double timestep) {
t = t + h; t = t + h;
double speed = new_vel.Length(); double speed = new_vel.Length();
if (param.perf_level > 2) generate_particles (this, h, new_pos, speed); if (param.perf_level > 2) generate_particles(this, h, new_pos, speed);
new_f = CalcNetForce (new_pos, new_vel); new_f = CalcNetForce(new_pos, new_vel);
if (!failed && solver.EstimateError != NULL) { if (!failed && solver.EstimateError != NULL) {
double temp = 1.25 * pow (err / tol, solver.TimestepExponent()); double temp = 1.25 * pow(err / tol, solver.TimestepExponent());
if (temp > 0.2) h = h / temp; if (temp > 0.2) h = h / temp;
else h = 5.0 * h; else h = 5.0 * h;
} }
h = AdjustTimeStep (h, new_vel); h = AdjustTimeStep(h, new_vel);
AdjustTreeCollision (new_pos, &new_vel); AdjustTreeCollision(new_pos, &new_vel);
// if (g_game.finish) new_vel = ScaleVector (0.99,new_vel); // if (g_game.finish) new_vel = ScaleVector (0.99,new_vel);
CheckItemCollection (new_pos); CheckItemCollection(new_pos);
} }
ode_time_step = h; ode_time_step = h;
cnet_force = new_f; cnet_force = new_f;
@ -621,7 +593,7 @@ void CControl::SolveOdeSystem (double timestep) {
// update tux position // update tux position
// -------------------------------------------------------------------- // --------------------------------------------------------------------
void CControl::UpdatePlayerPos (double timestep) { void CControl::UpdatePlayerPos(double timestep) {
CCharShape *shape = g_game.character->shape; CCharShape *shape = g_game.character->shape;
double paddling_factor; double paddling_factor;
double flap_factor; double flap_factor;
@ -637,17 +609,17 @@ void CControl::UpdatePlayerPos (double timestep) {
minFrictspeed = MIN_FRICT_SPEED; minFrictspeed = MIN_FRICT_SPEED;
} }
if (timestep > 2 * EPS) SolveOdeSystem (timestep); if (timestep > 2 * EPS) SolveOdeSystem(timestep);
TPlane surf_plane = Course.GetLocalCoursePlane (cpos); TPlane surf_plane = Course.GetLocalCoursePlane(cpos);
TVector3d surf_nml = surf_plane.nml; // normal vector of terrain TVector3d surf_nml = surf_plane.nml; // normal vector of terrain
dist_from_surface = DistanceToPlane (surf_plane, cpos); dist_from_surface = DistanceToPlane(surf_plane, cpos);
double speed = cvel.Length(); double speed = cvel.Length();
AdjustVelocity (surf_plane); AdjustVelocity(surf_plane);
AdjustPosition (surf_plane, dist_from_surface); AdjustPosition(surf_plane, dist_from_surface);
SetTuxPosition (speed); // speed only to set finish_speed SetTuxPosition(speed); // speed only to set finish_speed
shape->AdjustOrientation (this, timestep, dist_from_surface, surf_nml); shape->AdjustOrientation(this, timestep, dist_from_surface, surf_nml);
flap_factor = 0; flap_factor = 0;
if (is_paddling) { if (is_paddling) {
@ -665,11 +637,11 @@ void CControl::UpdatePlayerPos (double timestep) {
} }
TVector3d local_force = RotateVector TVector3d local_force = RotateVector
(ConjugateQuaternion (corientation), cnet_force); (ConjugateQuaternion(corientation), cnet_force);
if (jumping) if (jumping)
flap_factor = (g_game.time - jump_start_time) / JUMP_FORCE_DURATION; flap_factor = (g_game.time - jump_start_time) / JUMP_FORCE_DURATION;
shape->AdjustJoints (turn_animation, is_braking, paddling_factor, speed, shape->AdjustJoints(turn_animation, is_braking, paddling_factor, speed,
local_force, flap_factor); local_force, flap_factor);
} }

View File

@ -81,29 +81,29 @@ private:
double ode_time_step; double ode_time_step;
double finish_speed; double finish_speed;
bool CheckTreeCollisions (const TVector3d& pos, TVector3d *tree_loc, double *tree_diam); bool CheckTreeCollisions(const TVector3d& pos, TVector3d *tree_loc);
void AdjustTreeCollision (const TVector3d& pos, TVector3d *vel); void AdjustTreeCollision(const TVector3d& pos, TVector3d *vel);
void CheckItemCollection (const TVector3d& pos); void CheckItemCollection(const TVector3d& pos);
TVector3d CalcRollNormal (double speed); TVector3d CalcRollNormal(double speed);
TVector3d CalcAirForce (); TVector3d CalcAirForce();
TVector3d CalcSpringForce (); TVector3d CalcSpringForce();
TVector3d CalcNormalForce (); TVector3d CalcNormalForce();
TVector3d CalcJumpForce (); TVector3d CalcJumpForce();
TVector3d CalcFrictionForce (double speed, const TVector3d& nmlforce); TVector3d CalcFrictionForce(double speed, const TVector3d& nmlforce);
TVector3d CalcPaddleForce (double speed); TVector3d CalcPaddleForce(double speed);
TVector3d CalcBrakeForce (double speed); TVector3d CalcBrakeForce(double speed);
TVector3d CalcGravitationForce (); TVector3d CalcGravitationForce();
TVector3d CalcNetForce (const TVector3d& pos, const TVector3d& vel); TVector3d CalcNetForce(const TVector3d& pos, const TVector3d& vel);
TVector3d CalcFinishForce (const TVector3d& pos, const TVector3d& vel); TVector3d CalcFinishForce(const TVector3d& pos, const TVector3d& vel);
void AdjustVelocity (const TPlane& surf_plane); void AdjustVelocity(const TPlane& surf_plane);
void AdjustPosition (const TPlane& surf_plane, double dist_from_surface); void AdjustPosition(const TPlane& surf_plane, double dist_from_surface);
void SetTuxPosition (double speed); void SetTuxPosition(double speed);
double AdjustTimeStep (double h, const TVector3d& vel); double AdjustTimeStep(double h, const TVector3d& vel);
void SolveOdeSystem (double timestep); void SolveOdeSystem(double timestep);
public: public:
CControl (); CControl();
// view: // view:
TViewMode viewmode; TViewMode viewmode;
@ -147,8 +147,8 @@ public:
double minSpeed; double minSpeed;
double minFrictspeed; double minFrictspeed;
void Init (); void Init();
void UpdatePlayerPos (double timestep); void UpdatePlayerPos(double timestep);
}; };
#endif #endif

View File

@ -65,7 +65,7 @@ GLuint quadsquare::VertexArrayCounter;
GLuint quadsquare::VertexArrayMinIdx; GLuint quadsquare::VertexArrayMinIdx;
GLuint quadsquare::VertexArrayMaxIdx; GLuint quadsquare::VertexArrayMaxIdx;
quadsquare::quadsquare (quadcornerdata* pcd) { quadsquare::quadsquare(quadcornerdata* pcd) {
pcd->Square = this; pcd->Square = this;
Static = false; Static = false;
ForceEastVert = false; ForceEastVert = false;
@ -107,7 +107,7 @@ quadsquare::~quadsquare() {
} }
} }
void quadsquare::SetStatic (const quadcornerdata &cd) { void quadsquare::SetStatic(const quadcornerdata &cd) {
if (Static == false) { if (Static == false) {
Static = true; Static = true;
if (cd.Parent && cd.Parent->Square) { if (cd.Parent && cd.Parent->Square) {
@ -360,7 +360,7 @@ float quadsquare::RecomputeError(const quadcornerdata& cd) {
if (total > 0) { if (total > 0) {
terrain_error = (1.0 - max_count / total); terrain_error = (1.0 - max_count / total);
if (numTerr > 1) { if (numTerr > 1) {
terrain_error *= numTerr / (numTerr - 1.0); terrain_error *= numTerr / (numTerr - 1.0);
} }
} else terrain_error = 0; } else terrain_error = 0;
terrain_error *= whole * whole; terrain_error *= whole * whole;
@ -571,10 +571,10 @@ static float DetailThreshold = 100;
bool quadsquare::VertexTest(int x, float y, int z, float error, bool quadsquare::VertexTest(int x, float y, int z, float error,
const float Viewer[3], int level, vertex_loc_t vertex_loc) { const float Viewer[3], int level, vertex_loc_t vertex_loc) {
float dx = fabs(x - Viewer[0]) * fabs (ScaleX); float dx = fabs(x - Viewer[0]) * fabs(ScaleX);
float dy = fabs(y - Viewer[1]); float dy = fabs(y - Viewer[1]);
float dz = fabs(z - Viewer[2]) * fabs (ScaleZ); float dz = fabs(z - Viewer[2]) * fabs(ScaleZ);
float d = max (dx, max (dy, dz) ); float d = max(dx, max(dy, dz));
if (vertex_loc == South && ForceSouthVert && d < VERTEX_FORCE_THRESHOLD) { if (vertex_loc == South && ForceSouthVert && d < VERTEX_FORCE_THRESHOLD) {
return true; return true;
@ -591,10 +591,10 @@ bool quadsquare::VertexTest(int x, float y, int z, float error,
bool quadsquare::BoxTest(int x, int z, float size, float miny, float maxy, float error, const float Viewer[3]) { bool quadsquare::BoxTest(int x, int z, float size, float miny, float maxy, float error, const float Viewer[3]) {
float half = size * 0.5; float half = size * 0.5;
float dx = (fabs(x + half - Viewer[0]) - half ) * fabs(ScaleX); float dx = (fabs(x + half - Viewer[0]) - half) * fabs(ScaleX);
float dy = fabs((miny + maxy) * 0.5 - Viewer[1]) - (maxy - miny) * 0.5; float dy = fabs((miny + maxy) * 0.5 - Viewer[1]) - (maxy - miny) * 0.5;
float dz = (fabs(z + half - Viewer[2]) - half ) * fabs(ScaleZ); float dz = (fabs(z + half - Viewer[2]) - half) * fabs(ScaleZ);
float d = max (dx, max (dy , dz) ); float d = max(dx, max(dy , dz));
if (d < ERROR_MAGNIFICATION_THRESHOLD) { if (d < ERROR_MAGNIFICATION_THRESHOLD) {
error *= ERROR_MAGNIFICATION_AMOUNT; error *= ERROR_MAGNIFICATION_AMOUNT;
@ -603,15 +603,15 @@ bool quadsquare::BoxTest(int x, int z, float size, float miny, float maxy, float
if (error * DetailThreshold > d) { if (error * DetailThreshold > d) {
return true; return true;
} }
if ( (x < RowSize-1 && x+size >= RowSize) || if ((x < RowSize-1 && x+size >= RowSize) ||
(z < NumRows-1 && z+size >= NumRows) ) { (z < NumRows-1 && z+size >= NumRows)) {
return true; return true;
} }
return false; return false;
} }
void quadsquare::Update (const quadcornerdata& cd, const TVector3d& ViewerLocation, float Detail) { void quadsquare::Update(const quadcornerdata& cd, const TVector3d& ViewerLocation, float Detail) {
float Viewer[3]; float Viewer[3];
DetailThreshold = Detail; DetailThreshold = Detail;
@ -622,10 +622,10 @@ void quadsquare::Update (const quadcornerdata& cd, const TVector3d& ViewerLocati
} }
void quadsquare::UpdateAux (const quadcornerdata& cd, void quadsquare::UpdateAux(const quadcornerdata& cd,
const float ViewerLocation[3], float CenterError, clip_result_t vis) { const float ViewerLocation[3], float CenterError, clip_result_t vis) {
if (vis != NoClip) { if (vis != NoClip) {
vis = ClipSquare (cd); vis = ClipSquare(cd);
if (vis == NotVisible) { if (vis == NotVisible) {
return; return;
@ -639,13 +639,13 @@ void quadsquare::UpdateAux (const quadcornerdata& cd,
int whole = half << 1; int whole = half << 1;
if ((EnabledFlags & 1) == 0 && if ((EnabledFlags & 1) == 0 &&
VertexTest(cd.xorg + whole, Vertex[1].Y, cd.zorg + half, VertexTest(cd.xorg + whole, Vertex[1].Y, cd.zorg + half,
Error[0], ViewerLocation, cd.Level, East) == true ) { Error[0], ViewerLocation, cd.Level, East) == true) {
EnableEdgeVertex(0, false, cd); EnableEdgeVertex(0, false, cd);
} }
if ((EnabledFlags & 8) == 0 && if ((EnabledFlags & 8) == 0 &&
VertexTest(cd.xorg + half, Vertex[4].Y, cd.zorg + whole, VertexTest(cd.xorg + half, Vertex[4].Y, cd.zorg + whole,
Error[1], ViewerLocation, cd.Level, South) == true ) { Error[1], ViewerLocation, cd.Level, South) == true) {
EnableEdgeVertex(3, false, cd); EnableEdgeVertex(3, false, cd);
} }
@ -732,11 +732,11 @@ void quadsquare::DrawTris() {
if (glLockArraysEXT_p) { if (glLockArraysEXT_p) {
if (tmp_min_idx == 0) tmp_min_idx = 1; if (tmp_min_idx == 0) tmp_min_idx = 1;
glLockArraysEXT_p (tmp_min_idx, VertexArrayMaxIdx - tmp_min_idx + 1); glLockArraysEXT_p(tmp_min_idx, VertexArrayMaxIdx - tmp_min_idx + 1);
} }
glDrawElements (GL_TRIANGLES, VertexArrayCounter, glDrawElements(GL_TRIANGLES, VertexArrayCounter,
GL_UNSIGNED_INT, VertexArrayIndices); GL_UNSIGNED_INT, VertexArrayIndices);
if (glUnlockArraysEXT_p) glUnlockArraysEXT_p(); if (glUnlockArraysEXT_p) glUnlockArraysEXT_p();
} }
@ -746,11 +746,11 @@ void quadsquare::InitArrayCounters() {
VertexArrayMaxIdx = 0; VertexArrayMaxIdx = 0;
} }
void quadsquare::Render (const quadcornerdata& cd, GLubyte *vnc_array) { void quadsquare::Render(const quadcornerdata& cd, GLubyte *vnc_array) {
VNCArray = vnc_array; VNCArray = vnc_array;
bool fog_on; bool fog_on;
int nx, ny; int nx, ny;
Course.GetDivisions (&nx, &ny); Course.GetDivisions(&nx, &ny);
const TTerrType *TerrList = &Course.TerrList[0]; const TTerrType *TerrList = &Course.TerrList[0];
size_t numTerrains = Course.TerrList.size(); size_t numTerrains = Course.TerrList.size();
@ -759,34 +759,34 @@ void quadsquare::Render (const quadcornerdata& cd, GLubyte *vnc_array) {
for (size_t j=0; j<numTerrains; j++) { for (size_t j=0; j<numTerrains; j++) {
if (TerrList[j].texture != NULL) { if (TerrList[j].texture != NULL) {
InitArrayCounters(); InitArrayCounters();
RenderAux (cd, SomeClip, (int)j); RenderAux(cd, SomeClip, (int)j);
if (VertexArrayCounter == 0) continue; if (VertexArrayCounter == 0) continue;
Course.TerrList[j].texture->Bind(); Course.TerrList[j].texture->Bind();
DrawTris (); DrawTris();
} }
} }
if (param.perf_level > 1) { if (param.perf_level > 1) {
InitArrayCounters(); InitArrayCounters();
RenderAux (cd, SomeClip, -1); RenderAux(cd, SomeClip, -1);
if (VertexArrayCounter != 0) { if (VertexArrayCounter != 0) {
glDisable (GL_FOG); glDisable(GL_FOG);
for (GLuint i=0; i<VertexArrayCounter; i++) { for (GLuint i=0; i<VertexArrayCounter; i++) {
colorval (VertexArrayIndices[i], 0) = 0; colorval(VertexArrayIndices[i], 0) = 0;
colorval (VertexArrayIndices[i], 1) = 0; colorval(VertexArrayIndices[i], 1) = 0;
colorval (VertexArrayIndices[i], 2) = 0; colorval(VertexArrayIndices[i], 2) = 0;
colorval (VertexArrayIndices[i], 3) = 255; colorval(VertexArrayIndices[i], 3) = 255;
} }
Course.TerrList[0].texture->Bind(); Course.TerrList[0].texture->Bind();
DrawTris(); DrawTris();
if (fog_on) glEnable (GL_FOG); if (fog_on) glEnable(GL_FOG);
glBlendFunc (GL_SRC_ALPHA, GL_ONE); glBlendFunc(GL_SRC_ALPHA, GL_ONE);
for (GLuint i=0; i<VertexArrayCounter; i++) { for (GLuint i=0; i<VertexArrayCounter; i++) {
colorval (VertexArrayIndices[i], 0) = 255; colorval(VertexArrayIndices[i], 0) = 255;
colorval (VertexArrayIndices[i], 1) = 255; colorval(VertexArrayIndices[i], 1) = 255;
colorval (VertexArrayIndices[i], 2) = 255; colorval(VertexArrayIndices[i], 2) = 255;
} }
for (size_t j=0; j<numTerrains; j++) { for (size_t j=0; j<numTerrains; j++) {
@ -794,18 +794,18 @@ void quadsquare::Render (const quadcornerdata& cd, GLubyte *vnc_array) {
Course.TerrList[j].texture->Bind(); Course.TerrList[j].texture->Bind();
for (GLuint i=0; i<VertexArrayCounter; i++) { for (GLuint i=0; i<VertexArrayCounter; i++) {
colorval (VertexArrayIndices[i], 3) = colorval(VertexArrayIndices[i], 3) =
(Terrain[VertexArrayIndices[i]] == (char)j ) ? 255 : 0; (Terrain[VertexArrayIndices[i]] == (char)j) ? 255 : 0;
} }
DrawTris(); DrawTris();
} }
} }
} }
} }
glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
} }
clip_result_t quadsquare::ClipSquare (const quadcornerdata& cd) { clip_result_t quadsquare::ClipSquare(const quadcornerdata& cd) {
if (cd.xorg >= RowSize-1) { if (cd.xorg >= RowSize-1) {
return NotVisible; return NotVisible;
} }
@ -851,52 +851,52 @@ clip_result_t quadsquare::ClipSquare (const quadcornerdata& cd) {
} }
inline void quadsquare::MakeTri (int a, int b, int c, int terrain) { inline void quadsquare::MakeTri(int a, int b, int c, int terrain) {
if ( (VertexTerrains[a] == terrain || if ((VertexTerrains[a] == terrain ||
VertexTerrains[b] == terrain || VertexTerrains[b] == terrain ||
VertexTerrains[c] == terrain) ) { VertexTerrains[c] == terrain)) {
VertexArrayIndices[VertexArrayCounter++] = VertexIndices[a]; VertexArrayIndices[VertexArrayCounter++] = VertexIndices[a];
setalphaval(a); setalphaval(a);
update_min_max (VertexIndices[a]); update_min_max(VertexIndices[a]);
VertexArrayIndices[VertexArrayCounter++] = VertexIndices[b]; VertexArrayIndices[VertexArrayCounter++] = VertexIndices[b];
setalphaval(b); setalphaval(b);
update_min_max (VertexIndices[b]); update_min_max(VertexIndices[b]);
VertexArrayIndices[VertexArrayCounter++] = VertexIndices[c]; VertexArrayIndices[VertexArrayCounter++] = VertexIndices[c];
setalphaval(c); setalphaval(c);
update_min_max (VertexIndices[c]); update_min_max(VertexIndices[c]);
} }
} }
inline void quadsquare::MakeSpecialTri (int a, int b, int c, int terrain) { inline void quadsquare::MakeSpecialTri(int a, int b, int c, int terrain) {
if (VertexTerrains[a] != VertexTerrains[b] && if (VertexTerrains[a] != VertexTerrains[b] &&
VertexTerrains[a] != VertexTerrains[c] && VertexTerrains[a] != VertexTerrains[c] &&
VertexTerrains[b] != VertexTerrains[c]) { VertexTerrains[b] != VertexTerrains[c]) {
VertexArrayIndices[VertexArrayCounter++] = VertexIndices[a]; VertexArrayIndices[VertexArrayCounter++] = VertexIndices[a];
update_min_max (VertexIndices[a]); update_min_max(VertexIndices[a]);
VertexArrayIndices[VertexArrayCounter++] = VertexIndices[b]; VertexArrayIndices[VertexArrayCounter++] = VertexIndices[b];
update_min_max (VertexIndices[b]); update_min_max(VertexIndices[b]);
VertexArrayIndices[VertexArrayCounter++] = VertexIndices[c]; VertexArrayIndices[VertexArrayCounter++] = VertexIndices[c];
update_min_max (VertexIndices[c]); update_min_max(VertexIndices[c]);
} }
} }
inline void quadsquare::MakeNoBlendTri (int a, int b, int c, int terrain) { inline void quadsquare::MakeNoBlendTri(int a, int b, int c, int terrain) {
if ( (VertexTerrains[a] == terrain || if ((VertexTerrains[a] == terrain ||
VertexTerrains[b] == terrain || VertexTerrains[b] == terrain ||
VertexTerrains[c] == terrain) && VertexTerrains[c] == terrain) &&
(VertexTerrains[a] >= terrain && (VertexTerrains[a] >= terrain &&
VertexTerrains[b] >= terrain && VertexTerrains[b] >= terrain &&
VertexTerrains[c] >= terrain) ) { VertexTerrains[c] >= terrain)) {
VertexArrayIndices[VertexArrayCounter++] = VertexIndices[a]; VertexArrayIndices[VertexArrayCounter++] = VertexIndices[a];
setalphaval(a); setalphaval(a);
update_min_max (VertexIndices[a]); update_min_max(VertexIndices[a]);
VertexArrayIndices[VertexArrayCounter++] = VertexIndices[b]; VertexArrayIndices[VertexArrayCounter++] = VertexIndices[b];
setalphaval(b); setalphaval(b);
update_min_max (VertexIndices[b]); update_min_max(VertexIndices[b]);
VertexArrayIndices[VertexArrayCounter++] = VertexIndices[c]; VertexArrayIndices[VertexArrayCounter++] = VertexIndices[c];
setalphaval(c); setalphaval(c);
update_min_max (VertexIndices[c]); update_min_max(VertexIndices[c]);
} }
} }
@ -904,7 +904,7 @@ void quadsquare::RenderAux(const quadcornerdata& cd, clip_result_t vis, int terr
int half = 1 << cd.Level; int half = 1 << cd.Level;
int whole = 2 << cd.Level; int whole = 2 << cd.Level;
if (vis != NoClip) { if (vis != NoClip) {
vis = ClipSquare (cd); vis = ClipSquare(cd);
if (vis == NotVisible) return; if (vis == NotVisible) return;
} }
@ -1062,7 +1062,7 @@ void quadsquare::SetScale(double x, double z) {
} }
char* quadsquare::Terrain; char* quadsquare::Terrain;
void quadsquare::SetTerrain (char *t) { void quadsquare::SetTerrain(char *t) {
Terrain = t; Terrain = t;
} }
@ -1092,16 +1092,16 @@ void ResetQuadtree() {
} }
} }
static int get_root_level (int nx, int nz) { static int get_root_level(int nx, int nz) {
int xlev = (int) (log(static_cast<double>(nx)) / log (2.0)); int xlev = (int)(log(static_cast<double>(nx)) / log(2.0));
int zlev = (int) (log(static_cast<double>(nz)) / log (2.0)); int zlev = (int)(log(static_cast<double>(nz)) / log(2.0));
return max (xlev, zlev); return max(xlev, zlev);
} }
void InitQuadtree (double *elevation, int nx, int nz, void InitQuadtree(double *elevation, int nx, int nz,
double scalex, double scalez, const TVector3d& view_pos, double detail) { double scalex, double scalez, const TVector3d& view_pos, double detail) {
HeightMapInfo hm; HeightMapInfo hm;
hm.Data = elevation; hm.Data = elevation;
@ -1114,7 +1114,7 @@ void InitQuadtree (double *elevation, int nx, int nz,
root_corner_data.Square = (quadsquare*)NULL; root_corner_data.Square = (quadsquare*)NULL;
root_corner_data.ChildIndex = 0; root_corner_data.ChildIndex = 0;
root_corner_data.Level = get_root_level (nx, nz); root_corner_data.Level = get_root_level(nx, nz);
root_corner_data.xorg = 0; root_corner_data.xorg = 0;
root_corner_data.zorg = 0; root_corner_data.zorg = 0;
@ -1123,19 +1123,19 @@ void InitQuadtree (double *elevation, int nx, int nz,
root_corner_data.Verts[i].Y = 0; root_corner_data.Verts[i].Y = 0;
} }
root = new quadsquare (&root_corner_data); root = new quadsquare(&root_corner_data);
root->AddHeightMap (root_corner_data, hm); root->AddHeightMap(root_corner_data, hm);
root->SetScale (scalex, scalez); root->SetScale(scalex, scalez);
root->SetTerrain (Course.terrain); root->SetTerrain(Course.terrain);
root->StaticCullData (root_corner_data, CULL_DETAIL_FACTOR); root->StaticCullData(root_corner_data, CULL_DETAIL_FACTOR);
for (int i = 0; i < 10; i++) { for (int i = 0; i < 10; i++) {
root->Update(root_corner_data, view_pos, detail); root->Update(root_corner_data, view_pos, detail);
} }
} }
void UpdateQuadtree (const TVector3d& view_pos, float detail) { void UpdateQuadtree(const TVector3d& view_pos, float detail) {
root->Update(root_corner_data, view_pos, detail); root->Update(root_corner_data, view_pos, detail);
} }

View File

@ -77,14 +77,14 @@ struct quadsquare {
static GLuint VertexArrayMinIdx; static GLuint VertexArrayMinIdx;
static GLuint VertexArrayMaxIdx; static GLuint VertexArrayMaxIdx;
static void MakeTri( int a, int b, int c, int terrain ); static void MakeTri(int a, int b, int c, int terrain);
static void MakeSpecialTri( int a, int b, int c, int terrain ); static void MakeSpecialTri(int a, int b, int c, int terrain);
static void MakeNoBlendTri( int a, int b, int c, int terrain ); static void MakeNoBlendTri(int a, int b, int c, int terrain);
static void DrawTris(); static void DrawTris();
static void InitArrayCounters(); static void InitArrayCounters();
quadsquare (quadcornerdata* pcd); quadsquare(quadcornerdata* pcd);
~quadsquare(); ~quadsquare();
void AddHeightMap(const quadcornerdata& cd, const HeightMapInfo& hm); void AddHeightMap(const quadcornerdata& cd, const HeightMapInfo& hm);
@ -95,29 +95,29 @@ struct quadsquare {
void Render(const quadcornerdata& cd, GLubyte *vnc_array); void Render(const quadcornerdata& cd, GLubyte *vnc_array);
float GetHeight(const quadcornerdata& cd, float x, float z); float GetHeight(const quadcornerdata& cd, float x, float z);
void SetScale(double x, double z); void SetScale(double x, double z);
void SetTerrain (char *terrain); void SetTerrain(char *terrain);
private: private:
quadsquare* EnableDescendant(int count, int stack[], quadsquare* EnableDescendant(int count, int stack[],
const quadcornerdata& cd); const quadcornerdata& cd);
quadsquare* GetNeighbor(int dir, const quadcornerdata &cd); quadsquare* GetNeighbor(int dir, const quadcornerdata &cd);
clip_result_t ClipSquare( const quadcornerdata &cd ); clip_result_t ClipSquare(const quadcornerdata &cd);
void EnableEdgeVertex(int index, bool IncrementCount, void EnableEdgeVertex(int index, bool IncrementCount,
const quadcornerdata &cd); const quadcornerdata &cd);
void EnableChild(int index, const quadcornerdata &cd); void EnableChild(int index, const quadcornerdata &cd);
void NotifyChildDisable(const quadcornerdata& cd, int index); void NotifyChildDisable(const quadcornerdata& cd, int index);
void ResetTree(); void ResetTree();
void StaticCullAux (const quadcornerdata &cd, float ThresholdDetail, void StaticCullAux(const quadcornerdata &cd, float ThresholdDetail,
int TargetLevel); int TargetLevel);
void CreateChild(int index, const quadcornerdata &cd); void CreateChild(int index, const quadcornerdata &cd);
void SetupCornerData (quadcornerdata *q, const quadcornerdata &pd, void SetupCornerData(quadcornerdata *q, const quadcornerdata &pd,
int ChildIndex); int ChildIndex);
void UpdateAux(const quadcornerdata &cd, const float ViewerLocation[3], void UpdateAux(const quadcornerdata &cd, const float ViewerLocation[3],
float CenterError, clip_result_t vis); float CenterError, clip_result_t vis);
void RenderAux(const quadcornerdata &cd, clip_result_t vis, void RenderAux(const quadcornerdata &cd, clip_result_t vis,
int terrain); int terrain);
void SetStatic (const quadcornerdata &cd); void SetStatic(const quadcornerdata &cd);
void InitVert(int i, int x, int z); void InitVert(int i, int x, int z);
bool VertexTest(int x, float y, int z, float error, const float Viewer[3], bool VertexTest(int x, float y, int z, float error, const float Viewer[3],
int level, vertex_loc_t vertex_loc); int level, vertex_loc_t vertex_loc);
@ -130,11 +130,11 @@ private:
// -------------------------------------------------------------------- // --------------------------------------------------------------------
void ResetQuadtree(); void ResetQuadtree();
void InitQuadtree (double *elevation, int nx, int nz, void InitQuadtree(double *elevation, int nx, int nz,
double scalex, double scalez, double scalex, double scalez,
const TVector3d& view_pos, double detail); const TVector3d& view_pos, double detail);
void UpdateQuadtree (const TVector3d& view_pos, float detail); void UpdateQuadtree(const TVector3d& view_pos, float detail);
void RenderQuadtree(); void RenderQuadtree();

View File

@ -71,34 +71,34 @@ void SetRaceConditions() {
g_game.course = &Course.CourseList[course->GetValue()]; g_game.course = &Course.CourseList[course->GetValue()];
g_game.theme_id = CourseList[course->GetValue()].music_theme; g_game.theme_id = CourseList[course->GetValue()].music_theme;
g_game.game_type = PRACTICING; g_game.game_type = PRACTICING;
State::manager.RequestEnterState (Loading); State::manager.RequestEnterState(Loading);
} }
void CRaceSelect::Motion (int x, int y) { void CRaceSelect::Motion(int x, int y) {
MouseMoveGUI(x, y); MouseMoveGUI(x, y);
if (param.ui_snow) push_ui_snow (cursor_pos); if (param.ui_snow) push_ui_snow(cursor_pos);
UpdateInfo (); UpdateInfo();
} }
void CRaceSelect::Mouse (int button, int state, int x, int y) { void CRaceSelect::Mouse(int button, int state, int x, int y) {
if (state == 1) { if (state == 1) {
ClickGUI(x, y); ClickGUI(x, y);
if (textbuttons[0]->focussed()) if (textbuttons[0]->focussed())
SetRaceConditions (); SetRaceConditions();
else if (textbuttons[1]->focussed()) else if (textbuttons[1]->focussed())
State::manager.RequestEnterState (GameTypeSelect); State::manager.RequestEnterState(GameTypeSelect);
if (random_btn->focussed()) { if (random_btn->focussed()) {
mirror->SetValue(IRandom (0, 1)); mirror->SetValue(IRandom(0, 1));
light->SetValue(IRandom (0, 3)); light->SetValue(IRandom(0, 3));
snow->SetValue(IRandom (0, 3)); snow->SetValue(IRandom(0, 3));
wind->SetValue(IRandom (0, 3)); wind->SetValue(IRandom(0, 3));
} }
UpdateInfo (); UpdateInfo();
} }
} }
@ -107,7 +107,7 @@ void CRaceSelect::Keyb(unsigned int key, bool special, bool release, int x, int
KeyGUI(key, 0, release); KeyGUI(key, 0, release);
switch (key) { switch (key) {
case SDLK_ESCAPE: case SDLK_ESCAPE:
State::manager.RequestEnterState (GameTypeSelect); State::manager.RequestEnterState(GameTypeSelect);
break; break;
case SDLK_u: case SDLK_u:
param.ui_snow = !param.ui_snow; param.ui_snow = !param.ui_snow;
@ -125,9 +125,9 @@ void CRaceSelect::Keyb(unsigned int key, bool special, bool release, int x, int
break; break;
case SDLK_RETURN: case SDLK_RETURN:
if (textbuttons[1]->focussed()) if (textbuttons[1]->focussed())
State::manager.RequestEnterState (GameTypeSelect); State::manager.RequestEnterState(GameTypeSelect);
else else
SetRaceConditions (); SetRaceConditions();
break; break;
} }
} }
@ -139,40 +139,41 @@ static int prevtop, prevwidth, prevheight;
static int boxleft, boxwidth; static int boxleft, boxwidth;
void CRaceSelect::Enter() { void CRaceSelect::Enter() {
Winsys.ShowCursor (!param.ice_cursor); Winsys.ShowCursor(!param.ice_cursor);
Music.Play (param.menu_music, -1); Music.Play(param.menu_music, -1);
CourseList = &Course.CourseList[0]; CourseList = &Course.CourseList[0];
framewidth = 550 * Winsys.scale; framewidth = 550 * Winsys.scale;
frameheight = 50 * Winsys.scale; frameheight = 50 * Winsys.scale;
frametop = AutoYPosN (30); frametop = AutoYPosN(30);
area = AutoAreaN (30, 80, framewidth); area = AutoAreaN(30, 80, framewidth);
prevtop = AutoYPosN (50); prevtop = AutoYPosN(50);
prevheight = 144 * Winsys.scale; prevheight = 144 * Winsys.scale;
prevwidth = 192 * Winsys.scale; prevwidth = 192 * Winsys.scale;
boxwidth = framewidth - prevwidth - 20; boxwidth = framewidth - prevwidth - 20;
boxleft = area.right - boxwidth; boxleft = area.right - boxwidth;
int icontop = AutoYPosN(40); int icontop = AutoYPosN(40);
int iconsize = 32 * Winsys.scale; int iconsize = 32 * Winsys.scale;
int iconspace = (int) ((iconsize + 6) * 1.5); int iconspace = (int)((iconsize + 6) * 1.5);
int iconsumwidth = iconspace * 4 + iconsize; int iconsumwidth = iconspace * 4 + iconsize;
int iconleft = (Winsys.resolution.width - iconsumwidth) / 2; int iconleft = (Winsys.resolution.width - iconsumwidth) / 2;
ResetGUI (); ResetGUI();
course = AddUpDown(area.left + framewidth + 8, frametop, 0, (int)Course.CourseList.size() - 1, g_game.course?(int)Course.GetCourseIdx(g_game.course):0); course = AddUpDown(area.left + framewidth + 8, frametop, 0, (int)Course.CourseList.size() - 1, g_game.course?(int)Course.GetCourseIdx(g_game.course):0);
random_btn = AddIconButton(iconleft + iconspace * 4, icontop, Tex.GetTexture(RANDOM_BUTT), iconsize, 0, 0); random_btn = AddIconButton(iconleft + iconspace * 4, icontop, Tex.GetTexture(RANDOM_BUTT), iconsize, 0, 0);
light = AddIconButton (iconleft, icontop, Tex.GetTexture (LIGHT_BUTT), iconsize, 3, (int)g_game.light_id); light = AddIconButton(iconleft, icontop, Tex.GetTexture(LIGHT_BUTT), iconsize, 3, (int)g_game.light_id);
snow = AddIconButton (iconleft + iconspace, icontop, Tex.GetTexture (SNOW_BUTT), iconsize, 3, g_game.snow_id); snow = AddIconButton(iconleft + iconspace, icontop, Tex.GetTexture(SNOW_BUTT), iconsize, 3, g_game.snow_id);
wind = AddIconButton (iconleft + iconspace*2, icontop, Tex.GetTexture (WIND_BUTT), iconsize, 3, g_game.wind_id); wind = AddIconButton(iconleft + iconspace*2, icontop, Tex.GetTexture(WIND_BUTT), iconsize, 3, g_game.wind_id);
mirror = AddIconButton (iconleft + iconspace*3, icontop, Tex.GetTexture (MIRROR_BUTT), iconsize, 1, (int)g_game.mirrorred); mirror = AddIconButton(iconleft + iconspace*3, icontop, Tex.GetTexture(MIRROR_BUTT), iconsize, 1, (int)g_game.mirrorred);
random_btn = AddIconButton (iconleft + iconspace*4, icontop, Tex.GetTexture (RANDOM_BUTT), iconsize, 0, 0); int siz = FT.AutoSizeN (5); random_btn = AddIconButton(iconleft + iconspace*4, icontop, Tex.GetTexture(RANDOM_BUTT), iconsize, 0, 0);
int len1 = FT.GetTextWidth (Trans.Text(13)); int siz = FT.AutoSizeN(5);
textbuttons[0] = AddTextButton (Trans.Text(13), area.right-len1-50, AutoYPosN (80), siz); int len1 = FT.GetTextWidth(Trans.Text(13));
textbuttons[1] = AddTextButton (Trans.Text(8), area.left + 50, AutoYPosN (80), siz); textbuttons[0] = AddTextButton(Trans.Text(13), area.right-len1-50, AutoYPosN(80), siz);
textbuttons[1] = AddTextButton(Trans.Text(8), area.left + 50, AutoYPosN(80), siz);
} }
void CRaceSelect::Loop(double timestep) { void CRaceSelect::Loop(double timestep) {
@ -180,22 +181,21 @@ void CRaceSelect::Loop(double timestep) {
int hh = Winsys.resolution.height; int hh = Winsys.resolution.height;
TColor col; TColor col;
check_gl_error();
ScopedRenderMode rm(GUI); ScopedRenderMode rm(GUI);
ClearRenderContext (); ClearRenderContext();
SetupGuiDisplay (); SetupGuiDisplay();
Music.Update (); Music.Update();
if (param.ui_snow) { if (param.ui_snow) {
update_ui_snow (timestep); update_ui_snow(timestep);
draw_ui_snow (); draw_ui_snow();
} }
Tex.Draw (T_TITLE_SMALL, CENTER, AutoYPosN (5), 1.0); Tex.Draw(T_TITLE_SMALL, CENTER, AutoYPosN(5), 1.0);
Tex.Draw (BOTTOM_LEFT, 0, hh-256, 1); Tex.Draw(BOTTOM_LEFT, 0, hh-256, 1);
Tex.Draw (BOTTOM_RIGHT, ww-256, hh-256, 1); Tex.Draw(BOTTOM_RIGHT, ww-256, hh-256, 1);
Tex.Draw (TOP_LEFT, 0, 0, 1); Tex.Draw(TOP_LEFT, 0, 0, 1);
Tex.Draw (TOP_RIGHT, ww-256, 0, 1); Tex.Draw(TOP_RIGHT, ww-256, 0, 1);
// DrawFrameX (area.left, area.top, area.right-area.left, area.bottom - area.top, // DrawFrameX (area.left, area.top, area.right-area.left, area.bottom - area.top,
// 0, colMBackgr, colBlack, 0.2); // 0, colMBackgr, colBlack, 0.2);
@ -203,36 +203,36 @@ void CRaceSelect::Loop(double timestep) {
// course selection // course selection
if (course->focussed()) col = colDYell; if (course->focussed()) col = colDYell;
else col = colWhite; else col = colWhite;
DrawFrameX (area.left, frametop, framewidth, frameheight, 3, colMBackgr, col, 1.0); DrawFrameX(area.left, frametop, framewidth, frameheight, 3, colMBackgr, col, 1.0);
FT.AutoSizeN (4); FT.AutoSizeN(4);
FT.SetColor (colDYell); FT.SetColor(colDYell);
FT.DrawString (area.left+20, frametop, CourseList[course->GetValue()].name); FT.DrawString(area.left+20, frametop, CourseList[course->GetValue()].name);
if (CourseList[course->GetValue()].preview) if (CourseList[course->GetValue()].preview)
CourseList[course->GetValue()].preview->DrawFrame(area.left + 3, prevtop, prevwidth, prevheight, 3, colWhite); CourseList[course->GetValue()].preview->DrawFrame(area.left + 3, prevtop, prevwidth, prevheight, 3, colWhite);
DrawFrameX (area.right-boxwidth, prevtop-3, boxwidth, prevheight+6, 3, colBackgr, colWhite, 1.0); DrawFrameX(area.right-boxwidth, prevtop-3, boxwidth, prevheight+6, 3, colBackgr, colWhite, 1.0);
FT.AutoSizeN (2); FT.AutoSizeN(2);
FT.SetColor (colWhite); FT.SetColor(colWhite);
int dist = FT.AutoDistanceN (0); int dist = FT.AutoDistanceN(0);
for (size_t i=0; i<CourseList[course->GetValue()].num_lines; i++) { for (size_t i=0; i<CourseList[course->GetValue()].num_lines; i++) {
FT.DrawString (boxleft+8, prevtop+i*dist, CourseList[course->GetValue()].desc[i]); FT.DrawString(boxleft+8, prevtop+i*dist, CourseList[course->GetValue()].desc[i]);
} }
FT.DrawString (CENTER, prevtop + prevheight + 10, "Author: " + CourseList[course->GetValue()].author); FT.DrawString(CENTER, prevtop + prevheight + 10, "Author: " + CourseList[course->GetValue()].author);
FT.DrawString (CENTER, AutoYPosN (45), info); FT.DrawString(CENTER, AutoYPosN(45), info);
if (g_game.force_treemap) { if (g_game.force_treemap) {
FT.AutoSizeN (4); FT.AutoSizeN(4);
static const string forcetrees = "Load trees.png"; static const string forcetrees = "Load trees.png";
string sizevar = "Size: "; string sizevar = "Size: ";
sizevar += Int_StrN (g_game.treesize); sizevar += Int_StrN(g_game.treesize);
sizevar += " Variation: "; sizevar += " Variation: ";
sizevar += Int_StrN (g_game.treevar); sizevar += Int_StrN(g_game.treevar);
FT.SetColor (colYellow); FT.SetColor(colYellow);
FT.DrawString (CENTER, AutoYPosN (85), forcetrees); FT.DrawString(CENTER, AutoYPosN(85), forcetrees);
FT.DrawString (CENTER, AutoYPosN (90), sizevar); FT.DrawString(CENTER, AutoYPosN(90), sizevar);
} }
DrawGUI(); DrawGUI();

View File

@ -66,7 +66,7 @@ static bool trees = true;
static int newsound = -1; static int newsound = -1;
static int lastsound = -1; static int lastsound = -1;
void CRacing::Keyb (unsigned int key, bool special, bool release, int x, int y) { void CRacing::Keyb(unsigned int key, bool special, bool release, int x, int y) {
switch (key) { switch (key) {
// steering flipflops // steering flipflops
case SDLK_UP: case SDLK_UP:
@ -92,35 +92,35 @@ void CRacing::Keyb (unsigned int key, bool special, bool release, int x, int y)
if (!release) { if (!release) {
g_game.raceaborted = true; g_game.raceaborted = true;
g_game.race_result = -1; g_game.race_result = -1;
State::manager.RequestEnterState (GameOver); State::manager.RequestEnterState(GameOver);
} }
break; break;
case SDLK_p: case SDLK_p:
if (!release) State::manager.RequestEnterState (Paused); if (!release) State::manager.RequestEnterState(Paused);
break; break;
case SDLK_r: case SDLK_r:
if (!release) State::manager.RequestEnterState (Reset); if (!release) State::manager.RequestEnterState(Reset);
break; break;
case SDLK_s: case SDLK_s:
if (!release) ScreenshotN (); if (!release) ScreenshotN();
break; break;
// view changing // view changing
case SDLK_1: case SDLK_1:
if (!release) { if (!release) {
set_view_mode (g_game.player->ctrl, ABOVE); set_view_mode(g_game.player->ctrl, ABOVE);
param.view_mode = ABOVE; param.view_mode = ABOVE;
} }
break; break;
case SDLK_2: case SDLK_2:
if (!release) { if (!release) {
set_view_mode (g_game.player->ctrl, FOLLOW); set_view_mode(g_game.player->ctrl, FOLLOW);
param.view_mode = FOLLOW; param.view_mode = FOLLOW;
} }
break; break;
case SDLK_3: case SDLK_3:
if (!release) { if (!release) {
set_view_mode (g_game.player->ctrl, BEHIND); set_view_mode(g_game.player->ctrl, BEHIND);
param.view_mode = BEHIND; param.view_mode = BEHIND;
} }
break; break;
@ -147,7 +147,7 @@ void CRacing::Keyb (unsigned int key, bool special, bool release, int x, int y)
} }
} }
void CRacing::Jaxis (int axis, float value) { void CRacing::Jaxis(int axis, float value) {
if (axis == 0) { // left and right if (axis == 0) { // left and right
stick_turn = ((value < -0.2) || (value > 0.2)); stick_turn = ((value < -0.2) || (value > 0.2));
if (stick_turn) stick_turnfact = value; if (stick_turn) stick_turnfact = value;
@ -158,7 +158,7 @@ void CRacing::Jaxis (int axis, float value) {
} }
} }
void CRacing::Jbutt (int button, int state) { void CRacing::Jbutt(int button, int state) {
if (button == 0) { if (button == 0) {
key_charging = state != 0; key_charging = state != 0;
} else if (button == 1) { } else if (button == 1) {
@ -166,32 +166,32 @@ void CRacing::Jbutt (int button, int state) {
} }
} }
void CalcJumpEnergy (double time_step) { void CalcJumpEnergy(double time_step) {
CControl *ctrl = g_game.player->ctrl; CControl *ctrl = g_game.player->ctrl;
if (ctrl->jump_charging) { if (ctrl->jump_charging) {
ctrl->jump_amt = min (MAX_JUMP_AMT, g_game.time - charge_start_time); ctrl->jump_amt = min(MAX_JUMP_AMT, g_game.time - charge_start_time);
} else if (ctrl->jumping) { } else if (ctrl->jumping) {
ctrl->jump_amt *= (1.0 - (g_game.time - ctrl->jump_start_time) / ctrl->jump_amt *= (1.0 - (g_game.time - ctrl->jump_start_time) /
JUMP_FORCE_DURATION); JUMP_FORCE_DURATION);
} else { } else {
ctrl->jump_amt = 0; ctrl->jump_amt = 0;
} }
} }
int CalcSoundVol (float fact) { int CalcSoundVol(float fact) {
float vv = (float) param.sound_volume * fact; float vv = (float) param.sound_volume * fact;
if (vv > 120) vv = 120; if (vv > 120) vv = 120;
return (int) vv; return (int) vv;
} }
void SetSoundVolumes () { void SetSoundVolumes() {
Sound.SetVolume ("pickup1", CalcSoundVol (1.0)); Sound.SetVolume("pickup1", CalcSoundVol(1.0));
Sound.SetVolume ("pickup2", CalcSoundVol (0.8)); Sound.SetVolume("pickup2", CalcSoundVol(0.8));
Sound.SetVolume ("pickup3", CalcSoundVol (0.8)); Sound.SetVolume("pickup3", CalcSoundVol(0.8));
Sound.SetVolume ("snow_sound", CalcSoundVol (1.5)); Sound.SetVolume("snow_sound", CalcSoundVol(1.5));
Sound.SetVolume ("ice_sound", CalcSoundVol (0.6)); Sound.SetVolume("ice_sound", CalcSoundVol(0.6));
Sound.SetVolume ("rock_sound", CalcSoundVol (1.1)); Sound.SetVolume("rock_sound", CalcSoundVol(1.1));
} }
// ---------------------------- init ---------------------------------- // ---------------------------- init ----------------------------------
@ -201,7 +201,7 @@ void CRacing::Enter() {
if (param.view_mode < 0 || param.view_mode >= NUM_VIEW_MODES) { if (param.view_mode < 0 || param.view_mode >= NUM_VIEW_MODES) {
param.view_mode = ABOVE; param.view_mode = ABOVE;
} }
set_view_mode (ctrl, (TViewMode)param.view_mode); set_view_mode(ctrl, param.view_mode);
left_turn = right_turn = trick_modifier = false; left_turn = right_turn = trick_modifier = false;
ctrl->turn_fact = 0.0; ctrl->turn_fact = 0.0;
@ -214,11 +214,11 @@ void CRacing::Enter() {
lastsound = -1; lastsound = -1;
newsound = -1; newsound = -1;
if (State::manager.PreviousState() != &Paused) ctrl->Init (); if (State::manager.PreviousState() != &Paused) ctrl->Init();
g_game.raceaborted = false; g_game.raceaborted = false;
SetSoundVolumes (); SetSoundVolumes();
Music.PlayTheme (g_game.theme_id, MUS_RACING); Music.PlayTheme(g_game.theme_id, MUS_RACING);
g_game.finish = false; g_game.finish = false;
} }
@ -226,40 +226,40 @@ void CRacing::Enter() {
// -------------------- sound ----------------------------------------- // -------------------- sound -----------------------------------------
// this function is not used yet. // this function is not used yet.
int SlideVolume (CControl *ctrl, double speed, int typ) { int SlideVolume(CControl *ctrl, double speed, int typ) {
if (typ == 1) { // only at paddling or braking if (typ == 1) { // only at paddling or braking
return (int)(min ((((pow(ctrl->turn_fact, 2) * 128)) + return (int)(min((((pow(ctrl->turn_fact, 2) * 128)) +
(ctrl->is_braking ? 128:0) + (ctrl->is_braking ? 128:0) +
(ctrl->jumping ? 128:0) + 20) * (speed / 10), 128.0)); (ctrl->jumping ? 128:0) + 20) * (speed / 10), 128.0));
} else { // always } else { // always
return (int)(128 * pow((speed/2),2)); return (int)(128 * pow((speed/2),2));
} }
} }
void PlayTerrainSound (CControl *ctrl, bool airborne) { void PlayTerrainSound(CControl *ctrl, bool airborne) {
if (airborne == false) { if (airborne == false) {
int terridx = Course.GetTerrainIdx (ctrl->cpos.x, ctrl->cpos.z, 0.5); int terridx = Course.GetTerrainIdx(ctrl->cpos.x, ctrl->cpos.z, 0.5);
if (terridx >= 0) { if (terridx >= 0) {
newsound = (int)Course.TerrList[terridx].sound; newsound = (int)Course.TerrList[terridx].sound;
} else newsound = -1; } else newsound = -1;
} else newsound = -1; } else newsound = -1;
if ((newsound != lastsound) && (lastsound >= 0)) Sound.Halt (lastsound); if ((newsound != lastsound) && (lastsound >= 0)) Sound.Halt(lastsound);
if (newsound >= 0) Sound.Play (newsound, -1); if (newsound >= 0) Sound.Play(newsound, -1);
lastsound = newsound; lastsound = newsound;
} }
// ----------------------- controls ----------------------------------- // ----------------------- controls -----------------------------------
void CalcSteeringControls (CControl *ctrl, double time_step) { void CalcSteeringControls(CControl *ctrl, double time_step) {
if (stick_turn) { if (stick_turn) {
ctrl->turn_fact = stick_turnfact; ctrl->turn_fact = stick_turnfact;
ctrl->turn_animation += ctrl->turn_fact * 2 * time_step; ctrl->turn_animation += ctrl->turn_fact * 2 * time_step;
ctrl->turn_animation = clamp (-1.0, ctrl->turn_animation, 1.0); ctrl->turn_animation = clamp(-1.0, ctrl->turn_animation, 1.0);
} else if (left_turn ^ right_turn) { } else if (left_turn ^ right_turn) {
if (left_turn) ctrl->turn_fact = -1.0; if (left_turn) ctrl->turn_fact = -1.0;
else ctrl->turn_fact = 1.0; else ctrl->turn_fact = 1.0;
ctrl->turn_animation += ctrl->turn_fact * 2 * time_step; ctrl->turn_animation += ctrl->turn_fact * 2 * time_step;
ctrl->turn_animation = clamp (-1.0, ctrl->turn_animation, 1.0); ctrl->turn_animation = clamp(-1.0, ctrl->turn_animation, 1.0);
} else { } else {
ctrl->turn_fact = 0.0; ctrl->turn_fact = 0.0;
if (time_step < ROLL_DECAY) { if (time_step < ROLL_DECAY) {
@ -280,7 +280,7 @@ void CalcSteeringControls (CControl *ctrl, double time_step) {
bool charge = key_charging || stick_charging; bool charge = key_charging || stick_charging;
bool invcharge = !key_charging && !stick_charging; bool invcharge = !key_charging && !stick_charging;
CalcJumpEnergy (time_step); CalcJumpEnergy(time_step);
if ((charge) && !ctrl->jump_charging && !ctrl->jumping) { if ((charge) && !ctrl->jump_charging && !ctrl->jumping) {
ctrl->jump_charging = true; ctrl->jump_charging = true;
charge_start_time = g_game.time; charge_start_time = g_game.time;
@ -291,11 +291,11 @@ void CalcSteeringControls (CControl *ctrl, double time_step) {
} }
} }
void CalcFinishControls (CControl *ctrl, double timestep, bool airborne) { void CalcFinishControls(CControl *ctrl, double timestep, bool airborne) {
double speed = ctrl->cvel.Length(); double speed = ctrl->cvel.Length();
double dir_angle = RADIANS_TO_ANGLES(atan(ctrl->cvel.x / ctrl->cvel.z)); double dir_angle = RADIANS_TO_ANGLES(atan(ctrl->cvel.x / ctrl->cvel.z));
if (fabs (dir_angle) > 5 && speed > 5) { if (fabs(dir_angle) > 5 && speed > 5) {
ctrl->turn_fact = dir_angle / 20; ctrl->turn_fact = dir_angle / 20;
if (ctrl->turn_fact < -1) ctrl->turn_fact = -1; if (ctrl->turn_fact < -1) ctrl->turn_fact = -1;
if (ctrl->turn_fact > 1) ctrl->turn_fact = 1; if (ctrl->turn_fact > 1) ctrl->turn_fact = 1;
@ -310,7 +310,7 @@ void CalcFinishControls (CControl *ctrl, double timestep, bool airborne) {
// ----------------------- trick -------------------------------------- // ----------------------- trick --------------------------------------
void CalcTrickControls (CControl *ctrl, double time_step, bool airborne) { void CalcTrickControls(CControl *ctrl, double time_step, bool airborne) {
if (airborne && trick_modifier) { if (airborne && trick_modifier) {
if (left_turn) ctrl->roll_left = true; if (left_turn) ctrl->roll_left = true;
if (right_turn) ctrl->roll_right = true; if (right_turn) ctrl->roll_right = true;
@ -338,52 +338,51 @@ void CalcTrickControls (CControl *ctrl, double time_step, bool airborne) {
// loop // loop
// ==================================================================== // ====================================================================
void CRacing::Loop (double time_step) { void CRacing::Loop(double time_step) {
CControl *ctrl = g_game.player->ctrl; CControl *ctrl = g_game.player->ctrl;
double ycoord = Course.FindYCoord (ctrl->cpos.x, ctrl->cpos.z); double ycoord = Course.FindYCoord(ctrl->cpos.x, ctrl->cpos.z);
bool airborne = (bool) (ctrl->cpos.y > (ycoord + JUMP_MAX_START_HEIGHT)); bool airborne = (bool)(ctrl->cpos.y > (ycoord + JUMP_MAX_START_HEIGHT));
check_gl_error(); ClearRenderContext();
ClearRenderContext (); Env.SetupFog();
Env.SetupFog (); Music.Update();
Music.Update (); CalcTrickControls(ctrl, time_step, airborne);
CalcTrickControls (ctrl, time_step, airborne);
if (!g_game.finish) CalcSteeringControls (ctrl, time_step); if (!g_game.finish) CalcSteeringControls(ctrl, time_step);
else CalcFinishControls (ctrl, time_step, airborne); else CalcFinishControls(ctrl, time_step, airborne);
PlayTerrainSound (ctrl, airborne); PlayTerrainSound(ctrl, airborne);
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
ctrl->UpdatePlayerPos (time_step); ctrl->UpdatePlayerPos(time_step);
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
if (g_game.finish) IncCameraDistance (time_step); if (g_game.finish) IncCameraDistance(time_step);
update_view (ctrl, time_step); update_view(ctrl, time_step);
UpdateTrackmarks (ctrl); UpdateTrackmarks(ctrl);
SetupViewFrustum (ctrl); SetupViewFrustum(ctrl);
if (sky) Env.DrawSkybox (ctrl->viewpos); if (sky) Env.DrawSkybox(ctrl->viewpos);
if (fog) Env.DrawFog (); if (fog) Env.DrawFog();
void SetupLight (); void SetupLight();
if (terr) RenderCourse (); if (terr) RenderCourse();
DrawTrackmarks (); DrawTrackmarks();
if (trees) DrawTrees (); if (trees) DrawTrees();
if (param.perf_level > 2) { if (param.perf_level > 2) {
update_particles (time_step); update_particles(time_step);
draw_particles (ctrl); draw_particles(ctrl);
} }
g_game.character->shape->Draw(); g_game.character->shape->Draw();
UpdateWind (time_step); UpdateWind(time_step);
UpdateSnow (time_step, ctrl); UpdateSnow(time_step, ctrl);
DrawSnow (ctrl); DrawSnow(ctrl);
DrawHud (ctrl); DrawHud(ctrl);
Reshape (Winsys.resolution.width, Winsys.resolution.height); Reshape(Winsys.resolution.width, Winsys.resolution.height);
Winsys.SwapBuffers (); Winsys.SwapBuffers();
if (g_game.finish == false) g_game.time += time_step; if (g_game.finish == false) g_game.time += time_step;
} }
// ---------------------------------- term ------------------ // ---------------------------------- term ------------------
void CRacing::Exit() { void CRacing::Exit() {
Sound.HaltAll (); Sound.HaltAll();
break_track_marks (); break_track_marks();
} }

View File

@ -38,17 +38,17 @@ static TWidget* textbuttons[2];
static TUpDown* player; static TUpDown* player;
static TUpDown* character; static TUpDown* character;
void QuitRegistration () { void QuitRegistration() {
Players.ResetControls (); Players.ResetControls();
Players.AllocControl (player->GetValue()); Players.AllocControl(player->GetValue());
g_game.player = Players.GetPlayer(player->GetValue()); g_game.player = Players.GetPlayer(player->GetValue());
g_game.character = &Char.CharList[character->GetValue()]; g_game.character = &Char.CharList[character->GetValue()];
Char.FreeCharacterPreviews(); // From here on, character previews are no longer required Char.FreeCharacterPreviews(); // From here on, character previews are no longer required
State::manager.RequestEnterState (GameTypeSelect); State::manager.RequestEnterState(GameTypeSelect);
} }
void CRegist::Keyb (unsigned int key, bool special, bool release, int x, int y) { void CRegist::Keyb(unsigned int key, bool special, bool release, int x, int y) {
TWidget* focussed = KeyGUI(key, 0, release); TWidget* focussed = KeyGUI(key, 0, release);
if (release) return; if (release) return;
switch (key) { switch (key) {
@ -58,28 +58,28 @@ void CRegist::Keyb (unsigned int key, bool special, bool release, int x, int y)
case SDLK_RETURN: case SDLK_RETURN:
if (focussed == textbuttons[1]) { if (focussed == textbuttons[1]) {
g_game.player = Players.GetPlayer(player->GetValue()); g_game.player = Players.GetPlayer(player->GetValue());
State::manager.RequestEnterState (NewPlayer); State::manager.RequestEnterState(NewPlayer);
} else QuitRegistration (); } else QuitRegistration();
break; break;
} }
} }
void CRegist::Mouse (int button, int state, int x, int y) { void CRegist::Mouse(int button, int state, int x, int y) {
if (state == 1) { if (state == 1) {
TWidget* focussed = ClickGUI(x, y); TWidget* focussed = ClickGUI(x, y);
if (focussed == textbuttons[0]) if (focussed == textbuttons[0])
QuitRegistration (); QuitRegistration();
else if (focussed == textbuttons[1]) { else if (focussed == textbuttons[1]) {
g_game.player = Players.GetPlayer(player->GetValue()); g_game.player = Players.GetPlayer(player->GetValue());
State::manager.RequestEnterState (NewPlayer); State::manager.RequestEnterState(NewPlayer);
} }
} }
} }
void CRegist::Motion (int x, int y) { void CRegist::Motion(int x, int y) {
MouseMoveGUI(x, y); MouseMoveGUI(x, y);
if (param.ui_snow) push_ui_snow (cursor_pos); if (param.ui_snow) push_ui_snow(cursor_pos);
} }
static int framewidth, frameheight, arrowwidth; static int framewidth, frameheight, arrowwidth;
@ -87,78 +87,77 @@ static TArea area;
static double texsize; static double texsize;
void CRegist::Enter() { void CRegist::Enter() {
Winsys.ShowCursor (!param.ice_cursor); Winsys.ShowCursor(!param.ice_cursor);
Music.Play (param.menu_music, -1); Music.Play(param.menu_music, -1);
framewidth = (int) (Winsys.scale * 280); framewidth = (int)(Winsys.scale * 280);
frameheight = (int) (Winsys.scale * 50); frameheight = (int)(Winsys.scale * 50);
arrowwidth = 50; arrowwidth = 50;
int sumwidth = framewidth * 2 + arrowwidth * 2; int sumwidth = framewidth * 2 + arrowwidth * 2;
area = AutoAreaN (30, 80, sumwidth); area = AutoAreaN(30, 80, sumwidth);
texsize = 128 * Winsys.scale; texsize = 128 * Winsys.scale;
ResetGUI (); ResetGUI();
player = AddUpDown(area.left + framewidth + 8, area.top, 0, (int)Players.numPlayers() - 1, (int)g_game.start_player); player = AddUpDown(area.left + framewidth + 8, area.top, 0, (int)Players.numPlayers() - 1, (int)g_game.start_player);
character = AddUpDown(area.left + framewidth * 2 + arrowwidth + 8, area.top, 0, (int)Char.CharList.size() - 1, 0); character = AddUpDown(area.left + framewidth * 2 + arrowwidth + 8, area.top, 0, (int)Char.CharList.size() - 1, 0);
int siz = FT.AutoSizeN (5); int siz = FT.AutoSizeN(5);
textbuttons[0] = AddTextButton (Trans.Text(60), CENTER, AutoYPosN (62), siz); textbuttons[0] = AddTextButton(Trans.Text(60), CENTER, AutoYPosN(62), siz);
textbuttons[1] = AddTextButton (Trans.Text(61), CENTER, AutoYPosN (70), siz); textbuttons[1] = AddTextButton(Trans.Text(61), CENTER, AutoYPosN(70), siz);
if (Char.CharList.empty()) if (Char.CharList.empty())
Winsys.Terminate(); // Characters are necessary - ETR is unusable otherwise Winsys.Terminate(); // Characters are necessary - ETR is unusable otherwise
} }
void CRegist::Loop (double timestep) { void CRegist::Loop(double timestep) {
int ww = Winsys.resolution.width; int ww = Winsys.resolution.width;
int hh = Winsys.resolution.height; int hh = Winsys.resolution.height;
Music.Update (); Music.Update();
check_gl_error(); ClearRenderContext();
ClearRenderContext ();
ScopedRenderMode rm(GUI); ScopedRenderMode rm(GUI);
SetupGuiDisplay (); SetupGuiDisplay();
TColor col; TColor col;
if (param.ui_snow) { if (param.ui_snow) {
update_ui_snow (timestep); update_ui_snow(timestep);
draw_ui_snow(); draw_ui_snow();
} }
Tex.Draw (BOTTOM_LEFT, 0, hh - 256, 1); Tex.Draw(BOTTOM_LEFT, 0, hh - 256, 1);
Tex.Draw (BOTTOM_RIGHT, ww-256, hh-256, 1); Tex.Draw(BOTTOM_RIGHT, ww-256, hh-256, 1);
Tex.Draw (TOP_LEFT, 0, 0, 1); Tex.Draw(TOP_LEFT, 0, 0, 1);
Tex.Draw (TOP_RIGHT, ww-256, 0, 1); Tex.Draw(TOP_RIGHT, ww-256, 0, 1);
Tex.Draw(T_TITLE_SMALL, CENTER, AutoYPosN(5), Winsys.scale); Tex.Draw(T_TITLE_SMALL, CENTER, AutoYPosN(5), Winsys.scale);
FT.AutoSizeN (3); FT.AutoSizeN(3);
FT.SetColor (colWhite); FT.SetColor(colWhite);
int top = AutoYPosN (24); int top = AutoYPosN(24);
FT.DrawString (area.left, top, Trans.Text(58)); FT.DrawString(area.left, top, Trans.Text(58));
FT.DrawString (area.left + framewidth + arrowwidth, top, Trans.Text(59)); FT.DrawString(area.left + framewidth + arrowwidth, top, Trans.Text(59));
FT.AutoSizeN (4); FT.AutoSizeN(4);
if (player->focussed()) col = colDYell; if (player->focussed()) col = colDYell;
else col = colWhite; else col = colWhite;
DrawFrameX (area.left, area.top, framewidth, frameheight, 3, colMBackgr, col, 1.0); DrawFrameX(area.left, area.top, framewidth, frameheight, 3, colMBackgr, col, 1.0);
FT.SetColor (col); FT.SetColor(col);
FT.DrawString(area.left + 20, area.top, Players.GetPlayer(player->GetValue())->name); FT.DrawString(area.left + 20, area.top, Players.GetPlayer(player->GetValue())->name);
Players.GetAvatarTexture(player->GetValue())->DrawFrame( Players.GetAvatarTexture(player->GetValue())->DrawFrame(
area.left + 60, AutoYPosN (40), texsize, texsize, 3, colWhite); area.left + 60, AutoYPosN(40), texsize, texsize, 3, colWhite);
if (character->focussed()) col = colDYell; if (character->focussed()) col = colDYell;
else col = colWhite; else col = colWhite;
DrawFrameX (area.left + framewidth + arrowwidth, area.top, DrawFrameX(area.left + framewidth + arrowwidth, area.top,
framewidth, frameheight, 3, colMBackgr, col, 1.0); framewidth, frameheight, 3, colMBackgr, col, 1.0);
FT.SetColor (col); FT.SetColor(col);
FT.DrawString (area.left + framewidth + arrowwidth + 20, FT.DrawString(area.left + framewidth + arrowwidth + 20,
area.top, Char.CharList[character->GetValue()].name); area.top, Char.CharList[character->GetValue()].name);
if (Char.CharList[character->GetValue()].preview != NULL) if (Char.CharList[character->GetValue()].preview != NULL)
Char.CharList[character->GetValue()].preview->DrawFrame( Char.CharList[character->GetValue()].preview->DrawFrame(
area.right - texsize - 60 - arrowwidth, area.right - texsize - 60 - arrowwidth,
AutoYPosN (40), texsize, texsize, 3, colWhite); AutoYPosN(40), texsize, texsize, 3, colWhite);
FT.SetColor (colWhite); FT.SetColor(colWhite);
DrawGUI(); DrawGUI();
Winsys.SwapBuffers(); Winsys.SwapBuffers();

View File

@ -45,28 +45,27 @@ static bool position_reset;
//===================================================================== //=====================================================================
void CReset::Enter() { void CReset::Enter() {
reset_start_time = Winsys.ClockTime (); reset_start_time = Winsys.ClockTime();
position_reset = false; position_reset = false;
} }
void CReset::Loop(double time_step) { void CReset::Loop(double time_step) {
CControl *ctrl = g_game.player->ctrl; CControl *ctrl = g_game.player->ctrl;
double elapsed_time = Winsys.ClockTime () - reset_start_time; double elapsed_time = Winsys.ClockTime() - reset_start_time;
static bool tux_visible = true; static bool tux_visible = true;
static int tux_visible_count = 0; static int tux_visible_count = 0;
check_gl_error(); ClearRenderContext();
ClearRenderContext (); Env.SetupFog();
Env.SetupFog (); ctrl->UpdatePlayerPos(EPS);
ctrl->UpdatePlayerPos (EPS); update_view(ctrl, EPS);
update_view (ctrl, EPS); SetupViewFrustum(ctrl);
SetupViewFrustum (ctrl); Env.DrawSkybox(ctrl->viewpos);
Env.DrawSkybox (ctrl->viewpos); Env.DrawFog();
Env.DrawFog (); Env.SetupLight(); // and fog
Env.SetupLight (); // and fog
RenderCourse(); RenderCourse();
DrawTrackmarks (); DrawTrackmarks();
DrawTrees (); DrawTrees();
if ((elapsed_time > BLINK_IN_PLACE_TIME) && (!position_reset)) { if ((elapsed_time > BLINK_IN_PLACE_TIME) && (!position_reset)) {
TObjectType* object_types = &Course.ObjTypes[0]; TObjectType* object_types = &Course.ObjTypes[0];
@ -98,10 +97,10 @@ void CReset::Loop(double time_step) {
if (best_loc == -1) { if (best_loc == -1) {
ctrl->cpos.x = Course.GetDimensions().x/2.0; ctrl->cpos.x = Course.GetDimensions().x/2.0;
ctrl->cpos.z = min (ctrl->cpos.z + 10, -1.0); ctrl->cpos.z = min(ctrl->cpos.z + 10, -1.0);
} else if (item_locs[best_loc].pt.z <= ctrl->cpos.z) { } else if (item_locs[best_loc].pt.z <= ctrl->cpos.z) {
ctrl->cpos.x = Course.GetDimensions().x/2.0; ctrl->cpos.x = Course.GetDimensions().x/2.0;
ctrl->cpos.z = min (ctrl->cpos.z + 10, -1.0); ctrl->cpos.z = min(ctrl->cpos.z + 10, -1.0);
} else { } else {
ctrl->cpos.x = item_locs[best_loc].pt.x; ctrl->cpos.x = item_locs[best_loc].pt.x;
ctrl->cpos.z = item_locs[best_loc].pt.z; ctrl->cpos.z = item_locs[best_loc].pt.z;
@ -109,7 +108,7 @@ void CReset::Loop(double time_step) {
} }
ctrl->view_init = false; ctrl->view_init = false;
ctrl->Init (); ctrl->Init();
position_reset = true; position_reset = true;
} // if elapsed time } // if elapsed time
@ -120,12 +119,12 @@ void CReset::Loop(double time_step) {
tux_visible_count = 0; tux_visible_count = 0;
} }
DrawHud (ctrl); DrawHud(ctrl);
Reshape (Winsys.resolution.width, Winsys.resolution.height); Reshape(Winsys.resolution.width, Winsys.resolution.height);
Winsys.SwapBuffers (); Winsys.SwapBuffers();
g_game.time += time_step; g_game.time += time_step;
if (elapsed_time > TOTAL_RESET_TIME) { if (elapsed_time > TOTAL_RESET_TIME) {
State::manager.RequestEnterState (Racing); State::manager.RequestEnterState(Racing);
} }
} }

View File

@ -66,30 +66,30 @@ int CScore::AddScore(const TCourse* course, const TScore& score) {
} }
// for testing: // for testing:
void CScore::PrintScorelist (size_t list_idx) const { void CScore::PrintScorelist(size_t list_idx) const {
if (list_idx >= Scorelist.size()) return; if (list_idx >= Scorelist.size()) return;
const TScoreList *list = &Scorelist[list_idx]; const TScoreList *list = &Scorelist[list_idx];
if (list->numScores < 1) { if (list->numScores < 1) {
PrintStr ("no entries in this score list"); PrintStr("no entries in this score list");
} else { } else {
for (int i=0; i<list->numScores; i++) { for (int i=0; i<list->numScores; i++) {
string line = "player: " + list->scores[i].player; string line = "player: " + list->scores[i].player;
line += " points: " + Int_StrN (list->scores[i].points); line += " points: " + Int_StrN(list->scores[i].points);
line += " herrings: " + Int_StrN (list->scores[i].herrings); line += " herrings: " + Int_StrN(list->scores[i].herrings);
line += " time: " + Float_StrN (list->scores[i].time, 2); line += " time: " + Float_StrN(list->scores[i].time, 2);
PrintString (line); PrintString(line);
} }
} }
} }
const TScoreList *CScore::GetScorelist (size_t list_idx) const { const TScoreList *CScore::GetScorelist(size_t list_idx) const {
if (list_idx >= Scorelist.size()) return NULL; if (list_idx >= Scorelist.size()) return NULL;
return &Scorelist[list_idx]; return &Scorelist[list_idx];
} }
bool CScore::SaveHighScore () const { bool CScore::SaveHighScore() const {
CSPList splist ((int)Scorelist.size()*MAX_SCORES); CSPList splist((int)Scorelist.size()*MAX_SCORES);
for (size_t li=0; li<Scorelist.size(); li++) { for (size_t li=0; li<Scorelist.size(); li++) {
const TScoreList* lst = &Scorelist[li]; const TScoreList* lst = &Scorelist[li];
@ -100,43 +100,43 @@ bool CScore::SaveHighScore () const {
const TScore& score = lst->scores[sc]; const TScore& score = lst->scores[sc];
string line = "*[course] " + Course.CourseList[li].dir; string line = "*[course] " + Course.CourseList[li].dir;
line += " [plyr] " + score.player; line += " [plyr] " + score.player;
line += " [pts] " + Int_StrN (score.points); line += " [pts] " + Int_StrN(score.points);
line += " [herr] " + Int_StrN (score.herrings); line += " [herr] " + Int_StrN(score.herrings);
line += " [time] " + Float_StrN (score.time, 1); line += " [time] " + Float_StrN(score.time, 1);
splist.Add (line); splist.Add(line);
} }
} }
} }
} }
if (!splist.Save (param.config_dir, "highscore")) { if (!splist.Save(param.config_dir, "highscore")) {
Message ("could not save highscore list"); Message("could not save highscore list");
return false; return false;
} }
return true; return true;
} }
bool CScore::LoadHighScore () { bool CScore::LoadHighScore() {
CSPList list (520); CSPList list(520);
Scorelist.resize(Course.CourseList.size()); Scorelist.resize(Course.CourseList.size());
if (!list.Load (param.config_dir, "highscore")) { if (!list.Load(param.config_dir, "highscore")) {
Message ("could not load highscore list"); Message("could not load highscore list");
return false; return false;
} }
for (size_t i=0; i<list.Count(); i++) { for (size_t i=0; i<list.Count(); i++) {
const string& line = list.Line(i); const string& line = list.Line(i);
string course = SPStrN (line, "course", "unknown"); string course = SPStrN(line, "course", "unknown");
TCourse* cidx = Course.GetCourse(course); TCourse* cidx = Course.GetCourse(course);
TScore score; TScore score;
score.player = SPStrN (line, "plyr", "unknown"); score.player = SPStrN(line, "plyr", "unknown");
score.points = SPIntN (line, "pts", 0); score.points = SPIntN(line, "pts", 0);
score.herrings = SPIntN (line, "herr", 0); score.herrings = SPIntN(line, "herr", 0);
score.time = SPFloatN (line, "time", 0); score.time = SPFloatN(line, "time", 0);
AddScore (cidx, score); AddScore(cidx, score);
} }
return true; return true;
} }
@ -163,7 +163,7 @@ int CScore::CalcRaceResult() {
TempScore.time = g_game.time; TempScore.time = g_game.time;
TempScore.player = g_game.player->name; TempScore.player = g_game.player->name;
return AddScore (g_game.course, TempScore); return AddScore(g_game.course, TempScore);
} }
// -------------------------------------------------------------------- // --------------------------------------------------------------------
@ -174,40 +174,40 @@ static TCourse *CourseList;
static TUpDown* course; static TUpDown* course;
static TWidget* textbutton; static TWidget* textbutton;
void CScore::Keyb (unsigned int key, bool special, bool release, int x, int y) { void CScore::Keyb(unsigned int key, bool special, bool release, int x, int y) {
KeyGUI(key, 0, release); KeyGUI(key, 0, release);
if (release) return; if (release) return;
switch (key) { switch (key) {
case SDLK_ESCAPE: case SDLK_ESCAPE:
State::manager.RequestEnterState (GameTypeSelect); State::manager.RequestEnterState(GameTypeSelect);
break; break;
case SDLK_q: case SDLK_q:
State::manager.RequestQuit(); State::manager.RequestQuit();
break; break;
case SDLK_s: case SDLK_s:
Score.SaveHighScore (); Score.SaveHighScore();
break; break;
case SDLK_l: case SDLK_l:
Score.LoadHighScore (); Score.LoadHighScore();
break; break;
case SDLK_RETURN: case SDLK_RETURN:
State::manager.RequestEnterState (GameTypeSelect); State::manager.RequestEnterState(GameTypeSelect);
break; break;
} }
} }
void CScore::Mouse (int button, int state, int x, int y) { void CScore::Mouse(int button, int state, int x, int y) {
if (state == 1) { if (state == 1) {
TWidget* clicked = ClickGUI(x, y); TWidget* clicked = ClickGUI(x, y);
if (clicked == textbutton) if (clicked == textbutton)
State::manager.RequestEnterState (GameTypeSelect); State::manager.RequestEnterState(GameTypeSelect);
} }
} }
void CScore::Motion (int x, int y) { void CScore::Motion(int x, int y) {
MouseMoveGUI(x, y); MouseMoveGUI(x, y);
if (param.ui_snow) push_ui_snow (cursor_pos); if (param.ui_snow) push_ui_snow(cursor_pos);
} }
static TArea area; static TArea area;
@ -216,17 +216,17 @@ static int linedist, listtop;
static int dd1, dd2, dd3, dd4; static int dd1, dd2, dd3, dd4;
void CScore::Enter() { void CScore::Enter() {
Winsys.ShowCursor (!param.ice_cursor); Winsys.ShowCursor(!param.ice_cursor);
Winsys.KeyRepeat (true); Winsys.KeyRepeat(true);
Music.Play (param.menu_music, -1); Music.Play(param.menu_music, -1);
framewidth = 550 * Winsys.scale; framewidth = 550 * Winsys.scale;
frameheight = 50 * Winsys.scale; frameheight = 50 * Winsys.scale;
frametop = AutoYPosN (32); frametop = AutoYPosN(32);
area = AutoAreaN (30, 80, framewidth); area = AutoAreaN(30, 80, framewidth);
FT.AutoSizeN (3); FT.AutoSizeN(3);
linedist = FT.AutoDistanceN (1); linedist = FT.AutoDistanceN(1);
listtop = AutoYPosN (44); listtop = AutoYPosN(44);
dd1 = 50 * Winsys.scale; dd1 = 50 * Winsys.scale;
dd2 = 115 * Winsys.scale; dd2 = 115 * Winsys.scale;
dd3 = 250 * Winsys.scale; dd3 = 250 * Winsys.scale;
@ -234,68 +234,67 @@ void CScore::Enter() {
CourseList = &Course.CourseList[0]; CourseList = &Course.CourseList[0];
ResetGUI (); ResetGUI();
course = AddUpDown(area.right + 8, frametop, 0, (int)Course.CourseList.size()-1, 0); course = AddUpDown(area.right + 8, frametop, 0, (int)Course.CourseList.size()-1, 0);
int siz = FT.AutoSizeN (5); int siz = FT.AutoSizeN(5);
textbutton = AddTextButton (Trans.Text(64), CENTER, AutoYPosN (80), siz); textbutton = AddTextButton(Trans.Text(64), CENTER, AutoYPosN(80), siz);
} }
const string ordinals[10] = const string ordinals[10] =
{"1:st", "2:nd", "3:rd", "4:th", "5:th", "6:th", "7:th", "8:th", "9:th", "10:th"}; {"1:st", "2:nd", "3:rd", "4:th", "5:th", "6:th", "7:th", "8:th", "9:th", "10:th"};
void CScore::Loop (double timestep) { void CScore::Loop(double timestep) {
int ww = Winsys.resolution.width; int ww = Winsys.resolution.width;
int hh = Winsys.resolution.height; int hh = Winsys.resolution.height;
Music.Update (); Music.Update();
check_gl_error(); ClearRenderContext();
ClearRenderContext ();
ScopedRenderMode rm(GUI); ScopedRenderMode rm(GUI);
SetupGuiDisplay (); SetupGuiDisplay();
if (param.ui_snow) { if (param.ui_snow) {
update_ui_snow (timestep); update_ui_snow(timestep);
draw_ui_snow(); draw_ui_snow();
} }
Tex.Draw (BOTTOM_LEFT, 0, hh - 256, 1); Tex.Draw(BOTTOM_LEFT, 0, hh - 256, 1);
Tex.Draw (BOTTOM_RIGHT, ww-256, hh-256, 1); Tex.Draw(BOTTOM_RIGHT, ww-256, hh-256, 1);
Tex.Draw (TOP_LEFT, 0, 0, 1); Tex.Draw(TOP_LEFT, 0, 0, 1);
Tex.Draw (TOP_RIGHT, ww-256, 0, 1); Tex.Draw(TOP_RIGHT, ww-256, 0, 1);
Tex.Draw (T_TITLE_SMALL, CENTER, AutoYPosN (5), Winsys.scale); Tex.Draw(T_TITLE_SMALL, CENTER, AutoYPosN(5), Winsys.scale);
// DrawFrameX (area.left, area.top, area.right-area.left, area.bottom - area.top, // DrawFrameX (area.left, area.top, area.right-area.left, area.bottom - area.top,
// 0, colMBackgr, colBlack, 0.2); // 0, colMBackgr, colBlack, 0.2);
FT.AutoSizeN (7); FT.AutoSizeN(7);
FT.SetColor (colWhite); FT.SetColor(colWhite);
FT.DrawString (CENTER, AutoYPosN (22), Trans.Text(62)); FT.DrawString(CENTER, AutoYPosN(22), Trans.Text(62));
DrawFrameX (area.left, frametop, framewidth, frameheight, 3, colMBackgr, colDYell, 1.0); DrawFrameX(area.left, frametop, framewidth, frameheight, 3, colMBackgr, colDYell, 1.0);
FT.AutoSizeN (5); FT.AutoSizeN(5);
FT.SetColor (colWhite); FT.SetColor(colWhite);
FT.DrawString (area.left+20, frametop, CourseList[course->GetValue()].name); FT.DrawString(area.left+20, frametop, CourseList[course->GetValue()].name);
const TScoreList *list = Score.GetScorelist (course->GetValue()); const TScoreList *list = Score.GetScorelist(course->GetValue());
FT.SetColor (colWhite); FT.SetColor(colWhite);
if (list != NULL) { if (list != NULL) {
FT.AutoSizeN (3); FT.AutoSizeN(3);
if (list->numScores < 1) { if (list->numScores < 1) {
FT.DrawString (CENTER, area.top + 140, Trans.Text(63)); FT.DrawString(CENTER, area.top + 140, Trans.Text(63));
} else { } else {
for (int i=0; i<min(MAX_SCORES, list->numScores); i++) { for (int i=0; i<min(MAX_SCORES, list->numScores); i++) {
int y = listtop + i*linedist; int y = listtop + i*linedist;
FT.DrawString (area.left, y, ordinals[i]); FT.DrawString(area.left, y, ordinals[i]);
FT.DrawString (area.left + dd1, y, Int_StrN (list->scores[i].points)); FT.DrawString(area.left + dd1, y, Int_StrN(list->scores[i].points));
FT.DrawString (area.left + dd2, y, list->scores[i].player); FT.DrawString(area.left + dd2, y, list->scores[i].player);
FT.DrawString (area.left + dd3, y, FT.DrawString(area.left + dd3, y,
Int_StrN (list->scores[i].herrings) + " herrings"); Int_StrN(list->scores[i].herrings) + " herrings");
FT.DrawString (area.left + dd4, y, FT.DrawString(area.left + dd4, y,
Float_StrN (list->scores[i].time, 1) + " sec"); Float_StrN(list->scores[i].time, 1) + " sec");
} }
} }
} else Message ("score list out of range"); } else Message("score list out of range");
DrawGUI(); DrawGUI();

View File

@ -47,11 +47,11 @@ private:
void Motion(int x, int y); void Motion(int x, int y);
public: public:
int AddScore(const TCourse* course, const TScore& score); int AddScore(const TCourse* course, const TScore& score);
const TScoreList *GetScorelist (size_t list_idx) const; const TScoreList *GetScorelist(size_t list_idx) const;
void PrintScorelist (size_t list_idx) const; void PrintScorelist(size_t list_idx) const;
bool SaveHighScore () const; bool SaveHighScore() const;
bool LoadHighScore (); bool LoadHighScore();
int CalcRaceResult (); int CalcRaceResult();
}; };
extern CScore Score; extern CScore Score;

View File

@ -25,10 +25,8 @@ GNU General Public License for more details.
#include "audio.h" #include "audio.h"
#include "gui.h" #include "gui.h"
#include "course.h" #include "course.h"
#include "tux.h"
#include "env.h" #include "env.h"
#include "particles.h" #include "particles.h"
#include "credits.h"
#include "font.h" #include "font.h"
#include "game_ctrl.h" #include "game_ctrl.h"
#include "translation.h" #include "translation.h"
@ -45,48 +43,47 @@ void CSplashScreen::Keyb(unsigned int key, bool special, bool release, int x, in
State::manager.RequestQuit(); State::manager.RequestQuit();
break; break;
case SDLK_RETURN: case SDLK_RETURN:
State::manager.RequestEnterState (Regist); State::manager.RequestEnterState(Regist);
break; break;
} }
} }
void CSplashScreen::Enter() { void CSplashScreen::Enter() {
Winsys.ShowCursor (!param.ice_cursor); Winsys.ShowCursor(!param.ice_cursor);
init_ui_snow (); Music.Play(param.menu_music, -1);
Music.Play (param.menu_music, -1);
} }
void CSplashScreen::Loop(double timestep) { void CSplashScreen::Loop(double timestep) {
Music.Update (); Music.Update();
check_gl_error(); ClearRenderContext();
ClearRenderContext ();
ScopedRenderMode rm(GUI); ScopedRenderMode rm(GUI);
SetupGuiDisplay (); SetupGuiDisplay();
Trans.LoadLanguages (); Trans.LoadTranslations(param.language); // Before first texts are being displayed
Trans.LoadTranslations (param.language); // Before first texts are being displayed
Tex.Draw (TEXLOGO, CENTER, 60, Winsys.scale); Tex.Draw(TEXLOGO, CENTER, 60, Winsys.scale/2.0);
FT.SetColor (colDYell); FT.SetColor(colDYell);
FT.AutoSizeN (6); FT.AutoSizeN(6);
int top = AutoYPosN (60); int dist = FT.AutoDistanceN (3); int top = AutoYPosN(60);
FT.DrawString (CENTER, top, Trans.Text(67)); int dist = FT.AutoDistanceN(3);
FT.DrawString (CENTER, top+dist, Trans.Text(68)); FT.DrawString(CENTER, top, Trans.Text(67));
FT.DrawString(CENTER, top+dist, Trans.Text(68));
Winsys.SwapBuffers(); Winsys.SwapBuffers();
Course.MakeStandardPolyhedrons (); init_ui_snow();
Sound.LoadSoundList ();
Credits.LoadCreditList ();
Char.LoadCharacterList ();
Course.LoadObjectTypes ();
Course.LoadTerrainTypes ();
Env.LoadEnvironmentList ();
Course.LoadCourseList ();
Score.LoadHighScore (); // after LoadCourseList !!!
Events.LoadEventList ();
Players.LoadAvatars (); // before LoadPlayers !!!
Players.LoadPlayers ();
State::manager.RequestEnterState (Regist); Course.MakeStandardPolyhedrons();
Sound.LoadSoundList();
Char.LoadCharacterList();
Course.LoadObjectTypes();
Course.LoadTerrainTypes();
Env.LoadEnvironmentList();
Course.LoadCourseList();
Score.LoadHighScore(); // after LoadCourseList !!!
Events.LoadEventList();
Players.LoadAvatars(); // before LoadPlayers !!!
Players.LoadPlayers();
State::manager.RequestEnterState(Regist);
} }

View File

@ -32,70 +32,70 @@ const string errorString = "error";
// elementary string functions // elementary string functions
// -------------------------------------------------------------------- // --------------------------------------------------------------------
string MakePathStr (const string& src, const string& add) { string MakePathStr(const string& src, const string& add) {
string res = src; string res = src;
res += SEP; res += SEP;
res += add; res += add;
return res; return res;
} }
void SInsertN (string &s, size_t pos, const string& ins) { void SInsertN(string &s, size_t pos, const string& ins) {
if (pos > s.size()) pos = s.size(); if (pos > s.size()) pos = s.size();
s.insert (pos, ins); s.insert(pos, ins);
} }
void SDeleteN (string &s, size_t pos, size_t count) { void SDeleteN(string &s, size_t pos, size_t count) {
if (pos > s.size()) pos = s.size(); if (pos > s.size()) pos = s.size();
s.erase (pos, count); s.erase(pos, count);
} }
size_t SPosN (const string &s, const string& find) { size_t SPosN(const string &s, const string& find) {
return s.find (find); return s.find(find);
} }
void STrimLeftN (string &s) { void STrimLeftN(string &s) {
size_t i = s.find_first_not_of(" \t"); size_t i = s.find_first_not_of(" \t");
if (i > 0) if (i > 0)
SDeleteN (s, 0, i); SDeleteN(s, 0, i);
} }
void STrimRightN (string &s) { void STrimRightN(string &s) {
size_t i = s.find_last_not_of(" \t"); size_t i = s.find_last_not_of(" \t");
if (i != s.size()-1) if (i != s.size()-1)
s.erase (i+1); s.erase(i+1);
} }
void STrimN (string &s) { void STrimN(string &s) {
STrimLeftN (s); STrimLeftN(s);
STrimRightN (s); STrimRightN(s);
} }
// -------------------------------------------------------------------- // --------------------------------------------------------------------
// conversion functions // conversion functions
// -------------------------------------------------------------------- // --------------------------------------------------------------------
string Int_StrN (const int val) { string Int_StrN(const int val) {
ostringstream os; ostringstream os;
os << val; os << val;
return os.str(); return os.str();
} }
string Int_StrN (const int val, const streamsize count) { string Int_StrN(const int val, const streamsize count) {
ostringstream os; ostringstream os;
os << setw(count) << setfill('0') << val; os << setw(count) << setfill('0') << val;
return os.str(); return os.str();
} }
string Float_StrN (const float val, const streamsize count) { string Float_StrN(const float val, const streamsize count) {
ostringstream os; ostringstream os;
os << setprecision(count) << fixed << val; os << setprecision(count) << fixed << val;
return os.str(); return os.str();
} }
string Vector_StrN (const TVector3d& v, const streamsize count) { string Vector_StrN(const TVector3d& v, const streamsize count) {
string res = Float_StrN (v.x, count); string res = Float_StrN(v.x, count);
res += ' ' + Float_StrN (v.y, count); res += ' ' + Float_StrN(v.y, count);
res += ' ' + Float_StrN (v.z, count); res += ' ' + Float_StrN(v.z, count);
return res; return res;
} }
@ -104,7 +104,7 @@ string Bool_StrN(const bool val) {
else return "false"; else return "false";
} }
int Str_IntN (const string &s, const int def) { int Str_IntN(const string &s, const int def) {
int val; int val;
istringstream is(s); istringstream is(s);
is >> val; is >> val;
@ -112,7 +112,7 @@ int Str_IntN (const string &s, const int def) {
else return val; else return val;
} }
bool Str_BoolN (const string &s, const bool def) { bool Str_BoolN(const string &s, const bool def) {
if (s == "0" || s == "false") if (s == "0" || s == "false")
return false; return false;
if (s == "1" || s == "true") if (s == "1" || s == "true")
@ -120,7 +120,7 @@ bool Str_BoolN (const string &s, const bool def) {
return Str_IntN(s, (int)def) != 0; // Try to parse as int return Str_IntN(s, (int)def) != 0; // Try to parse as int
} }
float Str_FloatN (const string &s, const float def) { float Str_FloatN(const string &s, const float def) {
float val; float val;
istringstream is(s); istringstream is(s);
is >> val; is >> val;
@ -162,7 +162,7 @@ template TVector4<double> Str_Vector4(const string &s, const TVector4<double> &d
template TVector4<int> Str_Vector4(const string &s, const TVector4<int> &def); template TVector4<int> Str_Vector4(const string &s, const TVector4<int> &def);
TColor Str_ColorN (const string &s, const TColor &def) { TColor Str_ColorN(const string &s, const TColor &def) {
float r, g, b, a; float r, g, b, a;
istringstream is(s); istringstream is(s);
is >> r >> g >> b >> a; is >> r >> g >> b >> a;
@ -170,7 +170,7 @@ TColor Str_ColorN (const string &s, const TColor &def) {
else return TColor(r, g, b, a); else return TColor(r, g, b, a);
} }
TColor3 Str_Color3N (const string &s, const TColor3 &def) { TColor3 Str_Color3N(const string &s, const TColor3 &def) {
float r, g, b; float r, g, b;
istringstream is(s); istringstream is(s);
is >> r >> g >> b; is >> r >> g >> b;
@ -178,7 +178,7 @@ TColor3 Str_Color3N (const string &s, const TColor3 &def) {
else return TColor3(r, g, b); else return TColor3(r, g, b);
} }
void Str_ArrN (const string &s, float *arr, size_t count, float def) { void Str_ArrN(const string &s, float *arr, size_t count, float def) {
istringstream is(s); istringstream is(s);
for (size_t i = 0; i < count; i++) for (size_t i = 0; i < count; i++)
is >> arr[i]; is >> arr[i];
@ -190,11 +190,11 @@ void Str_ArrN (const string &s, float *arr, size_t count, float def) {
// SP functions for parsing lines // SP functions for parsing lines
// -------------------------------------------------------------------- // --------------------------------------------------------------------
string SPItemN (const string &s, const string &tag) { string SPItemN(const string &s, const string &tag) {
if (s.empty() || tag.empty()) return ""; if (s.empty() || tag.empty()) return "";
string tg = '[' + tag + ']'; string tg = '[' + tag + ']';
size_t i = SPosN (s, tg); size_t i = SPosN(s, tg);
if (i == string::npos) return ""; if (i == string::npos) return "";
size_t ii = i + tg.size(); size_t ii = i + tg.size();
string item; string item;
@ -205,30 +205,30 @@ string SPItemN (const string &s, const string &tag) {
return item; return item;
} }
string SPStrN (const string &s, const string &tag, const string& def) { string SPStrN(const string &s, const string &tag, const string& def) {
string item = SPItemN (s, tag); string item = SPItemN(s, tag);
if (item.empty()) return def; if (item.empty()) return def;
STrimN (item); STrimN(item);
return item; return item;
} }
int SPIntN (const string &s, const string &tag, const int def) { int SPIntN(const string &s, const string &tag, const int def) {
return (Str_IntN (SPItemN (s, tag), def)); return (Str_IntN(SPItemN(s, tag), def));
} }
bool SPBoolN (const string &s, const string &tag, const bool def) { bool SPBoolN(const string &s, const string &tag, const bool def) {
string item = SPItemN (s, tag); string item = SPItemN(s, tag);
STrimN (item); STrimN(item);
return Str_BoolN (item, def); return Str_BoolN(item, def);
} }
float SPFloatN (const string &s, const string &tag, const float def) { float SPFloatN(const string &s, const string &tag, const float def) {
return (Str_FloatN (SPItemN (s, tag), def)); return (Str_FloatN(SPItemN(s, tag), def));
} }
template<typename T> template<typename T>
TVector2<T> SPVector2 (const string &s, const string &tag, const TVector2<T>& def) { TVector2<T> SPVector2(const string &s, const string &tag, const TVector2<T>& def) {
return (Str_Vector2(SPItemN (s, tag), def)); return (Str_Vector2(SPItemN(s, tag), def));
} }
template TVector2<int> SPVector2(const string &s, const string &tag, const TVector2<int>& def); template TVector2<int> SPVector2(const string &s, const string &tag, const TVector2<int>& def);
template TVector2<double> SPVector2(const string &s, const string &tag, const TVector2<double>& def); template TVector2<double> SPVector2(const string &s, const string &tag, const TVector2<double>& def);
@ -247,69 +247,69 @@ TVector4<T> SPVector4(const string &s, const string &tag, const TVector4<T>& def
template TVector4<int> SPVector4(const string &s, const string &tag, const TVector4<int>& def); template TVector4<int> SPVector4(const string &s, const string &tag, const TVector4<int>& def);
template TVector4<double> SPVector4(const string &s, const string &tag, const TVector4<double>& def); template TVector4<double> SPVector4(const string &s, const string &tag, const TVector4<double>& def);
TColor SPColorN (const string &s, const string &tag, const TColor& def) { TColor SPColorN(const string &s, const string &tag, const TColor& def) {
return (Str_ColorN (SPItemN (s, tag), def)); return (Str_ColorN(SPItemN(s, tag), def));
} }
TColor3 SPColor3N (const string &s, const string &tag, const TColor3& def) { TColor3 SPColor3N(const string &s, const string &tag, const TColor3& def) {
return (Str_Color3N (SPItemN (s, tag), def)); return (Str_Color3N(SPItemN(s, tag), def));
} }
void SPArrN (const string &s, const string &tag, float *arr, size_t count, float def) { void SPArrN(const string &s, const string &tag, float *arr, size_t count, float def) {
Str_ArrN (SPItemN (s, tag), arr, count, def); Str_ArrN(SPItemN(s, tag), arr, count, def);
} }
size_t SPPosN (const string &s, const string &tag) { size_t SPPosN(const string &s, const string &tag) {
string tg = '[' + tag + ']'; string tg = '[' + tag + ']';
return SPosN (s, tg); return SPosN(s, tg);
} }
// ------------------ add --------------------------------------------- // ------------------ add ---------------------------------------------
void SPAddIntN (string &s, const string &tag, const int val) { void SPAddIntN(string &s, const string &tag, const int val) {
s += '['; s += '[';
s += tag; s += tag;
s += ']'; s += ']';
s += Int_StrN (val); s += Int_StrN(val);
} }
void SPAddFloatN (string &s, const string &tag, const float val, size_t count) { void SPAddFloatN(string &s, const string &tag, const float val, size_t count) {
s += '['; s += '[';
s += tag; s += tag;
s += ']'; s += ']';
s += Float_StrN (val, count); s += Float_StrN(val, count);
} }
void SPAddStrN (string &s, const string &tag, const string &val) { void SPAddStrN(string &s, const string &tag, const string &val) {
s += '['; s += '[';
s += tag; s += tag;
s += ']'; s += ']';
s += val; s += val;
} }
void SPAddVec2N (string &s, const string &tag, const TVector2d &val, size_t count) { void SPAddVec2N(string &s, const string &tag, const TVector2d &val, size_t count) {
s += '['; s += '[';
s += tag; s += tag;
s += ']'; s += ']';
s += ' '; s += ' ';
s += Float_StrN (val.x, count); s += Float_StrN(val.x, count);
s += ' '; s += ' ';
s += Float_StrN (val.y, count); s += Float_StrN(val.y, count);
} }
void SPAddVec3N (string &s, const string &tag, const TVector3d &val, size_t count) { void SPAddVec3N(string &s, const string &tag, const TVector3d &val, size_t count) {
s += '['; s += '[';
s += tag; s += tag;
s += ']'; s += ']';
s += ' '; s += ' ';
s += Float_StrN (val.x, count); s += Float_StrN(val.x, count);
s += ' '; s += ' ';
s += Float_StrN (val.y, count); s += Float_StrN(val.y, count);
s += ' '; s += ' ';
s += Float_StrN (val.z, count); s += Float_StrN(val.z, count);
} }
void SPAddBoolN (string &s, const string &tag, const bool val) { void SPAddBoolN(string &s, const string &tag, const bool val) {
s += '['; s += '[';
s += tag; s += tag;
s += ']'; s += ']';
@ -319,34 +319,34 @@ void SPAddBoolN (string &s, const string &tag, const bool val) {
// -------------------------------------------------------------------- // --------------------------------------------------------------------
void SPSetIntN (string &s, const string &tag, const int val) { void SPSetIntN(string &s, const string &tag, const int val) {
size_t pos = SPPosN (s, tag); size_t pos = SPPosN(s, tag);
if (pos != string::npos) { if (pos != string::npos) {
size_t ipos = pos + tag.size() + 2; size_t ipos = pos + tag.size() + 2;
string item = SPItemN (s, tag); string item = SPItemN(s, tag);
if (item.size() != string::npos) SDeleteN (s, ipos, item.size()); if (item.size() != string::npos) SDeleteN(s, ipos, item.size());
SInsertN (s, ipos, Int_StrN (val)); SInsertN(s, ipos, Int_StrN(val));
} else SPAddIntN (s, tag, val); } else SPAddIntN(s, tag, val);
} }
void SPSetFloatN (string &s, const string &tag, const float val, size_t count) { void SPSetFloatN(string &s, const string &tag, const float val, size_t count) {
size_t pos = SPPosN (s, tag); size_t pos = SPPosN(s, tag);
if (pos != string::npos) { if (pos != string::npos) {
size_t ipos = pos + tag.size() + 2; size_t ipos = pos + tag.size() + 2;
string item = SPItemN (s, tag); string item = SPItemN(s, tag);
if (item.size() != string::npos) SDeleteN (s, ipos, item.size()); if (item.size() != string::npos) SDeleteN(s, ipos, item.size());
SInsertN (s, ipos, Float_StrN (val, count)); SInsertN(s, ipos, Float_StrN(val, count));
} else SPAddFloatN (s, tag, val, count); } else SPAddFloatN(s, tag, val, count);
} }
void SPSetStrN (string &s, const string &tag, const string &val) { void SPSetStrN(string &s, const string &tag, const string &val) {
size_t pos = SPPosN (s, tag); size_t pos = SPPosN(s, tag);
if (pos != string::npos) { if (pos != string::npos) {
size_t ipos = pos + tag.size() + 2; size_t ipos = pos + tag.size() + 2;
string item = SPItemN (s, tag); string item = SPItemN(s, tag);
if (item.size() != string::npos) SDeleteN (s, ipos, item.size()); if (item.size() != string::npos) SDeleteN(s, ipos, item.size());
SInsertN (s, ipos, val); SInsertN(s, ipos, val);
} else SPAddStrN (s, tag, val); } else SPAddStrN(s, tag, val);
} }
// -------------------------------------------------------------------- // --------------------------------------------------------------------
@ -354,52 +354,52 @@ void SPSetStrN (string &s, const string &tag, const string &val) {
// -------------------------------------------------------------------- // --------------------------------------------------------------------
CSPList::CSPList (size_t maxlines, bool newlineflag) { CSPList::CSPList(size_t maxlines, bool newlineflag) {
fmax = maxlines; fmax = maxlines;
fnewlineflag = newlineflag; fnewlineflag = newlineflag;
} }
const string& CSPList::Line (size_t idx) const { const string& CSPList::Line(size_t idx) const {
if (idx >= flines.size()) return emptyString; if (idx >= flines.size()) return emptyString;
return flines[idx]; return flines[idx];
} }
void CSPList::Add (const string& line) { void CSPList::Add(const string& line) {
if (flines.size() < fmax) { if (flines.size() < fmax) {
flines.push_back(line); flines.push_back(line);
} }
} }
void CSPList::AddLine () { void CSPList::AddLine() {
if (flines.size() < fmax) { if (flines.size() < fmax) {
flines.push_back(emptyString); flines.push_back(emptyString);
} }
} }
void CSPList::Append (const string& line, size_t idx) { void CSPList::Append(const string& line, size_t idx) {
if (idx >= flines.size()) return; if (idx >= flines.size()) return;
flines[idx] += line; flines[idx] += line;
} }
void CSPList::Print () const { void CSPList::Print() const {
for (size_t i = 0; i < flines.size(); i++) for (size_t i = 0; i < flines.size(); i++)
cout << flines[i] << endl; cout << flines[i] << endl;
} }
bool CSPList::Load (const string &filepath) { bool CSPList::Load(const string &filepath) {
std::ifstream tempfile(filepath.c_str()); std::ifstream tempfile(filepath.c_str());
string line; string line;
if (!tempfile) { if (!tempfile) {
Message ("CSPList::Load - unable to open " + filepath); Message("CSPList::Load - unable to open " + filepath);
return false; return false;
} else { } else {
bool backflag = false; bool backflag = false;
while (getline(tempfile, line)) { while (getline(tempfile, line)) {
// delete new line char if in string // delete new line char if in string
size_t npos = line.rfind ('\n'); size_t npos = line.rfind('\n');
if (npos != string::npos) SDeleteN (line, npos, 1); if (npos != string::npos) SDeleteN(line, npos, 1);
bool valid = true; bool valid = true;
if (line.empty()) valid = false; // empty line if (line.empty()) valid = false; // empty line
@ -408,24 +408,24 @@ bool CSPList::Load (const string &filepath) {
if (valid) { if (valid) {
if (flines.size() < fmax) { if (flines.size() < fmax) {
if (!fnewlineflag) { if (!fnewlineflag) {
if (line[0] == '*' || flines.empty()) Add (line); if (line[0] == '*' || flines.empty()) Add(line);
else Append (line, flines.size()-1); else Append(line, flines.size()-1);
} else { } else {
bool fwdflag; bool fwdflag;
if (line[line.length()-1] == '\\') { if (line[line.length()-1] == '\\') {
SDeleteN (line, line.length()-1, 1); SDeleteN(line, line.length()-1, 1);
fwdflag = true; fwdflag = true;
} else { } else {
fwdflag = false; fwdflag = false;
} }
if (backflag == false) Add (line); if (backflag == false) Add(line);
else Append (line, flines.size()-1); else Append(line, flines.size()-1);
backflag = fwdflag; backflag = fwdflag;
} }
} else { } else {
Message ("CSPList::Load - not enough lines"); Message("CSPList::Load - not enough lines");
return false; return false;
} }
} }
@ -434,14 +434,14 @@ bool CSPList::Load (const string &filepath) {
} }
} }
bool CSPList::Load (const string& dir, const string& filename) { bool CSPList::Load(const string& dir, const string& filename) {
return Load (dir + SEP + filename); return Load(dir + SEP + filename);
} }
bool CSPList::Save (const string &filepath) const { bool CSPList::Save(const string &filepath) const {
std::ofstream tempfile(filepath.c_str()); std::ofstream tempfile(filepath.c_str());
if (!tempfile) { if (!tempfile) {
Message ("CSPList::Save - unable to open " + filepath); Message("CSPList::Save - unable to open " + filepath);
return false; return false;
} else { } else {
for (size_t i=0; i<flines.size(); i++) { for (size_t i=0; i<flines.size(); i++) {
@ -451,17 +451,17 @@ bool CSPList::Save (const string &filepath) const {
} }
} }
bool CSPList::Save (const string& dir, const string& filename) const { bool CSPList::Save(const string& dir, const string& filename) const {
return Save (dir + SEP + filename); return Save(dir + SEP + filename);
} }
void CSPList::MakeIndex (map<string, size_t>& index, const string &tag) { void CSPList::MakeIndex(map<string, size_t>& index, const string &tag) {
index.clear(); index.clear();
size_t idx = 0; size_t idx = 0;
for (size_t i=0; i<flines.size(); i++) { for (size_t i=0; i<flines.size(); i++) {
string item = SPItemN (flines[i], tag); string item = SPItemN(flines[i], tag);
STrimN (item); STrimN(item);
if (!item.empty()) { if (!item.empty()) {
index[item] = idx; index[item] = idx;
idx++; idx++;

View File

@ -28,22 +28,22 @@ extern const string emptyString;
extern const string errorString; extern const string errorString;
// ----- elementary string functions ---------------------------------- // ----- elementary string functions ----------------------------------
string MakePathStr (const string& src, const string& add); string MakePathStr(const string& src, const string& add);
void SInsertN (string &s, size_t pos, const string& ins); void SInsertN(string &s, size_t pos, const string& ins);
void SDeleteN (string &s, size_t pos, size_t count); void SDeleteN(string &s, size_t pos, size_t count);
size_t SPosN (const string &s, const string& find); size_t SPosN(const string &s, const string& find);
void STrimLeftN (string &s); void STrimLeftN(string &s);
void STrimRightN (string &s); void STrimRightN(string &s);
void STrimN (string &s); void STrimN(string &s);
// ----- conversion functions ----------------------------------------- // ----- conversion functions -----------------------------------------
string Int_StrN (const int val); string Int_StrN(const int val);
string Int_StrN (const int val, const streamsize count); string Int_StrN(const int val, const streamsize count);
string Float_StrN (const float val, const streamsize count); string Float_StrN(const float val, const streamsize count);
string Bool_StrN (const bool val); string Bool_StrN(const bool val);
string Vector_StrN (const TVector3d& v, const streamsize count); string Vector_StrN(const TVector3d& v, const streamsize count);
int Str_IntN (const string &s, const int def); int Str_IntN(const string &s, const int def);
bool Str_BoolN (const string &s, const bool def); bool Str_BoolN(const string &s, const bool def);
float Str_FloatN(const string &s, const float def); float Str_FloatN(const string &s, const float def);
template<typename T> template<typename T>
TVector2<T> Str_Vector2(const string &s, const TVector2<T>& def); TVector2<T> Str_Vector2(const string &s, const TVector2<T>& def);
@ -51,17 +51,17 @@ template<typename T>
TVector3<T> Str_Vector3(const string &s, const TVector3<T>& def); TVector3<T> Str_Vector3(const string &s, const TVector3<T>& def);
template<typename T> template<typename T>
TVector4<T> Str_Vector4(const string &s, const TVector4<T>& def); TVector4<T> Str_Vector4(const string &s, const TVector4<T>& def);
TColor Str_ColorN (const string &s, const TColor& def); TColor Str_ColorN(const string &s, const TColor& def);
TColor3 Str_Color3N (const string &s, const TColor3& def); TColor3 Str_Color3N(const string &s, const TColor3& def);
void Str_ArrN (const string &s, float *arr, size_t count, float def); void Str_ArrN(const string &s, float *arr, size_t count, float def);
// ----- SP functions for parsing lines -------------------------------- // ----- SP functions for parsing lines --------------------------------
size_t SPPosN (const string &s, const string &tag); size_t SPPosN(const string &s, const string &tag);
string SPStrN (const string &s, const string &tag, const string& def = emptyString); string SPStrN(const string &s, const string &tag, const string& def = emptyString);
int SPIntN (const string &s, const string &tag, const int def); int SPIntN(const string &s, const string &tag, const int def);
bool SPBoolN (const string &s, const string &tag, const bool def); bool SPBoolN(const string &s, const string &tag, const bool def);
float SPFloatN (const string &s, const string &tag, const float def); float SPFloatN(const string &s, const string &tag, const float def);
template<typename T> template<typename T>
TVector2<T> SPVector2(const string &s, const string &tag, const TVector2<T>& def); TVector2<T> SPVector2(const string &s, const string &tag, const TVector2<T>& def);
static inline TVector2d SPVector2d(const string &s, const string &tag) { return SPVector2(s, tag, NullVec2); } static inline TVector2d SPVector2d(const string &s, const string &tag) { return SPVector2(s, tag, NullVec2); }
@ -74,22 +74,22 @@ template<typename T>
TVector4<T> SPVector4(const string &s, const string &tag, const TVector4<T>& def); TVector4<T> SPVector4(const string &s, const string &tag, const TVector4<T>& def);
static inline TVector4d SPVector4d(const string &s, const string &tag) { return SPVector4(s, tag, NullVec4); } static inline TVector4d SPVector4d(const string &s, const string &tag) { return SPVector4(s, tag, NullVec4); }
static inline TVector4i SPVector4i(const string &s, const string &tag) { return SPVector4(s, tag, NullVec4i); } static inline TVector4i SPVector4i(const string &s, const string &tag) { return SPVector4(s, tag, NullVec4i); }
TColor SPColorN (const string &s, const string &tag, const TColor& def); TColor SPColorN(const string &s, const string &tag, const TColor& def);
TColor3 SPColor3N (const string &s, const string &tag, const TColor3& def); TColor3 SPColor3N(const string &s, const string &tag, const TColor3& def);
void SPArrN (const string &s, const string &tag, float *arr, size_t count, float def); void SPArrN(const string &s, const string &tag, float *arr, size_t count, float def);
// ----- making SP strings -------------------------------------------- // ----- making SP strings --------------------------------------------
void SPAddIntN (string &s, const string &tag, const int val); void SPAddIntN(string &s, const string &tag, const int val);
void SPAddFloatN (string &s, const string &tag, const float val, size_t count); void SPAddFloatN(string &s, const string &tag, const float val, size_t count);
void SPAddStrN (string &s, const string &tag, const string &val); void SPAddStrN(string &s, const string &tag, const string &val);
void SPAddVec2N (string &s, const string &tag, const TVector2d& val, size_t count); void SPAddVec2N(string &s, const string &tag, const TVector2d& val, size_t count);
void SPAddVec3N (string &s, const string &tag, const TVector3d& val, size_t count); void SPAddVec3N(string &s, const string &tag, const TVector3d& val, size_t count);
void SPAddBoolN (string &s, const string &tag, const bool val); void SPAddBoolN(string &s, const string &tag, const bool val);
// ----- manipulating SP strings -------------------------------------- // ----- manipulating SP strings --------------------------------------
void SPSetIntN (string &s, const string &tag, const int val); void SPSetIntN(string &s, const string &tag, const int val);
void SPSetFloatN (string &s, const string &tag, const float val, size_t count); void SPSetFloatN(string &s, const string &tag, const float val, size_t count);
void SPSetStrN (string &s, const string &tag, const string &val); void SPSetStrN(string &s, const string &tag, const string &val);
// -------------------------------------------------------------------- // --------------------------------------------------------------------
// string list // string list
@ -101,21 +101,21 @@ private:
size_t fmax; size_t fmax;
bool fnewlineflag; bool fnewlineflag;
public: public:
CSPList (size_t maxlines, bool newlineflag = false); CSPList(size_t maxlines, bool newlineflag = false);
const string& Line (size_t idx) const; const string& Line(size_t idx) const;
size_t Count () const { return flines.size(); } size_t Count() const { return flines.size(); }
void Clear () { flines.clear(); } void Clear() { flines.clear(); }
void Add (const string& line); void Add(const string& line);
void AddLine(); void AddLine();
void Append (const string& line, size_t idx); void Append(const string& line, size_t idx);
void Print () const; void Print() const;
bool Load (const string &filepath); bool Load(const string &filepath);
bool Load (const string& dir, const string& filename); bool Load(const string& dir, const string& filename);
bool Save (const string &filepath) const; bool Save(const string &filepath) const;
bool Save (const string& dir, const string& filename) const; bool Save(const string& dir, const string& filename) const;
void MakeIndex (map<string, size_t>& index, const string &tag); void MakeIndex(map<string, size_t>& index, const string &tag);
}; };
#endif #endif

View File

@ -66,7 +66,7 @@ void State::Manager::PollEvent() {
unsigned int key; unsigned int key;
int x, y; int x, y;
while (SDL_PollEvent (&event)) { while (SDL_PollEvent(&event)) {
if (!next) { if (!next) {
switch (event.type) { switch (event.type) {
case SDL_KEYDOWN: case SDL_KEYDOWN:
@ -116,7 +116,7 @@ void State::Manager::PollEvent() {
if (Winsys.resolution.width != event.resize.w || Winsys.resolution.height != event.resize.h) { if (Winsys.resolution.width != event.resize.w || Winsys.resolution.height != event.resize.h) {
Winsys.resolution.width = event.resize.w; Winsys.resolution.width = event.resize.w;
Winsys.resolution.height = event.resize.h; Winsys.resolution.height = event.resize.h;
Winsys.SetupVideoMode (param.res_type); Winsys.SetupVideoMode(param.res_type);
Reshape(event.resize.w, event.resize.h); Reshape(event.resize.w, event.resize.h);
} }
break; break;
@ -130,6 +130,8 @@ void State::Manager::PollEvent() {
} }
void State::Manager::CallLoopFunction() { void State::Manager::CallLoopFunction() {
check_gl_error();
float cur_time = SDL_GetTicks() * 1.e-3; float cur_time = SDL_GetTicks() * 1.e-3;
g_game.time_step = cur_time - clock_time; g_game.time_step = cur_time - clock_time;
if (g_game.time_step < 0.0001) g_game.time_step = 0.0001; if (g_game.time_step < 0.0001) g_game.time_step = 0.0001;

View File

@ -41,7 +41,7 @@ static const GLshort fullsize_texture[] = {
// class CImage // class CImage
// -------------------------------------------------------------------- // --------------------------------------------------------------------
CImage::CImage () { CImage::CImage() {
data = NULL; data = NULL;
nx = 0; nx = 0;
ny = 0; ny = 0;
@ -49,22 +49,22 @@ CImage::CImage () {
pitch = 0; pitch = 0;
} }
CImage::~CImage () { CImage::~CImage() {
DisposeData (); DisposeData();
} }
void CImage::DisposeData () { void CImage::DisposeData() {
delete[] data; delete[] data;
data = NULL; data = NULL;
} }
bool CImage::LoadPng (const char *filepath, bool mirroring) { bool CImage::LoadPng(const char *filepath, bool mirroring) {
SDL_Surface *sdlImage; SDL_Surface *sdlImage;
unsigned char *sdlData; unsigned char *sdlData;
sdlImage = IMG_Load (filepath); sdlImage = IMG_Load(filepath);
if (sdlImage == 0) { if (sdlImage == 0) {
Message ("could not load image", filepath); Message("could not load image", filepath);
return false; return false;
} }
@ -72,13 +72,13 @@ bool CImage::LoadPng (const char *filepath, bool mirroring) {
ny = sdlImage->h; ny = sdlImage->h;
depth = sdlImage->format->BytesPerPixel; depth = sdlImage->format->BytesPerPixel;
pitch = sdlImage->pitch; pitch = sdlImage->pitch;
DisposeData (); DisposeData();
data = new unsigned char[pitch * ny]; data = new unsigned char[pitch * ny];
if (SDL_MUSTLOCK (sdlImage)) { if (SDL_MUSTLOCK(sdlImage)) {
if (SDL_LockSurface (sdlImage) < 0) { if (SDL_LockSurface(sdlImage) < 0) {
SDL_FreeSurface (sdlImage); SDL_FreeSurface(sdlImage);
Message ("mustlock error"); Message("mustlock error");
return false; return false;
}; };
} }
@ -93,67 +93,67 @@ bool CImage::LoadPng (const char *filepath, bool mirroring) {
memcpy(data, sdlData, ny*pitch); memcpy(data, sdlData, ny*pitch);
} }
if (SDL_MUSTLOCK (sdlImage)) SDL_UnlockSurface (sdlImage); if (SDL_MUSTLOCK(sdlImage)) SDL_UnlockSurface(sdlImage);
SDL_FreeSurface (sdlImage); SDL_FreeSurface(sdlImage);
return true; return true;
} }
bool CImage::LoadPng (const char *dir, const char *filename, bool mirroring) { bool CImage::LoadPng(const char *dir, const char *filename, bool mirroring) {
string path = dir; string path = dir;
path += SEP; path += SEP;
path += filename; path += filename;
return LoadPng (path.c_str(), mirroring); return LoadPng(path.c_str(), mirroring);
} }
// ------------------ read framebuffer -------------------------------- // ------------------ read framebuffer --------------------------------
bool CImage::ReadFrameBuffer_PPM () { bool CImage::ReadFrameBuffer_PPM() {
int viewport[4]; int viewport[4];
glGetIntegerv (GL_VIEWPORT, viewport); glGetIntegerv(GL_VIEWPORT, viewport);
nx = viewport[2]; nx = viewport[2];
ny = viewport[3]; ny = viewport[3];
depth = 3; depth = 3;
DisposeData (); DisposeData();
data = new unsigned char[nx * ny * depth]; data = new unsigned char[nx * ny * depth];
glReadBuffer (GL_FRONT); glReadBuffer(GL_FRONT);
for (int i=0; i<viewport[3]; i++) { for (int i=0; i<viewport[3]; i++) {
glReadPixels (viewport[0], viewport[1] + viewport[3] - 1 - i, glReadPixels(viewport[0], viewport[1] + viewport[3] - 1 - i,
viewport[2], 1, GL_RGB, GL_UNSIGNED_BYTE, data + viewport[2] * i * 3); viewport[2], 1, GL_RGB, GL_UNSIGNED_BYTE, data + viewport[2] * i * 3);
} }
return true; return true;
} }
void CImage::ReadFrameBuffer_TGA () { void CImage::ReadFrameBuffer_TGA() {
nx = Winsys.resolution.width; nx = Winsys.resolution.width;
ny = Winsys.resolution.height; ny = Winsys.resolution.height;
depth = 3; depth = 3;
DisposeData (); DisposeData();
data = new unsigned char[nx * ny * depth]; data = new unsigned char[nx * ny * depth];
glReadBuffer (GL_FRONT); glReadBuffer(GL_FRONT);
glReadPixels (0, 0, nx, ny, GL_BGR, GL_UNSIGNED_BYTE, data); glReadPixels(0, 0, nx, ny, GL_BGR, GL_UNSIGNED_BYTE, data);
} }
void CImage::ReadFrameBuffer_BMP () { void CImage::ReadFrameBuffer_BMP() {
nx = Winsys.resolution.width; nx = Winsys.resolution.width;
ny = Winsys.resolution.height; ny = Winsys.resolution.height;
depth = 4; depth = 4;
DisposeData (); DisposeData();
data = new unsigned char[nx * ny * depth]; data = new unsigned char[nx * ny * depth];
glReadBuffer (GL_FRONT); glReadBuffer(GL_FRONT);
glReadPixels (0, 0, nx, ny, GL_BGRA, GL_UNSIGNED_BYTE, data); glReadPixels(0, 0, nx, ny, GL_BGRA, GL_UNSIGNED_BYTE, data);
} }
// --------------------------- // ---------------------------
void CImage::WritePPM (const char *filepath) { void CImage::WritePPM(const char *filepath) {
if (data == NULL) if (data == NULL)
return; return;
@ -188,7 +188,7 @@ struct TTgaHeader {
} __attribute__((packed)); } __attribute__((packed));
#endif #endif
void CImage::WriteTGA (const char *filepath) { void CImage::WriteTGA(const char *filepath) {
if (data == NULL) if (data == NULL)
return; return;
@ -246,7 +246,7 @@ struct TBmpInfo {
} __attribute__((packed)); } __attribute__((packed));
#endif #endif
void CImage::WriteBMP (const char *filepath) { void CImage::WriteBMP(const char *filepath) {
if (data == NULL) if (data == NULL)
return; return;
@ -282,7 +282,7 @@ void CImage::WriteBMP (const char *filepath) {
std::ofstream out(filepath, std::ios_base::out|std::ios_base::binary); std::ofstream out(filepath, std::ios_base::out|std::ios_base::binary);
if (!out) { if (!out) {
Message ("could not open bmp file", filepath); Message("could not open bmp file", filepath);
return; return;
} }
@ -297,26 +297,26 @@ void CImage::WriteBMP (const char *filepath) {
// -------------------------------------------------------------------- // --------------------------------------------------------------------
TTexture::~TTexture() { TTexture::~TTexture() {
glDeleteTextures (1, &id); glDeleteTextures(1, &id);
} }
bool TTexture::Load(const string& filename) { bool TTexture::Load(const string& filename) {
CImage texImage; CImage texImage;
if (texImage.LoadPng (filename.c_str(), true) == false) if (texImage.LoadPng(filename.c_str(), true) == false)
return false; return false;
glGenTextures (1, &id); glGenTextures(1, &id);
glBindTexture (GL_TEXTURE_2D, id); glBindTexture(GL_TEXTURE_2D, id);
glPixelStorei (GL_UNPACK_ALIGNMENT, 4); glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
GLenum format; GLenum format;
if (texImage.depth == 3) format = GL_RGB; if (texImage.depth == 3) format = GL_RGB;
else format = GL_RGBA; else format = GL_RGBA;
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexImage2D glTexImage2D
(GL_TEXTURE_2D, 0, texImage.depth, texImage.nx, (GL_TEXTURE_2D, 0, texImage.depth, texImage.nx,
@ -329,27 +329,27 @@ bool TTexture::Load(const string& dir, const string& filename) {
bool TTexture::LoadMipmap(const string& filename, bool repeatable) { bool TTexture::LoadMipmap(const string& filename, bool repeatable) {
CImage texImage; CImage texImage;
if (texImage.LoadPng (filename.c_str(), true) == false) if (texImage.LoadPng(filename.c_str(), true) == false)
return false; return false;
glGenTextures (1, &id); glGenTextures(1, &id);
glBindTexture (GL_TEXTURE_2D, id); glBindTexture(GL_TEXTURE_2D, id);
glPixelStorei (GL_UNPACK_ALIGNMENT, 4); glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
if (repeatable) { if (repeatable) {
glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
} else { } else {
glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
} }
GLenum format; GLenum format;
if (texImage.depth == 3) format = GL_RGB; if (texImage.depth == 3) format = GL_RGB;
else format = GL_RGBA; else format = GL_RGBA;
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
gluBuild2DMipmaps(GL_TEXTURE_2D, texImage.depth, texImage.nx, texImage.ny, format, GL_UNSIGNED_BYTE, texImage.data); gluBuild2DMipmaps(GL_TEXTURE_2D, texImage.depth, texImage.nx, texImage.ny, format, GL_UNSIGNED_BYTE, texImage.data);
return true; return true;
@ -359,18 +359,18 @@ bool TTexture::LoadMipmap(const string& dir, const string& filename, bool repeat
} }
void TTexture::Bind() { void TTexture::Bind() {
glBindTexture (GL_TEXTURE_2D, id); glBindTexture(GL_TEXTURE_2D, id);
} }
void TTexture::Draw() { void TTexture::Draw() {
GLint w, h; GLint w, h;
glEnable (GL_TEXTURE_2D); glEnable(GL_TEXTURE_2D);
glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glBindTexture (GL_TEXTURE_2D, id); glBindTexture(GL_TEXTURE_2D, id);
glGetTexLevelParameteriv (GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &w); glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &w);
glGetTexLevelParameteriv (GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &h); glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &h);
glColor4f(1.0, 1.0, 1.0, 1.0); glColor4f(1.0, 1.0, 1.0, 1.0);
const GLshort vtx[] = { const GLshort vtx[] = {
@ -394,12 +394,12 @@ void TTexture::Draw(int x, int y, float size, Orientation orientation) {
GLint w, h; GLint w, h;
GLfloat width, height, top, bott, left, right; GLfloat width, height, top, bott, left, right;
glEnable (GL_TEXTURE_2D); glEnable(GL_TEXTURE_2D);
glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glBindTexture (GL_TEXTURE_2D, id); glBindTexture(GL_TEXTURE_2D, id);
glGetTexLevelParameteriv (GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &w); glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &w);
glGetTexLevelParameteriv (GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &h); glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &h);
width = w * size; width = w * size;
height = h * size; height = h * size;
@ -437,9 +437,9 @@ void TTexture::Draw(int x, int y, float size, Orientation orientation) {
void TTexture::Draw(int x, int y, float width, float height, Orientation orientation) { void TTexture::Draw(int x, int y, float width, float height, Orientation orientation) {
GLfloat top, bott, left, right; GLfloat top, bott, left, right;
glEnable (GL_TEXTURE_2D); glEnable(GL_TEXTURE_2D);
glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glBindTexture (GL_TEXTURE_2D, id); glBindTexture(GL_TEXTURE_2D, id);
if (orientation == OR_TOP) { if (orientation == OR_TOP) {
top = Winsys.resolution.height - y; top = Winsys.resolution.height - y;
@ -479,17 +479,17 @@ void TTexture::DrawFrame(int x, int y, double w, double h, int frame, const TCol
GLint xx = x; GLint xx = x;
GLint yy = Winsys.resolution.height - hh - y; GLint yy = Winsys.resolution.height - hh - y;
glBindTexture (GL_TEXTURE_2D, id); glBindTexture(GL_TEXTURE_2D, id);
glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY);
if (frame > 0) { if (frame > 0) {
if (w < 1) glGetTexLevelParameteriv (GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &ww); if (w < 1) glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &ww);
if (h < 1) glGetTexLevelParameteriv (GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &hh); if (h < 1) glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &hh);
glColor(col, 1.0); glColor(col, 1.0);
glDisable (GL_TEXTURE_2D); glDisable(GL_TEXTURE_2D);
const GLint vtx [] = { const GLint vtx [] = {
xx - frame, yy - frame, xx - frame, yy - frame,
xx + ww + frame, yy - frame, xx + ww + frame, yy - frame,
@ -500,10 +500,10 @@ void TTexture::DrawFrame(int x, int y, double w, double h, int frame, const TCol
glVertexPointer(2, GL_INT, 0, vtx); glVertexPointer(2, GL_INT, 0, vtx);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4); glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
glEnable (GL_TEXTURE_2D); glEnable(GL_TEXTURE_2D);
} }
glColor4f (1.0, 1.0, 1.0, 1.0); glColor4f(1.0, 1.0, 1.0, 1.0);
const GLshort vtx[] = { const GLshort vtx[] = {
xx, yy, xx, yy,
@ -526,115 +526,83 @@ void TTexture::DrawFrame(int x, int y, double w, double h, int frame, const TCol
CTexture Tex; CTexture Tex;
CTexture::CTexture () { CTexture::CTexture() {
forientation = OR_TOP; forientation = OR_TOP;
} }
CTexture::~CTexture () { CTexture::~CTexture() {
FreeTextureList(); FreeTextureList();
} }
void CTexture::LoadTextureList () { void CTexture::LoadTextureList() {
FreeTextureList(); FreeTextureList();
CSPList list (200); CSPList list(200);
if (list.Load (param.tex_dir, "textures.lst")) { if (list.Load(param.tex_dir, "textures.lst")) {
for (size_t i=0; i<list.Count(); i++) { for (size_t i=0; i<list.Count(); i++) {
const string& line = list.Line(i); const string& line = list.Line(i);
string name = SPStrN (line, "name"); string name = SPStrN(line, "name");
int id = SPIntN (line, "id", -1); int id = SPIntN(line, "id", -1);
CommonTex.resize(max(CommonTex.size(), (size_t)id+1)); CommonTex.resize(max(CommonTex.size(), (size_t)id+1));
string texfile = SPStrN (line, "file"); string texfile = SPStrN(line, "file");
bool rep = SPBoolN (line, "repeat", false); bool rep = SPBoolN(line, "repeat", false);
if (id >= 0) { if (id >= 0) {
CommonTex[id] = new TTexture(); CommonTex[id] = new TTexture();
if (rep) if (rep)
CommonTex[id]->LoadMipmap(param.tex_dir, texfile, rep); CommonTex[id]->LoadMipmap(param.tex_dir, texfile, rep);
else else
CommonTex[id]->Load(param.tex_dir, texfile); CommonTex[id]->Load(param.tex_dir, texfile);
} else Message("wrong texture id in textures.lst");
Index[name] = CommonTex[id];
} else Message ("wrong texture id in textures.lst");
} }
} else Message ("failed to load common textures"); } else Message("failed to load common textures");
} }
void CTexture::FreeTextureList () { void CTexture::FreeTextureList() {
for (size_t i=0; i<CommonTex.size(); i++) { for (size_t i=0; i<CommonTex.size(); i++) {
delete CommonTex[i]; delete CommonTex[i];
} }
CommonTex.clear(); CommonTex.clear();
Index.clear();
} }
TTexture* CTexture::GetTexture (size_t idx) const { TTexture* CTexture::GetTexture(size_t idx) const {
if (idx >= CommonTex.size()) return NULL; if (idx >= CommonTex.size()) return NULL;
return CommonTex[idx]; return CommonTex[idx];
} }
TTexture* CTexture::GetTexture (const string& name) const { bool CTexture::BindTex(size_t idx) {
return Index.at(name);
}
bool CTexture::BindTex (size_t idx) {
if (idx >= CommonTex.size()) return false; if (idx >= CommonTex.size()) return false;
CommonTex[idx]->Bind(); CommonTex[idx]->Bind();
return true; return true;
} }
bool CTexture::BindTex (const string& name) {
try {
Index.at(name)->Bind();
} catch (...) {
return false;
}
return true;
}
// ---------------------------- Draw ---------------------------------- // ---------------------------- Draw ----------------------------------
void CTexture::Draw (size_t idx) { void CTexture::Draw(size_t idx) {
if (CommonTex.size() > idx) if (CommonTex.size() > idx)
CommonTex[idx]->Draw(); CommonTex[idx]->Draw();
} }
void CTexture::Draw (const string& name) { void CTexture::Draw(size_t idx, int x, int y, float size) {
Index[name]->Draw();
}
void CTexture::Draw (size_t idx, int x, int y, float size) {
if (CommonTex.size() > idx) if (CommonTex.size() > idx)
CommonTex[idx]->Draw(x, y, size, forientation); CommonTex[idx]->Draw(x, y, size, forientation);
} }
void CTexture::Draw (const string& name, int x, int y, float size) { void CTexture::Draw(size_t idx, int x, int y, int width, int height) {
Index[name]->Draw(x, y, size, forientation);
}
void CTexture::Draw (size_t idx, int x, int y, int width, int height) {
if (CommonTex.size() > idx) if (CommonTex.size() > idx)
CommonTex[idx]->Draw (x, y, width, height, forientation); CommonTex[idx]->Draw(x, y, width, height, forientation);
} }
void CTexture::Draw (const string& name, int x, int y, int width, int height) { void CTexture::DrawFrame(size_t idx, int x, int y, double w, double h, int frame, const TColor& col) {
Index[name]->Draw (x, y, width, height, forientation);
}
void CTexture::DrawFrame (size_t idx, int x, int y, double w, double h, int frame, const TColor& col) {
if (CommonTex.size() > idx) if (CommonTex.size() > idx)
CommonTex[idx]->DrawFrame (x, y, w, h, frame, col); CommonTex[idx]->DrawFrame(x, y, w, h, frame, col);
} }
void CTexture::DrawFrame (const string& name, int x, int y, double w, double h, int frame, const TColor& col) { void CTexture::SetOrientation(Orientation orientation) {
Index[name]->DrawFrame (x, y, w, h, frame, col);
}
void CTexture::SetOrientation (Orientation orientation) {
forientation = orientation; forientation = orientation;
} }
// -------------------------- numeric strings ------------------------- // -------------------------- numeric strings -------------------------
void CTexture::DrawNumChr (char c, int x, int y, int w, int h, const TColor& col) { void CTexture::DrawNumChr(char c, int x, int y, int w, int h, const TColor& col) {
int idx; int idx;
if (isdigit(c)) { if (isdigit(c)) {
char chrname[2] = {c, '\0'}; char chrname[2] = {c, '\0'};
@ -669,13 +637,13 @@ void CTexture::DrawNumChr (char c, int x, int y, int w, int h, const TColor& col
glDrawArrays(GL_TRIANGLE_FAN, 0, 4); glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
} }
void CTexture::DrawNumStr (const string& s, int x, int y, float size, const TColor& col) { void CTexture::DrawNumStr(const string& s, int x, int y, float size, const TColor& col) {
if (!BindTex ("ziff032")) { if (!BindTex(NUMERIC_FONT)) {
Message ("DrawNumStr: missing texture"); Message("DrawNumStr: missing texture");
return; return;
} }
glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable (GL_TEXTURE_2D); glEnable(GL_TEXTURE_2D);
int qw = (int)(22 * size); int qw = (int)(22 * size);
int qh = (int)(32 * size); int qh = (int)(32 * size);
@ -683,7 +651,7 @@ void CTexture::DrawNumStr (const string& s, int x, int y, float size, const TCol
glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY);
for (size_t i=0; i < s.size(); i++) { for (size_t i=0; i < s.size(); i++) {
DrawNumChr (s[i], x + (int)i*qw, y, qw, qh, col); DrawNumChr(s[i], x + (int)i*qw, y, qw, qh, col);
} }
glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_VERTEX_ARRAY);
@ -696,7 +664,7 @@ void CTexture::DrawNumStr (const string& s, int x, int y, float size, const TCol
// 0 ppm, 1 tga, 2 bmp // 0 ppm, 1 tga, 2 bmp
#define SCREENSHOT_PROC 2 #define SCREENSHOT_PROC 2
void ScreenshotN () { void ScreenshotN() {
CImage image; CImage image;
string path = param.screenshot_dir; string path = param.screenshot_dir;
path += SEP; path += SEP;
@ -708,18 +676,18 @@ void ScreenshotN () {
switch (type) { switch (type) {
case 0: case 0:
path += ".ppm"; path += ".ppm";
image.ReadFrameBuffer_PPM (); image.ReadFrameBuffer_PPM();
image.WritePPM (path.c_str()); image.WritePPM(path.c_str());
break; break;
case 1: case 1:
path += ".tga"; path += ".tga";
image.ReadFrameBuffer_TGA (); image.ReadFrameBuffer_TGA();
image.WriteTGA (path.c_str()); image.WriteTGA(path.c_str());
break; break;
case 2: case 2:
path += ".bmp"; path += ".bmp";
image.ReadFrameBuffer_BMP (); image.ReadFrameBuffer_BMP();
image.WriteBMP (path.c_str()); image.WriteBMP(path.c_str());
break; break;
} }
} }

View File

@ -20,7 +20,6 @@ GNU General Public License for more details.
#include "bh.h" #include "bh.h"
#include <vector> #include <vector>
#include <map>
#define TEXLOGO 0 #define TEXLOGO 0
#define SNOW_START 1 #define SNOW_START 1
@ -72,8 +71,8 @@ GNU General Public License for more details.
class CImage { class CImage {
private: private:
public: public:
CImage (); CImage();
~CImage (); ~CImage();
unsigned char *data; unsigned char *data;
int nx; int nx;
@ -81,19 +80,19 @@ public:
int depth; int depth;
int pitch; int pitch;
void DisposeData (); void DisposeData();
// load: // load:
bool LoadPng (const char *filepath, bool mirroring); bool LoadPng(const char *filepath, bool mirroring);
bool LoadPng (const char *dir, const char *filepath, bool mirroring); bool LoadPng(const char *dir, const char *filepath, bool mirroring);
// write: // write:
bool ReadFrameBuffer_PPM (); bool ReadFrameBuffer_PPM();
void ReadFrameBuffer_TGA (); void ReadFrameBuffer_TGA();
void ReadFrameBuffer_BMP (); void ReadFrameBuffer_BMP();
void WritePPM (const char *filepath); void WritePPM(const char *filepath);
void WriteTGA (const char *filepath); void WriteTGA(const char *filepath);
void WriteBMP (const char *filepath); void WriteBMP(const char *filepath);
}; };
// -------------------------------------------------------------------- // --------------------------------------------------------------------
@ -124,40 +123,31 @@ public:
class CTexture { class CTexture {
private: private:
vector<TTexture*> CommonTex; vector<TTexture*> CommonTex;
map<string, TTexture*> Index;
Orientation forientation; Orientation forientation;
void DrawNumChr (char c, int x, int y, int w, int h, const TColor& col); void DrawNumChr(char c, int x, int y, int w, int h, const TColor& col);
public: public:
CTexture (); CTexture();
~CTexture (); ~CTexture();
void LoadTextureList (); void LoadTextureList();
void FreeTextureList (); void FreeTextureList();
TTexture* GetTexture (size_t idx) const; TTexture* GetTexture(size_t idx) const;
TTexture* GetTexture (const string& name) const; bool BindTex(size_t idx);
bool BindTex (size_t idx);
bool BindTex (const string& name);
void Draw (size_t idx); void Draw(size_t idx);
void Draw (const string& name); void Draw(size_t idx, int x, int y, float size);
void Draw(size_t idx, int x, int y, int width, int height);
void Draw (size_t idx, int x, int y, float size); void DrawFrame(size_t idx, int x, int y, double w, double h, int frame, const TColor& col);
void Draw (const string& name, int x, int y, float size);
void Draw (size_t idx, int x, int y, int width, int height); void SetOrientation(Orientation orientation);
void Draw (const string& name, int x, int y, int width, int height); void DrawNumStr(const string& s, int x, int y, float size, const TColor& col);
void DrawFrame (size_t idx, int x, int y, double w, double h, int frame, const TColor& col);
void DrawFrame (const string& name, int x, int y, double w, double h, int frame, const TColor& col);
void SetOrientation (Orientation orientation);
void DrawNumStr (const string& s, int x, int y, float size, const TColor& col);
}; };
extern CTexture Tex; extern CTexture Tex;
void ScreenshotN (); void ScreenshotN();
#endif #endif

View File

@ -56,32 +56,32 @@ static bool rotactive = false;
static bool moveactive = false; static bool moveactive = false;
static int comp = 0; static int comp = 0;
void InitCharTools () { void InitCharTools() {
charbase = (int)((Winsys.resolution.height - 200) / 18); charbase = (int)((Winsys.resolution.height - 200) / 18);
firstnode = 1; firstnode = 1;
lastnode = TestChar.GetNumNodes () -1; lastnode = TestChar.GetNumNodes() -1;
curr_node = firstnode; curr_node = firstnode;
curr_act = firstact; curr_act = firstact;
lastact = TestChar.GetNumActs (curr_node) -1; lastact = TestChar.GetNumActs(curr_node) -1;
action = TestChar.GetAction (curr_node); action = TestChar.GetAction(curr_node);
StoreAction (action); StoreAction(action);
} }
void StoreAction (TCharAction *act) { void StoreAction(TCharAction *act) {
for (size_t i=0; i<=act->num; i++) { for (size_t i=0; i<=act->num; i++) {
Undo.vec[i] = act->vec[i]; Undo.vec[i] = act->vec[i];
Undo.dval[i] = act->dval[i]; Undo.dval[i] = act->dval[i];
} }
} }
void RecallAction (TCharAction *act) { void RecallAction(TCharAction *act) {
for (size_t i=0; i<=act->num; i++) { for (size_t i=0; i<=act->num; i++) {
act->vec[i] = Undo.vec[i]; act->vec[i] = Undo.vec[i];
act->dval[i] = Undo.dval[i]; act->dval[i] = Undo.dval[i];
} }
} }
void ChangeValue (int type, double fact) { void ChangeValue(int type, double fact) {
if (type == 0 || type == 4) { if (type == 0 || type == 4) {
if (comp == 0) { if (comp == 0) {
action->vec[curr_act].x += 0.02 * fact; action->vec[curr_act].x += 0.02 * fact;
@ -95,38 +95,38 @@ void ChangeValue (int type, double fact) {
} else if (type == 5) { } else if (type == 5) {
action->dval[curr_act] += 1 * fact; action->dval[curr_act] += 1 * fact;
} }
TestChar.RefreshNode (curr_node); TestChar.RefreshNode(curr_node);
SetCharChanged (true); SetCharChanged(true);
} }
void ChangeNode (int steps) { void ChangeNode(int steps) {
bool ch; bool ch;
if (steps > 0) ch = (curr_node + steps <= lastnode); if (steps > 0) ch = (curr_node + steps <= lastnode);
else ch = (curr_node + steps >= firstnode); else ch = (curr_node + steps >= firstnode);
if (ch) { if (ch) {
curr_node += steps; curr_node += steps;
curr_act = firstact; curr_act = firstact;
lastact = TestChar.GetNumActs (curr_node) -1; lastact = TestChar.GetNumActs(curr_node) -1;
action = TestChar.GetAction (curr_node); action = TestChar.GetAction(curr_node);
if (action->num > 0 && action->type[0] == 4) comp = 0; if (action->num > 0 && action->type[0] == 4) comp = 0;
else comp = 1; else comp = 1;
StoreAction (action); StoreAction(action);
} }
} }
void SetRotation (double x, double y, double z) { void SetRotation(double x, double y, double z) {
xrotation = x; xrotation = x;
yrotation = y; yrotation = y;
zrotation = z; zrotation = z;
} }
void CharKeys (unsigned int key, bool special, bool release, int x, int y) { void CharKeys(unsigned int key, bool special, bool release, int x, int y) {
must_render = true; must_render = true;
if (ToolsFinalStage ()) { if (ToolsFinalStage()) {
if (key == SDLK_y || key == SDLK_j) { if (key == SDLK_y || key == SDLK_j) {
SaveToolCharacter (); SaveToolCharacter();
SaveToolFrame (); SaveToolFrame();
State::manager.RequestQuit(); State::manager.RequestQuit();
} else if (key == SDLK_n) State::manager.RequestQuit(); } else if (key == SDLK_n) State::manager.RequestQuit();
return; return;
@ -141,20 +141,20 @@ void CharKeys (unsigned int key, bool special, bool release, int x, int y) {
int type = action->type[curr_act]; int type = action->type[curr_act];
switch (key) { switch (key) {
case SDLK_TAB: case SDLK_TAB:
SetToolMode (1); SetToolMode(1);
break; break;
case SDLK_ESCAPE: case SDLK_ESCAPE:
case SDLK_q: case SDLK_q:
QuitTool (); QuitTool();
break; break;
case SDLK_F10: case SDLK_F10:
ScreenshotN (); ScreenshotN();
break; break;
case SDLK_s: case SDLK_s:
SaveToolCharacter (); SaveToolCharacter();
break; break;
case SDLK_c: case SDLK_c:
ScreenshotN (); ScreenshotN();
break; break;
case SDLK_m: case SDLK_m:
TestChar.useMaterials = !TestChar.useMaterials; TestChar.useMaterials = !TestChar.useMaterials;
@ -163,14 +163,14 @@ void CharKeys (unsigned int key, bool special, bool release, int x, int y) {
TestChar.useHighlighting = !TestChar.useHighlighting; TestChar.useHighlighting = !TestChar.useHighlighting;
break; break;
case SDLK_r: case SDLK_r:
TestChar.Reset (); TestChar.Reset();
ReloadToolCharacter (); ReloadToolCharacter();
Tools.Enter (); Tools.Enter();
break; break;
case SDLK_u: case SDLK_u:
if (action != NULL) { if (action != NULL) {
RecallAction (action); RecallAction(action);
TestChar.RefreshNode (curr_node); TestChar.RefreshNode(curr_node);
} }
break; break;
case SDLK_PLUS: case SDLK_PLUS:
@ -185,30 +185,30 @@ void CharKeys (unsigned int key, bool special, bool release, int x, int y) {
// set rotations for view // set rotations for view
case SDLK_1: case SDLK_1:
SetRotation (0, 0, 0); SetRotation(0, 0, 0);
break; break;
case SDLK_2: case SDLK_2:
SetRotation (-50, 180, 15); SetRotation(-50, 180, 15);
break; break;
case SDLK_3: case SDLK_3:
SetRotation (0, 180, 0); SetRotation(0, 180, 0);
break; break;
case SDLK_4: case SDLK_4:
SetRotation (0, -80, 0); SetRotation(0, -80, 0);
break; break;
// select node // select node
case SDLK_PAGEUP: case SDLK_PAGEUP:
ChangeNode (-1); ChangeNode(-1);
break; break;
case SDLK_PAGEDOWN: case SDLK_PAGEDOWN:
ChangeNode (1); ChangeNode(1);
break; break;
case SDLK_END: case SDLK_END:
ChangeNode (charbase); ChangeNode(charbase);
break; break;
case SDLK_HOME: case SDLK_HOME:
ChangeNode (-charbase); ChangeNode(-charbase);
break; break;
// select action // select action
@ -223,10 +223,10 @@ void CharKeys (unsigned int key, bool special, bool release, int x, int y) {
else comp = 1; else comp = 1;
break; break;
case SDLK_LEFT: case SDLK_LEFT:
ChangeValue (type, -1); ChangeValue(type, -1);
break; break;
case SDLK_RIGHT: case SDLK_RIGHT:
ChangeValue (type, 1); ChangeValue(type, 1);
break; break;
// select value // select value
@ -242,9 +242,9 @@ void CharKeys (unsigned int key, bool special, bool release, int x, int y) {
} }
} }
void CharMouse (int button, int state, int x, int y) { void CharMouse(int button, int state, int x, int y) {
must_render = true; must_render = true;
if (ToolsFinalStage ()) return; if (ToolsFinalStage()) return;
if (state<1) { if (state<1) {
rotactive = false; rotactive = false;
@ -272,7 +272,7 @@ void CharMouse (int button, int state, int x, int y) {
} }
} }
void CharMotion (int x, int y) { void CharMotion(int x, int y) {
must_render = true; must_render = true;
if (rotactive) { if (rotactive) {
int diffx = cursor_pos.x - startx; int diffx = cursor_pos.x - startx;
@ -282,93 +282,92 @@ void CharMotion (int x, int y) {
} }
if (moveactive) { if (moveactive) {
float diffposx = (float)(cursor_pos.x - startx) / 200; float diffposx = (float)(cursor_pos.x - startx) / 200;
float diffposy = (float) (cursor_pos.y - starty) / 200; float diffposy = (float)(cursor_pos.y - starty) / 200;
yposition = startposy - diffposy; yposition = startposy - diffposy;
xposition = startposx + diffposx; xposition = startposx + diffposx;
} }
} }
void DrawActionVec (size_t nr, const string& s, int y, const TVector3d& v) { void DrawActionVec(size_t nr, const string& s, int y, const TVector3d& v) {
FT.SetColor (colLGrey); FT.SetColor(colLGrey);
FT.DrawString (20, y, s); FT.DrawString(20, y, s);
if (nr == curr_act) { if (nr == curr_act) {
if (comp == 0) { if (comp == 0) {
FT.SetColor (colYellow); FT.SetColor(colYellow);
FT.DrawString (100, y, Float_StrN (v.x, 2)); FT.DrawString(100, y, Float_StrN(v.x, 2));
FT.DrawString (150, y, Float_StrN (v.y, 2)); FT.DrawString(150, y, Float_StrN(v.y, 2));
FT.DrawString (200, y, Float_StrN (v.z, 2)); FT.DrawString(200, y, Float_StrN(v.z, 2));
} else { } else {
if (comp == 1) FT.SetColor (colYellow); if (comp == 1) FT.SetColor(colYellow);
else FT.SetColor (colLGrey); else FT.SetColor(colLGrey);
FT.DrawString (100, y, Float_StrN (v.x, 2)); FT.DrawString(100, y, Float_StrN(v.x, 2));
if (comp == 2) FT.SetColor (colYellow); if (comp == 2) FT.SetColor(colYellow);
else FT.SetColor (colLGrey); else FT.SetColor(colLGrey);
FT.DrawString (150, y, Float_StrN (v.y, 2)); FT.DrawString(150, y, Float_StrN(v.y, 2));
if (comp == 3) FT.SetColor (colYellow); if (comp == 3) FT.SetColor(colYellow);
else FT.SetColor (colLGrey); else FT.SetColor(colLGrey);
FT.DrawString (200, y, Float_StrN (v.z, 2)); FT.DrawString(200, y, Float_StrN(v.z, 2));
} }
} else { } else {
FT.DrawString (100, y, Float_StrN (v.x, 2)); FT.DrawString(100, y, Float_StrN(v.x, 2));
FT.DrawString (150, y, Float_StrN (v.y, 2)); FT.DrawString(150, y, Float_StrN(v.y, 2));
FT.DrawString (200, y, Float_StrN (v.z, 2)); FT.DrawString(200, y, Float_StrN(v.z, 2));
} }
} }
void DrawActionFloat (size_t nr, const string& s, int y, float f) { void DrawActionFloat(size_t nr, const string& s, int y, float f) {
FT.SetColor (colLGrey); FT.SetColor(colLGrey);
FT.DrawString (20, y, s); FT.DrawString(20, y, s);
if (nr == curr_act) FT.SetColor (colYellow); if (nr == curr_act) FT.SetColor(colYellow);
else FT.SetColor (colLGrey); else FT.SetColor(colLGrey);
FT.DrawString (100, y, Float_StrN (f, 2)); FT.DrawString(100, y, Float_StrN(f, 2));
} }
void RenderChar (double timestep) { void RenderChar(double timestep) {
if (!must_render) return; if (!must_render) return;
bool is_visible = false; bool is_visible = false;
check_gl_error();
// ------------- 3d scenery --------------------------------------- // ------------- 3d scenery ---------------------------------------
ScopedRenderMode rm1(TUX); ScopedRenderMode rm1(TUX);
ClearRenderContext (colDDBackgr); ClearRenderContext(colDDBackgr);
TestChar.highlight_node = TestChar.GetNodeName (curr_node); TestChar.highlight_node = TestChar.GetNodeName(curr_node);
glLoadIdentity (); glLoadIdentity();
glPushMatrix (); glPushMatrix();
SetToolLight (); SetToolLight();
TestChar.ResetRoot (); TestChar.ResetRoot();
TestChar.ResetJoints (); TestChar.ResetJoints();
glTranslatef (xposition, yposition, zposition); glTranslatef(xposition, yposition, zposition);
glRotatef (xrotation, 1, 0, 0); glRotatef(xrotation, 1, 0, 0);
glRotatef (yrotation, 0, 1, 0); glRotatef(yrotation, 0, 1, 0);
glRotatef (zrotation, 0, 0, 1); glRotatef(zrotation, 0, 0, 1);
if (drawcount > 0) TestChar.Draw (); if (drawcount > 0) TestChar.Draw();
glPopMatrix (); glPopMatrix();
drawcount++; drawcount++;
// --------------- 2d screen -------------------------------------- // --------------- 2d screen --------------------------------------
SetupGuiDisplay (); SetupGuiDisplay();
ScopedRenderMode rm2(TEXFONT); ScopedRenderMode rm2(TEXFONT);
FT.SetProps("bold", 20, colYellow); FT.SetProps("bold", 20, colYellow);
FT.DrawString (-1, 10, "Edit mode"); FT.DrawString(-1, 10, "Edit mode");
if (CharHasChanged ()) DrawChanged (); if (CharHasChanged()) DrawChanged();
FT.SetSize (16); FT.SetSize(16);
for (size_t i=0; i<=lastnode; i++) { for (size_t i=0; i<=lastnode; i++) {
if (i != curr_node) { if (i != curr_node) {
FT.SetColor (colLGrey); FT.SetColor(colLGrey);
FT.SetFont ("normal"); FT.SetFont("normal");
} else { } else {
FT.SetColor (colYellow); FT.SetColor(colYellow);
FT.SetFont ("bold"); FT.SetFont("bold");
} }
int xl = ITrunc ((int)i, charbase) * 100 + 20; int xl = ITrunc((int)i, charbase) * 100 + 20;
int yt = IFrac ((int)i, charbase) * 18 + 60; int yt = IFrac((int)i, charbase) * 18 + 60;
FT.DrawString (xl, yt, TestChar.GetNodeJoint (i)); FT.DrawString(xl, yt, TestChar.GetNodeJoint(i));
} }
size_t num = action->num; size_t num = action->num;
@ -380,22 +379,22 @@ void RenderChar (double timestep) {
int yt = Winsys.resolution.height - 120 + (int)i * 18; int yt = Winsys.resolution.height - 120 + (int)i * 18;
switch (type) { switch (type) {
case 0: case 0:
DrawActionVec (i, "trans", yt, action->vec[i]); DrawActionVec(i, "trans", yt, action->vec[i]);
break; break;
case 1: case 1:
DrawActionFloat (i, "x-rot", yt, action->dval[i]); DrawActionFloat(i, "x-rot", yt, action->dval[i]);
break; break;
case 2: case 2:
DrawActionFloat (i, "y-rot", yt, action->dval[i]); DrawActionFloat(i, "y-rot", yt, action->dval[i]);
break; break;
case 3: case 3:
DrawActionFloat (i, "z-rot", yt, action->dval[i]); DrawActionFloat(i, "z-rot", yt, action->dval[i]);
break; break;
case 4: case 4:
DrawActionVec (i, "scale", yt, action->vec[i]); DrawActionVec(i, "scale", yt, action->vec[i]);
break; break;
case 5: case 5:
DrawActionFloat (i, "vis", yt, action->dval[i]); DrawActionFloat(i, "vis", yt, action->dval[i]);
is_visible = true; is_visible = true;
break; break;
default: default:
@ -405,17 +404,17 @@ void RenderChar (double timestep) {
} }
FT.SetFont("normal"); FT.SetFont("normal");
if (is_visible) FT.SetColor (colYellow); if (is_visible) FT.SetColor(colYellow);
else FT.SetColor (colLGrey); else FT.SetColor(colLGrey);
FT.DrawString (20, 20, action->name); FT.DrawString(20, 20, action->name);
if (ToolsFinalStage ()) { if (ToolsFinalStage()) {
FT.SetSize (20); FT.SetSize(20);
FT.SetColor (colYellow); FT.SetColor(colYellow);
FT.DrawString (-1, Winsys.resolution.height - 50, "Quit program. Save character list (y/n)"); FT.DrawString(-1, Winsys.resolution.height - 50, "Quit program. Save character list (y/n)");
} }
Reshape (Winsys.resolution.width, Winsys.resolution.height); Reshape(Winsys.resolution.width, Winsys.resolution.height);
Winsys.SwapBuffers (); Winsys.SwapBuffers();
if (drawcount > 3) must_render = false; if (drawcount > 3) must_render = false;
} }

View File

@ -22,12 +22,12 @@ GNU General Public License for more details.
struct TCharAction; struct TCharAction;
void InitCharTools (); void InitCharTools();
void CharKeys (unsigned int key, bool special, bool release, int x, int y); void CharKeys(unsigned int key, bool special, bool release, int x, int y);
void CharMouse (int button, int state, int x, int y); void CharMouse(int button, int state, int x, int y);
void CharMotion (int x, int y); void CharMotion(int x, int y);
void RenderChar (double timestep); void RenderChar(double timestep);
void StoreAction (TCharAction *act); void StoreAction(TCharAction *act);
#endif #endif

View File

@ -42,19 +42,19 @@ static bool alt = false;
static bool lastframe = 0; static bool lastframe = 0;
static bool keyrun = false; static bool keyrun = false;
void InitFrameTools () { void InitFrameTools() {
framebase = (int)((Winsys.resolution.height - 350) / 18); framebase = (int)((Winsys.resolution.height - 350) / 18);
if (TestFrame.numFrames() < 1) TestFrame.AddFrame (); if (TestFrame.numFrames() < 1) TestFrame.AddFrame();
curr_joint = 0; curr_joint = 0;
last_joint = TestFrame.GetNumJoints () -1; last_joint = TestFrame.GetNumJoints() -1;
} }
void SingleFrameKeys (unsigned int key, bool special, bool release, int x, int y) { void SingleFrameKeys(unsigned int key, bool special, bool release, int x, int y) {
//PrintInt (key); //PrintInt (key);
must_render = true; must_render = true;
int keyfact; int keyfact;
lastframe = TestFrame.numFrames() != 1; lastframe = TestFrame.numFrames() != 1;
TKeyframe *frame = TestFrame.GetFrame (curr_frame); TKeyframe *frame = TestFrame.GetFrame(curr_frame);
// setting the camera change state // setting the camera change state
if (key == SDLK_F1) {GluCamera.turnright = !release; return;} if (key == SDLK_F1) {GluCamera.turnright = !release; return;}
@ -74,38 +74,38 @@ void SingleFrameKeys (unsigned int key, bool special, bool release, int x, int y
switch (key) { switch (key) {
case SDLK_y: case SDLK_y:
case SDLK_j: case SDLK_j:
if (ToolsFinalStage ()) { if (ToolsFinalStage()) {
SaveToolCharacter (); SaveToolCharacter();
SaveToolFrame (); SaveToolFrame();
State::manager.RequestQuit(); State::manager.RequestQuit();
} }
break; break;
case SDLK_n: case SDLK_n:
if (ToolsFinalStage ()) State::manager.RequestQuit(); if (ToolsFinalStage()) State::manager.RequestQuit();
break; break;
case SDLK_ESCAPE: case SDLK_ESCAPE:
case SDLK_q: case SDLK_q:
QuitTool (); QuitTool();
break; break;
case SDLK_s: case SDLK_s:
SaveToolFrame (); SaveToolFrame();
break; break;
case SDLK_TAB: case SDLK_TAB:
SetToolMode (0); SetToolMode(0);
break; break;
case SDLK_a: case SDLK_a:
TestFrame.AddFrame (); TestFrame.AddFrame();
SetFrameChanged (true); SetFrameChanged(true);
break; break;
case SDLK_INSERT: case SDLK_INSERT:
TestFrame.InsertFrame (curr_frame); TestFrame.InsertFrame(curr_frame);
SetFrameChanged (true); SetFrameChanged(true);
break; break;
case SDLK_DELETE: case SDLK_DELETE:
curr_frame = TestFrame.DeleteFrame (curr_frame); curr_frame = TestFrame.DeleteFrame(curr_frame);
SetFrameChanged (true); SetFrameChanged(true);
break; break;
case SDLK_PAGEDOWN: case SDLK_PAGEDOWN:
if (curr_frame < TestFrame.numFrames()-1) curr_frame++; if (curr_frame < TestFrame.numFrames()-1) curr_frame++;
@ -122,26 +122,26 @@ void SingleFrameKeys (unsigned int key, bool special, bool release, int x, int y
case SDLK_RIGHT: case SDLK_RIGHT:
if (curr_joint < 4) frame->val[curr_joint] += 0.05; if (curr_joint < 4) frame->val[curr_joint] += 0.05;
else frame->val[curr_joint] += 1; else frame->val[curr_joint] += 1;
SetFrameChanged (true); SetFrameChanged(true);
break; break;
case SDLK_LEFT: case SDLK_LEFT:
if (curr_joint < 4) frame->val[curr_joint] -= 0.05; if (curr_joint < 4) frame->val[curr_joint] -= 0.05;
else frame->val[curr_joint] -= 1; else frame->val[curr_joint] -= 1;
SetFrameChanged (true); SetFrameChanged(true);
break; break;
case SDLK_0: case SDLK_0:
frame->val[curr_joint] = 0.0; frame->val[curr_joint] = 0.0;
SetFrameChanged (true); SetFrameChanged(true);
break; break;
case SDLK_SPACE: case SDLK_SPACE:
if (curr_joint < 4) frame->val[curr_joint] += 0.05 * keyfact; if (curr_joint < 4) frame->val[curr_joint] += 0.05 * keyfact;
else frame->val[curr_joint] += 1 * keyfact; else frame->val[curr_joint] += 1 * keyfact;
SetFrameChanged (true); SetFrameChanged(true);
break; break;
case SDLK_RETURN: case SDLK_RETURN:
TestFrame.InitTest (ref_position, &TestChar); TestFrame.InitTest(ref_position, &TestChar);
SetToolMode (2); SetToolMode(2);
must_render = true; must_render = true;
break; break;
@ -152,20 +152,20 @@ void SingleFrameKeys (unsigned int key, bool special, bool release, int x, int y
TestChar.useHighlighting = !TestChar.useHighlighting; TestChar.useHighlighting = !TestChar.useHighlighting;
break; break;
case SDLK_c: case SDLK_c:
if (control) TestFrame.CopyToClipboard (curr_frame); if (control) TestFrame.CopyToClipboard(curr_frame);
else TestFrame.ClearFrame (curr_frame); else TestFrame.ClearFrame(curr_frame);
SetFrameChanged (true); SetFrameChanged(true);
break; break;
case SDLK_v: case SDLK_v:
if (control) TestFrame.PasteFromClipboard (curr_frame); if (control) TestFrame.PasteFromClipboard(curr_frame);
SetFrameChanged (true); SetFrameChanged(true);
break; break;
case SDLK_p: case SDLK_p:
if (curr_frame>0) if (curr_frame>0)
TestFrame.CopyFrame (curr_frame-1, curr_frame); TestFrame.CopyFrame(curr_frame-1, curr_frame);
break; break;
case SDLK_F10: case SDLK_F10:
ScreenshotN (); ScreenshotN();
break; break;
case SDLK_1: case SDLK_1:
@ -195,9 +195,9 @@ void SingleFrameKeys (unsigned int key, bool special, bool release, int x, int y
} }
} }
void SingleFrameMouse (int button, int state, int x, int y) { void SingleFrameMouse(int button, int state, int x, int y) {
must_render = true; must_render = true;
if (ToolsFinalStage ()) return; if (ToolsFinalStage()) return;
if (button == 4) { if (button == 4) {
GluCamera.distance += 0.1; GluCamera.distance += 0.1;
@ -206,78 +206,77 @@ void SingleFrameMouse (int button, int state, int x, int y) {
} }
} }
void SingleFrameMotion (int x, int y) { void SingleFrameMotion(int x, int y) {
} }
void PrintFrameParams (int ytop, TKeyframe *frame) { void PrintFrameParams(int ytop, TKeyframe *frame) {
int offs = 18; int offs = 18;
for (int i=0; i<=last_joint; i++) { for (int i=0; i<=last_joint; i++) {
if (i == curr_joint) FT.SetColor (colYellow); if (i == curr_joint) FT.SetColor(colYellow);
else FT.SetColor (colLGrey); else FT.SetColor(colLGrey);
int x = ITrunc (i, jointbase) * 140 + 20; int x = ITrunc(i, jointbase) * 140 + 20;
int y = IFrac (i, jointbase) * offs + ytop; int y = IFrac(i, jointbase) * offs + ytop;
FT.DrawString (x, y, TestFrame.GetJointName(i)); FT.DrawString(x, y, TestFrame.GetJointName(i));
if (i < 4) FT.DrawString (x+80, y, Float_StrN (frame->val[i], 2)); if (i < 4) FT.DrawString(x+80, y, Float_StrN(frame->val[i], 2));
else FT.DrawString (x+80, y, Float_StrN (frame->val[i], 0)); else FT.DrawString(x+80, y, Float_StrN(frame->val[i], 0));
} }
} }
void RenderSingleFrame (double timestep) { void RenderSingleFrame(double timestep) {
if (!must_render) return; if (!must_render) return;
check_gl_error ();
// ------------------ 3d scenery ---------------------------------- // ------------------ 3d scenery ----------------------------------
ScopedRenderMode rm1(TUX); ScopedRenderMode rm1(TUX);
ClearRenderContext (colDDBackgr); ClearRenderContext(colDDBackgr);
const string& hlname = TestFrame.GetHighlightName (curr_joint); const string& hlname = TestFrame.GetHighlightName(curr_joint);
TestChar.highlight_node = TestChar.GetNodeName (hlname); TestChar.highlight_node = TestChar.GetNodeName(hlname);
glPushMatrix (); glPushMatrix();
SetToolLight (); SetToolLight();
GluCamera.Update (timestep); GluCamera.Update(timestep);
TestFrame.CalcKeyframe (curr_frame, &TestChar, ref_position); TestFrame.CalcKeyframe(curr_frame, &TestChar, ref_position);
TestChar.Draw (); TestChar.Draw();
glPopMatrix (); glPopMatrix();
// ----------------- 2d screen ------------------------------------ // ----------------- 2d screen ------------------------------------
SetupGuiDisplay (); SetupGuiDisplay();
ScopedRenderMode rm2(TEXFONT); ScopedRenderMode rm2(TEXFONT);
if (FrameHasChanged ()) DrawChanged (); if (FrameHasChanged()) DrawChanged();
FT.SetProps("bold", 20, colYellow); FT.SetProps("bold", 20, colYellow);
FT.DrawString (-1, 10, "Keyframe mode"); FT.DrawString(-1, 10, "Keyframe mode");
FT.SetProps("normal", 16); FT.SetProps("normal", 16);
for (size_t i=0; i<TestFrame.numFrames(); i++) { for (size_t i=0; i<TestFrame.numFrames(); i++) {
if (i != curr_frame) { if (i != curr_frame) {
FT.SetColor (colLGrey); FT.SetColor(colLGrey);
FT.SetFont ("normal"); FT.SetFont("normal");
} else { } else {
FT.SetColor (colYellow); FT.SetColor(colYellow);
FT.SetFont ("bold"); FT.SetFont("bold");
} }
int xl = ITrunc ((int)i, framebase) * 100 + 20; int xl = ITrunc((int)i, framebase) * 100 + 20;
int yt = IFrac ((int)i, framebase) * 18 + 20; int yt = IFrac((int)i, framebase) * 18 + 20;
FT.DrawString (xl, yt, Int_StrN ((int)i)); FT.DrawString(xl, yt, Int_StrN((int)i));
} }
FT.SetFont ("normal"); FT.SetFont("normal");
FT.SetColor (colLGrey); FT.SetColor(colLGrey);
PrintFrameParams (Winsys.resolution.height - 330, TestFrame.GetFrame (curr_frame)); PrintFrameParams(Winsys.resolution.height - 330, TestFrame.GetFrame(curr_frame));
if (ToolsFinalStage ()) { if (ToolsFinalStage()) {
FT.SetSize (20); FT.SetSize(20);
FT.SetColor (colYellow); FT.SetColor(colYellow);
FT.DrawString (-1, Winsys.resolution.height - 50, "Quit program. Save character list (y/n)"); FT.DrawString(-1, Winsys.resolution.height - 50, "Quit program. Save character list (y/n)");
} }
Reshape (Winsys.resolution.width, Winsys.resolution.height); Reshape(Winsys.resolution.width, Winsys.resolution.height);
Winsys.SwapBuffers(); Winsys.SwapBuffers();
must_render = false; must_render = false;
} }
@ -287,7 +286,7 @@ void RenderSingleFrame (double timestep) {
// frame sequence // frame sequence
// -------------------------------------------------------------------- // --------------------------------------------------------------------
void SequenceKeys (unsigned int key, bool special, bool release, int x, int y) { void SequenceKeys(unsigned int key, bool special, bool release, int x, int y) {
if (release) return; if (release) return;
switch (key) { switch (key) {
case SDLK_RETURN: case SDLK_RETURN:
@ -295,33 +294,32 @@ void SequenceKeys (unsigned int key, bool special, bool release, int x, int y) {
break; break;
case SDLK_ESCAPE: case SDLK_ESCAPE:
case SDLK_TAB: case SDLK_TAB:
SetToolMode (1); SetToolMode(1);
break; break;
case SDLK_q: case SDLK_q:
QuitTool (); QuitTool();
break; break;
} }
} }
void SequenceMouse (int button, int state, int x, int y) {} void SequenceMouse(int button, int state, int x, int y) {}
void SequenceMotion (int x, int y) {} void SequenceMotion(int x, int y) {}
void RenderSequence (double timestep) { void RenderSequence(double timestep) {
check_gl_error();
ScopedRenderMode rm(TUX); ScopedRenderMode rm(TUX);
ClearRenderContext (colDDBackgr); ClearRenderContext(colDDBackgr);
GluCamera.Update (timestep); GluCamera.Update(timestep);
if (TestFrame.active) TestFrame.UpdateTest (timestep, &TestChar); if (TestFrame.active) TestFrame.UpdateTest(timestep, &TestChar);
else if (keyrun) { else if (keyrun) {
TestFrame.InitTest (NullVec3, &TestChar); TestFrame.InitTest(NullVec3, &TestChar);
keyrun = false; keyrun = false;
} }
glPushMatrix (); glPushMatrix();
TestChar.Draw (); TestChar.Draw();
glPopMatrix (); glPopMatrix();
Reshape (Winsys.resolution.width, Winsys.resolution.height); Reshape(Winsys.resolution.width, Winsys.resolution.height);
Winsys.SwapBuffers(); Winsys.SwapBuffers();
} }

View File

@ -20,20 +20,20 @@ GNU General Public License for more details.
#include "bh.h" #include "bh.h"
void InitFrameTools (); void InitFrameTools();
void SingleFrameKeys (unsigned int key, bool special, bool release, int x, int y); void SingleFrameKeys(unsigned int key, bool special, bool release, int x, int y);
void SingleFrameMouse (int button, int state, int x, int y); void SingleFrameMouse(int button, int state, int x, int y);
void SingleFrameMotion (int x, int y); void SingleFrameMotion(int x, int y);
void RenderSingleFrame (double timestep); void RenderSingleFrame(double timestep);
// -------------------------------------------------------------------- // --------------------------------------------------------------------
// frame sequence // frame sequence
// -------------------------------------------------------------------- // --------------------------------------------------------------------
void SequenceKeys (unsigned int key, bool special, bool release, int x, int y); void SequenceKeys(unsigned int key, bool special, bool release, int x, int y);
void SequenceMouse (int button, int state, int x, int y); void SequenceMouse(int button, int state, int x, int y);
void SequenceMotion (int x, int y); void SequenceMotion(int x, int y);
void RenderSequence (double timestep); void RenderSequence(double timestep);
#endif #endif

View File

@ -33,7 +33,7 @@ GNU General Public License for more details.
CGluCamera GluCamera; CGluCamera GluCamera;
CCamera::CCamera () { CCamera::CCamera() {
xview = 0; xview = 0;
yview = 0; yview = 0;
zview = 4; zview = 4;
@ -52,48 +52,48 @@ CCamera::CCamera () {
pitchdown = false; pitchdown = false;
} }
void CCamera::XMove (GLfloat step) { void CCamera::XMove(GLfloat step) {
zview += (float)sin(-vhead * 3.14 / 180) * step; zview += (float)sin(-vhead * 3.14 / 180) * step;
xview += (float)cos(-vhead * 3.14 / 180) * step; xview += (float)cos(-vhead * 3.14 / 180) * step;
} }
void CCamera::YMove (GLfloat step) { void CCamera::YMove(GLfloat step) {
yview += step; yview += step;
} }
void CCamera::ZMove (GLfloat step) { void CCamera::ZMove(GLfloat step) {
xview += (float)sin (vhead * 3.14 / 180) * step; xview += (float)sin(vhead * 3.14 / 180) * step;
zview += (float)cos (vhead * 3.14 / 180) * step; zview += (float)cos(vhead * 3.14 / 180) * step;
} }
void CCamera::RotateHead (GLfloat step) { void CCamera::RotateHead(GLfloat step) {
vhead += step; vhead += step;
} }
void CCamera::RotatePitch (GLfloat step) { void CCamera::RotatePitch(GLfloat step) {
vpitch += step; vpitch += step;
} }
void CCamera::Update (float timestep) { void CCamera::Update(float timestep) {
if (fore) ZMove (-2 * timestep); if (fore) ZMove(-2 * timestep);
if (back) ZMove (2 * timestep); if (back) ZMove(2 * timestep);
if (left) XMove (-1 * timestep); if (left) XMove(-1 * timestep);
if (right) XMove (1 * timestep); if (right) XMove(1 * timestep);
if (up) YMove (1 * timestep); if (up) YMove(1 * timestep);
if (down) YMove (-1 * timestep); if (down) YMove(-1 * timestep);
if (headleft) RotateHead (5 * timestep); if (headleft) RotateHead(5 * timestep);
if (headright) RotateHead (-5 * timestep); if (headright) RotateHead(-5 * timestep);
if (pitchup) RotatePitch (-2 * timestep); if (pitchup) RotatePitch(-2 * timestep);
if (pitchdown) RotatePitch (2 * timestep); if (pitchdown) RotatePitch(2 * timestep);
glLoadIdentity (); glLoadIdentity();
glRotatef (-vpitch, 1.0, 0.0 , 0.0); glRotatef(-vpitch, 1.0, 0.0 , 0.0);
glRotatef (-vhead, 0.0, 1.0 , 0.0); glRotatef(-vhead, 0.0, 1.0 , 0.0);
glTranslatef (-xview, -yview, -zview); glTranslatef(-xview, -yview, -zview);
} }
CGluCamera::CGluCamera () { CGluCamera::CGluCamera() {
angle = 0.0; angle = 0.0;
distance = 3.0; distance = 3.0;
turnright = false; turnright = false;
@ -102,15 +102,15 @@ CGluCamera::CGluCamera () {
farther = false; farther = false;
} }
void CGluCamera::Update (double timestep) { void CGluCamera::Update(double timestep) {
if (turnright) angle += timestep * 2000; if (turnright) angle += timestep * 2000;
if (turnleft) angle -= timestep * 2000; if (turnleft) angle -= timestep * 2000;
if (nearer) distance -= timestep * 100; if (nearer) distance -= timestep * 100;
if (farther) distance += timestep * 100; if (farther) distance += timestep * 100;
double xx = distance * sin (angle * M_PI / 180); double xx = distance * sin(angle * M_PI / 180);
double zz = distance * sin ((90 - angle) * M_PI / 180); double zz = distance * sin((90 - angle) * M_PI / 180);
glLoadIdentity (); glLoadIdentity();
gluLookAt (xx, 0, zz, 0, 0, 0, 0, 1, 0); gluLookAt(xx, 0, zz, 0, 0, 0, 0, 1, 0);
} }
// -------------------------------------------------------------------- // --------------------------------------------------------------------
@ -135,8 +135,8 @@ static const TLight toollight = {
}; };
static int tool_mode = 0; static int tool_mode = 0;
void DrawQuad (float x, float y, float w, float h, float scrheight, const TColor& col, int frame) { void DrawQuad(float x, float y, float w, float h, float scrheight, const TColor& col, int frame) {
glDisable (GL_TEXTURE_2D); glDisable(GL_TEXTURE_2D);
glColor(col); glColor(col);
const GLfloat vtx[] = { const GLfloat vtx[] = {
x - frame, scrheight - y - h - frame, x - frame, scrheight - y - h - frame,
@ -150,26 +150,26 @@ void DrawQuad (float x, float y, float w, float h, float scrheight, const TColor
glDrawArrays(GL_TRIANGLE_FAN, 0, 4); glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_VERTEX_ARRAY);
glEnable (GL_TEXTURE_2D); glEnable(GL_TEXTURE_2D);
} }
void DrawChanged () { void DrawChanged() {
DrawQuad (Winsys.resolution.width - 120, 10, 100, 22, Winsys.resolution.height, colRed, 0); DrawQuad(Winsys.resolution.width - 120, 10, 100, 22, Winsys.resolution.height, colRed, 0);
FT.SetProps("normal", 18, colBlack); FT.SetProps("normal", 18, colBlack);
FT.DrawString (Winsys.resolution.width - 110, 8, "changed"); FT.DrawString(Winsys.resolution.width - 110, 8, "changed");
} }
void SetToolLight () { void SetToolLight() {
toollight.Enable(GL_LIGHT0); toollight.Enable(GL_LIGHT0);
glEnable(GL_LIGHTING); glEnable(GL_LIGHTING);
} }
void QuitTool () { void QuitTool() {
if (!charchanged && !framechanged) State::manager.RequestQuit(); if (!charchanged && !framechanged) State::manager.RequestQuit();
else finalstage = true; else finalstage = true;
} }
void SetToolMode (int newmode) { void SetToolMode(int newmode) {
if (newmode == tool_mode) return; if (newmode == tool_mode) return;
if (newmode > 2) tool_mode = 0; if (newmode > 2) tool_mode = 0;
else tool_mode = newmode; else tool_mode = newmode;
@ -183,35 +183,35 @@ void SetToolMode (int newmode) {
} }
} }
bool CharHasChanged () {return charchanged;} bool CharHasChanged() {return charchanged;}
bool FrameHasChanged () {return framechanged;} bool FrameHasChanged() {return framechanged;}
bool ToolsFinalStage () { bool ToolsFinalStage() {
return finalstage; return finalstage;
} }
void SetCharChanged (bool val) { void SetCharChanged(bool val) {
charchanged = val; charchanged = val;
} }
void SetFrameChanged (bool val) { void SetFrameChanged(bool val) {
framechanged = val; framechanged = val;
} }
void SaveToolCharacter () { void SaveToolCharacter() {
if (!charchanged) return; if (!charchanged) return;
TestChar.SaveCharNodes (char_dir, char_file); TestChar.SaveCharNodes(char_dir, char_file);
charchanged = false; charchanged = false;
} }
void ReloadToolCharacter () { void ReloadToolCharacter() {
TestChar.Load (char_dir, char_file, true); TestChar.Load(char_dir, char_file, true);
charchanged = false; charchanged = false;
} }
void SaveToolFrame () { void SaveToolFrame() {
if (!framechanged) return; if (!framechanged) return;
TestFrame.SaveTest (char_dir, frame_file); TestFrame.SaveTest(char_dir, frame_file);
framechanged = false; framechanged = false;
} }
@ -222,33 +222,33 @@ void CTools::SetParameter(const string& dir, const string& file) {
} }
void CTools::Enter() { void CTools::Enter() {
if (TestChar.Load (char_dir, char_file, true) == false) { if (TestChar.Load(char_dir, char_file, true) == false) {
Message ("could not load 'shape.lst'"); Message("could not load 'shape.lst'");
Winsys.Terminate(); Winsys.Terminate();
} }
if (TestFrame.Load (char_dir, frame_file) == false) { if (TestFrame.Load(char_dir, frame_file) == false) {
Message ("could not load 'frame.lst'"); Message("could not load 'frame.lst'");
Winsys.Terminate(); Winsys.Terminate();
} }
charchanged = false; charchanged = false;
framechanged = false; framechanged = false;
InitCharTools (); InitCharTools();
InitFrameTools (); InitFrameTools();
Winsys.KeyRepeat (true); Winsys.KeyRepeat(true);
} }
void CTools::Keyb(unsigned int key, bool special, bool release, int x, int y) { void CTools::Keyb(unsigned int key, bool special, bool release, int x, int y) {
switch (tool_mode) { switch (tool_mode) {
case 0: case 0:
CharKeys (key, special, release, x, y); CharKeys(key, special, release, x, y);
break; break;
case 1: case 1:
SingleFrameKeys (key, special, release, x, y); SingleFrameKeys(key, special, release, x, y);
break; break;
case 2: case 2:
SequenceKeys (key, special, release, x, y); SequenceKeys(key, special, release, x, y);
break; break;
} }
} }
@ -256,13 +256,13 @@ void CTools::Keyb(unsigned int key, bool special, bool release, int x, int y) {
void CTools::Mouse(int button, int state, int x, int y) { void CTools::Mouse(int button, int state, int x, int y) {
switch (tool_mode) { switch (tool_mode) {
case 0: case 0:
CharMouse (button, state, x, y); CharMouse(button, state, x, y);
break; break;
case 1: case 1:
SingleFrameMouse (button, state, x, y); SingleFrameMouse(button, state, x, y);
break; break;
case 2: case 2:
SequenceMouse (button, state, x, y); SequenceMouse(button, state, x, y);
break; break;
} }
} }
@ -270,13 +270,13 @@ void CTools::Mouse(int button, int state, int x, int y) {
void CTools::Motion(int x, int y) { void CTools::Motion(int x, int y) {
switch (tool_mode) { switch (tool_mode) {
case 0: case 0:
CharMotion (x, y); CharMotion(x, y);
break; break;
case 1: case 1:
SingleFrameMotion (x, y); SingleFrameMotion(x, y);
break; break;
case 2: case 2:
SequenceMotion (x, y); SequenceMotion(x, y);
break; break;
} }
} }
@ -284,13 +284,13 @@ void CTools::Motion(int x, int y) {
void CTools::Loop(double timestep) { void CTools::Loop(double timestep) {
switch (tool_mode) { switch (tool_mode) {
case 0: case 0:
RenderChar (timestep); RenderChar(timestep);
break; break;
case 1: case 1:
RenderSingleFrame (timestep); RenderSingleFrame(timestep);
break; break;
case 2: case 2:
RenderSequence (timestep); RenderSequence(timestep);
break; break;
} }
} }

View File

@ -29,13 +29,13 @@ private:
GLfloat vhead; // heading - Rundumsicht GLfloat vhead; // heading - Rundumsicht
GLfloat vpitch; // pitch - Drehung nach oben/unten GLfloat vpitch; // pitch - Drehung nach oben/unten
void XMove (GLfloat step); void XMove(GLfloat step);
void YMove (GLfloat step); void YMove(GLfloat step);
void ZMove (GLfloat step); void ZMove(GLfloat step);
void RotateHead (GLfloat step); void RotateHead(GLfloat step);
void RotatePitch (GLfloat step); void RotatePitch(GLfloat step);
public: public:
CCamera (); CCamera();
bool fore; bool fore;
bool back; bool back;
@ -47,7 +47,7 @@ public:
bool headright; bool headright;
bool pitchup; bool pitchup;
bool pitchdown; bool pitchdown;
void Update (float timestep); void Update(float timestep);
}; };
// --------------------------------------------------------------- // ---------------------------------------------------------------
@ -57,10 +57,10 @@ public:
class CGluCamera { class CGluCamera {
private: private:
public: public:
CGluCamera (); CGluCamera();
double distance; double distance;
double angle; double angle;
void Update (double timestep); void Update(double timestep);
bool turnright; bool turnright;
bool turnleft; bool turnleft;
@ -72,18 +72,18 @@ extern CGluCamera GluCamera;
// -------------------------------------------------------------------- // --------------------------------------------------------------------
void SetToolLight (); void SetToolLight();
void QuitTool (); void QuitTool();
void SetToolMode (int newmode); void SetToolMode(int newmode);
bool ToolsFinalStage (); bool ToolsFinalStage();
void SetCharChanged (bool val); void SetCharChanged(bool val);
void SetFrameChanged (bool val); void SetFrameChanged(bool val);
bool CharHasChanged (); bool CharHasChanged();
bool FrameHasChanged (); bool FrameHasChanged();
void SaveToolCharacter (); void SaveToolCharacter();
void SaveToolFrame (); void SaveToolFrame();
void ReloadToolCharacter (); void ReloadToolCharacter();
void DrawChanged (); void DrawChanged();
class CTools : public State { class CTools : public State {

View File

@ -105,15 +105,15 @@ void DrawTrackmarks() {
TColor track_colour = colWhite; TColor track_colour = colWhite;
ScopedRenderMode rm(TRACK_MARKS); ScopedRenderMode rm(TRACK_MARKS);
textures[TRACK_HEAD] = Tex.GetTexture (trackid1); textures[TRACK_HEAD] = Tex.GetTexture(trackid1);
textures[TRACK_MARK] = Tex.GetTexture (trackid2); textures[TRACK_MARK] = Tex.GetTexture(trackid2);
textures[TRACK_TAIL] = Tex.GetTexture (trackid3); textures[TRACK_TAIL] = Tex.GetTexture(trackid3);
glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
for (list<track_quad_t>::const_iterator q = track_marks.quads.begin(); q != track_marks.quads.end(); ++q) { for (list<track_quad_t>::const_iterator q = track_marks.quads.begin(); q != track_marks.quads.end(); ++q) {
track_colour.a = q->alpha; track_colour.a = q->alpha;
set_material (track_colour, colBlack, 1.0); set_material(track_colour, colBlack, 1.0);
textures[q->track_type]->Bind(); textures[q->track_type]->Bind();
if ((q->track_type == TRACK_HEAD) || (q->track_type == TRACK_TAIL)) { if ((q->track_type == TRACK_HEAD) || (q->track_type == TRACK_TAIL)) {
@ -160,7 +160,7 @@ void DrawTrackmarks() {
while (qnext != track_marks.quads.end() && qnext->track_type != TRACK_TAIL) { while (qnext != track_marks.quads.end() && qnext->track_type != TRACK_TAIL) {
q = qnext; q = qnext;
track_colour.a = q->alpha; track_colour.a = q->alpha;
set_material (track_colour, colBlack, 1.0); set_material(track_colour, colBlack, 1.0);
glNormal3(q->n4); glNormal3(q->n4);
glTexCoord2(q->t4); glTexCoord2(q->t4);
@ -203,7 +203,7 @@ void add_track_mark(const CControl *ctrl, int *id) {
TTerrType *TerrList = &Course.TerrList[0]; TTerrType *TerrList = &Course.TerrList[0];
*id = Course.GetTerrainIdx (ctrl->cpos.x, ctrl->cpos.z, 0.5); *id = Course.GetTerrainIdx(ctrl->cpos.x, ctrl->cpos.z, 0.5);
if (*id < 1) { if (*id < 1) {
break_track_marks(); break_track_marks();
return; return;
@ -220,7 +220,7 @@ void add_track_mark(const CControl *ctrl, int *id) {
return; return;
} }
TVector3d width_vector = CrossProduct (ctrl->cdirection, TVector3d (0, 1, 0)); TVector3d width_vector = CrossProduct(ctrl->cdirection, TVector3d(0, 1, 0));
double magnitude = width_vector.Norm(); double magnitude = width_vector.Norm();
if (magnitude == 0) { if (magnitude == 0) {
break_track_marks(); break_track_marks();
@ -231,16 +231,16 @@ void add_track_mark(const CControl *ctrl, int *id) {
TVector3d right_vector = -TRACK_WIDTH/2.0 * width_vector; TVector3d right_vector = -TRACK_WIDTH/2.0 * width_vector;
TVector3d left_wing = ctrl->cpos - left_vector; TVector3d left_wing = ctrl->cpos - left_vector;
TVector3d right_wing = ctrl->cpos - right_vector; TVector3d right_wing = ctrl->cpos - right_vector;
double left_y = Course.FindYCoord (left_wing.x, left_wing.z); double left_y = Course.FindYCoord(left_wing.x, left_wing.z);
double right_y = Course.FindYCoord (right_wing.x, right_wing.z); double right_y = Course.FindYCoord(right_wing.x, right_wing.z);
if (fabs(left_y-right_y) > MAX_TRACK_DEPTH) { if (fabs(left_y-right_y) > MAX_TRACK_DEPTH) {
break_track_marks(); break_track_marks();
return; return;
} }
TPlane surf_plane = Course.GetLocalCoursePlane (ctrl->cpos); TPlane surf_plane = Course.GetLocalCoursePlane(ctrl->cpos);
double dist_from_surface = DistanceToPlane (surf_plane, ctrl->cpos); double dist_from_surface = DistanceToPlane(surf_plane, ctrl->cpos);
// comp_depth = get_compression_depth(Snow); // comp_depth = get_compression_depth(Snow);
double comp_depth = 0.1; double comp_depth = 0.1;
if (dist_from_surface >= (2 * comp_depth)) { if (dist_from_surface >= (2 * comp_depth)) {
@ -259,12 +259,12 @@ void add_track_mark(const CControl *ctrl, int *id) {
if (!continuing_track) { if (!continuing_track) {
q->track_type = TRACK_HEAD; q->track_type = TRACK_HEAD;
q->v1 = TVector3d (left_wing.x, left_y + TRACK_HEIGHT, left_wing.z); q->v1 = TVector3d(left_wing.x, left_y + TRACK_HEIGHT, left_wing.z);
q->v2 = TVector3d (right_wing.x, right_y + TRACK_HEIGHT, right_wing.z); q->v2 = TVector3d(right_wing.x, right_y + TRACK_HEIGHT, right_wing.z);
q->v3 = TVector3d (left_wing.x, left_y + TRACK_HEIGHT, left_wing.z); q->v3 = TVector3d(left_wing.x, left_y + TRACK_HEIGHT, left_wing.z);
q->v4 = TVector3d (right_wing.x, right_y + TRACK_HEIGHT, right_wing.z); q->v4 = TVector3d(right_wing.x, right_y + TRACK_HEIGHT, right_wing.z);
q->n1 = Course.FindCourseNormal (q->v1.x, q->v1.z); q->n1 = Course.FindCourseNormal(q->v1.x, q->v1.z);
q->n2 = Course.FindCourseNormal (q->v2.x, q->v2.z); q->n2 = Course.FindCourseNormal(q->v2.x, q->v2.z);
q->t1 = TVector2d(0.0, 0.0); q->t1 = TVector2d(0.0, 0.0);
q->t2 = TVector2d(1.0, 0.0); q->t2 = TVector2d(1.0, 0.0);
} else { } else {
@ -278,20 +278,20 @@ void add_track_mark(const CControl *ctrl, int *id) {
q->t2 = qprev->t4; q->t2 = qprev->t4;
if (qprev->track_type == TRACK_TAIL) qprev->track_type = TRACK_MARK; if (qprev->track_type == TRACK_TAIL) qprev->track_type = TRACK_MARK;
} }
q->v3 = TVector3d (left_wing.x, left_y + TRACK_HEIGHT, left_wing.z); q->v3 = TVector3d(left_wing.x, left_y + TRACK_HEIGHT, left_wing.z);
q->v4 = TVector3d (right_wing.x, right_y + TRACK_HEIGHT, right_wing.z); q->v4 = TVector3d(right_wing.x, right_y + TRACK_HEIGHT, right_wing.z);
q->n3 = Course.FindCourseNormal (q->v3.x, q->v3.z); q->n3 = Course.FindCourseNormal(q->v3.x, q->v3.z);
q->n4 = Course.FindCourseNormal (q->v4.x, q->v4.z); q->n4 = Course.FindCourseNormal(q->v4.x, q->v4.z);
double tex_end = speed*g_game.time_step/TRACK_WIDTH; double tex_end = speed*g_game.time_step/TRACK_WIDTH;
if (q->track_type == TRACK_HEAD) { if (q->track_type == TRACK_HEAD) {
q->t3= TVector2d (0.0, 1.0); q->t3= TVector2d(0.0, 1.0);
q->t4= TVector2d (1.0, 1.0); q->t4= TVector2d(1.0, 1.0);
} else { } else {
q->t3 = TVector2d (0.0, q->t1.y + tex_end); q->t3 = TVector2d(0.0, q->t1.y + tex_end);
q->t4 = TVector2d (1.0, q->t2.y + tex_end); q->t4 = TVector2d(1.0, q->t2.y + tex_end);
} }
} }
q->alpha = min ((2*comp_depth-dist_from_surface)/(4*comp_depth), 1.0); q->alpha = min((2*comp_depth-dist_from_surface)/(4*comp_depth), 1.0);
continuing_track = true; continuing_track = true;
} }
@ -302,10 +302,10 @@ void UpdateTrackmarks(const CControl *ctrl) {
int trackid; int trackid;
TTerrType *TerrList = &Course.TerrList[0]; TTerrType *TerrList = &Course.TerrList[0];
add_track_mark (ctrl, &trackid); add_track_mark(ctrl, &trackid);
if (trackid >= 0 && TerrList[trackid].trackmarks) { if (trackid >= 0 && TerrList[trackid].trackmarks) {
SetTrackIDs (TerrList[trackid].starttex, SetTrackIDs(TerrList[trackid].starttex,
TerrList[trackid].tracktex, TerrList[trackid].tracktex,
TerrList[trackid].stoptex); TerrList[trackid].stoptex);
} }
} }

View File

@ -26,7 +26,7 @@ CTranslation Trans;
// if anything is wrong with an translation, the program will fall back // if anything is wrong with an translation, the program will fall back
// to these defaults (only the wrong items) // to these defaults (only the wrong items)
void CTranslation::SetDefaultTranslations () { void CTranslation::SetDefaultTranslations() {
texts[0] = "Press any key to start"; texts[0] = "Press any key to start";
texts[1] = "Enter an event"; texts[1] = "Enter an event";
texts[2] = "Practice"; texts[2] = "Practice";
@ -125,20 +125,25 @@ void CTranslation::SetDefaultTranslations () {
texts[83] = "Randomize settings"; texts[83] = "Randomize settings";
texts[84] = "Fullscreen setting has changed,"; texts[84] = "Score";
texts[85] = "You need to restart the game"; texts[85] = "Herring";
texts[86] = "Time";
texts[87] = "Path length";
texts[88] = "Average speed";
texts[89] = "Position";
texts[90] = "in highscore list";
} }
const string& CTranslation::Text (size_t idx) const { const string& CTranslation::Text(size_t idx) const {
if (idx >= NUM_COMMON_TEXTS) return emptyString; if (idx >= NUM_COMMON_TEXTS) return emptyString;
return texts[idx]; return texts[idx];
} }
void CTranslation::LoadLanguages () { void CTranslation::LoadLanguages() {
CSPList list (MAX_LANGUAGES); CSPList list(MAX_LANGUAGES);
if (!list.Load (param.trans_dir, "languages.lst")) { if (!list.Load(param.trans_dir, "languages.lst")) {
Message ("could not load language list"); Message("could not load language list");
return; return;
} }
@ -147,44 +152,35 @@ void CTranslation::LoadLanguages () {
languages[0].language = "English"; languages[0].language = "English";
for (size_t i=1; i<list.Count()+1; i++) { for (size_t i=1; i<list.Count()+1; i++) {
const string& line = list.Line(i-1); const string& line = list.Line(i-1);
languages[i].lang = SPStrN (line, "lang", "en_GB"); languages[i].lang = SPStrN(line, "lang", "en_GB");
languages[i].language = SPStrN (line, "language", "English"); languages[i].language = SPStrN(line, "language", "English");
LangIndex[languages[i].lang] = i;
} }
if (param.language == string::npos) if (param.language == string::npos)
param.language = GetSystemDefaultLangIdx(); param.language = GetSystemDefaultLangIdx();
} }
size_t CTranslation::GetLangIdx (const string& lang) const { const string& CTranslation::GetLanguage(size_t idx) const {
return LangIndex.at(lang);
}
const string& CTranslation::GetLanguage (size_t idx) const {
if (idx >= languages.size()) return errorString; if (idx >= languages.size()) return errorString;
return languages[idx].language; return languages[idx].language;
} }
const string& CTranslation::GetLanguage (const string& lang) const { void CTranslation::LoadTranslations(size_t langidx) {
return GetLanguage (GetLangIdx (lang)); SetDefaultTranslations();
}
void CTranslation::LoadTranslations (size_t langidx) {
SetDefaultTranslations ();
if (langidx == 0 || langidx >= languages.size()) return; if (langidx == 0 || langidx >= languages.size()) return;
CSPList list(MAX_COMMON_TEXT_LINES); CSPList list(MAX_COMMON_TEXT_LINES);
string filename = languages[langidx].lang + ".lst"; string filename = languages[langidx].lang + ".lst";
if (!list.Load (param.trans_dir, filename)) { if (!list.Load(param.trans_dir, filename)) {
Message ("could not load translations list:", filename); Message("could not load translations list:", filename);
return; return;
} }
for (size_t i=0; i<list.Count(); i++) { for (size_t i=0; i<list.Count(); i++) {
const string& line = list.Line(i); const string& line = list.Line(i);
int idx = SPIntN (line, "idx", -1); int idx = SPIntN(line, "idx", -1);
if (idx >= 0 && idx < NUM_COMMON_TEXTS) { if (idx >= 0 && idx < NUM_COMMON_TEXTS) {
texts[idx] = SPStrN (line, "trans", texts[idx]); texts[idx] = SPStrN(line, "trans", texts[idx]);
} }
} }
} }
@ -205,9 +201,13 @@ string CTranslation::GetSystemDefaultLang() {
} }
size_t CTranslation::GetSystemDefaultLangIdx() const { size_t CTranslation::GetSystemDefaultLangIdx() const {
try { std::string name = GetSystemDefaultLang();
return GetLangIdx(GetSystemDefaultLang()); return GetLangIdx(name);
} catch (...) { }
return 0;
} size_t CTranslation::GetLangIdx(const string& lang) const {
for (size_t i = 0; i < languages.size(); i++)
if (languages[i].lang == lang)
return i;
return 0;
} }

View File

@ -24,11 +24,10 @@ An name convention:
#define TRANSLATION_H #define TRANSLATION_H
#include "bh.h" #include "bh.h"
#include <map>
#include <vector> #include <vector>
#define MAX_LANGUAGES 32 #define MAX_LANGUAGES 32
#define NUM_COMMON_TEXTS 86 #define NUM_COMMON_TEXTS 93
#define MAX_COMMON_TEXT_LINES NUM_COMMON_TEXTS*2 #define MAX_COMMON_TEXT_LINES NUM_COMMON_TEXTS*2
@ -40,19 +39,17 @@ struct TLang {
class CTranslation { class CTranslation {
private: private:
string texts[NUM_COMMON_TEXTS]; string texts[NUM_COMMON_TEXTS];
map<string, size_t> LangIndex;
public: public:
vector<TLang> languages; vector<TLang> languages;
void LoadLanguages (); void LoadLanguages();
size_t GetLangIdx (const string& lang) const; const string& GetLanguage(size_t idx) const;
const string& GetLanguage (size_t idx) const; void SetDefaultTranslations();
const string& GetLanguage (const string& lang) const; const string& Text(size_t idx) const;
void SetDefaultTranslations (); void LoadTranslations(size_t langidx);
const string& Text (size_t idx) const;
void LoadTranslations (size_t langidx);
static string GetSystemDefaultLang(); static string GetSystemDefaultLang();
size_t GetSystemDefaultLangIdx() const; size_t GetSystemDefaultLangIdx() const;
size_t GetLangIdx(const string& lang) const;
}; };
extern CTranslation Trans; extern CTranslation Trans;

View File

@ -52,7 +52,7 @@ static const TCharMaterial TuxDefMat = {TColor(0.5, 0.5, 0.5, 1.0), TColor(0.0,
static const TCharMaterial Highlight = {TColor(0.8, 0.15, 0.15, 1.0), TColor(0.0, 0.0, 0.0, 1.0), 0.0}; static const TCharMaterial Highlight = {TColor(0.8, 0.15, 0.15, 1.0), TColor(0.0, 0.0, 0.0, 1.0), 0.0};
CCharShape TestChar; CCharShape TestChar;
CCharShape::CCharShape () { CCharShape::CCharShape() {
for (int i=0; i<MAX_CHAR_NODES; i++) { for (int i=0; i<MAX_CHAR_NODES; i++) {
Nodes[i] = NULL; Nodes[i] = NULL;
Index[i] = -1; Index[i] = -1;
@ -80,18 +80,18 @@ CCharShape::~CCharShape() {
// nodes // nodes
// -------------------------------------------------------------------- // --------------------------------------------------------------------
size_t CCharShape::GetNodeIdx (size_t node_name) const { size_t CCharShape::GetNodeIdx(size_t node_name) const {
if (node_name >= MAX_CHAR_NODES) return -1; if (node_name >= MAX_CHAR_NODES) return -1;
return Index[node_name]; return Index[node_name];
} }
TCharNode *CCharShape::GetNode (size_t node_name) { TCharNode *CCharShape::GetNode(size_t node_name) {
size_t idx = GetNodeIdx (node_name); size_t idx = GetNodeIdx(node_name);
if (idx >= numNodes) return NULL; if (idx >= numNodes) return NULL;
return Nodes[idx]; return Nodes[idx];
} }
void CCharShape::CreateRootNode () { void CCharShape::CreateRootNode() {
TCharNode *node = new TCharNode; TCharNode *node = new TCharNode;
node->node_name = 0; node->node_name = 0;
node->parent = NULL; node->parent = NULL;
@ -116,9 +116,9 @@ void CCharShape::CreateRootNode () {
} }
bool CCharShape::CreateCharNode(int parent_name, size_t node_name, const string& joint, const string& name, const string& order, bool shadow) { bool CCharShape::CreateCharNode(int parent_name, size_t node_name, const string& joint, const string& name, const string& order, bool shadow) {
TCharNode *parent = GetNode (parent_name); TCharNode *parent = GetNode(parent_name);
if (parent == NULL) { if (parent == NULL) {
Message ("wrong parent node"); Message("wrong parent node");
return false; return false;
} }
TCharNode *node = new TCharNode; TCharNode *node = new TCharNode;
@ -167,8 +167,8 @@ bool CCharShape::CreateCharNode(int parent_name, size_t node_name, const string&
return true; return true;
} }
void CCharShape::AddAction (size_t node_name, int type, const TVector3d& vec, double val) { void CCharShape::AddAction(size_t node_name, int type, const TVector3d& vec, double val) {
size_t idx = GetNodeIdx (node_name); size_t idx = GetNodeIdx(node_name);
TCharAction *act = Nodes[idx]->action; TCharAction *act = Nodes[idx]->action;
act->type[act->num] = type; act->type[act->num] = type;
act->vec[act->num] = vec; act->vec[act->num] = vec;
@ -176,8 +176,8 @@ void CCharShape::AddAction (size_t node_name, int type, const TVector3d& vec, do
act->num++; act->num++;
} }
bool CCharShape::TranslateNode (size_t node_name, const TVector3d& vec) { bool CCharShape::TranslateNode(size_t node_name, const TVector3d& vec) {
TCharNode *node = GetNode (node_name); TCharNode *node = GetNode(node_name);
if (node == NULL) return false; if (node == NULL) return false;
TMatrix<4, 4> TransMatrix; TMatrix<4, 4> TransMatrix;
@ -187,12 +187,12 @@ bool CCharShape::TranslateNode (size_t node_name, const TVector3d& vec) {
TransMatrix.SetTranslationMatrix(-vec.x, -vec.y, -vec.z); TransMatrix.SetTranslationMatrix(-vec.x, -vec.y, -vec.z);
node->invtrans = TransMatrix * node->invtrans; node->invtrans = TransMatrix * node->invtrans;
if (newActions && useActions) AddAction (node_name, 0, vec, 0); if (newActions && useActions) AddAction(node_name, 0, vec, 0);
return true; return true;
} }
bool CCharShape::RotateNode (size_t node_name, int axis, double angle) { bool CCharShape::RotateNode(size_t node_name, int axis, double angle) {
TCharNode *node = GetNode (node_name); TCharNode *node = GetNode(node_name);
if (node == NULL) return false; if (node == NULL) return false;
if (axis > 3) return false; if (axis > 3) return false;
@ -216,17 +216,17 @@ bool CCharShape::RotateNode (size_t node_name, int axis, double angle) {
rotMatrix.SetRotationMatrix(-angle, caxis); rotMatrix.SetRotationMatrix(-angle, caxis);
node->invtrans = rotMatrix * node->invtrans; node->invtrans = rotMatrix * node->invtrans;
if (newActions && useActions) AddAction (node_name, axis, NullVec3, angle); if (newActions && useActions) AddAction(node_name, axis, NullVec3, angle);
return true; return true;
} }
bool CCharShape::RotateNode (const string& node_trivialname, int axis, double angle) { bool CCharShape::RotateNode(const string& node_trivialname, int axis, double angle) {
map<string, size_t>::const_iterator i = NodeIndex.find(node_trivialname); map<string, size_t>::const_iterator i = NodeIndex.find(node_trivialname);
if (i == NodeIndex.end()) return false; if (i == NodeIndex.end()) return false;
return RotateNode (i->second, axis, angle); return RotateNode(i->second, axis, angle);
} }
void CCharShape::ScaleNode (size_t node_name, const TVector3d& vec) { void CCharShape::ScaleNode(size_t node_name, const TVector3d& vec) {
TCharNode *node = GetNode(node_name); TCharNode *node = GetNode(node_name);
if (node == NULL) return; if (node == NULL) return;
@ -237,10 +237,10 @@ void CCharShape::ScaleNode (size_t node_name, const TVector3d& vec) {
matrix.SetScalingMatrix(1.0 / vec.x, 1.0 / vec.y, 1.0 / vec.z); matrix.SetScalingMatrix(1.0 / vec.x, 1.0 / vec.y, 1.0 / vec.z);
node->invtrans = matrix * node->invtrans; node->invtrans = matrix * node->invtrans;
if (newActions && useActions) AddAction (node_name, 4, vec, 0); if (newActions && useActions) AddAction(node_name, 4, vec, 0);
} }
bool CCharShape::VisibleNode (size_t node_name, float level) { bool CCharShape::VisibleNode(size_t node_name, float level) {
TCharNode *node = GetNode(node_name); TCharNode *node = GetNode(node_name);
if (node == NULL) return false; if (node == NULL) return false;
@ -248,14 +248,14 @@ bool CCharShape::VisibleNode (size_t node_name, float level) {
if (node->visible) { if (node->visible) {
node->divisions = node->divisions =
clamp (MIN_SPHERE_DIV, ROUND_TO_NEAREST (param.tux_sphere_divisions * level / 10), MAX_SPHERE_DIV); clamp(MIN_SPHERE_DIV, ROUND_TO_NEAREST(param.tux_sphere_divisions * level / 10), MAX_SPHERE_DIV);
node->radius = 1.0; node->radius = 1.0;
} }
if (newActions && useActions) AddAction (node_name, 5, NullVec3, level); if (newActions && useActions) AddAction(node_name, 5, NullVec3, level);
return true; return true;
} }
bool CCharShape::MaterialNode (size_t node_name, const string& mat_name) { bool CCharShape::MaterialNode(size_t node_name, const string& mat_name) {
TCharNode *node = GetNode(node_name); TCharNode *node = GetNode(node_name);
if (node == NULL) return false; if (node == NULL) return false;
TCharMaterial *mat = GetMaterial(mat_name); TCharMaterial *mat = GetMaterial(mat_name);
@ -265,7 +265,7 @@ bool CCharShape::MaterialNode (size_t node_name, const string& mat_name) {
return true; return true;
} }
bool CCharShape::ResetNode (size_t node_name) { bool CCharShape::ResetNode(size_t node_name) {
TCharNode *node = GetNode(node_name); TCharNode *node = GetNode(node_name);
if (node == NULL) return false; if (node == NULL) return false;
@ -274,10 +274,10 @@ bool CCharShape::ResetNode (size_t node_name) {
return true; return true;
} }
bool CCharShape::ResetNode (const string& node_trivialname) { bool CCharShape::ResetNode(const string& node_trivialname) {
map<string, size_t>::const_iterator i = NodeIndex.find(node_trivialname); map<string, size_t>::const_iterator i = NodeIndex.find(node_trivialname);
if (i == NodeIndex.end()) return false; if (i == NodeIndex.end()) return false;
return ResetNode (i->second); return ResetNode(i->second);
} }
bool CCharShape::TransformNode(size_t node_name, const TMatrix<4, 4>& mat, const TMatrix<4, 4>& invmat) { bool CCharShape::TransformNode(size_t node_name, const TMatrix<4, 4>& mat, const TMatrix<4, 4>& invmat) {
@ -289,21 +289,21 @@ bool CCharShape::TransformNode(size_t node_name, const TMatrix<4, 4>& mat, const
return true; return true;
} }
void CCharShape::ResetJoints () { void CCharShape::ResetJoints() {
ResetNode ("left_shldr"); ResetNode("left_shldr");
ResetNode ("right_shldr"); ResetNode("right_shldr");
ResetNode ("left_hip"); ResetNode("left_hip");
ResetNode ("right_hip"); ResetNode("right_hip");
ResetNode ("left_knee"); ResetNode("left_knee");
ResetNode ("right_knee"); ResetNode("right_knee");
ResetNode ("left_ankle"); ResetNode("left_ankle");
ResetNode ("right_ankle"); ResetNode("right_ankle");
ResetNode ("tail"); ResetNode("tail");
ResetNode ("neck"); ResetNode("neck");
ResetNode ("head"); ResetNode("head");
} }
void CCharShape::Reset () { void CCharShape::Reset() {
for (int i=0; i<MAX_CHAR_NODES; i++) { for (int i=0; i<MAX_CHAR_NODES; i++) {
if (Nodes[i] != NULL) { if (Nodes[i] != NULL) {
delete Nodes[i]->action; delete Nodes[i]->action;
@ -329,7 +329,7 @@ void CCharShape::Reset () {
// materials // materials
// -------------------------------------------------------------------- // --------------------------------------------------------------------
TCharMaterial* CCharShape::GetMaterial (const string& mat_name) { TCharMaterial* CCharShape::GetMaterial(const string& mat_name) {
map<string, size_t>::const_iterator i = MaterialIndex.find(mat_name); map<string, size_t>::const_iterator i = MaterialIndex.find(mat_name);
if (i != MaterialIndex.end() && i->second < Materials.size()) { if (i != MaterialIndex.end() && i->second < Materials.size()) {
return &Materials[i->second]; return &Materials[i->second];
@ -337,10 +337,10 @@ TCharMaterial* CCharShape::GetMaterial (const string& mat_name) {
return NULL; return NULL;
} }
void CCharShape::CreateMaterial (const string& line) { void CCharShape::CreateMaterial(const string& line) {
TVector3d diff = SPVector3d(line, "diff"); TVector3d diff = SPVector3d(line, "diff");
TVector3d spec = SPVector3d(line, "spec"); TVector3d spec = SPVector3d(line, "spec");
float exp = SPFloatN (line, "exp", 50); float exp = SPFloatN(line, "exp", 50);
std::string mat = SPStrN(line, "mat"); std::string mat = SPStrN(line, "mat");
Materials.push_back(TCharMaterial()); Materials.push_back(TCharMaterial());
@ -363,16 +363,16 @@ void CCharShape::CreateMaterial (const string& line) {
// drawing // drawing
// -------------------------------------------------------------------- // --------------------------------------------------------------------
void CCharShape::DrawCharSphere (int num_divisions) { void CCharShape::DrawCharSphere(int num_divisions) {
GLUquadricObj *qobj = gluNewQuadric(); GLUquadricObj *qobj = gluNewQuadric();
gluQuadricDrawStyle (qobj, GLU_FILL); gluQuadricDrawStyle(qobj, GLU_FILL);
gluQuadricOrientation (qobj, GLU_OUTSIDE); gluQuadricOrientation(qobj, GLU_OUTSIDE);
gluQuadricNormals (qobj, GLU_SMOOTH); gluQuadricNormals(qobj, GLU_SMOOTH);
gluSphere (qobj, 1.0, (GLint)2.0 * num_divisions, num_divisions); gluSphere(qobj, 1.0, (GLint)2.0 * num_divisions, num_divisions);
gluDeleteQuadric (qobj); gluDeleteQuadric(qobj);
} }
void CCharShape::DrawNodes (const TCharNode *node) { void CCharShape::DrawNodes(const TCharNode *node) {
glPushMatrix(); glPushMatrix();
glMultMatrix(node->trans); glMultMatrix(node->trans);
@ -386,14 +386,14 @@ void CCharShape::DrawNodes (const TCharNode *node) {
} }
if (node->visible == true) { if (node->visible == true) {
set_material (mat->diffuse, mat->specular, mat->exp); set_material(mat->diffuse, mat->specular, mat->exp);
DrawCharSphere (node->divisions); DrawCharSphere(node->divisions);
} }
// -------------- recursive loop ------------------------------------- // -------------- recursive loop -------------------------------------
TCharNode *child = node->child; TCharNode *child = node->child;
while (child != NULL) { while (child != NULL) {
DrawNodes (child); DrawNodes(child);
if (child->node_name == highlight_node) highlighted = false; if (child->node_name == highlight_node) highlighted = false;
child = child->next; child = child->next;
} }
@ -401,80 +401,80 @@ void CCharShape::DrawNodes (const TCharNode *node) {
glPopMatrix(); glPopMatrix();
} }
void CCharShape::Draw () { void CCharShape::Draw() {
static const float dummy_color[] = {0.0, 0.0, 0.0, 1.0}; static const float dummy_color[] = {0.0, 0.0, 0.0, 1.0};
glMaterialfv (GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, dummy_color); glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, dummy_color);
ScopedRenderMode rm(TUX); ScopedRenderMode rm(TUX);
glEnable (GL_NORMALIZE); glEnable(GL_NORMALIZE);
TCharNode *node = GetNode(0); TCharNode *node = GetNode(0);
if (node == NULL) return; if (node == NULL) return;
DrawNodes (node); DrawNodes(node);
glDisable (GL_NORMALIZE); glDisable(GL_NORMALIZE);
if (param.perf_level > 2 && g_game.argument == 0) DrawShadow (); if (param.perf_level > 2 && g_game.argument == 0) DrawShadow();
highlighted = false; highlighted = false;
} }
// -------------------------------------------------------------------- // --------------------------------------------------------------------
bool CCharShape::Load (const string& dir, const string& filename, bool with_actions) { bool CCharShape::Load(const string& dir, const string& filename, bool with_actions) {
CSPList list (500); CSPList list(500);
useActions = with_actions; useActions = with_actions;
CreateRootNode (); CreateRootNode();
newActions = true; newActions = true;
if (!list.Load (dir, filename)) { if (!list.Load(dir, filename)) {
Message ("could not load character", filename); Message("could not load character", filename);
return false; return false;
} }
for (size_t i=0; i<list.Count(); i++) { for (size_t i=0; i<list.Count(); i++) {
const string& line = list.Line(i); const string& line = list.Line(i);
int node_name = SPIntN (line, "node", -1); int node_name = SPIntN(line, "node", -1);
int parent_name = SPIntN (line, "par", -1); int parent_name = SPIntN(line, "par", -1);
string mat_name = SPStrN (line, "mat"); string mat_name = SPStrN(line, "mat");
string name = SPStrN (line, "joint"); string name = SPStrN(line, "joint");
string fullname = SPStrN (line, "name"); string fullname = SPStrN(line, "name");
if (SPIntN (line, "material", 0) > 0) { if (SPIntN(line, "material", 0) > 0) {
CreateMaterial (line); CreateMaterial(line);
} else { } else {
float visible = SPFloatN (line, "vis", -1.0); float visible = SPFloatN(line, "vis", -1.0);
bool shadow = SPBoolN (line, "shad", false); bool shadow = SPBoolN(line, "shad", false);
string order = SPStrN (line, "order"); string order = SPStrN(line, "order");
CreateCharNode (parent_name, node_name, name, fullname, order, shadow); CreateCharNode(parent_name, node_name, name, fullname, order, shadow);
TVector3d rot = SPVector3d(line, "rot"); TVector3d rot = SPVector3d(line, "rot");
MaterialNode (node_name, mat_name); MaterialNode(node_name, mat_name);
for (size_t ii = 0; ii < order.size(); ii++) { for (size_t ii = 0; ii < order.size(); ii++) {
int act = order[ii]-48; int act = order[ii]-48;
switch (act) { switch (act) {
case 0: { case 0: {
TVector3d trans = SPVector3d(line, "trans"); TVector3d trans = SPVector3d(line, "trans");
TranslateNode (node_name, trans); TranslateNode(node_name, trans);
break; break;
} }
case 1: case 1:
RotateNode (node_name, 1, rot.x); RotateNode(node_name, 1, rot.x);
break; break;
case 2: case 2:
RotateNode (node_name, 2, rot.y); RotateNode(node_name, 2, rot.y);
break; break;
case 3: case 3:
RotateNode (node_name, 3, rot.z); RotateNode(node_name, 3, rot.z);
break; break;
case 4: { case 4: {
TVector3d scale = SPVector3(line, "scale", TVector3d(1, 1, 1)); TVector3d scale = SPVector3(line, "scale", TVector3d(1, 1, 1));
ScaleNode (node_name, scale); ScaleNode(node_name, scale);
break; break;
} }
case 5: case 5:
VisibleNode (node_name, visible); VisibleNode(node_name, visible);
break; break;
case 9: case 9:
RotateNode (node_name, 2, rot.z); RotateNode(node_name, 2, rot.z);
break; break;
default: default:
break; break;
@ -486,20 +486,20 @@ bool CCharShape::Load (const string& dir, const string& filename, bool with_acti
return true; return true;
} }
TVector3d CCharShape::AdjustRollvector (const CControl *ctrl, const TVector3d& vel_, const TVector3d& zvec) { TVector3d CCharShape::AdjustRollvector(const CControl *ctrl, const TVector3d& vel_, const TVector3d& zvec) {
TMatrix<4, 4> rot_mat; TMatrix<4, 4> rot_mat;
TVector3d vel = ProjectToPlane(zvec, vel_); TVector3d vel = ProjectToPlane(zvec, vel_);
vel.Norm(); vel.Norm();
if (ctrl->is_braking) { if (ctrl->is_braking) {
rot_mat = RotateAboutVectorMatrix (vel, ctrl->turn_fact * BRAKING_ROLL_ANGLE); rot_mat = RotateAboutVectorMatrix(vel, ctrl->turn_fact * BRAKING_ROLL_ANGLE);
} else { } else {
rot_mat = RotateAboutVectorMatrix (vel, ctrl->turn_fact * MAX_ROLL_ANGLE); rot_mat = RotateAboutVectorMatrix(vel, ctrl->turn_fact * MAX_ROLL_ANGLE);
} }
return TransformVector (rot_mat, zvec); return TransformVector(rot_mat, zvec);
} }
void CCharShape::AdjustOrientation (CControl *ctrl, double dtime, void CCharShape::AdjustOrientation(CControl *ctrl, double dtime,
double dist_from_surface, const TVector3d& surf_nml) { double dist_from_surface, const TVector3d& surf_nml) {
TVector3d new_y, new_z; TVector3d new_y, new_z;
static const TVector3d minus_z_vec(0, 0, -1); static const TVector3d minus_z_vec(0, 0, -1);
static const TVector3d y_vec(0, 1, 0); static const TVector3d y_vec(0, 1, 0);
@ -507,19 +507,19 @@ void CCharShape::AdjustOrientation (CControl *ctrl, double dtime,
if (dist_from_surface > 0) { if (dist_from_surface > 0) {
new_y = ctrl->cvel; new_y = ctrl->cvel;
new_y.Norm(); new_y.Norm();
new_z = ProjectToPlane (new_y, TVector3d(0, -1, 0)); new_z = ProjectToPlane(new_y, TVector3d(0, -1, 0));
new_z.Norm(); new_z.Norm();
new_z = AdjustRollvector (ctrl, ctrl->cvel, new_z); new_z = AdjustRollvector(ctrl, ctrl->cvel, new_z);
} else { } else {
new_z = -1.0 * surf_nml; new_z = -1.0 * surf_nml;
new_z = AdjustRollvector (ctrl, ctrl->cvel, new_z); new_z = AdjustRollvector(ctrl, ctrl->cvel, new_z);
new_y = ProjectToPlane (surf_nml, ctrl->cvel); new_y = ProjectToPlane(surf_nml, ctrl->cvel);
new_y.Norm(); new_y.Norm();
} }
TVector3d new_x = CrossProduct (new_y, new_z); TVector3d new_x = CrossProduct(new_y, new_z);
TMatrix<4, 4> cob_mat(new_x, new_y, new_z); TMatrix<4, 4> cob_mat(new_x, new_y, new_z);
TQuaternion new_orient = MakeQuaternionFromMatrix (cob_mat); TQuaternion new_orient = MakeQuaternionFromMatrix(cob_mat);
if (!ctrl->orientation_initialized) { if (!ctrl->orientation_initialized) {
ctrl->orientation_initialized = true; ctrl->orientation_initialized = true;
@ -528,28 +528,28 @@ void CCharShape::AdjustOrientation (CControl *ctrl, double dtime,
double time_constant = dist_from_surface > 0 ? TO_AIR_TIME : TO_TIME; double time_constant = dist_from_surface > 0 ? TO_AIR_TIME : TO_TIME;
ctrl->corientation = InterpolateQuaternions ( ctrl->corientation = InterpolateQuaternions(
ctrl->corientation, new_orient, ctrl->corientation, new_orient,
min (dtime / time_constant, 1.0)); min(dtime / time_constant, 1.0));
ctrl->plane_nml = RotateVector (ctrl->corientation, minus_z_vec); ctrl->plane_nml = RotateVector(ctrl->corientation, minus_z_vec);
ctrl->cdirection = RotateVector (ctrl->corientation, y_vec); ctrl->cdirection = RotateVector(ctrl->corientation, y_vec);
cob_mat = MakeMatrixFromQuaternion(ctrl->corientation); cob_mat = MakeMatrixFromQuaternion(ctrl->corientation);
// Trick rotations // Trick rotations
new_y = TVector3d (cob_mat[1][0], cob_mat[1][1], cob_mat[1][2]); new_y = TVector3d(cob_mat[1][0], cob_mat[1][1], cob_mat[1][2]);
TMatrix<4, 4> rot_mat = RotateAboutVectorMatrix(new_y, (ctrl->roll_factor * 360)); TMatrix<4, 4> rot_mat = RotateAboutVectorMatrix(new_y, (ctrl->roll_factor * 360));
cob_mat = rot_mat * cob_mat; cob_mat = rot_mat * cob_mat;
new_x = TVector3d (cob_mat[0][0], cob_mat[0][1], cob_mat[0][2]); new_x = TVector3d(cob_mat[0][0], cob_mat[0][1], cob_mat[0][2]);
rot_mat = RotateAboutVectorMatrix (new_x, ctrl->flip_factor * 360); rot_mat = RotateAboutVectorMatrix(new_x, ctrl->flip_factor * 360);
cob_mat = rot_mat * cob_mat; cob_mat = rot_mat * cob_mat;
TransformNode (0, cob_mat, cob_mat.GetTransposed()); TransformNode(0, cob_mat, cob_mat.GetTransposed());
} }
void CCharShape::AdjustJoints (double turnFact, bool isBraking, void CCharShape::AdjustJoints(double turnFact, bool isBraking,
double paddling_factor, double speed, double paddling_factor, double speed,
const TVector3d& net_force, double flap_factor) { const TVector3d& net_force, double flap_factor) {
double turning_angle[2]; double turning_angle[2];
double paddling_angle = 0; double paddling_angle = 0;
double ext_paddling_angle = 0; double ext_paddling_angle = 0;
@ -567,33 +567,33 @@ void CCharShape::AdjustJoints (double turnFact, bool isBraking,
turning_angle[0] = max(-turnFact,0.0) * MAX_ARM_ANGLE2; turning_angle[0] = max(-turnFact,0.0) * MAX_ARM_ANGLE2;
turning_angle[1] = max(turnFact,0.0) * MAX_ARM_ANGLE2; turning_angle[1] = max(turnFact,0.0) * MAX_ARM_ANGLE2;
flap_angle = MAX_ARM_ANGLE2 * (0.5 + 0.5 * sin (M_PI * flap_factor * 6 - M_PI / 2)); flap_angle = MAX_ARM_ANGLE2 * (0.5 + 0.5 * sin(M_PI * flap_factor * 6 - M_PI / 2));
force_angle = clamp (-20.0, -net_force.z / 300.0, 20.0); force_angle = clamp(-20.0, -net_force.z / 300.0, 20.0);
turn_leg_angle = turnFact * 10; turn_leg_angle = turnFact * 10;
ResetJoints (); ResetJoints();
RotateNode ("left_shldr", 3, RotateNode("left_shldr", 3,
min (braking_angle + paddling_angle + turning_angle[0], MAX_ARM_ANGLE2) + flap_angle); min(braking_angle + paddling_angle + turning_angle[0], MAX_ARM_ANGLE2) + flap_angle);
RotateNode ("right_shldr", 3, RotateNode("right_shldr", 3,
min (braking_angle + paddling_angle + turning_angle[1], MAX_ARM_ANGLE2) + flap_angle); min(braking_angle + paddling_angle + turning_angle[1], MAX_ARM_ANGLE2) + flap_angle);
RotateNode ("left_shldr", 2, -ext_paddling_angle); RotateNode("left_shldr", 2, -ext_paddling_angle);
RotateNode ("right_shldr", 2, ext_paddling_angle); RotateNode("right_shldr", 2, ext_paddling_angle);
RotateNode ("left_hip", 3, -20 + turn_leg_angle + force_angle); RotateNode("left_hip", 3, -20 + turn_leg_angle + force_angle);
RotateNode ("right_hip", 3, -20 - turn_leg_angle + force_angle); RotateNode("right_hip", 3, -20 - turn_leg_angle + force_angle);
RotateNode ("left_knee", 3, RotateNode("left_knee", 3,
-10 + turn_leg_angle - min (35.0, speed) + kick_paddling_angle + force_angle); -10 + turn_leg_angle - min(35.0, speed) + kick_paddling_angle + force_angle);
RotateNode ("right_knee", 3, RotateNode("right_knee", 3,
-10 - turn_leg_angle - min (35.0, speed) - kick_paddling_angle + force_angle); -10 - turn_leg_angle - min(35.0, speed) - kick_paddling_angle + force_angle);
RotateNode ("left_ankle", 3, -20 + min (50.0, speed)); RotateNode("left_ankle", 3, -20 + min(50.0, speed));
RotateNode ("right_ankle", 3, -20 + min (50.0, speed)); RotateNode("right_ankle", 3, -20 + min(50.0, speed));
RotateNode ("tail", 3, turnFact * 20); RotateNode("tail", 3, turnFact * 20);
RotateNode ("neck", 3, -50); RotateNode("neck", 3, -50);
RotateNode ("head", 3, -30); RotateNode("head", 3, -30);
RotateNode ("head", 2, -turnFact * 70); RotateNode("head", 2, -turnFact * 70);
} }
// -------------------------------------------------------------------- // --------------------------------------------------------------------
@ -609,31 +609,31 @@ bool CCharShape::CheckPolyhedronCollision(const TCharNode *node, const TMatrix<4
if (node->visible) { if (node->visible) {
TPolyhedron newph = ph; TPolyhedron newph = ph;
TransPolyhedron (newInvModelMatrix, newph); TransPolyhedron(newInvModelMatrix, newph);
hit = IntersectPolyhedron (newph); hit = IntersectPolyhedron(newph);
} }
if (hit == true) return hit; if (hit == true) return hit;
const TCharNode *child = node->child; const TCharNode *child = node->child;
while (child != NULL) { while (child != NULL) {
hit = CheckPolyhedronCollision (child, newModelMatrix, newInvModelMatrix, ph); hit = CheckPolyhedronCollision(child, newModelMatrix, newInvModelMatrix, ph);
if (hit == true) return hit; if (hit == true) return hit;
child = child->next; child = child->next;
} }
return false; return false;
} }
bool CCharShape::CheckCollision (const TPolyhedron& ph) { bool CCharShape::CheckCollision(const TPolyhedron& ph) {
TCharNode *node = GetNode(0); TCharNode *node = GetNode(0);
if (node == NULL) return false; if (node == NULL) return false;
const TMatrix<4, 4>& identity = TMatrix<4, 4>::getIdentity(); const TMatrix<4, 4>& identity = TMatrix<4, 4>::getIdentity();
return CheckPolyhedronCollision(node, identity, identity, ph); return CheckPolyhedronCollision(node, identity, identity, ph);
} }
bool CCharShape::Collision (const TVector3d& pos, const TPolyhedron& ph) { bool CCharShape::Collision(const TVector3d& pos, const TPolyhedron& ph) {
ResetNode (0); ResetNode(0);
TranslateNode (0, TVector3d (pos.x, pos.y, pos.z)); TranslateNode(0, TVector3d(pos.x, pos.y, pos.z));
return CheckCollision (ph); return CheckCollision(ph);
} }
// -------------------------------------------------------------------- // --------------------------------------------------------------------
@ -642,10 +642,10 @@ bool CCharShape::Collision (const TVector3d& pos, const TPolyhedron& ph) {
void CCharShape::DrawShadowVertex(double x, double y, double z, const TMatrix<4, 4>& mat) { void CCharShape::DrawShadowVertex(double x, double y, double z, const TMatrix<4, 4>& mat) {
TVector3d pt(x, y, z); TVector3d pt(x, y, z);
pt = TransformPoint (mat, pt); pt = TransformPoint(mat, pt);
double old_y = pt.y; double old_y = pt.y;
TVector3d nml = Course.FindCourseNormal (pt.x, pt.z); TVector3d nml = Course.FindCourseNormal(pt.x, pt.z);
pt.y = Course.FindYCoord (pt.x, pt.z) + SHADOW_HEIGHT; pt.y = Course.FindYCoord(pt.x, pt.z) + SHADOW_HEIGHT;
if (pt.y > old_y) pt.y = old_y; if (pt.y > old_y) pt.y = old_y;
glNormal3(nml); glNormal3(nml);
glVertex3(pt); glVertex3(pt);
@ -665,68 +665,68 @@ void CCharShape::DrawShadowSphere(const TMatrix<4, 4>& mat) {
double sin_phi, cos_phi; double sin_phi, cos_phi;
double sin_phi_d_phi, cos_phi_d_phi; double sin_phi_d_phi, cos_phi_d_phi;
sin_phi = sin (phi); sin_phi = sin(phi);
cos_phi = cos (phi); cos_phi = cos(phi);
sin_phi_d_phi = sin (phi + d_phi); sin_phi_d_phi = sin(phi + d_phi);
cos_phi_d_phi = cos (phi + d_phi); cos_phi_d_phi = cos(phi + d_phi);
if (phi <= eps) { if (phi <= eps) {
glBegin (GL_TRIANGLE_FAN); glBegin(GL_TRIANGLE_FAN);
DrawShadowVertex (0., 0., 1., mat); DrawShadowVertex(0., 0., 1., mat);
for (theta = 0.0; theta + eps < twopi; theta += d_theta) { for (theta = 0.0; theta + eps < twopi; theta += d_theta) {
sin_theta = sin (theta); sin_theta = sin(theta);
cos_theta = cos (theta); cos_theta = cos(theta);
x = cos_theta * sin_phi_d_phi; x = cos_theta * sin_phi_d_phi;
y = sin_theta * sin_phi_d_phi; y = sin_theta * sin_phi_d_phi;
z = cos_phi_d_phi; z = cos_phi_d_phi;
DrawShadowVertex (x, y, z, mat); DrawShadowVertex(x, y, z, mat);
} }
x = sin_phi_d_phi; x = sin_phi_d_phi;
y = 0.0; y = 0.0;
z = cos_phi_d_phi; z = cos_phi_d_phi;
DrawShadowVertex (x, y, z, mat); DrawShadowVertex(x, y, z, mat);
glEnd(); glEnd();
} else if (phi + d_phi + eps >= M_PI) { } else if (phi + d_phi + eps >= M_PI) {
glBegin (GL_TRIANGLE_FAN); glBegin(GL_TRIANGLE_FAN);
DrawShadowVertex (0., 0., -1., mat); DrawShadowVertex(0., 0., -1., mat);
for (theta = twopi; theta - eps > 0; theta -= d_theta) { for (theta = twopi; theta - eps > 0; theta -= d_theta) {
sin_theta = sin (theta); sin_theta = sin(theta);
cos_theta = cos (theta); cos_theta = cos(theta);
x = cos_theta * sin_phi; x = cos_theta * sin_phi;
y = sin_theta * sin_phi; y = sin_theta * sin_phi;
z = cos_phi; z = cos_phi;
DrawShadowVertex (x, y, z, mat); DrawShadowVertex(x, y, z, mat);
} }
x = sin_phi; x = sin_phi;
y = 0.0; y = 0.0;
z = cos_phi; z = cos_phi;
DrawShadowVertex (x, y, z, mat); DrawShadowVertex(x, y, z, mat);
glEnd(); glEnd();
} else { } else {
glBegin (GL_TRIANGLE_STRIP); glBegin(GL_TRIANGLE_STRIP);
for (theta = 0.0; theta + eps < twopi; theta += d_theta) { for (theta = 0.0; theta + eps < twopi; theta += d_theta) {
sin_theta = sin (theta); sin_theta = sin(theta);
cos_theta = cos (theta); cos_theta = cos(theta);
x = cos_theta * sin_phi; x = cos_theta * sin_phi;
y = sin_theta * sin_phi; y = sin_theta * sin_phi;
z = cos_phi; z = cos_phi;
DrawShadowVertex (x, y, z, mat); DrawShadowVertex(x, y, z, mat);
x = cos_theta * sin_phi_d_phi; x = cos_theta * sin_phi_d_phi;
y = sin_theta * sin_phi_d_phi; y = sin_theta * sin_phi_d_phi;
z = cos_phi_d_phi; z = cos_phi_d_phi;
DrawShadowVertex (x, y, z, mat); DrawShadowVertex(x, y, z, mat);
} }
x = sin_phi; x = sin_phi;
y = 0.0; y = 0.0;
z = cos_phi; z = cos_phi;
DrawShadowVertex (x, y, z, mat); DrawShadowVertex(x, y, z, mat);
x = sin_phi_d_phi; x = sin_phi_d_phi;
y = 0.0; y = 0.0;
z = cos_phi_d_phi; z = cos_phi_d_phi;
DrawShadowVertex (x, y, z, mat); DrawShadowVertex(x, y, z, mat);
glEnd(); glEnd();
} }
} }
@ -735,16 +735,16 @@ void CCharShape::DrawShadowSphere(const TMatrix<4, 4>& mat) {
void CCharShape::TraverseDagForShadow(const TCharNode *node, const TMatrix<4, 4>& mat) { void CCharShape::TraverseDagForShadow(const TCharNode *node, const TMatrix<4, 4>& mat) {
TMatrix<4, 4> new_matrix = mat * node->trans; TMatrix<4, 4> new_matrix = mat * node->trans;
if (node->visible && node->render_shadow) if (node->visible && node->render_shadow)
DrawShadowSphere (new_matrix); DrawShadowSphere(new_matrix);
TCharNode* child = node->child; TCharNode* child = node->child;
while (child != NULL) { while (child != NULL) {
TraverseDagForShadow (child, new_matrix); TraverseDagForShadow(child, new_matrix);
child = child->next; child = child->next;
} }
} }
void CCharShape::DrawShadow () { void CCharShape::DrawShadow() {
if (g_game.light_id == 1 || g_game.light_id == 3) return; if (g_game.light_id == 1 || g_game.light_id == 3) return;
ScopedRenderMode rm(TUX_SHADOW); ScopedRenderMode rm(TUX_SHADOW);
@ -752,7 +752,7 @@ void CCharShape::DrawShadow () {
TCharNode *node = GetNode(0); TCharNode *node = GetNode(0);
if (node == NULL) { if (node == NULL) {
Message ("couldn't find tux's root node"); Message("couldn't find tux's root node");
return; return;
} }
TraverseDagForShadow(node, TMatrix<4, 4>::getIdentity()); TraverseDagForShadow(node, TMatrix<4, 4>::getIdentity());
@ -762,25 +762,25 @@ void CCharShape::DrawShadow () {
// testing and tools // testing and tools
// -------------------------------------------------------------------- // --------------------------------------------------------------------
string CCharShape::GetNodeJoint (size_t idx) const { string CCharShape::GetNodeJoint(size_t idx) const {
if (idx >= numNodes) return ""; if (idx >= numNodes) return "";
TCharNode *node = Nodes[idx]; TCharNode *node = Nodes[idx];
if (node == NULL) return ""; if (node == NULL) return "";
if (!node->joint.empty()) return node->joint; if (!node->joint.empty()) return node->joint;
else return Int_StrN ((int)node->node_name); else return Int_StrN((int)node->node_name);
} }
size_t CCharShape::GetNodeName (size_t idx) const { size_t CCharShape::GetNodeName(size_t idx) const {
if (idx >= numNodes) return -1; if (idx >= numNodes) return -1;
return Nodes[idx]->node_name; return Nodes[idx]->node_name;
} }
size_t CCharShape::GetNodeName (const string& node_trivialname) const { size_t CCharShape::GetNodeName(const string& node_trivialname) const {
return NodeIndex.at(node_trivialname); return NodeIndex.at(node_trivialname);
} }
void CCharShape::RefreshNode (size_t idx) { void CCharShape::RefreshNode(size_t idx) {
if (idx >= numNodes) return; if (idx >= numNodes) return;
TMatrix<4, 4> TempMatrix; TMatrix<4, 4> TempMatrix;
char caxis; char caxis;
@ -837,7 +837,7 @@ void CCharShape::RefreshNode (size_t idx) {
node->invtrans = TempMatrix * node->invtrans; node->invtrans = TempMatrix * node->invtrans;
break; break;
case 5: case 5:
VisibleNode (node->node_name, dval); VisibleNode(node->node_name, dval);
break; break;
default: default:
break; break;
@ -845,60 +845,60 @@ void CCharShape::RefreshNode (size_t idx) {
} }
} }
const string& CCharShape::GetNodeFullname (size_t idx) const { const string& CCharShape::GetNodeFullname(size_t idx) const {
if (idx >= numNodes) return emptyString; if (idx >= numNodes) return emptyString;
return Nodes[idx]->action->name; return Nodes[idx]->action->name;
} }
size_t CCharShape::GetNumActs (size_t idx) const { size_t CCharShape::GetNumActs(size_t idx) const {
if (idx >= numNodes) return -1; if (idx >= numNodes) return -1;
return Nodes[idx]->action->num; return Nodes[idx]->action->num;
} }
TCharAction *CCharShape::GetAction (size_t idx) const { TCharAction *CCharShape::GetAction(size_t idx) const {
if (idx >= numNodes) return NULL; if (idx >= numNodes) return NULL;
return Nodes[idx]->action; return Nodes[idx]->action;
} }
void CCharShape::PrintAction (size_t idx) const { void CCharShape::PrintAction(size_t idx) const {
if (idx >= numNodes) return; if (idx >= numNodes) return;
TCharAction *act = Nodes[idx]->action; TCharAction *act = Nodes[idx]->action;
PrintInt ((int)act->num); PrintInt((int)act->num);
for (size_t i=0; i<act->num; i++) { for (size_t i=0; i<act->num; i++) {
PrintInt (act->type[i]); PrintInt(act->type[i]);
PrintDouble (act->dval[i]); PrintDouble(act->dval[i]);
PrintVector (act->vec[i]); PrintVector(act->vec[i]);
} }
} }
void CCharShape::PrintNode (size_t idx) const { void CCharShape::PrintNode(size_t idx) const {
TCharNode *node = Nodes[idx]; TCharNode *node = Nodes[idx];
PrintInt ("node: ", (int)node->node_name); PrintInt("node: ", (int)node->node_name);
PrintInt ("parent: ", (int)node->parent_name); PrintInt("parent: ", (int)node->parent_name);
PrintInt ("child: ", (int)node->child_name); PrintInt("child: ", (int)node->child_name);
PrintInt ("next: ", (int)node->next_name); PrintInt("next: ", (int)node->next_name);
} }
void CCharShape::SaveCharNodes (const string& dir, const string& filename) { void CCharShape::SaveCharNodes(const string& dir, const string& filename) {
CSPList list (MAX_CHAR_NODES + 10); CSPList list(MAX_CHAR_NODES + 10);
list.Add ("# Generated by Tuxracer tools"); list.Add("# Generated by Tuxracer tools");
list.AddLine (); list.AddLine();
if (!Materials.empty()) { if (!Materials.empty()) {
list.Add ("# Materials:"); list.Add("# Materials:");
for (size_t i=0; i<Materials.size(); i++) for (size_t i=0; i<Materials.size(); i++)
if (!Materials[i].matline.empty()) if (!Materials[i].matline.empty())
list.Add (Materials[i].matline); list.Add(Materials[i].matline);
list.AddLine (); list.AddLine();
} }
list.Add ("# Nodes:"); list.Add("# Nodes:");
for (size_t i=1; i<numNodes; i++) { for (size_t i=1; i<numNodes; i++) {
TCharNode* node = Nodes[i]; TCharNode* node = Nodes[i];
TCharAction* act = node->action; TCharAction* act = node->action;
if (node->parent_name >= node->node_name) Message ("wrong parent index"); if (node->parent_name >= node->node_name) Message("wrong parent index");
string line = "*[node] " + Int_StrN ((int)node->node_name); string line = "*[node] " + Int_StrN((int)node->node_name);
line += " [par] " + Int_StrN ((int)node->parent_name); line += " [par] " + Int_StrN((int)node->parent_name);
if (!act->order.empty()) { if (!act->order.empty()) {
bool rotflag = false; bool rotflag = false;
@ -908,10 +908,10 @@ void CCharShape::SaveCharNodes (const string& dir, const string& filename) {
int aa = act->order[ii]-48; int aa = act->order[ii]-48;
switch (aa) { switch (aa) {
case 0: case 0:
line += " [trans] " + Vector_StrN (act->vec[ii], 2); line += " [trans] " + Vector_StrN(act->vec[ii], 2);
break; break;
case 4: case 4:
line += " [scale] " + Vector_StrN (act->vec[ii], 2); line += " [scale] " + Vector_StrN(act->vec[ii], 2);
break; break;
case 1: case 1:
rotation.x = act->dval[ii]; rotation.x = act->dval[ii];
@ -926,7 +926,7 @@ void CCharShape::SaveCharNodes (const string& dir, const string& filename) {
rotflag = true; rotflag = true;
break; break;
case 5: case 5:
line += " [vis] " + Float_StrN (act->dval[ii], 0); line += " [vis] " + Float_StrN(act->dval[ii], 0);
break; break;
case 9: case 9:
rotation.z = act->dval[ii]; rotation.z = act->dval[ii];
@ -934,19 +934,19 @@ void CCharShape::SaveCharNodes (const string& dir, const string& filename) {
break; break;
} }
} }
if (rotflag) line += " [rot] " + Vector_StrN (rotation, 2); if (rotflag) line += " [rot] " + Vector_StrN(rotation, 2);
} }
if (!act->mat.empty()) line += " [mat] " + act->mat; if (!act->mat.empty()) line += " [mat] " + act->mat;
if (!node->joint.empty()) line += " [joint] " + node->joint; if (!node->joint.empty()) line += " [joint] " + node->joint;
if (!act->name.empty()) line += " [name] " + act->name; if (!act->name.empty()) line += " [name] " + act->name;
if (node->render_shadow) line += " [shad] 1"; if (node->render_shadow) line += " [shad] 1";
list.Add (line); list.Add(line);
if (i<numNodes-3) { if (i<numNodes-3) {
if (node->visible && !Nodes[i+1]->visible) list.AddLine (); if (node->visible && !Nodes[i+1]->visible) list.AddLine();
const string& joint = Nodes[i+2]->joint; const string& joint = Nodes[i+2]->joint;
if (joint.empty()) list.Add ("# " + joint); if (joint.empty()) list.Add("# " + joint);
} }
} }
list.Save (dir, filename); list.Save(dir, filename);
} }

View File

@ -81,29 +81,29 @@ private:
map<string, size_t> MaterialIndex; map<string, size_t> MaterialIndex;
// nodes // nodes
size_t GetNodeIdx (size_t node_name) const; size_t GetNodeIdx(size_t node_name) const;
TCharNode *GetNode (size_t node_name); TCharNode *GetNode(size_t node_name);
void CreateRootNode (); void CreateRootNode();
bool CreateCharNode bool CreateCharNode
(int parent_name, size_t node_name, const string& joint, (int parent_name, size_t node_name, const string& joint,
const string& name, const string& order, bool shadow); const string& name, const string& order, bool shadow);
bool VisibleNode (size_t node_name, float level); bool VisibleNode(size_t node_name, float level);
bool MaterialNode (size_t node_name, const string& mat_name); bool MaterialNode(size_t node_name, const string& mat_name);
bool TransformNode(size_t node_name, const TMatrix<4, 4>& mat, const TMatrix<4, 4>& invmat); bool TransformNode(size_t node_name, const TMatrix<4, 4>& mat, const TMatrix<4, 4>& invmat);
// material // material
TCharMaterial* GetMaterial (const string& mat_name); TCharMaterial* GetMaterial(const string& mat_name);
void CreateMaterial (const string& line); void CreateMaterial(const string& line);
// drawing // drawing
void DrawCharSphere (int num_divisions); void DrawCharSphere(int num_divisions);
void DrawNodes (const TCharNode *node); void DrawNodes(const TCharNode *node);
TVector3d AdjustRollvector (const CControl *ctrl, const TVector3d& vel, const TVector3d& zvec); TVector3d AdjustRollvector(const CControl *ctrl, const TVector3d& vel, const TVector3d& zvec);
// collision // collision
bool CheckPolyhedronCollision(const TCharNode *node, const TMatrix<4, 4>& modelMatrix, bool CheckPolyhedronCollision(const TCharNode *node, const TMatrix<4, 4>& modelMatrix,
const TMatrix<4, 4>& invModelMatrix, const TPolyhedron& ph); const TMatrix<4, 4>& invModelMatrix, const TPolyhedron& ph);
bool CheckCollision (const TPolyhedron& ph); bool CheckCollision(const TPolyhedron& ph);
// shadow // shadow
void DrawShadowVertex(double x, double y, double z, const TMatrix<4, 4>& mat); void DrawShadowVertex(double x, double y, double z, const TMatrix<4, 4>& mat);
@ -111,52 +111,52 @@ private:
void TraverseDagForShadow(const TCharNode *node, const TMatrix<4, 4>& mat); void TraverseDagForShadow(const TCharNode *node, const TMatrix<4, 4>& mat);
// testing and developing // testing and developing
void AddAction (size_t node_name, int type, const TVector3d& vec, double val); void AddAction(size_t node_name, int type, const TVector3d& vec, double val);
public: public:
CCharShape (); CCharShape();
~CCharShape(); ~CCharShape();
bool useMaterials; bool useMaterials;
bool useHighlighting; bool useHighlighting;
map<string, size_t> NodeIndex; map<string, size_t> NodeIndex;
// nodes // nodes
bool ResetNode (size_t node_name); bool ResetNode(size_t node_name);
bool ResetNode (const string& node_trivialname); bool ResetNode(const string& node_trivialname);
bool TranslateNode (size_t node_name, const TVector3d& vec); bool TranslateNode(size_t node_name, const TVector3d& vec);
bool RotateNode (size_t node_name, int axis, double angle); bool RotateNode(size_t node_name, int axis, double angle);
bool RotateNode (const string& node_trivialname, int axis, double angle); bool RotateNode(const string& node_trivialname, int axis, double angle);
void ScaleNode (size_t node_name, const TVector3d& vec); void ScaleNode(size_t node_name, const TVector3d& vec);
void ResetRoot () { ResetNode (0); } void ResetRoot() { ResetNode(0); }
void ResetJoints (); void ResetJoints();
// global functions // global functions
void Reset (); void Reset();
void Draw (); void Draw();
void DrawShadow (); void DrawShadow();
bool Load (const string& dir, const string& filename, bool with_actions); bool Load(const string& dir, const string& filename, bool with_actions);
void AdjustOrientation (CControl *ctrl, double dtime, void AdjustOrientation(CControl *ctrl, double dtime,
double dist_from_surface, const TVector3d& surf_nml); double dist_from_surface, const TVector3d& surf_nml);
void AdjustJoints (double turnFact, bool isBraking, void AdjustJoints(double turnFact, bool isBraking,
double paddling_factor, double speed, double paddling_factor, double speed,
const TVector3d& net_force, double flap_factor); const TVector3d& net_force, double flap_factor);
bool Collision (const TVector3d& pos, const TPolyhedron& ph); bool Collision(const TVector3d& pos, const TPolyhedron& ph);
// testing and tools // testing and tools
bool highlighted; bool highlighted;
size_t highlight_node; size_t highlight_node;
size_t GetNodeName (size_t idx) const; size_t GetNodeName(size_t idx) const;
size_t GetNodeName (const string& node_trivialname) const; size_t GetNodeName(const string& node_trivialname) const;
string GetNodeJoint (size_t idx) const; string GetNodeJoint(size_t idx) const;
size_t GetNumNodes () const { return numNodes; } size_t GetNumNodes() const { return numNodes; }
const string& GetNodeFullname (size_t idx) const; const string& GetNodeFullname(size_t idx) const;
size_t GetNumActs (size_t idx) const; size_t GetNumActs(size_t idx) const;
TCharAction *GetAction (size_t idx) const; TCharAction *GetAction(size_t idx) const;
void PrintAction (size_t idx) const; void PrintAction(size_t idx) const;
void PrintNode (size_t idx) const; void PrintNode(size_t idx) const;
void RefreshNode (size_t idx); void RefreshNode(size_t idx);
void SaveCharNodes (const string& dir, const string& filename); void SaveCharNodes(const string& dir, const string& filename);
}; };
// only for char tools, the characters for playing are in // only for char tools, the characters for playing are in

View File

@ -55,24 +55,24 @@ struct TVector3 : public TVector2<T> {
: TVector2<T>(_x, _y), z(_z) : TVector2<T>(_x, _y), z(_z)
{} {}
double Length() const { double Length() const {
return sqrt(static_cast<double>(TVector2<T>::x*TVector2<T>::x + return sqrt(static_cast<double>(TVector2<T>::x*TVector2<T>::x +
TVector2<T>::y*TVector2<T>::y + z*z)); TVector2<T>::y*TVector2<T>::y + z*z));
} }
double Norm(); double Norm();
TVector3<T>& operator*=(T f) { TVector3<T>& operator*=(T f) {
TVector2<T>::x *= f; TVector2<T>::x *= f;
TVector2<T>::y *= f; TVector2<T>::y *= f;
z *= f; z *= f;
return *this; return *this;
} }
TVector3<T>& operator+=(const TVector3<T>& v) { TVector3<T>& operator+=(const TVector3<T>& v) {
TVector2<T>::x += v.x; TVector2<T>::x += v.x;
TVector2<T>::y += v.y; TVector2<T>::y += v.y;
z += v.z; z += v.z;
return *this; return *this;
} }
TVector3<T>& operator-=(const TVector3<T>& v) { TVector3<T>& operator-=(const TVector3<T>& v) {
TVector2<T>::x -= v.x; TVector2<T>::x -= v.x;
TVector2<T>::y -= v.y; TVector2<T>::y -= v.y;
z -= v.z; z -= v.z;
return *this; return *this;
@ -86,13 +86,13 @@ struct TVector4 : public TVector3<T> {
: TVector3<T>(_x, _y, _z), w(_w) : TVector3<T>(_x, _y, _z), w(_w)
{} {}
double Length() const { double Length() const {
return sqrt(static_cast<double>(TVector2<T>::x*TVector2<T>::x + return sqrt(static_cast<double>(TVector2<T>::x*TVector2<T>::x +
TVector2<T>::y*TVector2<T>::y + TVector2<T>::y*TVector2<T>::y +
TVector3<T>::z*TVector3<T>::z + w*w)); TVector3<T>::z*TVector3<T>::z + w*w));
} }
double Norm(); double Norm();
TVector4<T>& operator*=(T f) { TVector4<T>& operator*=(T f) {
TVector2<T>::x *= f; TVector2<T>::x *= f;
TVector2<T>::y *= f; TVector2<T>::y *= f;
TVector3<T>::z *= f; TVector3<T>::z *= f;
w *= f; w *= f;

View File

@ -43,7 +43,7 @@ static TMatrix<4, 4> stationary_matrix;
static bool is_stationary = false; static bool is_stationary = false;
static bool shall_stationary = false; static bool shall_stationary = false;
void SetStationaryCamera (bool stat) { void SetStationaryCamera(bool stat) {
if (stat == false) { if (stat == false) {
is_stationary = false; is_stationary = false;
shall_stationary = false; shall_stationary = false;
@ -53,20 +53,20 @@ void SetStationaryCamera (bool stat) {
} }
static double camera_distance = 4.0; static double camera_distance = 4.0;
void IncCameraDistance (double timestep) { void IncCameraDistance(double timestep) {
camera_distance += timestep * CAMERA_DISTANCE_INCREMENT; camera_distance += timestep * CAMERA_DISTANCE_INCREMENT;
} }
void SetCameraDistance (double val) {camera_distance = val;} void SetCameraDistance(double val) {camera_distance = val;}
void set_view_mode (CControl *ctrl, TViewMode mode) {ctrl->viewmode = mode;} void set_view_mode(CControl *ctrl, TViewMode mode) {ctrl->viewmode = mode;}
TVector3d interpolate_view_pos (const TVector3d& ctrl_pos1, const TVector3d& ctrl_pos2, TVector3d interpolate_view_pos(const TVector3d& ctrl_pos1, const TVector3d& ctrl_pos2,
double max_vec_angle, double max_vec_angle,
const TVector3d& pos1, const TVector3d& pos2, const TVector3d& pos1, const TVector3d& pos2,
double dist, double dt, double dist, double dt,
double time_constant) { double time_constant) {
static TVector3d y_vec(0.0, 1.0, 0.0); static TVector3d y_vec(0.0, 1.0, 0.0);
TVector3d vec1 = pos1 - ctrl_pos1; TVector3d vec1 = pos1 - ctrl_pos1;
@ -75,43 +75,43 @@ TVector3d interpolate_view_pos (const TVector3d& ctrl_pos1, const TVector3d& ctr
vec1.Norm(); vec1.Norm();
vec2.Norm(); vec2.Norm();
TQuaternion q1 = MakeRotationQuaternion (y_vec, vec1); TQuaternion q1 = MakeRotationQuaternion(y_vec, vec1);
TQuaternion q2 = MakeRotationQuaternion (y_vec, vec2); TQuaternion q2 = MakeRotationQuaternion(y_vec, vec2);
double alpha = min (MAX_INTERPOLATION_VALUE, 1.0 - exp (-dt / time_constant)); double alpha = min(MAX_INTERPOLATION_VALUE, 1.0 - exp(-dt / time_constant));
q2 = InterpolateQuaternions (q1, q2, alpha); q2 = InterpolateQuaternions(q1, q2, alpha);
vec2 = RotateVector (q2, y_vec); vec2 = RotateVector(q2, y_vec);
double theta = RADIANS_TO_ANGLES (M_PI/2 - acos (DotProduct (vec2, y_vec))); double theta = RADIANS_TO_ANGLES(M_PI/2 - acos(DotProduct(vec2, y_vec)));
if (theta > max_vec_angle) { if (theta > max_vec_angle) {
TVector3d axis = CrossProduct (y_vec, vec2); TVector3d axis = CrossProduct(y_vec, vec2);
axis.Norm(); axis.Norm();
TMatrix<4, 4> rot_mat = RotateAboutVectorMatrix(axis, theta - max_vec_angle); TMatrix<4, 4> rot_mat = RotateAboutVectorMatrix(axis, theta - max_vec_angle);
vec2 = TransformVector (rot_mat, vec2); vec2 = TransformVector(rot_mat, vec2);
} }
return ctrl_pos2 + dist * vec2; return ctrl_pos2 + dist * vec2;
} }
void interpolate_view_frame (const TVector3d& up1, const TVector3d& dir1, void interpolate_view_frame(const TVector3d& up1, const TVector3d& dir1,
TVector3d *p_up2, TVector3d *p_dir2, TVector3d *p_up2, TVector3d *p_dir2,
double dt, double time_constant) { double dt, double time_constant) {
TVector3d z1 = -1.0 * dir1; TVector3d z1 = -1.0 * dir1;
z1.Norm(); z1.Norm();
TVector3d y1 = ProjectToPlane (z1, up1); TVector3d y1 = ProjectToPlane(z1, up1);
y1.Norm(); y1.Norm();
TVector3d x1 = CrossProduct (y1, z1); TVector3d x1 = CrossProduct(y1, z1);
TMatrix<4, 4> cob_mat1(x1, y1, z1); TMatrix<4, 4> cob_mat1(x1, y1, z1);
TQuaternion q1 = MakeQuaternionFromMatrix (cob_mat1); TQuaternion q1 = MakeQuaternionFromMatrix(cob_mat1);
TVector3d z2 = -1.0 * *p_dir2; TVector3d z2 = -1.0 * *p_dir2;
z2.Norm(); z2.Norm();
TVector3d y2 = ProjectToPlane (z2, *p_up2); TVector3d y2 = ProjectToPlane(z2, *p_up2);
y2.Norm(); y2.Norm();
TVector3d x2 = CrossProduct (y2, z2); TVector3d x2 = CrossProduct(y2, z2);
TMatrix<4, 4> cob_mat2(x2, y2, z2); TMatrix<4, 4> cob_mat2(x2, y2, z2);
TQuaternion q2 = MakeQuaternionFromMatrix (cob_mat2); TQuaternion q2 = MakeQuaternionFromMatrix(cob_mat2);
double alpha = min (MAX_INTERPOLATION_VALUE, 1.0 - exp (-dt / time_constant)); double alpha = min(MAX_INTERPOLATION_VALUE, 1.0 - exp(-dt / time_constant));
q2 = InterpolateQuaternions (q1, q2, alpha); q2 = InterpolateQuaternions(q1, q2, alpha);
cob_mat2 = MakeMatrixFromQuaternion(q2); cob_mat2 = MakeMatrixFromQuaternion(q2);
p_up2->x = cob_mat2[1][0]; p_up2->x = cob_mat2[1][0];
@ -123,10 +123,10 @@ void interpolate_view_frame (const TVector3d& up1, const TVector3d& dir1,
p_dir2->z = -cob_mat2[2][2]; p_dir2->z = -cob_mat2[2][2];
} }
void setup_view_matrix (CControl *ctrl, bool save_mat) { void setup_view_matrix(CControl *ctrl, bool save_mat) {
TVector3d view_z = -1.0 * ctrl->viewdir; TVector3d view_z = -1.0 * ctrl->viewdir;
TVector3d view_x = CrossProduct (ctrl->viewup, view_z); TVector3d view_x = CrossProduct(ctrl->viewup, view_z);
TVector3d view_y = CrossProduct (view_z, view_x); TVector3d view_y = CrossProduct(view_z, view_x);
view_z.Norm(); view_z.Norm();
view_x.Norm(); view_x.Norm();
view_y.Norm(); view_y.Norm();
@ -143,7 +143,7 @@ void setup_view_matrix (CControl *ctrl, bool save_mat) {
view_mat[1][3] = 0; view_mat[1][3] = 0;
view_mat[2][3] = 0; view_mat[2][3] = 0;
TVector3d viewpt_in_view_frame = TransformPoint (view_mat, ctrl->viewpos); TVector3d viewpt_in_view_frame = TransformPoint(view_mat, ctrl->viewpos);
view_mat[3][0] = -viewpt_in_view_frame.x; view_mat[3][0] = -viewpt_in_view_frame.x;
view_mat[3][1] = -viewpt_in_view_frame.y; view_mat[3][1] = -viewpt_in_view_frame.y;
@ -152,13 +152,12 @@ void setup_view_matrix (CControl *ctrl, bool save_mat) {
if (save_mat) { if (save_mat) {
stationary_matrix = view_mat; stationary_matrix = view_mat;
} }
glLoadIdentity(); glLoadMatrix(view_mat);
glMultMatrix(view_mat);
} }
TVector3d MakeViewVector () { TVector3d MakeViewVector() {
double course_angle = Course.GetCourseAngle(); double course_angle = Course.GetCourseAngle();
double rad = ANGLES_TO_RADIANS ( double rad = ANGLES_TO_RADIANS(
course_angle - course_angle -
CAMERA_ANGLE_ABOVE_SLOPE + CAMERA_ANGLE_ABOVE_SLOPE +
PLAYER_ANGLE_IN_CAMERA); PLAYER_ANGLE_IN_CAMERA);
@ -166,10 +165,9 @@ TVector3d MakeViewVector () {
return camera_distance * res; return camera_distance * res;
} }
void update_view (CControl *ctrl, double dt) { void update_view(CControl *ctrl, double dt) {
if (is_stationary) { if (is_stationary) {
glLoadIdentity(); glLoadMatrix(stationary_matrix);
glMultMatrix(stationary_matrix);
return; return;
} }
@ -181,9 +179,9 @@ void update_view (CControl *ctrl, double dt) {
double speed = ctrl->cvel.Length(); double speed = ctrl->cvel.Length();
double time_constant_mult = 1.0 / double time_constant_mult = 1.0 /
clamp (0.0, clamp(0.0,
(speed - NO_INTERPOLATION_SPEED) / (BASELINE_INTERPOLATION_SPEED - NO_INTERPOLATION_SPEED), (speed - NO_INTERPOLATION_SPEED) / (BASELINE_INTERPOLATION_SPEED - NO_INTERPOLATION_SPEED),
1.0); 1.0);
TVector3d vel_dir = ctrl->cvel; TVector3d vel_dir = ctrl->cvel;
vel_dir.Norm(); vel_dir.Norm();
@ -192,12 +190,12 @@ void update_view (CControl *ctrl, double dt) {
switch (ctrl->viewmode) { switch (ctrl->viewmode) {
case BEHIND: { case BEHIND: {
TVector3d vel_proj = ProjectToPlane (y_vec, vel_dir); TVector3d vel_proj = ProjectToPlane(y_vec, vel_dir);
vel_proj.Norm(); vel_proj.Norm();
TQuaternion rot_quat = MakeRotationQuaternion (mz_vec, vel_proj); TQuaternion rot_quat = MakeRotationQuaternion(mz_vec, vel_proj);
view_vec = RotateVector (rot_quat, view_vec); view_vec = RotateVector(rot_quat, view_vec);
view_pt = ctrl->cpos + view_vec; view_pt = ctrl->cpos + view_vec;
double ycoord = Course.FindYCoord (view_pt.x, view_pt.z); double ycoord = Course.FindYCoord(view_pt.x, view_pt.z);
if (view_pt.y < ycoord + MIN_CAMERA_HEIGHT) { if (view_pt.y < ycoord + MIN_CAMERA_HEIGHT) {
view_pt.y = ycoord + MIN_CAMERA_HEIGHT; view_pt.y = ycoord + MIN_CAMERA_HEIGHT;
@ -205,73 +203,73 @@ void update_view (CControl *ctrl, double dt) {
if (ctrl->view_init) { if (ctrl->view_init) {
for (int i=0; i<2; i++) { for (int i=0; i<2; i++) {
view_pt = interpolate_view_pos (ctrl->cpos, ctrl->cpos, view_pt = interpolate_view_pos(ctrl->cpos, ctrl->cpos,
MAX_CAMERA_PITCH, ctrl->viewpos, MAX_CAMERA_PITCH, ctrl->viewpos,
view_pt, camera_distance, dt, view_pt, camera_distance, dt,
BEHIND_ORBIT_TIME_CONSTANT * BEHIND_ORBIT_TIME_CONSTANT *
time_constant_mult); time_constant_mult);
} }
} }
ycoord = Course.FindYCoord (view_pt.x, view_pt.z); ycoord = Course.FindYCoord(view_pt.x, view_pt.z);
if (view_pt.y < ycoord + ABSOLUTE_MIN_CAMERA_HEIGHT) { if (view_pt.y < ycoord + ABSOLUTE_MIN_CAMERA_HEIGHT) {
view_pt.y = ycoord + ABSOLUTE_MIN_CAMERA_HEIGHT; view_pt.y = ycoord + ABSOLUTE_MIN_CAMERA_HEIGHT;
} }
view_vec = view_pt - ctrl->cpos; view_vec = view_pt - ctrl->cpos;
TVector3d axis = CrossProduct (y_vec, view_vec); TVector3d axis = CrossProduct(y_vec, view_vec);
axis.Norm(); axis.Norm();
TMatrix<4, 4> rot_mat = RotateAboutVectorMatrix(axis, PLAYER_ANGLE_IN_CAMERA); TMatrix<4, 4> rot_mat = RotateAboutVectorMatrix(axis, PLAYER_ANGLE_IN_CAMERA);
view_dir = -1.0 * TransformVector (rot_mat, view_vec); view_dir = -1.0 * TransformVector(rot_mat, view_vec);
if (ctrl->view_init) { if (ctrl->view_init) {
for (int i=0; i<2; i++) { for (int i=0; i<2; i++) {
TVector3d up_dir(0, 1, 0); TVector3d up_dir(0, 1, 0);
interpolate_view_frame (ctrl->viewup, ctrl->viewdir, interpolate_view_frame(ctrl->viewup, ctrl->viewdir,
&up_dir, &view_dir, dt, &up_dir, &view_dir, dt,
BEHIND_ORIENT_TIME_CONSTANT); BEHIND_ORIENT_TIME_CONSTANT);
} }
} }
break; break;
} }
case FOLLOW: { // normale Einstellung case FOLLOW: { // normale Einstellung
TVector3d vel_proj = ProjectToPlane (y_vec, vel_dir); TVector3d vel_proj = ProjectToPlane(y_vec, vel_dir);
vel_proj.Norm(); vel_proj.Norm();
TQuaternion rot_quat = MakeRotationQuaternion (mz_vec, vel_proj); TQuaternion rot_quat = MakeRotationQuaternion(mz_vec, vel_proj);
view_vec = RotateVector (rot_quat, view_vec); view_vec = RotateVector(rot_quat, view_vec);
view_pt = ctrl->cpos + view_vec; view_pt = ctrl->cpos + view_vec;
double ycoord = Course.FindYCoord (view_pt.x, view_pt.z); double ycoord = Course.FindYCoord(view_pt.x, view_pt.z);
if (view_pt.y < ycoord + MIN_CAMERA_HEIGHT) { if (view_pt.y < ycoord + MIN_CAMERA_HEIGHT) {
view_pt.y = ycoord + MIN_CAMERA_HEIGHT; view_pt.y = ycoord + MIN_CAMERA_HEIGHT;
} }
if (ctrl->view_init) { if (ctrl->view_init) {
for (int i=0; i<2; i++) { for (int i=0; i<2; i++) {
view_pt = interpolate_view_pos (ctrl->plyr_pos, ctrl->cpos, view_pt = interpolate_view_pos(ctrl->plyr_pos, ctrl->cpos,
MAX_CAMERA_PITCH, ctrl->viewpos, MAX_CAMERA_PITCH, ctrl->viewpos,
view_pt, camera_distance, dt, view_pt, camera_distance, dt,
FOLLOW_ORBIT_TIME_CONSTANT * FOLLOW_ORBIT_TIME_CONSTANT *
time_constant_mult); time_constant_mult);
} }
} }
ycoord = Course.FindYCoord (view_pt.x, view_pt.z); ycoord = Course.FindYCoord(view_pt.x, view_pt.z);
if (view_pt.y < ycoord + ABSOLUTE_MIN_CAMERA_HEIGHT) { if (view_pt.y < ycoord + ABSOLUTE_MIN_CAMERA_HEIGHT) {
view_pt.y = ycoord + ABSOLUTE_MIN_CAMERA_HEIGHT; view_pt.y = ycoord + ABSOLUTE_MIN_CAMERA_HEIGHT;
} }
view_vec = view_pt - ctrl->cpos; view_vec = view_pt - ctrl->cpos;
TVector3d axis = CrossProduct (y_vec, view_vec); TVector3d axis = CrossProduct(y_vec, view_vec);
axis.Norm(); axis.Norm();
TMatrix<4, 4> rot_mat = RotateAboutVectorMatrix(axis, PLAYER_ANGLE_IN_CAMERA); TMatrix<4, 4> rot_mat = RotateAboutVectorMatrix(axis, PLAYER_ANGLE_IN_CAMERA);
view_dir = -1.0 * TransformVector (rot_mat, view_vec); view_dir = -1.0 * TransformVector(rot_mat, view_vec);
if (ctrl->view_init) { if (ctrl->view_init) {
for (int i=0; i<2; i++) { for (int i=0; i<2; i++) {
TVector3d up_dir(0, 1, 0); TVector3d up_dir(0, 1, 0);
interpolate_view_frame (ctrl->viewup, ctrl->viewdir, interpolate_view_frame(ctrl->viewup, ctrl->viewdir,
&up_dir, &view_dir, dt, &up_dir, &view_dir, dt,
FOLLOW_ORIENT_TIME_CONSTANT); FOLLOW_ORIENT_TIME_CONSTANT);
} }
} }
break; break;
@ -279,7 +277,7 @@ void update_view (CControl *ctrl, double dt) {
case ABOVE: { case ABOVE: {
view_pt = ctrl->cpos + view_vec; view_pt = ctrl->cpos + view_vec;
double ycoord = Course.FindYCoord (view_pt.x, view_pt.z); double ycoord = Course.FindYCoord(view_pt.x, view_pt.z);
if (view_pt.y < ycoord + MIN_CAMERA_HEIGHT) { if (view_pt.y < ycoord + MIN_CAMERA_HEIGHT) {
view_pt.y = ycoord + MIN_CAMERA_HEIGHT; view_pt.y = ycoord + MIN_CAMERA_HEIGHT;
} }
@ -287,12 +285,12 @@ void update_view (CControl *ctrl, double dt) {
view_vec = view_pt - ctrl->cpos; view_vec = view_pt - ctrl->cpos;
TMatrix<4, 4> rot_mat; TMatrix<4, 4> rot_mat;
rot_mat.SetRotationMatrix(PLAYER_ANGLE_IN_CAMERA, 'x'); rot_mat.SetRotationMatrix(PLAYER_ANGLE_IN_CAMERA, 'x');
view_dir = -1.0 * TransformVector (rot_mat, view_vec); view_dir = -1.0 * TransformVector(rot_mat, view_vec);
break; break;
} }
default: default:
Message ("code not reached"); Message("code not reached");
return; return;
} }
@ -304,10 +302,10 @@ void update_view (CControl *ctrl, double dt) {
ctrl->view_init = true; ctrl->view_init = true;
if (shall_stationary) { if (shall_stationary) {
setup_view_matrix (ctrl, true); setup_view_matrix(ctrl, true);
is_stationary = true; is_stationary = true;
} else { } else {
setup_view_matrix (ctrl, false); setup_view_matrix(ctrl, false);
} }
} }
@ -320,14 +318,14 @@ static TPlane frustum_planes[6];
static char p_vertex_code[6]; static char p_vertex_code[6];
void SetupViewFrustum (const CControl *ctrl) { void SetupViewFrustum(const CControl *ctrl) {
double aspect = (double) Winsys.resolution.width /Winsys.resolution.height; double aspect = (double) Winsys.resolution.width /Winsys.resolution.height;
double near_dist = NEAR_CLIP_DIST; double near_dist = NEAR_CLIP_DIST;
double far_dist = param.forward_clip_distance; double far_dist = param.forward_clip_distance;
TVector3d origin(0., 0., 0.); TVector3d origin(0., 0., 0.);
double half_fov = ANGLES_TO_RADIANS (param.fov * 0.5); double half_fov = ANGLES_TO_RADIANS(param.fov * 0.5);
double half_fov_horiz = atan (tan (half_fov) * aspect); double half_fov_horiz = atan(tan(half_fov) * aspect);
frustum_planes[0] = TPlane(0, 0, 1, near_dist); frustum_planes[0] = TPlane(0, 0, 1, near_dist);
frustum_planes[1] = TPlane(0, 0, -1, -far_dist); frustum_planes[1] = TPlane(0, 0, -1, -far_dist);
@ -341,13 +339,13 @@ void SetupViewFrustum (const CControl *ctrl) {
= TPlane(0, -cos(half_fov), sin(half_fov), 0); = TPlane(0, -cos(half_fov), sin(half_fov), 0);
for (int i=0; i<6; i++) { for (int i=0; i<6; i++) {
TVector3d pt = TransformPoint (ctrl->view_mat, TVector3d pt = TransformPoint(ctrl->view_mat,
origin + -frustum_planes[i].d * frustum_planes[i].nml); origin + -frustum_planes[i].d * frustum_planes[i].nml);
frustum_planes[i].nml = TransformVector ( frustum_planes[i].nml = TransformVector(
ctrl->view_mat, frustum_planes[i].nml); ctrl->view_mat, frustum_planes[i].nml);
frustum_planes[i].d = -DotProduct ( frustum_planes[i].d = -DotProduct(
frustum_planes[i].nml, frustum_planes[i].nml,
pt - origin); pt - origin);
} }
@ -361,7 +359,7 @@ void SetupViewFrustum (const CControl *ctrl) {
} }
} }
clip_result_t clip_aabb_to_view_frustum (const TVector3d& min, const TVector3d& max) { clip_result_t clip_aabb_to_view_frustum(const TVector3d& min, const TVector3d& max) {
bool intersect = false; bool intersect = false;
for (int i=0; i<6; i++) { for (int i=0; i<6; i++) {
@ -383,11 +381,11 @@ clip_result_t clip_aabb_to_view_frustum (const TVector3d& min, const TVector3d&
n.z = min.z; n.z = min.z;
} }
if (DotProduct (n, frustum_planes[i].nml) + frustum_planes[i].d > 0) { if (DotProduct(n, frustum_planes[i].nml) + frustum_planes[i].d > 0) {
return NotVisible; return NotVisible;
} }
if (DotProduct (p, frustum_planes[i].nml) + frustum_planes[i].d > 0) { if (DotProduct(p, frustum_planes[i].nml) + frustum_planes[i].d > 0) {
intersect = true; intersect = true;
} }
} }

View File

@ -21,12 +21,12 @@ GNU General Public License for more details.
#include "bh.h" #include "bh.h"
#include "mathlib.h" #include "mathlib.h"
void set_view_mode (CControl *ctrl, TViewMode mode); void set_view_mode(CControl *ctrl, TViewMode mode);
void update_view (CControl *ctrl, double dt); void update_view(CControl *ctrl, double dt);
void SetStationaryCamera (bool stat); // 0 follow, 1 stationary void SetStationaryCamera(bool stat); // 0 follow, 1 stationary
void IncCameraDistance (double timestep); void IncCameraDistance(double timestep);
void SetCameraDistance (double val); void SetCameraDistance(double val);
// ------------- viewfrustum ------------------------------------------ // ------------- viewfrustum ------------------------------------------
@ -36,8 +36,8 @@ enum clip_result_t {
NotVisible NotVisible
}; };
void SetupViewFrustum (const CControl *ctrl); void SetupViewFrustum(const CControl *ctrl);
clip_result_t clip_aabb_to_view_frustum (const TVector3d& min, const TVector3d& max); clip_result_t clip_aabb_to_view_frustum(const TVector3d& min, const TVector3d& max);
const TPlane& get_far_clip_plane(); const TPlane& get_far_clip_plane();
const TPlane& get_left_clip_plane(); const TPlane& get_left_clip_plane();

View File

@ -37,7 +37,7 @@ TVector2i cursor_pos(0, 0);
CWinsys Winsys; CWinsys Winsys;
CWinsys::CWinsys () CWinsys::CWinsys()
: auto_resolution(800, 600) { : auto_resolution(800, 600) {
screen = NULL; screen = NULL;
@ -57,26 +57,26 @@ CWinsys::CWinsys ()
resolutions[9] = TScreenRes(1680, 1050); resolutions[9] = TScreenRes(1680, 1050);
} }
const TScreenRes& CWinsys::GetResolution (size_t idx) const { const TScreenRes& CWinsys::GetResolution(size_t idx) const {
if (idx >= NUM_RESOLUTIONS || (idx == 0 && !param.fullscreen)) return auto_resolution; if (idx >= NUM_RESOLUTIONS || (idx == 0 && !param.fullscreen)) return auto_resolution;
return resolutions[idx]; return resolutions[idx];
} }
string CWinsys::GetResName (size_t idx) const { string CWinsys::GetResName(size_t idx) const {
if (idx >= NUM_RESOLUTIONS) return "800 x 600"; if (idx >= NUM_RESOLUTIONS) return "800 x 600";
if (idx == 0) return ("auto"); if (idx == 0) return ("auto");
string line = Int_StrN (resolutions[idx].width); string line = Int_StrN(resolutions[idx].width);
line += " x " + Int_StrN (resolutions[idx].height); line += " x " + Int_StrN(resolutions[idx].height);
return line; return line;
} }
double CWinsys::CalcScreenScale () const { double CWinsys::CalcScreenScale() const {
if (resolution.height < 768) return 0.78; if (resolution.height < 768) return 0.78;
else if (resolution.height == 768) return 1.0; else if (resolution.height == 768) return 1.0;
else return (resolution.height / 768); else return (resolution.height / 768);
} }
void CWinsys::SetupVideoMode (const TScreenRes& resolution_) { void CWinsys::SetupVideoMode(const TScreenRes& resolution_) {
int bpp = 0; int bpp = 0;
Uint32 video_flags = SDL_OPENGL; Uint32 video_flags = SDL_OPENGL;
if (param.fullscreen) video_flags |= SDL_FULLSCREEN; if (param.fullscreen) video_flags |= SDL_FULLSCREEN;
@ -107,11 +107,11 @@ void CWinsys::SetupVideoMode (const TScreenRes& resolution_) {
if ((screen = SDL_SetVideoMode if ((screen = SDL_SetVideoMode
(resolution_.width, resolution_.height, bpp, video_flags)) == NULL) { (resolution_.width, resolution_.height, bpp, video_flags)) == NULL) {
Message ("couldn't initialize video", SDL_GetError()); Message("couldn't initialize video", SDL_GetError());
Message ("set to 800 x 600"); Message("set to 800 x 600");
screen = SDL_SetVideoMode (800, 600, bpp, video_flags); screen = SDL_SetVideoMode(800, 600, bpp, video_flags);
param.res_type = 1; param.res_type = 1;
SaveConfigFile (); SaveConfigFile();
} }
#ifdef _WIN32 #ifdef _WIN32
@ -121,107 +121,98 @@ void CWinsys::SetupVideoMode (const TScreenRes& resolution_) {
wglDeleteContext(tempRC); wglDeleteContext(tempRC);
#endif #endif
SDL_Surface *surf = SDL_GetVideoSurface (); SDL_Surface *surf = SDL_GetVideoSurface();
resolution.width = surf->w; resolution.width = surf->w;
resolution.height = surf->h; resolution.height = surf->h;
if (resolution.width == 0 && resolution.height == 0) { if (resolution.width == 0 && resolution.height == 0) {
auto_resolution = resolution; auto_resolution = resolution;
} }
scale = CalcScreenScale (); scale = CalcScreenScale();
if (param.use_quad_scale) scale = sqrt (scale); if (param.use_quad_scale) scale = sqrt(scale);
} }
void CWinsys::SetupVideoMode (size_t idx) { void CWinsys::SetupVideoMode(size_t idx) {
SetupVideoMode (GetResolution(idx)); SetupVideoMode(GetResolution(idx));
} }
void CWinsys::SetupVideoMode (int width, int height) { void CWinsys::SetupVideoMode(int width, int height) {
SetupVideoMode (TScreenRes(width, height)); SetupVideoMode(TScreenRes(width, height));
} }
void CWinsys::InitJoystick () { void CWinsys::InitJoystick() {
if (SDL_InitSubSystem (SDL_INIT_JOYSTICK) < 0) { if (SDL_InitSubSystem(SDL_INIT_JOYSTICK) < 0) {
Message ("Could not initialize SDL_joystick: %s", SDL_GetError()); Message("Could not initialize SDL_joystick: %s", SDL_GetError());
return; return;
} }
numJoysticks = SDL_NumJoysticks (); numJoysticks = SDL_NumJoysticks();
if (numJoysticks < 1) { if (numJoysticks < 1) {
joystick = NULL; joystick = NULL;
return; return;
} }
SDL_JoystickEventState (SDL_ENABLE); SDL_JoystickEventState(SDL_ENABLE);
joystick = SDL_JoystickOpen (0); // first stick with number 0 joystick = SDL_JoystickOpen(0); // first stick with number 0
if (joystick == NULL) { if (joystick == NULL) {
Message ("Cannot open joystick %s", SDL_GetError ()); Message("Cannot open joystick %s", SDL_GetError());
return; return;
} }
joystick_active = true; joystick_active = true;
} }
void CWinsys::Init () { void CWinsys::Init() {
Uint32 sdl_flags = SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE | SDL_INIT_TIMER; Uint32 sdl_flags = SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE | SDL_INIT_TIMER;
if (SDL_Init (sdl_flags) < 0) Message ("Could not initialize SDL"); if (SDL_Init(sdl_flags) < 0) Message("Could not initialize SDL");
SDL_GL_SetAttribute (SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
#if defined (USE_STENCIL_BUFFER) #if defined (USE_STENCIL_BUFFER)
SDL_GL_SetAttribute (SDL_GL_STENCIL_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
#endif #endif
SetupVideoMode (GetResolution (param.res_type)); SetupVideoMode(GetResolution(param.res_type));
Reshape (resolution.width, resolution.height); Reshape(resolution.width, resolution.height);
SDL_WM_SetCaption (WINDOW_TITLE, WINDOW_TITLE); SDL_WM_SetCaption(WINDOW_TITLE, WINDOW_TITLE);
KeyRepeat (false); KeyRepeat(false);
if (USE_JOYSTICK) InitJoystick (); if (USE_JOYSTICK) InitJoystick();
// SDL_EnableUNICODE (1); // SDL_EnableUNICODE (1);
} }
void CWinsys::KeyRepeat (bool repeat) { void CWinsys::KeyRepeat(bool repeat) {
if (repeat) if (repeat)
SDL_EnableKeyRepeat (SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL); SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
else SDL_EnableKeyRepeat (0, 0); else SDL_EnableKeyRepeat(0, 0);
} }
void CWinsys::SetFonttype () { void CWinsys::CloseJoystick() {
if (param.use_papercut_font > 0) { if (joystick_active) SDL_JoystickClose(joystick);
FT.SetFont ("pc20");
} else {
FT.SetFont ("bold");
}
} }
void CWinsys::CloseJoystick () { void CWinsys::Quit() {
if (joystick_active) SDL_JoystickClose (joystick); CloseJoystick();
Score.SaveHighScore();
SaveMessages();
Audio.Close(); // frees music and sound as well
if (g_game.argument < 1) Players.SavePlayers();
SDL_Quit();
} }
void CWinsys::Quit () { void CWinsys::Terminate() {
CloseJoystick ();
Score.SaveHighScore ();
SaveMessages ();
Audio.Close (); // frees music and sound as well
FT.Clear ();
if (g_game.argument < 1) Players.SavePlayers ();
SDL_Quit ();
}
void CWinsys::Terminate () {
Quit(); Quit();
exit(0); exit(0);
} }
void CWinsys::PrintJoystickInfo () const { void CWinsys::PrintJoystickInfo() const {
if (joystick_active == false) { if (joystick_active == false) {
Message ("No joystick found"); Message("No joystick found");
return; return;
} }
PrintStr (""); PrintStr("");
PrintStr (SDL_JoystickName (0)); PrintStr(SDL_JoystickName(0));
int num_buttons = SDL_JoystickNumButtons (joystick); int num_buttons = SDL_JoystickNumButtons(joystick);
cout << "Joystick has " << num_buttons << " button" << (num_buttons == 1 ? "" : "s") << '\n'; cout << "Joystick has " << num_buttons << " button" << (num_buttons == 1 ? "" : "s") << '\n';
int num_axes = SDL_JoystickNumAxes (joystick); int num_axes = SDL_JoystickNumAxes(joystick);
cout << "Joystick has " << num_axes << " ax" << (num_axes == 1 ? "i" : "e") << "s\n\n"; cout << "Joystick has " << num_axes << " ax" << (num_axes == 1 ? "i" : "e") << "s\n\n";
} }
unsigned char *CWinsys::GetSurfaceData () const { unsigned char *CWinsys::GetSurfaceData() const {
return (unsigned char*)screen->pixels; return (unsigned char*)screen->pixels;
} }

View File

@ -41,32 +41,31 @@ private:
TScreenRes resolutions[NUM_RESOLUTIONS]; TScreenRes resolutions[NUM_RESOLUTIONS];
TScreenRes auto_resolution; TScreenRes auto_resolution;
SDL_Surface *screen; SDL_Surface *screen;
double CalcScreenScale () const; double CalcScreenScale() const;
public: public:
TScreenRes resolution; TScreenRes resolution;
double scale; // scale factor for screen, see 'use_quad_scale' double scale; // scale factor for screen, see 'use_quad_scale'
CWinsys (); CWinsys();
// sdl window // sdl window
const TScreenRes& GetResolution (size_t idx) const; const TScreenRes& GetResolution(size_t idx) const;
string GetResName (size_t idx) const; string GetResName(size_t idx) const;
void Init (); void Init();
void SetupVideoMode (const TScreenRes& resolution); void SetupVideoMode(const TScreenRes& resolution);
void SetupVideoMode (size_t idx); void SetupVideoMode(size_t idx);
void SetupVideoMode (int width, int height); void SetupVideoMode(int width, int height);
void KeyRepeat (bool repeat); void KeyRepeat(bool repeat);
void SetFonttype (); void PrintJoystickInfo() const;
void PrintJoystickInfo () const; void ShowCursor(bool visible) {SDL_ShowCursor(visible);}
void ShowCursor (bool visible) {SDL_ShowCursor (visible);} void SwapBuffers() {SDL_GL_SwapBuffers();}
void SwapBuffers () {SDL_GL_SwapBuffers ();} void Quit();
void Quit (); void Terminate();
void Terminate (); void InitJoystick();
void InitJoystick (); void CloseJoystick();
void CloseJoystick ();
bool joystick_isActive() const { return joystick_active; } bool joystick_isActive() const { return joystick_active; }
double ClockTime () const {return SDL_GetTicks() * 1.e-3; } double ClockTime() const {return SDL_GetTicks() * 1.e-3; }
unsigned char *GetSurfaceData () const; unsigned char *GetSurfaceData() const;
}; };
extern CWinsys Winsys; extern CWinsys Winsys;