Repository: matricks/teeworlds Branch: master Commit: 30e6e0877b97 Files: 627 Total size: 4.6 MB Directory structure: gitextract_e20lamu3/ ├── .gitignore ├── .gitmodules ├── bam.lua ├── configure.lua ├── data/ │ ├── audio/ │ │ ├── foley_body_impact-01.wv │ │ ├── foley_body_impact-02.wv │ │ ├── foley_body_impact-03.wv │ │ ├── foley_body_splat-01.wv │ │ ├── foley_body_splat-02.wv │ │ ├── foley_body_splat-03.wv │ │ ├── foley_body_splat-04.wv │ │ ├── foley_dbljump-01.wv │ │ ├── foley_dbljump-02.wv │ │ ├── foley_dbljump-03.wv │ │ ├── foley_foot_left-01.wv │ │ ├── foley_foot_left-02.wv │ │ ├── foley_foot_left-03.wv │ │ ├── foley_foot_left-04.wv │ │ ├── foley_foot_right-01.wv │ │ ├── foley_foot_right-02.wv │ │ ├── foley_foot_right-03.wv │ │ ├── foley_foot_right-04.wv │ │ ├── foley_land-01.wv │ │ ├── foley_land-02.wv │ │ ├── foley_land-03.wv │ │ ├── foley_land-04.wv │ │ ├── hook_attach-01.wv │ │ ├── hook_attach-02.wv │ │ ├── hook_attach-03.wv │ │ ├── hook_loop-01.wv │ │ ├── hook_loop-02.wv │ │ ├── hook_noattach-01.wv │ │ ├── hook_noattach-02.wv │ │ ├── hook_noattach-03.wv │ │ ├── music_menu.wv │ │ ├── sfx_ctf_cap_pl.wv │ │ ├── sfx_ctf_drop.wv │ │ ├── sfx_ctf_grab_en.wv │ │ ├── sfx_ctf_grab_pl.wv │ │ ├── sfx_ctf_rtn.wv │ │ ├── sfx_hit_strong-01.wv │ │ ├── sfx_hit_strong-02.wv │ │ ├── sfx_hit_weak-01.wv │ │ ├── sfx_hit_weak-02.wv │ │ ├── sfx_hit_weak-03.wv │ │ ├── sfx_msg-client.wv │ │ ├── sfx_msg-highlight.wv │ │ ├── sfx_msg-server.wv │ │ ├── sfx_pickup_arm-01.wv │ │ ├── sfx_pickup_arm-02.wv │ │ ├── sfx_pickup_arm-03.wv │ │ ├── sfx_pickup_arm-04.wv │ │ ├── sfx_pickup_gun.wv │ │ ├── sfx_pickup_hrt-01.wv │ │ ├── sfx_pickup_hrt-02.wv │ │ ├── sfx_pickup_launcher.wv │ │ ├── sfx_pickup_ninja.wv │ │ ├── sfx_pickup_sg.wv │ │ ├── sfx_skid-01.wv │ │ ├── sfx_skid-02.wv │ │ ├── sfx_skid-03.wv │ │ ├── sfx_skid-04.wv │ │ ├── sfx_spawn_wpn-01.wv │ │ ├── sfx_spawn_wpn-02.wv │ │ ├── sfx_spawn_wpn-03.wv │ │ ├── vo_teefault_cry-01.wv │ │ ├── vo_teefault_cry-02.wv │ │ ├── vo_teefault_ninja-01.wv │ │ ├── vo_teefault_ninja-02.wv │ │ ├── vo_teefault_ninja-03.wv │ │ ├── vo_teefault_ninja-04.wv │ │ ├── vo_teefault_pain_long-01.wv │ │ ├── vo_teefault_pain_long-02.wv │ │ ├── vo_teefault_pain_short-01.wv │ │ ├── vo_teefault_pain_short-02.wv │ │ ├── vo_teefault_pain_short-03.wv │ │ ├── vo_teefault_pain_short-04.wv │ │ ├── vo_teefault_pain_short-05.wv │ │ ├── vo_teefault_pain_short-06.wv │ │ ├── vo_teefault_pain_short-07.wv │ │ ├── vo_teefault_pain_short-08.wv │ │ ├── vo_teefault_pain_short-09.wv │ │ ├── vo_teefault_pain_short-10.wv │ │ ├── vo_teefault_pain_short-11.wv │ │ ├── vo_teefault_pain_short-12.wv │ │ ├── vo_teefault_sledge-01.wv │ │ ├── vo_teefault_sledge-02.wv │ │ ├── vo_teefault_sledge-03.wv │ │ ├── vo_teefault_spawn-01.wv │ │ ├── vo_teefault_spawn-02.wv │ │ ├── vo_teefault_spawn-03.wv │ │ ├── vo_teefault_spawn-04.wv │ │ ├── vo_teefault_spawn-05.wv │ │ ├── vo_teefault_spawn-06.wv │ │ ├── vo_teefault_spawn-07.wv │ │ ├── wp_flump_explo-01.wv │ │ ├── wp_flump_explo-02.wv │ │ ├── wp_flump_explo-03.wv │ │ ├── wp_flump_launch-01.wv │ │ ├── wp_flump_launch-02.wv │ │ ├── wp_flump_launch-03.wv │ │ ├── wp_gun_fire-01.wv │ │ ├── wp_gun_fire-02.wv │ │ ├── wp_gun_fire-03.wv │ │ ├── wp_hammer_hit-01.wv │ │ ├── wp_hammer_hit-02.wv │ │ ├── wp_hammer_hit-03.wv │ │ ├── wp_hammer_swing-01.wv │ │ ├── wp_hammer_swing-02.wv │ │ ├── wp_hammer_swing-03.wv │ │ ├── wp_laser_bnce-01.wv │ │ ├── wp_laser_bnce-02.wv │ │ ├── wp_laser_bnce-03.wv │ │ ├── wp_laser_fire-01.wv │ │ ├── wp_laser_fire-02.wv │ │ ├── wp_laser_fire-03.wv │ │ ├── wp_ninja_attack-01.wv │ │ ├── wp_ninja_attack-02.wv │ │ ├── wp_ninja_attack-03.wv │ │ ├── wp_ninja_attack-04.wv │ │ ├── wp_ninja_hit-01.wv │ │ ├── wp_ninja_hit-02.wv │ │ ├── wp_ninja_hit-03.wv │ │ ├── wp_ninja_hit-04.wv │ │ ├── wp_noammo-01.wv │ │ ├── wp_noammo-02.wv │ │ ├── wp_noammo-03.wv │ │ ├── wp_noammo-04.wv │ │ ├── wp_noammo-05.wv │ │ ├── wp_shotty_fire-01.wv │ │ ├── wp_shotty_fire-02.wv │ │ ├── wp_shotty_fire-03.wv │ │ ├── wp_switch-01.wv │ │ ├── wp_switch-02.wv │ │ └── wp_switch-03.wv │ ├── countryflags/ │ │ └── index.json │ ├── editor/ │ │ ├── automap/ │ │ │ ├── grass_doodads.json │ │ │ └── grass_main.json │ │ ├── desert_main.rules │ │ ├── grass_main.rules │ │ ├── jungle_main.rules │ │ └── winter_main.rules │ ├── fonts/ │ │ ├── LICENSE │ │ └── VERSION │ └── skins/ │ ├── bluekitty.json │ ├── bluestripe.json │ ├── brownbear.json │ ├── cammo.json │ ├── cammostripes.json │ ├── coala.json │ ├── default.json │ ├── limekitty.json │ ├── pinky.json │ ├── redbopp.json │ ├── redstripe.json │ ├── saddo.json │ ├── toptri.json │ ├── twinbop.json │ ├── twintri.json │ ├── warpaint.json │ └── x_ninja.json ├── datasrc/ │ ├── compile.py │ ├── content.py │ ├── datatypes.py │ └── network.py ├── license.txt ├── other/ │ ├── config_directory.bat │ ├── freetype/ │ │ ├── VERSION │ │ ├── freetype.lua │ │ ├── include/ │ │ │ ├── freetype/ │ │ │ │ ├── config/ │ │ │ │ │ ├── ftconfig.h │ │ │ │ │ ├── ftheader.h │ │ │ │ │ ├── ftmodule.h │ │ │ │ │ ├── ftoption.h │ │ │ │ │ └── ftstdlib.h │ │ │ │ ├── freetype.h │ │ │ │ ├── ftadvanc.h │ │ │ │ ├── ftbbox.h │ │ │ │ ├── ftbdf.h │ │ │ │ ├── ftbitmap.h │ │ │ │ ├── ftbzip2.h │ │ │ │ ├── ftcache.h │ │ │ │ ├── ftchapters.h │ │ │ │ ├── ftcid.h │ │ │ │ ├── fterrdef.h │ │ │ │ ├── fterrors.h │ │ │ │ ├── ftgasp.h │ │ │ │ ├── ftglyph.h │ │ │ │ ├── ftgxval.h │ │ │ │ ├── ftgzip.h │ │ │ │ ├── ftimage.h │ │ │ │ ├── ftincrem.h │ │ │ │ ├── ftlcdfil.h │ │ │ │ ├── ftlist.h │ │ │ │ ├── ftlzw.h │ │ │ │ ├── ftmac.h │ │ │ │ ├── ftmm.h │ │ │ │ ├── ftmodapi.h │ │ │ │ ├── ftmoderr.h │ │ │ │ ├── ftotval.h │ │ │ │ ├── ftoutln.h │ │ │ │ ├── ftpfr.h │ │ │ │ ├── ftrender.h │ │ │ │ ├── ftsizes.h │ │ │ │ ├── ftsnames.h │ │ │ │ ├── ftstroke.h │ │ │ │ ├── ftsynth.h │ │ │ │ ├── ftsystem.h │ │ │ │ ├── fttrigon.h │ │ │ │ ├── fttypes.h │ │ │ │ ├── ftwinfnt.h │ │ │ │ ├── ftxf86.h │ │ │ │ ├── internal/ │ │ │ │ │ ├── autohint.h │ │ │ │ │ ├── ftcalc.h │ │ │ │ │ ├── ftdebug.h │ │ │ │ │ ├── ftdriver.h │ │ │ │ │ ├── ftgloadr.h │ │ │ │ │ ├── ftmemory.h │ │ │ │ │ ├── ftobjs.h │ │ │ │ │ ├── ftpic.h │ │ │ │ │ ├── ftrfork.h │ │ │ │ │ ├── ftserv.h │ │ │ │ │ ├── ftstream.h │ │ │ │ │ ├── fttrace.h │ │ │ │ │ ├── ftvalid.h │ │ │ │ │ ├── internal.h │ │ │ │ │ ├── psaux.h │ │ │ │ │ ├── pshints.h │ │ │ │ │ ├── services/ │ │ │ │ │ │ ├── svbdf.h │ │ │ │ │ │ ├── svcid.h │ │ │ │ │ │ ├── svgldict.h │ │ │ │ │ │ ├── svgxval.h │ │ │ │ │ │ ├── svkern.h │ │ │ │ │ │ ├── svmm.h │ │ │ │ │ │ ├── svotval.h │ │ │ │ │ │ ├── svpfr.h │ │ │ │ │ │ ├── svpostnm.h │ │ │ │ │ │ ├── svpscmap.h │ │ │ │ │ │ ├── svpsinfo.h │ │ │ │ │ │ ├── svsfnt.h │ │ │ │ │ │ ├── svttcmap.h │ │ │ │ │ │ ├── svtteng.h │ │ │ │ │ │ ├── svttglyf.h │ │ │ │ │ │ ├── svwinfnt.h │ │ │ │ │ │ └── svxf86nm.h │ │ │ │ │ ├── sfnt.h │ │ │ │ │ ├── t1types.h │ │ │ │ │ └── tttypes.h │ │ │ │ ├── t1tables.h │ │ │ │ ├── ttnameid.h │ │ │ │ ├── tttables.h │ │ │ │ ├── tttags.h │ │ │ │ └── ttunpat.h │ │ │ └── ft2build.h │ │ ├── lib32/ │ │ │ └── freetype.lib │ │ └── lib64/ │ │ └── freetype.lib │ ├── icons/ │ │ ├── Teeworlds.icns │ │ ├── Teeworlds_srv.icns │ │ ├── teeworlds_cl.rc │ │ ├── teeworlds_gcc.rc │ │ ├── teeworlds_srv_cl.rc │ │ └── teeworlds_srv_gcc.rc │ └── sdl/ │ ├── include/ │ │ ├── SDL.h │ │ ├── SDL_active.h │ │ ├── SDL_audio.h │ │ ├── SDL_byteorder.h │ │ ├── SDL_cdrom.h │ │ ├── SDL_config.h │ │ ├── SDL_config.h.default │ │ ├── SDL_config.h.in │ │ ├── SDL_config_amiga.h │ │ ├── SDL_config_dreamcast.h │ │ ├── SDL_config_macos.h │ │ ├── SDL_config_macosx.h │ │ ├── SDL_config_minimal.h │ │ ├── SDL_config_nds.h │ │ ├── SDL_config_os2.h │ │ ├── SDL_config_symbian.h │ │ ├── SDL_config_win32.h │ │ ├── SDL_copying.h │ │ ├── SDL_cpuinfo.h │ │ ├── SDL_endian.h │ │ ├── SDL_error.h │ │ ├── SDL_events.h │ │ ├── SDL_getenv.h │ │ ├── SDL_joystick.h │ │ ├── SDL_keyboard.h │ │ ├── SDL_keysym.h │ │ ├── SDL_loadso.h │ │ ├── SDL_main.h │ │ ├── SDL_mouse.h │ │ ├── SDL_mutex.h │ │ ├── SDL_name.h │ │ ├── SDL_opengl.h │ │ ├── SDL_platform.h │ │ ├── SDL_quit.h │ │ ├── SDL_rwops.h │ │ ├── SDL_stdinc.h │ │ ├── SDL_syswm.h │ │ ├── SDL_thread.h │ │ ├── SDL_timer.h │ │ ├── SDL_types.h │ │ ├── SDL_version.h │ │ ├── SDL_video.h │ │ ├── begin_code.h │ │ └── close_code.h │ ├── lib32/ │ │ ├── SDL.lib │ │ └── SDLmain.lib │ ├── lib64/ │ │ ├── SDL.lib │ │ └── SDLmain.lib │ ├── sdl.lua │ └── sdlnotes.txt ├── readme.txt ├── scripts/ │ ├── SDL_keysym.h │ ├── build.py │ ├── check_header_guards.py │ ├── cmd5.py │ ├── compiler.py │ ├── copyright.py │ ├── count_source.sh │ ├── dat2c.py │ ├── font_converter.py │ ├── font_installer.sh │ ├── gen_keys.py │ ├── linecount.sh │ ├── make_docs.sh │ ├── make_release.py │ ├── make_src.py │ ├── mass_server.py │ ├── netobj.py │ ├── nicks.txt │ ├── png.py │ ├── process_blame.py │ ├── refactor_count.py │ ├── tw_api.py │ ├── twlib.py │ └── update_localization.py ├── src/ │ ├── base/ │ │ ├── detect.h │ │ ├── math.h │ │ ├── system.c │ │ ├── system.h │ │ ├── tl/ │ │ │ ├── algorithm.h │ │ │ ├── allocator.h │ │ │ ├── array.h │ │ │ ├── base.h │ │ │ ├── range.h │ │ │ ├── sorted_array.h │ │ │ ├── string.h │ │ │ └── threading.h │ │ └── vmath.h │ ├── engine/ │ │ ├── client/ │ │ │ ├── backend_sdl.cpp │ │ │ ├── backend_sdl.h │ │ │ ├── client.cpp │ │ │ ├── client.h │ │ │ ├── friends.cpp │ │ │ ├── friends.h │ │ │ ├── graphics_threaded.cpp │ │ │ ├── graphics_threaded.h │ │ │ ├── input.cpp │ │ │ ├── input.h │ │ │ ├── keynames.h │ │ │ ├── serverbrowser.cpp │ │ │ ├── serverbrowser.h │ │ │ ├── sound.cpp │ │ │ ├── sound.h │ │ │ └── text.cpp │ │ ├── client.h │ │ ├── config.h │ │ ├── console.h │ │ ├── demo.h │ │ ├── docs/ │ │ │ ├── client_time.txt │ │ │ ├── prediction.txt │ │ │ ├── server_op.txt │ │ │ └── snapshots.txt │ │ ├── editor.h │ │ ├── engine.h │ │ ├── external/ │ │ │ ├── important.txt │ │ │ ├── json-parser/ │ │ │ │ ├── json.c │ │ │ │ └── json.h │ │ │ ├── pnglite/ │ │ │ │ ├── VERSION │ │ │ │ ├── pnglite.c │ │ │ │ └── pnglite.h │ │ │ ├── wavpack/ │ │ │ │ ├── VERSION │ │ │ │ ├── arm.S │ │ │ │ ├── arml.S │ │ │ │ ├── bits.c │ │ │ │ ├── coldfire.S │ │ │ │ ├── float.c │ │ │ │ ├── license.txt │ │ │ │ ├── metadata.c │ │ │ │ ├── readme.txt │ │ │ │ ├── unpack.c │ │ │ │ ├── wavpack.h │ │ │ │ ├── words.c │ │ │ │ ├── wputils.c │ │ │ │ └── wvfilter.c.no_compile │ │ │ └── zlib/ │ │ │ ├── VERSION │ │ │ ├── adler32.c │ │ │ ├── compress.c │ │ │ ├── crc32.c │ │ │ ├── crc32.h │ │ │ ├── deflate.c │ │ │ ├── deflate.h │ │ │ ├── infback.c │ │ │ ├── inffast.c │ │ │ ├── inffast.h │ │ │ ├── inffixed.h │ │ │ ├── inflate.c │ │ │ ├── inflate.h │ │ │ ├── inftrees.c │ │ │ ├── inftrees.h │ │ │ ├── trees.c │ │ │ ├── trees.h │ │ │ ├── uncompr.c │ │ │ ├── zconf.h │ │ │ ├── zlib.h │ │ │ ├── zutil.c │ │ │ └── zutil.h │ │ ├── friends.h │ │ ├── graphics.h │ │ ├── input.h │ │ ├── kernel.h │ │ ├── keys.h │ │ ├── map.h │ │ ├── masterserver.h │ │ ├── message.h │ │ ├── server/ │ │ │ ├── register.cpp │ │ │ ├── register.h │ │ │ ├── server.cpp │ │ │ └── server.h │ │ ├── server.h │ │ ├── serverbrowser.h │ │ ├── shared/ │ │ │ ├── compression.cpp │ │ │ ├── compression.h │ │ │ ├── config.cpp │ │ │ ├── config.h │ │ │ ├── config_variables.h │ │ │ ├── console.cpp │ │ │ ├── console.h │ │ │ ├── datafile.cpp │ │ │ ├── datafile.h │ │ │ ├── demo.cpp │ │ │ ├── demo.h │ │ │ ├── econ.cpp │ │ │ ├── econ.h │ │ │ ├── engine.cpp │ │ │ ├── filecollection.cpp │ │ │ ├── filecollection.h │ │ │ ├── huffman.cpp │ │ │ ├── huffman.h │ │ │ ├── jobs.cpp │ │ │ ├── jobs.h │ │ │ ├── kernel.cpp │ │ │ ├── linereader.cpp │ │ │ ├── linereader.h │ │ │ ├── map.cpp │ │ │ ├── mapchecker.cpp │ │ │ ├── mapchecker.h │ │ │ ├── masterserver.cpp │ │ │ ├── memheap.cpp │ │ │ ├── memheap.h │ │ │ ├── message.h │ │ │ ├── netban.cpp │ │ │ ├── netban.h │ │ │ ├── network.cpp │ │ │ ├── network.h │ │ │ ├── network_client.cpp │ │ │ ├── network_conn.cpp │ │ │ ├── network_console.cpp │ │ │ ├── network_console_conn.cpp │ │ │ ├── network_server.cpp │ │ │ ├── packer.cpp │ │ │ ├── packer.h │ │ │ ├── protocol.h │ │ │ ├── ringbuffer.cpp │ │ │ ├── ringbuffer.h │ │ │ ├── snapshot.cpp │ │ │ ├── snapshot.h │ │ │ └── storage.cpp │ │ ├── sound.h │ │ ├── storage.h │ │ └── textrender.h │ ├── game/ │ │ ├── client/ │ │ │ ├── animstate.cpp │ │ │ ├── animstate.h │ │ │ ├── component.h │ │ │ ├── components/ │ │ │ │ ├── binds.cpp │ │ │ │ ├── binds.h │ │ │ │ ├── broadcast.cpp │ │ │ │ ├── broadcast.h │ │ │ │ ├── camera.cpp │ │ │ │ ├── camera.h │ │ │ │ ├── chat.cpp │ │ │ │ ├── chat.h │ │ │ │ ├── console.cpp │ │ │ │ ├── console.h │ │ │ │ ├── controls.cpp │ │ │ │ ├── controls.h │ │ │ │ ├── countryflags.cpp │ │ │ │ ├── countryflags.h │ │ │ │ ├── damageind.cpp │ │ │ │ ├── damageind.h │ │ │ │ ├── debughud.cpp │ │ │ │ ├── debughud.h │ │ │ │ ├── effects.cpp │ │ │ │ ├── effects.h │ │ │ │ ├── emoticon.cpp │ │ │ │ ├── emoticon.h │ │ │ │ ├── flow.cpp │ │ │ │ ├── flow.h │ │ │ │ ├── hud.cpp │ │ │ │ ├── hud.h │ │ │ │ ├── items.cpp │ │ │ │ ├── items.h │ │ │ │ ├── killmessages.cpp │ │ │ │ ├── killmessages.h │ │ │ │ ├── mapimages.cpp │ │ │ │ ├── mapimages.h │ │ │ │ ├── maplayers.cpp │ │ │ │ ├── maplayers.h │ │ │ │ ├── menus.cpp │ │ │ │ ├── menus.h │ │ │ │ ├── menus_browser.cpp │ │ │ │ ├── menus_callback.cpp │ │ │ │ ├── menus_demo.cpp │ │ │ │ ├── menus_ingame.cpp │ │ │ │ ├── menus_popups.cpp │ │ │ │ ├── menus_settings.cpp │ │ │ │ ├── menus_start.cpp │ │ │ │ ├── motd.cpp │ │ │ │ ├── motd.h │ │ │ │ ├── nameplates.cpp │ │ │ │ ├── nameplates.h │ │ │ │ ├── particles.cpp │ │ │ │ ├── particles.h │ │ │ │ ├── players.cpp │ │ │ │ ├── players.h │ │ │ │ ├── scoreboard.cpp │ │ │ │ ├── scoreboard.h │ │ │ │ ├── skins.cpp │ │ │ │ ├── skins.h │ │ │ │ ├── sounds.cpp │ │ │ │ ├── sounds.h │ │ │ │ ├── spectator.cpp │ │ │ │ ├── spectator.h │ │ │ │ ├── voting.cpp │ │ │ │ └── voting.h │ │ │ ├── gameclient.cpp │ │ │ ├── gameclient.h │ │ │ ├── lineinput.cpp │ │ │ ├── lineinput.h │ │ │ ├── localization.cpp │ │ │ ├── localization.h │ │ │ ├── render.cpp │ │ │ ├── render.h │ │ │ ├── render_map.cpp │ │ │ ├── ui.cpp │ │ │ └── ui.h │ │ ├── collision.cpp │ │ ├── collision.h │ │ ├── editor/ │ │ │ ├── auto_map.cpp │ │ │ ├── auto_map.h │ │ │ ├── editor.cpp │ │ │ ├── editor.h │ │ │ ├── io.cpp │ │ │ ├── layer_game.cpp │ │ │ ├── layer_quads.cpp │ │ │ ├── layer_tiles.cpp │ │ │ └── popups.cpp │ │ ├── gamecore.cpp │ │ ├── gamecore.h │ │ ├── layers.cpp │ │ ├── layers.h │ │ ├── mapitems.h │ │ ├── server/ │ │ │ ├── alloc.h │ │ │ ├── entities/ │ │ │ │ ├── character.cpp │ │ │ │ ├── character.h │ │ │ │ ├── flag.cpp │ │ │ │ ├── flag.h │ │ │ │ ├── laser.cpp │ │ │ │ ├── laser.h │ │ │ │ ├── pickup.cpp │ │ │ │ ├── pickup.h │ │ │ │ ├── projectile.cpp │ │ │ │ └── projectile.h │ │ │ ├── entity.cpp │ │ │ ├── entity.h │ │ │ ├── eventhandler.cpp │ │ │ ├── eventhandler.h │ │ │ ├── gamecontext.cpp │ │ │ ├── gamecontext.h │ │ │ ├── gamecontroller.cpp │ │ │ ├── gamecontroller.h │ │ │ ├── gamemodes/ │ │ │ │ ├── ctf.cpp │ │ │ │ ├── ctf.h │ │ │ │ ├── dm.cpp │ │ │ │ ├── dm.h │ │ │ │ ├── lms.cpp │ │ │ │ ├── lms.h │ │ │ │ ├── mod.cpp │ │ │ │ ├── mod.h │ │ │ │ ├── sur.cpp │ │ │ │ ├── sur.h │ │ │ │ ├── tdm.cpp │ │ │ │ └── tdm.h │ │ │ ├── gameworld.cpp │ │ │ ├── gameworld.h │ │ │ ├── player.cpp │ │ │ └── player.h │ │ ├── tuning.h │ │ ├── variables.h │ │ ├── version.h │ │ └── voting.h │ ├── mastersrv/ │ │ ├── mastersrv.cpp │ │ └── mastersrv.h │ ├── osxlaunch/ │ │ ├── client.h │ │ ├── client.m │ │ └── server.m │ ├── tools/ │ │ ├── crapnet.cpp │ │ ├── dilate.cpp │ │ ├── fake_server.cpp │ │ ├── map_resave.cpp │ │ ├── map_version.cpp │ │ ├── packetgen.cpp │ │ └── tileset_borderop.cpp │ └── versionsrv/ │ ├── mapversions.h │ ├── versionsrv.cpp │ └── versionsrv.h └── storage.cfg ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ /bam /.bam /config.lua /objs __pycache__/ *.pyc *.pyo scripts/work/ src/game/generated/ other/icons/*.res /SDL.dll /freetype.dll /autoexec.cfg /crapnet* /dilate* /fake_server* /map_resave* /map_version* /mastersrv* /packetgen* /teeworlds* /teeworlds_srv* /serverlaunch* /tileset_border* /versionsrv* ================================================ FILE: .gitmodules ================================================ [submodule "data/languages"] path = data/languages url = git://github.com/teeworlds/teeworlds-translation.git [submodule "data/maps"] path = data/maps url = git://github.com/teeworlds/teeworlds-maps.git ================================================ FILE: bam.lua ================================================ CheckVersion("0.4") Import("configure.lua") Import("other/sdl/sdl.lua") Import("other/freetype/freetype.lua") --- Setup Config ------- config = NewConfig() config:Add(OptCCompiler("compiler")) config:Add(OptTestCompileC("stackprotector", "int main(){return 0;}", "-fstack-protector -fstack-protector-all")) config:Add(OptTestCompileC("minmacosxsdk", "int main(){return 0;}", "-mmacosx-version-min=10.5 -isysroot /Developer/SDKs/MacOSX10.5.sdk")) config:Add(OptTestCompileC("macosxppc", "int main(){return 0;}", "-arch ppc")) config:Add(OptLibrary("zlib", "zlib.h", false)) config:Add(SDL.OptFind("sdl", true)) config:Add(FreeType.OptFind("freetype", true)) config:Finalize("config.lua") -- data compiler function Script(name) if family == "windows" then return str_replace(name, "/", "\\") end return "python " .. name end function CHash(output, ...) local inputs = TableFlatten({...}) output = Path(output) -- compile all the files local cmd = Script("scripts/cmd5.py") .. " " for index, inname in ipairs(inputs) do cmd = cmd .. Path(inname) .. " " end cmd = cmd .. " > " .. output AddJob(output, "cmd5 " .. output, cmd) for index, inname in ipairs(inputs) do AddDependency(output, inname) end AddDependency(output, "scripts/cmd5.py") return output end --[[ function DuplicateDirectoryStructure(orgpath, srcpath, dstpath) for _,v in pairs(CollectDirs(srcpath .. "/")) do MakeDirectory(dstpath .. "/" .. string.sub(v, string.len(orgpath)+2)) DuplicateDirectoryStructure(orgpath, v, dstpath) end end DuplicateDirectoryStructure("src", "src", "objs") ]] function ResCompile(scriptfile) scriptfile = Path(scriptfile) if config.compiler.driver == "cl" then output = PathBase(scriptfile) .. ".res" AddJob(output, "rc " .. scriptfile, "rc /fo " .. output .. " " .. scriptfile) elseif config.compiler.driver == "gcc" then output = PathBase(scriptfile) .. ".coff" AddJob(output, "windres " .. scriptfile, "windres -i " .. scriptfile .. " -o " .. output) end AddDependency(output, scriptfile) return output end function Dat2c(datafile, sourcefile, arrayname) datafile = Path(datafile) sourcefile = Path(sourcefile) AddJob( sourcefile, "dat2c " .. PathFilename(sourcefile) .. " = " .. PathFilename(datafile), Script("scripts/dat2c.py").. "\" " .. sourcefile .. " " .. datafile .. " " .. arrayname ) AddDependency(sourcefile, datafile) return sourcefile end function ContentCompile(action, output) output = Path(output) AddJob( output, action .. " > " .. output, --Script("datasrc/compile.py") .. "\" ".. Path(output) .. " " .. action Script("datasrc/compile.py") .. " " .. action .. " > " .. Path(output) ) AddDependency(output, Path("datasrc/content.py")) -- do this more proper AddDependency(output, Path("datasrc/network.py")) AddDependency(output, Path("datasrc/compile.py")) AddDependency(output, Path("datasrc/datatypes.py")) return output end -- Content Compile network_source = ContentCompile("network_source", "src/game/generated/protocol.cpp") network_header = ContentCompile("network_header", "src/game/generated/protocol.h") client_content_source = ContentCompile("client_content_source", "src/game/generated/client_data.cpp") client_content_header = ContentCompile("client_content_header", "src/game/generated/client_data.h") server_content_source = ContentCompile("server_content_source", "src/game/generated/server_data.cpp") server_content_header = ContentCompile("server_content_header", "src/game/generated/server_data.h") AddDependency(network_source, network_header) AddDependency(client_content_source, client_content_header) AddDependency(server_content_source, server_content_header) nethash = CHash("src/game/generated/nethash.cpp", "src/engine/shared/protocol.h", "src/game/generated/protocol.h", "src/game/tuning.h", "src/game/gamecore.cpp", network_header) client_link_other = {} client_depends = {} server_link_other = {} if family == "windows" then if platform == "win32" then table.insert(client_depends, CopyToDirectory(".", "other\\freetype\\lib32\\freetype.dll")) table.insert(client_depends, CopyToDirectory(".", "other\\sdl\\lib32\\SDL.dll")) else table.insert(client_depends, CopyToDirectory(".", "other\\freetype\\lib64\\freetype.dll")) table.insert(client_depends, CopyToDirectory(".", "other\\sdl\\lib64\\SDL.dll")) end if config.compiler.driver == "cl" then client_link_other = {ResCompile("other/icons/teeworlds_cl.rc")} server_link_other = {ResCompile("other/icons/teeworlds_srv_cl.rc")} elseif config.compiler.driver == "gcc" then client_link_other = {ResCompile("other/icons/teeworlds_gcc.rc")} server_link_other = {ResCompile("other/icons/teeworlds_srv_gcc.rc")} end end function Intermediate_Output(settings, input) return "objs/" .. string.sub(PathBase(input), string.len("src/")+1) .. settings.config_ext end function build(settings) -- apply compiler settings config.compiler:Apply(settings) --settings.objdir = Path("objs") settings.cc.Output = Intermediate_Output if config.compiler.driver == "cl" then settings.cc.flags:Add("/wd4244") else settings.cc.flags:Add("-Wall", "-fno-exceptions") if family == "windows" then -- disable visibility attribute support for gcc on windows settings.cc.defines:Add("NO_VIZ") elseif platform == "macosx" then settings.cc.flags:Add("-mmacosx-version-min=10.5") settings.link.flags:Add("-mmacosx-version-min=10.5") if config.minmacosxsdk.value == 1 then settings.cc.flags:Add("-isysroot /Developer/SDKs/MacOSX10.5.sdk") settings.link.flags:Add("-isysroot /Developer/SDKs/MacOSX10.5.sdk") end elseif config.stackprotector.value == 1 then settings.cc.flags:Add("-fstack-protector", "-fstack-protector-all") settings.link.flags:Add("-fstack-protector", "-fstack-protector-all") end end -- set some platform specific settings settings.cc.includes:Add("src") if family == "unix" then if platform == "macosx" then settings.link.frameworks:Add("Carbon") settings.link.frameworks:Add("AppKit") else settings.link.libs:Add("pthread") end if platform == "solaris" then settings.link.flags:Add("-lsocket") settings.link.flags:Add("-lnsl") end elseif family == "windows" then settings.link.libs:Add("gdi32") settings.link.libs:Add("user32") settings.link.libs:Add("ws2_32") settings.link.libs:Add("ole32") settings.link.libs:Add("shell32") end -- compile zlib if needed if config.zlib.value == 1 then settings.link.libs:Add("z") if config.zlib.include_path then settings.cc.includes:Add(config.zlib.include_path) end zlib = {} else zlib = Compile(settings, Collect("src/engine/external/zlib/*.c")) settings.cc.includes:Add("src/engine/external/zlib") end -- build the small libraries wavpack = Compile(settings, Collect("src/engine/external/wavpack/*.c")) pnglite = Compile(settings, Collect("src/engine/external/pnglite/*.c")) jsonparser = Compile(settings, Collect("src/engine/external/json-parser/*.c")) -- build game components engine_settings = settings:Copy() server_settings = engine_settings:Copy() client_settings = engine_settings:Copy() launcher_settings = engine_settings:Copy() if family == "unix" then if platform == "macosx" then client_settings.link.frameworks:Add("OpenGL") client_settings.link.frameworks:Add("AGL") client_settings.link.frameworks:Add("Carbon") client_settings.link.frameworks:Add("Cocoa") launcher_settings.link.frameworks:Add("Cocoa") else client_settings.link.libs:Add("X11") client_settings.link.libs:Add("GL") client_settings.link.libs:Add("GLU") end elseif family == "windows" then client_settings.link.libs:Add("opengl32") client_settings.link.libs:Add("glu32") client_settings.link.libs:Add("winmm") end -- apply sdl settings config.sdl:Apply(client_settings) -- apply freetype settings config.freetype:Apply(client_settings) engine = Compile(engine_settings, Collect("src/engine/shared/*.cpp", "src/base/*.c")) client = Compile(client_settings, Collect("src/engine/client/*.cpp")) server = Compile(server_settings, Collect("src/engine/server/*.cpp")) versionserver = Compile(settings, Collect("src/versionsrv/*.cpp")) masterserver = Compile(settings, Collect("src/mastersrv/*.cpp")) game_shared = Compile(settings, Collect("src/game/*.cpp"), nethash, network_source) game_client = Compile(settings, CollectRecursive("src/game/client/*.cpp"), client_content_source) game_server = Compile(settings, CollectRecursive("src/game/server/*.cpp"), server_content_source) game_editor = Compile(settings, Collect("src/game/editor/*.cpp")) -- build tools (TODO: fix this so we don't get double _d_d stuff) tools_src = Collect("src/tools/*.cpp", "src/tools/*.c") client_osxlaunch = {} server_osxlaunch = {} if platform == "macosx" then client_osxlaunch = Compile(client_settings, "src/osxlaunch/client.m") server_osxlaunch = Compile(launcher_settings, "src/osxlaunch/server.m") end tools = {} for i,v in ipairs(tools_src) do toolname = PathFilename(PathBase(v)) tools[i] = Link(settings, toolname, Compile(settings, v), engine, zlib, pnglite) end -- build client, server, version server and master server client_exe = Link(client_settings, "teeworlds", game_shared, game_client, engine, client, game_editor, zlib, pnglite, wavpack, jsonparser, client_link_other, client_osxlaunch) server_exe = Link(server_settings, "teeworlds_srv", engine, server, game_shared, game_server, zlib, server_link_other) serverlaunch = {} if platform == "macosx" then serverlaunch = Link(launcher_settings, "serverlaunch", server_osxlaunch) end versionserver_exe = Link(server_settings, "versionsrv", versionserver, engine, zlib) masterserver_exe = Link(server_settings, "mastersrv", masterserver, engine, zlib) -- make targets c = PseudoTarget("client".."_"..settings.config_name, client_exe, client_depends) s = PseudoTarget("server".."_"..settings.config_name, server_exe, serverlaunch) g = PseudoTarget("game".."_"..settings.config_name, client_exe, server_exe) v = PseudoTarget("versionserver".."_"..settings.config_name, versionserver_exe) m = PseudoTarget("masterserver".."_"..settings.config_name, masterserver_exe) t = PseudoTarget("tools".."_"..settings.config_name, tools) all = PseudoTarget(settings.config_name, c, s, v, m, t) return all end debug_settings = NewSettings() debug_settings.config_name = "debug" debug_settings.config_ext = "_d" debug_settings.debug = 1 debug_settings.optimize = 0 debug_settings.cc.defines:Add("CONF_DEBUG") release_settings = NewSettings() release_settings.config_name = "release" release_settings.config_ext = "" release_settings.debug = 0 release_settings.optimize = 1 release_settings.cc.defines:Add("CONF_RELEASE") if platform == "macosx" then debug_settings_ppc = debug_settings:Copy() debug_settings_ppc.config_name = "debug_ppc" debug_settings_ppc.config_ext = "_ppc_d" debug_settings_ppc.cc.flags:Add("-arch ppc") debug_settings_ppc.link.flags:Add("-arch ppc") debug_settings_ppc.cc.defines:Add("CONF_DEBUG") release_settings_ppc = release_settings:Copy() release_settings_ppc.config_name = "release_ppc" release_settings_ppc.config_ext = "_ppc" release_settings_ppc.cc.flags:Add("-arch ppc") release_settings_ppc.link.flags:Add("-arch ppc") release_settings_ppc.cc.defines:Add("CONF_RELEASE") ppc_d = build(debug_settings_ppc) ppc_r = build(release_settings_ppc) if arch == "ia32" or arch == "amd64" then debug_settings_x86 = debug_settings:Copy() debug_settings_x86.config_name = "debug_x86" debug_settings_x86.config_ext = "_x86_d" debug_settings_x86.cc.flags:Add("-arch i386") debug_settings_x86.link.flags:Add("-arch i386") debug_settings_x86.cc.defines:Add("CONF_DEBUG") release_settings_x86 = release_settings:Copy() release_settings_x86.config_name = "release_x86" release_settings_x86.config_ext = "_x86" release_settings_x86.cc.flags:Add("-arch i386") release_settings_x86.link.flags:Add("-arch i386") release_settings_x86.cc.defines:Add("CONF_RELEASE") x86_d = build(debug_settings_x86) x86_r = build(release_settings_x86) end if arch == "amd64" then debug_settings_x86_64 = debug_settings:Copy() debug_settings_x86_64.config_name = "debug_x86_64" debug_settings_x86_64.config_ext = "_x86_64_d" debug_settings_x86_64.cc.flags:Add("-arch x86_64") debug_settings_x86_64.link.flags:Add("-arch x86_64") debug_settings_x86_64.cc.defines:Add("CONF_DEBUG") release_settings_x86_64 = release_settings:Copy() release_settings_x86_64.config_name = "release_x86_64" release_settings_x86_64.config_ext = "_x86_64" release_settings_x86_64.cc.flags:Add("-arch x86_64") release_settings_x86_64.link.flags:Add("-arch x86_64") release_settings_x86_64.cc.defines:Add("CONF_RELEASE") x86_64_d = build(debug_settings_x86_64) x86_64_r = build(release_settings_x86_64) end DefaultTarget("game_debug_x86") if config.macosxppc.value == 1 then if arch == "ia32" then PseudoTarget("release", ppc_r, x86_r) PseudoTarget("debug", ppc_d, x86_d) PseudoTarget("server_release", "server_release_ppc", "server_release_x86") PseudoTarget("server_debug", "server_debug_ppc", "server_debug_x86") PseudoTarget("client_release", "client_release_ppc", "client_release_x86") PseudoTarget("client_debug", "client_debug_ppc", "client_debug_x86") elseif arch == "amd64" then PseudoTarget("release", ppc_r, x86_r, x86_64_r) PseudoTarget("debug", ppc_d, x86_d, x86_64_d) PseudoTarget("server_release", "server_release_ppc", "server_release_x86", "server_release_x86_64") PseudoTarget("server_debug", "server_debug_ppc", "server_debug_x86", "server_debug_x86_64") PseudoTarget("client_release", "client_release_ppc", "client_release_x86", "client_release_x86_64") PseudoTarget("client_debug", "client_debug_ppc", "client_debug_x86", "client_debug_x86_64") else PseudoTarget("release", ppc_r) PseudoTarget("debug", ppc_d) PseudoTarget("server_release", "server_release_ppc") PseudoTarget("server_debug", "server_debug_ppc") PseudoTarget("client_release", "client_release_ppc") PseudoTarget("client_debug", "client_debug_ppc") end else if arch == "ia32" then PseudoTarget("release", x86_r) PseudoTarget("debug", x86_d) PseudoTarget("server_release", "server_release_x86") PseudoTarget("server_debug", "server_debug_x86") PseudoTarget("client_release", "client_release_x86") PseudoTarget("client_debug", "client_debug_x86") elseif arch == "amd64" then PseudoTarget("release", x86_r, x86_64_r) PseudoTarget("debug", x86_d, x86_64_d) PseudoTarget("server_release", "server_release_x86", "server_release_x86_64") PseudoTarget("server_debug", "server_debug_x86", "server_debug_x86_64") PseudoTarget("client_release", "client_release_x86", "client_release_x86_64") PseudoTarget("client_debug", "client_debug_x86", "client_debug_x86_64") end end else build(debug_settings) build(release_settings) DefaultTarget("game_debug") end ================================================ FILE: configure.lua ================================================ --[[@GROUP Configuration@END]]-- --[[@FUNCTION TODO @END]]-- function NewConfig(on_configured_callback) local config = {} config.OnConfigured = function(self) return true end if on_configured_callback then config.OnConfigured = on_configured_callback end config.options = {} config.settings = NewSettings() config.NewSettings = function(self) local s = NewSettings() for _,v in pairs(self.options) do v:Apply(s) end return s end config.Add = function(self, o) table.insert(self.options, o) self[o.name] = o end config.Print = function(self) for k,v in pairs(self.options) do print(v:FormatDisplay()) end end config.Save = function(self, filename) print("saved configuration to '"..filename.."'") local file = io.open(filename, "w") -- Define a little helper function to save options local saver = {} saver.file = file saver.line = function(self, str) self.file:write(str .. "\n") end saver.option = function(self, option, name) local valuestr = "no" if type(option[name]) == type(0) then valuestr = option[name] elseif type(option[name]) == type(true) then valuestr = "false" if option[name] then valuestr = "true" end elseif type(option[name]) == type("") then valuestr = "'"..option[name].."'" else error("option "..name.." have a value of type ".. type(option[name]).." that can't be saved") end self.file:write(option.name.."."..name.." = ".. valuestr.."\n") end -- Save all the options for k,v in pairs(self.options) do v:Save(saver) end file:close() end config.Load = function(self, filename) local options_func = loadfile(filename) local options_table = {} if not options_func then print("auto configuration") self:Config(filename) options_func = loadfile(filename) end if options_func then -- Setup the options tables for k,v in pairs(self.options) do options_table[v.name] = {} end setfenv(options_func, options_table) -- this is to make sure that we get nice error messages when -- someone sets an option that isn't valid. local mt = {} mt.__index = function(t, key) local v = rawget(t, key) if v ~= nil then return v end error("there is no configuration option named '" .. key .. "'") end setmetatable(options_table, mt) -- Process the options options_func() -- Copy the options for k,v in pairs(self.options) do if options_table[v.name] then for k2,v2 in pairs(options_table[v.name]) do v[k2] = v2 end v.auto_detected = false end end else print("error: no '"..filename.."' found") print("") print("run 'bam config' to generate") print("run 'bam config help' for configuration options") print("") os.exit(1) end end config.Config = function(self, filename) print("") print("configuration:") if _bam_targets[1] == "print" then self:Load(filename) self:Print() print("") print("notes:") self:OnConfigured() print("") else self:Autodetect() print("") print("notes:") if self:OnConfigured() then self:Save(filename) end print("") end end config.Autodetect = function(self) for k,v in pairs(self.options) do v:Check(self.settings) print(v:FormatDisplay()) self[v.name] = v end end config.PrintHelp = function(self) print("options:") for k,v in pairs(self.options) do if v.PrintHelp then v:PrintHelp() end end end config.Finalize = function(self, filename) if _bam_targets[0] == "config" then if _bam_targets[1] == "help" then self:PrintHelp() os.exit(0) end self:Config(filename) os.exit(0) end self:Load(filename) bam_update_globalstamp(filename) end return config end -- Helper functions -------------------------------------- function DefaultOptionDisplay(option) if not option.value then return "no" end if option.value == 1 or option.value == true then return "yes" end return option.value end function IsNegativeTerm(s) if s == "no" then return true end if s == "false" then return true end if s == "off" then return true end if s == "disable" then return true end if s == "0" then return true end return false end function IsPositiveTerm(s) if s == "yes" then return true end if s == "true" then return true end if s == "on" then return true end if s == "enable" then return true end if s == "1" then return true end return false end function MakeOption(name, value, check, save, display, printhelp) local o = {} o.name = name o.value = value o.Check = check o.Save = save o.auto_detected = true o.FormatDisplay = function(self) local a = "SET" if self.auto_detected then a = "AUTO" end return string.format("%-5s %-20s %s", a, self.name, self:Display()) end o.Display = display o.PrintHelp = printhelp if o.Display == nil then o.Display = DefaultOptionDisplay end return o end -- Test Compile C -------------------------------------- function OptTestCompileC(name, source, compileoptions, desc) local check = function(option, settings) option.value = false if ScriptArgs[option.name] then if IsNegativeTerm(ScriptArgs[option.name]) then option.value = false elseif IsPositiveTerm(ScriptArgs[option.name]) then option.value = true else error(ScriptArgs[option.name].." is not a valid value for option "..option.name) end option.auto_detected = false else if CTestCompile(settings, option.source, option.compileoptions) then option.value = true end end end local save = function(option, output) output:option(option, "value") end local printhelp = function(option) print("\t"..option.name.."=on|off") if option.desc then print("\t\t"..option.desc) end end local o = MakeOption(name, false, check, save, nil, printhelp) o.desc = desc o.source = source o.compileoptions = compileoptions return o end -- OptToggle -------------------------------------- function OptToggle(name, default_value, desc) local check = function(option, settings) if ScriptArgs[option.name] then if IsNegativeTerm(ScriptArgs[option.name]) then option.value = false elseif IsPositiveTerm(ScriptArgs[option.name]) then option.value = true else error(ScriptArgs[option.name].." is not a valid value for option "..option.name) end end end local save = function(option, output) output:option(option, "value") end local printhelp = function(option) print("\t"..option.name.."=on|off") if option.desc then print("\t\t"..option.desc) end end local o = MakeOption(name, default_value, check, save, nil, printhelp) o.desc = desc return o end -- OptInteger -------------------------------------- function OptInteger(name, default_value, desc) local check = function(option, settings) if ScriptArgs[option.name] then option.value = tonumber(ScriptArgs[option.name]) end end local save = function(option, output) output:option(option, "value") end local printhelp = function(option) print("\t"..option.name.."=N") if option.desc then print("\t\t"..option.desc) end end local o = MakeOption(name, default_value, check, save, nil, printhelp) o.desc = desc return o end -- OptString -------------------------------------- function OptString(name, default_value, desc) local check = function(option, settings) if ScriptArgs[option.name] then option.value = ScriptArgs[option.name] end end local save = function(option, output) output:option(option, "value") end local printhelp = function(option) print("\t"..option.name.."=STRING") if option.desc then print("\t\t"..option.desc) end end local o = MakeOption(name, default_value, check, save, nil, printhelp) o.desc = desc return o end -- Find Compiler -------------------------------------- --[[@FUNCTION TODO @END]]-- function OptCCompiler(name, default_driver, default_c, default_cxx, desc) local check = function(option, settings) if ScriptArgs[option.name] then -- set compile driver option.driver = ScriptArgs[option.name] -- set c compiler if ScriptArgs[option.name..".c"] then option.c_compiler = ScriptArgs[option.name..".c"] end -- set c+= compiler if ScriptArgs[option.name..".cxx"] then option.cxx_compiler = ScriptArgs[option.name..".cxx"] end option.auto_detected = false elseif option.driver then -- no need todo anything if we have a driver -- TODO: test if we can find the compiler else if ExecuteSilent("cl") == 0 then option.driver = "cl" elseif ExecuteSilent("g++ -v") == 0 then option.driver = "gcc" else error("no c/c++ compiler found") end end --setup_compiler(option.value) end local apply = function(option, settings) if option.driver == "cl" then SetDriversCL(settings) elseif option.driver == "gcc" then SetDriversGCC(settings) elseif option.driver == "clang" then SetDriversClang(settings) else error(option.driver.." is not a known c/c++ compile driver") end if option.c_compiler then settings.cc.c_compiler = option.c_compiler end if option.cxx_compiler then settings.cc.cxx_compiler = option.cxx_compiler end end local save = function(option, output) output:option(option, "driver") output:option(option, "c_compiler") output:option(option, "cxx_compiler") end local printhelp = function(option) local a = "" if option.desc then a = "for "..option.desc end print("\t"..option.name.."=gcc|cl|clang") print("\t\twhat c/c++ compile driver to use"..a) print("\t"..option.name..".c=FILENAME") print("\t\twhat c compiler executable to use"..a) print("\t"..option.name..".cxx=FILENAME") print("\t\twhat c++ compiler executable to use"..a) end local display = function(option) local s = option.driver if option.c_compiler then s = s .. " c="..option.c_compiler end if option.cxx_compiler then s = s .. " cxx="..option.cxx_compiler end return s end local o = MakeOption(name, nil, check, save, display, printhelp) o.desc = desc o.driver = false o.c_compiler = false o.cxx_compiler = false if default_driver then o.driver = default_driver end if default_c then o.c_compiler = default_c end if default_cxx then o.cxx_compiler = default_cxx end o.Apply = apply return o end -- Option Library -------------------------------------- --[[@FUNCTION TODO @END]]-- function OptLibrary(name, header, desc) local check = function(option, settings) option.value = false option.include_path = false local function check_compile_include(filename, paths) if CTestCompile(settings, "#include <" .. filename .. ">\nint main(){return 0;}", "") then return "" end for k,v in pairs(paths) do if CTestCompile(settings, "#include <" .. filename .. ">\nint main(){return 0;}", "-I"..v) then return v end end return false end if ScriptArgs[option.name] then if IsNegativeTerm(ScriptArgs[option.name]) then option.value = false elseif ScriptArgs[option.name] == "system" then option.value = true else option.value = true option.include_path = ScriptArgs[option.name] end option.auto_detected = false else option.include_path = check_compile_include(option.header, {}) if option.include_path == false then if option.required then print(name.." library not found and is required") error("required library not found") end else option.value = true option.include_path = false end end end local save = function(option, output) output:option(option, "value") output:option(option, "include_path") end local display = function(option) if option.value then if option.include_path then return option.include_path else return "(in system path)" end else return "not found" end end local printhelp = function(option) print("\t"..option.name.."=disable|system|PATH") if option.desc then print("\t\t"..option.desc) end end local o = MakeOption(name, false, check, save, display, printhelp) o.include_path = false o.header = header o.desc = desc return o end ================================================ FILE: data/countryflags/index.json ================================================ {"country codes": {"custom": [ { "id": "SS", "code": 737 }, { "id": "XEN", "code": 901 }, { "id": "XNI", "code": 902 }, { "id": "XSC", "code": 903 }, { "id": "XWA", "code": 904 }, { "id": "default", "code": -1 } ], "ISO 3166-1": [ { "id": "AD", "code": 20 }, { "id": "AE", "code": 784 }, { "id": "AF", "code": 4 }, { "id": "AG", "code": 28 }, { "id": "AI", "code": 660 }, { "id": "AL", "code": 8 }, { "id": "AM", "code": 51 }, { "id": "AO", "code": 24 }, { "id": "AR", "code": 32 }, { "id": "AS", "code": 16 }, { "id": "AT", "code": 40 }, { "id": "AU", "code": 36 }, { "id": "AW", "code": 533 }, { "id": "AX", "code": 248 }, { "id": "AZ", "code": 31 }, { "id": "BA", "code": 70 }, { "id": "BB", "code": 52 }, { "id": "BD", "code": 50 }, { "id": "BE", "code": 56 }, { "id": "BF", "code": 854 }, { "id": "BG", "code": 100 }, { "id": "BH", "code": 48 }, { "id": "BI", "code": 108 }, { "id": "BJ", "code": 204 }, { "id": "BL", "code": 652 }, { "id": "BM", "code": 60 }, { "id": "BN", "code": 96 }, { "id": "BO", "code": 68 }, { "id": "BR", "code": 76 }, { "id": "BS", "code": 44 }, { "id": "BT", "code": 64 }, { "id": "BW", "code": 72 }, { "id": "BY", "code": 112 }, { "id": "BZ", "code": 84 }, { "id": "CA", "code": 124 }, { "id": "CC", "code": 166 }, { "id": "CD", "code": 180 }, { "id": "CF", "code": 140 }, { "id": "CG", "code": 178 }, { "id": "CH", "code": 756 }, { "id": "CI", "code": 384 }, { "id": "CK", "code": 184 }, { "id": "CL", "code": 152 }, { "id": "CM", "code": 120 }, { "id": "CN", "code": 156 }, { "id": "CO", "code": 170 }, { "id": "CR", "code": 188 }, { "id": "CU", "code": 192 }, { "id": "CV", "code": 132 }, { "id": "CW", "code": 531 }, { "id": "CX", "code": 162 }, { "id": "CY", "code": 196 }, { "id": "CZ", "code": 203 }, { "id": "DE", "code": 276 }, { "id": "DJ", "code": 262 }, { "id": "DK", "code": 208 }, { "id": "DM", "code": 212 }, { "id": "DO", "code": 214 }, { "id": "DZ", "code": 12 }, { "id": "EC", "code": 218 }, { "id": "EE", "code": 233 }, { "id": "EG", "code": 818 }, { "id": "EH", "code": 732 }, { "id": "ER", "code": 232 }, { "id": "ES", "code": 724 }, { "id": "ET", "code": 231 }, { "id": "FI", "code": 246 }, { "id": "FJ", "code": 242 }, { "id": "FK", "code": 238 }, { "id": "FM", "code": 583 }, { "id": "FO", "code": 234 }, { "id": "FR", "code": 250 }, { "id": "GA", "code": 266 }, { "id": "GB", "code": 826 }, { "id": "GD", "code": 308 }, { "id": "GE", "code": 268 }, { "id": "GF", "code": 254 }, { "id": "GG", "code": 831 }, { "id": "GH", "code": 288 }, { "id": "GI", "code": 292 }, { "id": "GL", "code": 304 }, { "id": "GM", "code": 270 }, { "id": "GN", "code": 324 }, { "id": "GP", "code": 312 }, { "id": "GQ", "code": 226 }, { "id": "GR", "code": 300 }, { "id": "GS", "code": 239 }, { "id": "GT", "code": 320 }, { "id": "GU", "code": 316 }, { "id": "GW", "code": 624 }, { "id": "GY", "code": 328 }, { "id": "HK", "code": 344 }, { "id": "HN", "code": 340 }, { "id": "HR", "code": 191 }, { "id": "HT", "code": 332 }, { "id": "HU", "code": 348 }, { "id": "ID", "code": 360 }, { "id": "IE", "code": 372 }, { "id": "IL", "code": 376 }, { "id": "IM", "code": 833 }, { "id": "IN", "code": 356 }, { "id": "IO", "code": 86 }, { "id": "IQ", "code": 368 }, { "id": "IR", "code": 364 }, { "id": "IS", "code": 352 }, { "id": "IT", "code": 380 }, { "id": "JE", "code": 832 }, { "id": "JM", "code": 388 }, { "id": "JO", "code": 400 }, { "id": "JP", "code": 392 }, { "id": "KE", "code": 404 }, { "id": "KG", "code": 417 }, { "id": "KH", "code": 116 }, { "id": "KI", "code": 296 }, { "id": "KM", "code": 174 }, { "id": "KN", "code": 659 }, { "id": "KP", "code": 408 }, { "id": "KR", "code": 410 }, { "id": "KW", "code": 414 }, { "id": "KY", "code": 136 }, { "id": "KZ", "code": 398 }, { "id": "LA", "code": 418 }, { "id": "LB", "code": 422 }, { "id": "LC", "code": 662 }, { "id": "LI", "code": 438 }, { "id": "LK", "code": 144 }, { "id": "LR", "code": 430 }, { "id": "LS", "code": 426 }, { "id": "LT", "code": 440 }, { "id": "LU", "code": 442 }, { "id": "LV", "code": 428 }, { "id": "LY", "code": 434 }, { "id": "MA", "code": 504 }, { "id": "MC", "code": 492 }, { "id": "MD", "code": 498 }, { "id": "ME", "code": 499 }, { "id": "MF", "code": 663 }, { "id": "MG", "code": 450 }, { "id": "MH", "code": 584 }, { "id": "MK", "code": 807 }, { "id": "ML", "code": 466 }, { "id": "MM", "code": 104 }, { "id": "MN", "code": 496 }, { "id": "MO", "code": 446 }, { "id": "MP", "code": 580 }, { "id": "MQ", "code": 474 }, { "id": "MR", "code": 478 }, { "id": "MS", "code": 500 }, { "id": "MT", "code": 470 }, { "id": "MU", "code": 480 }, { "id": "MV", "code": 462 }, { "id": "MW", "code": 454 }, { "id": "MX", "code": 484 }, { "id": "MY", "code": 458 }, { "id": "MZ", "code": 508 }, { "id": "NA", "code": 516 }, { "id": "NC", "code": 540 }, { "id": "NE", "code": 562 }, { "id": "NF", "code": 574 }, { "id": "NG", "code": 566 }, { "id": "NI", "code": 558 }, { "id": "NL", "code": 528 }, { "id": "NO", "code": 578 }, { "id": "NP", "code": 524 }, { "id": "NR", "code": 520 }, { "id": "NU", "code": 570 }, { "id": "NZ", "code": 554 }, { "id": "OM", "code": 512 }, { "id": "PA", "code": 591 }, { "id": "PE", "code": 604 }, { "id": "PF", "code": 258 }, { "id": "PG", "code": 598 }, { "id": "PH", "code": 608 }, { "id": "PK", "code": 586 }, { "id": "PL", "code": 616 }, { "id": "PM", "code": 666 }, { "id": "PN", "code": 612 }, { "id": "PR", "code": 630 }, { "id": "PT", "code": 620 }, { "id": "PW", "code": 585 }, { "id": "PY", "code": 600 }, { "id": "QA", "code": 634 }, { "id": "RE", "code": 638 }, { "id": "RO", "code": 642 }, { "id": "RS", "code": 688 }, { "id": "RU", "code": 643 }, { "id": "RW", "code": 646 }, { "id": "SA", "code": 682 }, { "id": "SB", "code": 90 }, { "id": "SC", "code": 690 }, { "id": "SD", "code": 736 }, { "id": "SE", "code": 752 }, { "id": "SG", "code": 702 }, { "id": "SH", "code": 654 }, { "id": "SI", "code": 705 }, { "id": "SK", "code": 703 }, { "id": "SL", "code": 694 }, { "id": "SM", "code": 674 }, { "id": "SN", "code": 686 }, { "id": "SO", "code": 706 }, { "id": "SR", "code": 740 }, { "id": "ST", "code": 678 }, { "id": "SV", "code": 222 }, { "id": "SX", "code": 534 }, { "id": "SY", "code": 760 }, { "id": "SZ", "code": 748 }, { "id": "TC", "code": 796 }, { "id": "TD", "code": 148 }, { "id": "TF", "code": 260 }, { "id": "TG", "code": 768 }, { "id": "TH", "code": 764 }, { "id": "TJ", "code": 762 }, { "id": "TK", "code": 772 }, { "id": "TL", "code": 626 }, { "id": "TM", "code": 795 }, { "id": "TN", "code": 788 }, { "id": "TO", "code": 776 }, { "id": "TR", "code": 792 }, { "id": "TT", "code": 780 }, { "id": "TV", "code": 798 }, { "id": "TW", "code": 158 }, { "id": "TZ", "code": 834 }, { "id": "UA", "code": 804 }, { "id": "UG", "code": 800 }, { "id": "US", "code": 840 }, { "id": "UY", "code": 858 }, { "id": "UZ", "code": 860 }, { "id": "VA", "code": 336 }, { "id": "VC", "code": 670 }, { "id": "VE", "code": 862 }, { "id": "VG", "code": 92 }, { "id": "VI", "code": 850 }, { "id": "VN", "code": 704 }, { "id": "VU", "code": 548 }, { "id": "WF", "code": 876 }, { "id": "WS", "code": 882 }, { "id": "YE", "code": 887 }, { "id": "ZA", "code": 710 }, { "id": "ZM", "code": 894 }, { "id": "ZW", "code": 716 } ], "not used": [ { "id": "AQ", "code": 10 }, { "id": "BQ", "code": 535 }, { "id": "BV", "code": 74 }, { "id": "HM", "code": 334 }, { "id": "PS", "code": 275 }, { "id": "SJ", "code": 744 }, { "id": "UM", "code": 581 }, { "id": "YT", "code": 175 } ]}, } ================================================ FILE: data/editor/automap/grass_doodads.json ================================================ {"doodads": [ {"vegetation": { "rules": [ { "startid": 1, "endid": 35, "ry": -3, "Location": "floor", "random": 25 }, { "startid": 44, "endid": 45, "ry": -1, "location": "floor", "random": 25 }, { "startid": 56, "endid": 74, "ry": -2, "location": "floor", "random": 35 }, { "startid": 59, "endid": 77, "ry": -2, "location": "floor", "random": 35 }, { "startid": 48, "endid": 87, "ry": -3, "location": "floor", "random": 50 }, { "startid": 96, "endid": 164, "ry": -5, "location": "floor", "random": 50 }, { "startid": 101, "endid": 168, "ry": -5, "location": "floor", "random": 50 }, { "startid": 90, "endid": 175, "ry": -6, "location": "floor", "random": 50 }] } }, {"grass": { "rules": [ { "startid": 42, "endid": 42, "ry": -1, "location": "floor", "random": 1 }] } }] } ================================================ FILE: data/editor/automap/grass_main.json ================================================ {"tileset": [ {"grass": { "basetile": 1, "rules": [ { "index": 2, "condition": [ {"x": 0, "y": 1, "value": "full"}, {"x": 0, "y": -1, "value": "full"}, {"x": 1, "y": 0, "value": "full"}, {"x": -1, "y": 0, "value": "full"} ], "random": 150 }, { "index": 3, "condition": [ {"x": 0, "y": 1, "value": "full"}, {"x": 0, "y": -1, "value": "full"}, {"x": 1, "y": 0, "value": "full"}, {"x": -1, "y": 0, "value": "full"} ], "random": 150 }, { "index": 66, "condition": [ {"x": 0, "y": 1, "value": "full"}, {"x": 0, "y": -1, "value": "full"}, {"x": 1, "y": 0, "value": "full"}, {"x": -1, "y": 0, "value": "full"} ], "random": 150 }, { "index": 67, "condition": [ {"x": 0, "y": 1, "value": "full"}, {"x": 0, "y": -1, "value": "full"}, {"x": 1, "y": 0, "value": "full"}, {"x": -1, "y": 0, "value": "full"} ], "random": 150 }, { "index": 68, "condition": [ {"x": 0, "y": 1, "value": "full"}, {"x": 0, "y": -1, "value": "full"}, {"x": 1, "y": 0, "value": "full"}, {"x": -1, "y": 0, "value": "full"} ], "random": 150 }, { "index": 16, "condition": [ {"x": 0, "y": -1, "value": "empty"} ] }, { "index": 21, "condition": [ {"x": 1, "y": 0, "value": "empty"} ] }, { "index": 52, "condition": [ {"x": 0, "y": 1, "value": "empty"} ] }, { "index": 20, "condition": [ {"x": -1, "y": 0, "value": "empty"} ] }, { "index": 5, "condition": [ {"x": 0, "y": -1, "value": "empty"}, {"x": 1, "y": 0, "value": "empty"} ] }, { "index": 4, "condition": [ {"x": 0, "y": -1, "value": "empty"}, {"x": -1, "y": 0, "value": "empty"} ] }, { "index": 36, "condition": [ {"x": 0, "y": 1, "value": "empty"}, {"x": -1, "y": 0, "value": "empty"} ] }, { "index": 37, "condition": [ {"x": 0, "y": 1, "value": "empty"}, {"x": 1, "y": 0, "value": "empty"} ] }, { "index": 54, "condition": [ {"x": -1, "y": 1, "value": "empty"}, {"x": -1, "y": 0, "value": "full"}, {"x": 0, "y": 1, "value": "full"} ] }, { "index": 53, "condition": [ {"x": 1, "y": 1, "value": "empty"}, {"x": 1, "y": 0, "value": "full"}, {"x": 0, "y": 1, "value": "full"} ] }, { "index": 49, "condition": [ {"x": 1, "y": -1, "value": "empty"}, {"x": 1, "y": 0, "value": "full"}, {"x": 0, "y": -1, "value": "full"} ] }, { "index": 48, "condition": [ {"x": -1, "y": -1, "value": "empty"}, {"x": -1, "y": 0, "value": "full"}, {"x": 0, "y": -1, "value": "full"} ] }, { "index": 22, "condition": [ {"x": -1, "y": 0, "value": "empty"}, {"x": -1, "y": 1, "value": "full"}, {"x": 0, "y": 1, "value": "full"} ] }, { "index": 38, "condition": [ {"x": 1, "y": 0, "value": "empty"}, {"x": 1, "y": 1, "value": "full"}, {"x": 0, "y": 1, "value": "full"} ] }, { "index": 33, "condition": [ {"x": 0, "y": -1, "value": "empty"}, {"x": 1, "y": 0, "value": "empty"}, {"x": 1, "y": 1, "value": "full"}, ] }, { "index": 32, "condition": [ {"x": 0, "y": -1, "value": "empty"}, {"x": -1, "y": 0, "value": "empty"}, {"x": -1, "y": 1, "value": "full"} ] }] } }, {"cave": { "basetile": 13, "rules": [ { "index": 29, "condition": [ {"x": 0, "y": 1, "value": "full"}, {"x": 0, "y": -1, "value": "full"}, {"x": 1, "y": 0, "value": "full"}, {"x": -1, "y": 0, "value": "full"} ], "random": 150 }, { "index": 42, "condition": [ {"x": 0, "y": 1, "value": "full"}, {"x": 0, "y": -1, "value": "full"}, {"x": 1, "y": 0, "value": "full"}, {"x": -1, "y": 0, "value": "full"} ], "random": 150 }, { "index": 43, "condition": [ {"x": 0, "y": 1, "value": "full"}, {"x": 0, "y": -1, "value": "full"}, {"x": 1, "y": 0, "value": "full"}, {"x": -1, "y": 0, "value": "full"} ], "random": 150 }, { "index": 44, "condition": [ {"x": 0, "y": 1, "value": "full"}, {"x": 0, "y": -1, "value": "full"}, {"x": 1, "y": 0, "value": "full"}, {"x": -1, "y": 0, "value": "full"} ], "random": 150 }, { "index": 45, "condition": [ {"x": 0, "y": 1, "value": "full"}, {"x": 0, "y": -1, "value": "full"}, {"x": 1, "y": 0, "value": "full"}, {"x": -1, "y": 0, "value": "full"} ], "random": 150 }, { "index": 26, "condition": [ {"x": 0, "y": -1, "value": "empty"} ] }, { "index": 25, "condition": [ {"x": 1, "y": 0, "value": "empty"} ] }, { "index": 10, "condition": [ {"x": 0, "y": 1, "value": "empty"} ] }, { "index": 24, "condition": [ {"x": -1, "y": 0, "value": "empty"} ] }, { "index": 9, "condition": [ {"x": 0, "y": -1, "value": "empty"}, {"x": 1, "y": 0, "value": "empty"} ] }, { "index": 8, "condition": [ {"x": 0, "y": -1, "value": "empty"}, {"x": -1, "y": 0, "value": "empty"} ] }, { "index": 40, "condition": [ {"x": 0, "y": 1, "value": "empty"}, {"x": -1, "y": 0, "value": "empty"} ] }, { "index": 41, "condition": [ {"x": 0, "y": 1, "value": "empty"}, {"x": 1, "y": 0, "value": "empty"} ] }, { "index": 12, "condition": [ {"x": -1, "y": 1, "value": "empty"}, {"x": -1, "y": 0, "value": "full"}, {"x": 0, "y": 1, "value": "full"} ] }, { "index": 11, "condition": [ {"x": 1, "y": 1, "value": "empty"}, {"x": 1, "y": 0, "value": "full"}, {"x": 0, "y": 1, "value": "full"} ] }, { "index": 27, "condition": [ {"x": 1, "y": -1, "value": "empty"}, {"x": 1, "y": 0, "value": "full"}, {"x": 0, "y": -1, "value": "full"} ] }, { "index": 28, "condition": [ {"x": -1, "y": -1, "value": "empty"}, {"x": -1, "y": 0, "value": "full"}, {"x": 0, "y": -1, "value": "full"} ] }] } }] } ================================================ FILE: data/editor/desert_main.rules ================================================ [Desert] Index 1 BaseTile #random Index 2 Pos 0 1 FULL Pos 0 -1 FULL Pos 1 0 FULL Pos -1 0 FULL Random 150 Index 3 Pos 0 1 FULL Pos 0 -1 FULL Pos 1 0 FULL Pos -1 0 FULL Random 150 #top Index 16 Pos 0 -1 EMPTY #right Index 17 Pos 1 0 EMPTY #bottom Index 18 Pos 0 1 EMPTY #left Index 19 Pos -1 0 EMPTY #corner top-right Index 33 Pos 0 -1 EMPTY Pos 1 0 EMPTY #corner top-left Index 32 Pos 0 -1 EMPTY Pos -1 0 EMPTY #corner bottom-left Index 35 Pos 0 1 EMPTY Pos -1 0 EMPTY #corner bottom-right Index 34 Pos 0 1 EMPTY Pos 1 0 EMPTY #inside corner top-right Index 51 Pos -1 1 EMPTY Pos -1 0 FULL Pos 0 1 FULL #inside corner top-left Index 50 Pos 1 1 EMPTY Pos 1 0 FULL Pos 0 1 FULL #inside corner bottom-left Index 49 Pos 1 -1 EMPTY Pos 1 0 FULL Pos 0 -1 FULL #inside corner bottom-right Index 48 Pos -1 -1 EMPTY Pos -1 0 FULL Pos 0 -1 FULL [Mine] Index 81 BaseTile #random Index 82 Pos 0 1 FULL Pos 0 -1 FULL Pos 1 0 FULL Pos -1 0 FULL Random 500 Index 83 Pos 0 1 FULL Pos 0 -1 FULL Pos 1 0 FULL Pos -1 0 FULL Random 500 Index 84 Pos 0 1 FULL Pos 0 -1 FULL Pos 1 0 FULL Pos -1 0 FULL Random 500 Index 85 Pos 0 1 FULL Pos 0 -1 FULL Pos 1 0 FULL Pos -1 0 FULL Random 500 Index 86 Pos 0 1 FULL Pos 0 -1 FULL Pos 1 0 FULL Pos -1 0 FULL Random 500 Index 100 Pos 0 1 FULL Pos 0 -1 FULL Pos 1 0 FULL Pos -1 0 FULL Random 500 Index 101 Pos 0 1 FULL Pos 0 -1 FULL Pos 1 0 FULL Pos -1 0 FULL Random 500 Index 102 Pos 0 1 FULL Pos 0 -1 FULL Pos 1 0 FULL Pos -1 0 FULL Random 500 Index 117 Pos 0 1 FULL Pos 0 -1 FULL Pos 1 0 FULL Pos -1 0 FULL Random 500 Index 118 Pos 0 1 FULL Pos 0 -1 FULL Pos 1 0 FULL Pos -1 0 FULL Random 500 Index 133 Pos 0 1 FULL Pos 0 -1 FULL Pos 1 0 FULL Pos -1 0 FULL Random 500 Index 134 Pos 0 1 FULL Pos 0 -1 FULL Pos 1 0 FULL Pos -1 0 FULL Random 500 #top Index 96 Pos 0 -1 EMPTY #right Index 97 Pos 1 0 EMPTY #bottom Index 98 Pos 0 1 EMPTY #left Index 99 Pos -1 0 EMPTY #corner top-right Index 113 Pos 0 -1 EMPTY Pos 1 0 EMPTY #corner top-left Index 112 Pos 0 -1 EMPTY Pos -1 0 EMPTY #corner bottom-left Index 115 Pos 0 1 EMPTY Pos -1 0 EMPTY #corner bottom-right Index 114 Pos 0 1 EMPTY Pos 1 0 EMPTY #inside corner top-right Index 131 Pos -1 1 EMPTY Pos -1 0 FULL Pos 0 1 FULL #inside corner top-left Index 130 Pos 1 1 EMPTY Pos 1 0 FULL Pos 0 1 FULL #inside corner bottom-left Index 129 Pos 1 -1 EMPTY Pos 1 0 FULL Pos 0 -1 FULL #inside corner bottom-right Index 128 Pos -1 -1 EMPTY Pos -1 0 FULL Pos 0 -1 FULL ================================================ FILE: data/editor/grass_main.rules ================================================ [Grass] Index 1 BaseTile #random bones Index 2 Pos 0 1 FULL Pos 0 -1 FULL Pos 1 0 FULL Pos -1 0 FULL Random 150 Index 3 Pos 0 1 FULL Pos 0 -1 FULL Pos 1 0 FULL Pos -1 0 FULL Random 150 Index 66 Pos 0 1 FULL Pos 0 -1 FULL Pos 1 0 FULL Pos -1 0 FULL Random 150 Index 67 Pos 0 1 FULL Pos 0 -1 FULL Pos 1 0 FULL Pos -1 0 FULL Random 150 Index 68 Pos 0 1 FULL Pos 0 -1 FULL Pos 1 0 FULL Pos -1 0 FULL Random 150 #--------- #top Index 16 Pos 0 -1 EMPTY #right Index 21 Pos 1 0 EMPTY #bottom Index 52 Pos 0 1 EMPTY #left Index 20 Pos -1 0 EMPTY #corner top-right Index 5 Pos 0 -1 EMPTY Pos 1 0 EMPTY #corner top-left Index 4 Pos 0 -1 EMPTY Pos -1 0 EMPTY #corner bottom-left Index 36 Pos 0 1 EMPTY Pos -1 0 EMPTY #corner bottom-right Index 37 Pos 0 1 EMPTY Pos 1 0 EMPTY #inside corner top-right Index 54 Pos -1 1 EMPTY Pos -1 0 FULL Pos 0 1 FULL #inside corner top-left Index 53 Pos 1 1 EMPTY Pos 1 0 FULL Pos 0 1 FULL #inside corner bottom-left Index 49 Pos 1 -1 EMPTY Pos 1 0 FULL Pos 0 -1 FULL #inside corner bottom-right Index 48 Pos -1 -1 EMPTY Pos -1 0 FULL Pos 0 -1 FULL #right bottom Index 22 Pos -1 0 EMPTY Pos -1 1 FULL Pos 0 1 FULL #left bottom Index 38 Pos 1 0 EMPTY Pos 1 1 FULL Pos 0 1 FULL #top corner right 2 Index 33 Pos 0 -1 EMPTY Pos 1 0 EMPTY Pos 1 1 FULL #top corner left 2 Index 32 Pos 0 -1 EMPTY Pos -1 0 EMPTY Pos -1 1 FULL [Cave] Index 13 BaseTile #random bones Index 29 Pos 0 1 FULL Pos 0 -1 FULL Pos 1 0 FULL Pos -1 0 FULL Random 150 Index 42 Pos 0 1 FULL Pos 0 -1 FULL Pos 1 0 FULL Pos -1 0 FULL Random 150 Index 43 Pos 0 1 FULL Pos 0 -1 FULL Pos 1 0 FULL Pos -1 0 FULL Random 150 Index 44 Pos 0 1 FULL Pos 0 -1 FULL Pos 1 0 FULL Pos -1 0 FULL Random 150 Index 45 Pos 0 1 FULL Pos 0 -1 FULL Pos 1 0 FULL Pos -1 0 FULL Random 150 #--------- #top Index 26 Pos 0 -1 EMPTY #right Index 25 Pos 1 0 EMPTY #bottom Index 10 Pos 0 1 EMPTY #left Index 24 Pos -1 0 EMPTY #corner top-right Index 9 Pos 0 -1 EMPTY Pos 1 0 EMPTY #corner top-left Index 8 Pos 0 -1 EMPTY Pos -1 0 EMPTY #corner bottom-left Index 40 Pos 0 1 EMPTY Pos -1 0 EMPTY #corner bottom-right Index 41 Pos 0 1 EMPTY Pos 1 0 EMPTY #inside corner top-right Index 12 Pos -1 1 EMPTY Pos -1 0 FULL Pos 0 1 FULL #inside corner top-left Index 11 Pos 1 1 EMPTY Pos 1 0 FULL Pos 0 1 FULL #inside corner bottom-left Index 27 Pos 1 -1 EMPTY Pos 1 0 FULL Pos 0 -1 FULL #inside corner bottom-right Index 28 Pos -1 -1 EMPTY Pos -1 0 FULL Pos 0 -1 FULL ================================================ FILE: data/editor/jungle_main.rules ================================================ [Jungle] Index 1 BaseTile #random bricks Index 66 Pos 0 1 FULL Pos 0 -1 FULL Pos 1 0 FULL Pos -1 0 FULL Random 200 Index 67 Pos 0 1 FULL Pos 0 -1 FULL Pos 1 0 FULL Pos -1 0 FULL Random 200 #top Index 16 Pos 0 -1 EMPTY Index 96 Pos 0 -1 EMPTY Random 15 Index 97 Pos 0 -1 EMPTY Random 15 Index 98 Pos 0 -1 EMPTY Random 15 #right Index 21 Pos 1 0 EMPTY #bottom Index 52 Pos 0 1 EMPTY Index 99 Pos 0 1 EMPTY Random 10 Index 100 Pos 0 1 EMPTY Random 10 Index 101 Pos 0 1 EMPTY Random 10 #left Index 21 XFLIP Pos -1 0 EMPTY #corner top-right Index 5 Pos 0 -1 EMPTY Pos 1 0 EMPTY #corner top-left Index 5 XFLIP Pos 0 -1 EMPTY Pos -1 0 EMPTY #corner bottom-left Index 37 XFLIP Pos 0 1 EMPTY Pos -1 0 EMPTY Index 39 XFLIP Pos 0 1 EMPTY Pos -1 0 EMPTY Random 2 #corner bottom-right Index 37 Pos 0 1 EMPTY Pos 1 0 EMPTY Index 39 Pos 0 1 EMPTY Pos 1 0 EMPTY Random 2 #inside corner top-right Index 54 Pos -1 1 EMPTY Pos -1 0 FULL Pos 0 1 FULL Index 53 XFLIP Pos -1 1 EMPTY Pos -1 0 FULL Pos 0 1 FULL Random 2 #inside corner top-left Index 54 XFLIP Pos 1 1 EMPTY Pos 1 0 FULL Pos 0 1 FULL Index 53 Pos 1 1 EMPTY Pos 1 0 FULL Pos 0 1 FULL Random 2 #inside corner bottom-left Index 48 XFLIP Pos 1 -1 EMPTY Pos 1 0 FULL Pos 0 -1 FULL Index 49 Pos 1 -1 EMPTY Pos 1 0 FULL Pos 0 -1 FULL Random 3 Index 50 YFLIP Pos 1 -1 EMPTY Pos 1 0 FULL Pos 0 -1 FULL Random 3 #inside corner bottom-right Index 48 Pos -1 -1 EMPTY Pos -1 0 FULL Pos 0 -1 FULL Index 49 XFLIP Pos -1 -1 EMPTY Pos -1 0 FULL Pos 0 -1 FULL Random 3 Index 51 YFLIP Pos -1 -1 EMPTY Pos -1 0 FULL Pos 0 -1 FULL Random 3 #right bottom Index 22 Pos -1 0 EMPTY Pos -1 1 FULL Pos 0 1 FULL #left bottom Index 22 XFLIP Pos 1 0 EMPTY Pos 1 1 FULL Pos 0 1 FULL #top corner right 2 Index 33 Pos 0 -1 EMPTY Pos 1 0 EMPTY Pos 1 1 FULL #top corner left 2 Index 32 Pos 0 -1 EMPTY Pos -1 0 EMPTY Pos -1 1 FULL [Jungle dark] Index 13 BaseTile #random bricks Index 42 Pos 0 1 FULL Pos 0 -1 FULL Pos 1 0 FULL Pos -1 0 FULL Random 150 Index 43 Pos 0 1 FULL Pos 0 -1 FULL Pos 1 0 FULL Pos -1 0 FULL Random 150 Index 44 Pos 0 1 FULL Pos 0 -1 FULL Pos 1 0 FULL Pos -1 0 FULL Random 150 Index 45 Pos 0 1 FULL Pos 0 -1 FULL Pos 1 0 FULL Pos -1 0 FULL Random 150 #--------- #top Index 26 Pos 0 -1 EMPTY #right Index 25 Pos 1 0 EMPTY #bottom Index 10 Pos 0 1 EMPTY #left Index 24 Pos -1 0 EMPTY #corner top-right Index 9 Pos 0 -1 EMPTY Pos 1 0 EMPTY #corner top-left Index 8 Pos 0 -1 EMPTY Pos -1 0 EMPTY #corner bottom-left Index 40 Pos 0 1 EMPTY Pos -1 0 EMPTY #corner bottom-right Index 41 Pos 0 1 EMPTY Pos 1 0 EMPTY #inside corner top-right Index 12 Pos -1 1 EMPTY Pos -1 0 FULL Pos 0 1 FULL #inside corner top-left Index 11 Pos 1 1 EMPTY Pos 1 0 FULL Pos 0 1 FULL #inside corner bottom-left Index 27 Pos 1 -1 EMPTY Pos 1 0 FULL Pos 0 -1 FULL #inside corner bottom-right Index 28 Pos -1 -1 EMPTY Pos -1 0 FULL Pos 0 -1 FULL ================================================ FILE: data/editor/winter_main.rules ================================================ [Winter] Index 1 BaseTile #top Index 17 Pos 0 -1 EMPTY Index 18 Pos 0 -1 EMPTY Pos -1 0 INDEX 17 Index 19 Pos 0 -1 EMPTY Pos -1 0 INDEX 18 #bottom Index 97 Pos 0 1 EMPTY Index 98 Pos 0 1 EMPTY Pos -1 0 INDEX 97 Index 99 Pos 0 1 EMPTY Pos -1 0 INDEX 98 #right Index 2 XFLIP Pos 1 0 EMPTY #left Index 2 Pos -1 0 EMPTY #corner top right Index 20 Pos 0 -1 EMPTY Pos 1 0 EMPTY Index 24 Pos 0 -1 EMPTY Pos 1 0 EMPTY Pos -1 0 INDEX 17 #corner top left Index 16 Pos 0 -1 EMPTY Pos -1 0 EMPTY #corner bottom right Index 100 Pos 0 1 EMPTY Pos 1 0 EMPTY #corner bottom left Index 96 Pos 0 1 EMPTY Pos -1 0 EMPTY #inside corner top right Index 8 Pos 0 1 FULL Pos -1 0 FULL Pos -1 1 EMPTY #inside corner top left Index 7 Pos 0 1 FULL Pos 1 0 FULL Pos 1 1 EMPTY #inside corner bottom right Index 4 Pos 0 -1 FULL Pos -1 0 FULL Pos -1 -1 EMPTY #inside corner bottom left Index 3 Pos 0 -1 FULL Pos 1 0 FULL Pos 1 -1 EMPTY #one tile height Index 113 Pos 0 1 EMPTY Pos 0 -1 EMPTY Index 114 Pos 0 1 EMPTY Pos 0 -1 EMPTY Pos -1 0 INDEX 113 Index 115 Pos 0 1 EMPTY Pos 0 -1 EMPTY Pos -1 0 INDEX 114 #one tile height right Index 116 Pos 0 1 EMPTY Pos 0 -1 EMPTY Pos 1 0 EMPTY Index 120 Pos 0 1 EMPTY Pos 0 -1 EMPTY Pos 1 0 EMPTY Pos -1 0 INDEX 113 #one tile height left Index 112 Pos 0 1 EMPTY Pos 0 -1 EMPTY Pos -1 0 EMPTY #one tile height link right Index 6 Pos -1 -1 EMPTY Pos -1 0 FULL Pos 0 -1 FULL Pos -1 1 EMPTY #one tile height link left Index 5 Pos 1 -1 EMPTY Pos 1 0 FULL Pos 0 -1 FULL Pos 1 1 EMPTY [Winter dark] Index 177 BaseTile #bottom Index 194 Pos 0 1 EMPTY Index 195 Pos 0 1 EMPTY Pos -1 0 INDEX 194 Index 196 Pos 0 1 EMPTY Pos -1 0 INDEX 195 #right Index 178 XFLIP Pos 1 0 EMPTY #left Index 178 Pos -1 0 EMPTY #corner bottom right Index 197 Pos 0 1 EMPTY Pos 1 0 EMPTY #corner bottom left Index 193 Pos 0 1 EMPTY Pos -1 0 EMPTY #inside corner top right Index 180 Pos 0 1 FULL Pos -1 0 FULL Pos -1 1 EMPTY #inside corner top left Index 179 Pos 0 1 FULL Pos 1 0 FULL Pos 1 1 EMPTY ================================================ FILE: data/fonts/LICENSE ================================================ Fonts are (c) Bitstream (see below). DejaVu changes are in public domain. Glyphs imported from Arev fonts are (c) Tavmjong Bah (see below) Bitstream Vera Fonts Copyright ------------------------------ Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera is a trademark of Bitstream, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of the fonts accompanying this license ("Fonts") and associated documentation files (the "Font Software"), to reproduce and distribute the Font Software, including without limitation the rights to use, copy, merge, publish, distribute, and/or sell copies of the Font Software, and to permit persons to whom the Font Software is furnished to do so, subject to the following conditions: The above copyright and trademark notices and this permission notice shall be included in all copies of one or more of the Font Software typefaces. The Font Software may be modified, altered, or added to, and in particular the designs of glyphs or characters in the Fonts may be modified and additional glyphs or characters may be added to the Fonts, only if the fonts are renamed to names not containing either the words "Bitstream" or the word "Vera". This License becomes null and void to the extent applicable to Fonts or Font Software that has been modified and is distributed under the "Bitstream Vera" names. The Font Software may be sold as part of a larger software package but no copy of one or more of the Font Software typefaces may be sold by itself. THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE. Except as contained in this notice, the names of Gnome, the Gnome Foundation, and Bitstream Inc., shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Font Software without prior written authorization from the Gnome Foundation or Bitstream Inc., respectively. For further information, contact: fonts at gnome dot org. Arev Fonts Copyright ------------------------------ Copyright (c) 2006 by Tavmjong Bah. All Rights Reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of the fonts accompanying this license ("Fonts") and associated documentation files (the "Font Software"), to reproduce and distribute the modifications to the Bitstream Vera Font Software, including without limitation the rights to use, copy, merge, publish, distribute, and/or sell copies of the Font Software, and to permit persons to whom the Font Software is furnished to do so, subject to the following conditions: The above copyright and trademark notices and this permission notice shall be included in all copies of one or more of the Font Software typefaces. The Font Software may be modified, altered, or added to, and in particular the designs of glyphs or characters in the Fonts may be modified and additional glyphs or characters may be added to the Fonts, only if the fonts are renamed to names not containing either the words "Tavmjong Bah" or the word "Arev". This License becomes null and void to the extent applicable to Fonts or Font Software that has been modified and is distributed under the "Tavmjong Bah Arev" names. The Font Software may be sold as part of a larger software package but no copy of one or more of the Font Software typefaces may be sold by itself. THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL TAVMJONG BAH BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE. Except as contained in this notice, the name of Tavmjong Bah shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Font Software without prior written authorization from Tavmjong Bah. For further information, contact: tavmjong @ free . fr. $Id: LICENSE 2133 2007-11-28 02:46:28Z lechimp $ ================================================ FILE: data/fonts/VERSION ================================================ 2.33 ================================================ FILE: data/skins/bluekitty.json ================================================ {"skin": { "body": { "filename": "kitty", "custom_colors": "true", "hue": 132, "sat": 118, "lgt": 184 }, "tattoo": { "filename": "whisker", "custom_colors": "true", "hue": 130, "sat": 109, "lgt": 219, "alp": 255 }, "hands": { "filename": "standard", "custom_colors": "true", "hue": 120, "sat": 82, "lgt": 235 }, "feet": { "filename": "standard", "custom_colors": "true", "hue": 120, "sat": 82, "lgt": 235 }, "eyes": { "filename": "standard", "custom_colors": "false" }} } ================================================ FILE: data/skins/bluestripe.json ================================================ {"skin": { "body": { "filename": "standard", "custom_colors": "true", "hue": 155, "sat": 116, "lgt": 122 }, "tattoo": { "filename": "stripes", "custom_colors": "false" }, "hands": { "filename": "standard", "custom_colors": "true", "hue": 11, "sat": 117, "lgt": 0 }, "feet": { "filename": "standard", "custom_colors": "true", "hue": 29, "sat": 173, "lgt": 87 }, "eyes": { "filename": "standard", "custom_colors": "false" }} } ================================================ FILE: data/skins/brownbear.json ================================================ {"skin": { "body": { "filename": "bear", "custom_colors": "true", "hue": 16, "sat": 133, "lgt": 121 }, "tattoo": { "filename": "bear", "custom_colors": "true", "hue": 17, "sat": 110, "lgt": 168, "alp": 255 }, "decoration": { "filename": "hair", "custom_colors": "false" }, "hands": { "filename": "standard", "custom_colors": "true", "hue": 16, "sat": 133, "lgt": 121 }, "feet": { "filename": "standard", "custom_colors": "true", "hue": 17, "sat": 129, "lgt": 38 }, "eyes": { "filename": "standard", "custom_colors": "false" }} } ================================================ FILE: data/skins/cammo.json ================================================ {"skin": { "body": { "filename": "standard", "custom_colors": "true", "hue": 81, "sat": 101, "lgt": 70 }, "tattoo": { "filename": "cammo2", "custom_colors": "true", "hue": 76, "sat": 97, "lgt": 45, "alp": 255 }, "hands": { "filename": "standard", "custom_colors": "true", "hue": 11, "sat": 117, "lgt": 0 }, "feet": { "filename": "standard", "custom_colors": "true", "hue": 29, "sat": 173, "lgt": 87 }, "eyes": { "filename": "standard", "custom_colors": "false" }} } ================================================ FILE: data/skins/cammostripes.json ================================================ {"skin": { "body": { "filename": "standard", "custom_colors": "true", "hue": 81, "sat": 101, "lgt": 70 }, "tattoo": { "filename": "cammostripes", "custom_colors": "true", "hue": 29, "sat": 142, "lgt": 0, "alp": 255 }, "hands": { "filename": "standard", "custom_colors": "true", "hue": 11, "sat": 117, "lgt": 0 }, "feet": { "filename": "standard", "custom_colors": "true", "hue": 29, "sat": 173, "lgt": 87 }, "eyes": { "filename": "standard", "custom_colors": "false" }} } ================================================ FILE: data/skins/coala.json ================================================ {"skin": { "body": { "filename": "bear", "custom_colors": "true", "hue": 0, "sat": 0, "lgt": 184 }, "tattoo": { "filename": "bear", "custom_colors": "true", "hue": 21, "sat": 12, "lgt": 226, "alp": 255 }, "decoration": { "filename": "hair", "custom_colors": "false" }, "hands": { "filename": "standard", "custom_colors": "true", "hue": 0, "sat": 0, "lgt": 184 }, "feet": { "filename": "standard", "custom_colors": "true", "hue": 149, "sat": 4, "lgt": 71 }, "eyes": { "filename": "standard", "custom_colors": "false" }} } ================================================ FILE: data/skins/default.json ================================================ {"skin": { "body": { "filename": "standard", "custom_colors": "true", "hue": 27, "sat": 111, "lgt": 116 }, "hands": { "filename": "standard", "custom_colors": "true", "hue": 27, "sat": 117, "lgt": 158 }, "feet": { "filename": "standard", "custom_colors": "true", "hue": 28, "sat": 135, "lgt": 62 }, "eyes": { "filename": "standard", "custom_colors": "false" }} } ================================================ FILE: data/skins/limekitty.json ================================================ {"skin": { "body": { "filename": "kitty", "custom_colors": "true", "hue": 70, "sat": 98, "lgt": 195 }, "tattoo": { "filename": "whisker", "custom_colors": "true", "hue": 69, "sat": 98, "lgt": 224, "alp": 255 }, "hands": { "filename": "standard", "custom_colors": "true", "hue": 58, "sat": 104, "lgt": 239 }, "feet": { "filename": "standard", "custom_colors": "true", "hue": 58, "sat": 104, "lgt": 239 }, "eyes": { "filename": "standard", "custom_colors": "false" }} } ================================================ FILE: data/skins/pinky.json ================================================ {"skin": { "body": { "filename": "standard", "custom_colors": "true", "hue": 242, "sat": 201, "lgt": 187 }, "tattoo": { "filename": "whisker", "custom_colors": "true", "hue": 243, "sat": 198, "lgt": 214, "alp": 255 }, "hands": { "filename": "standard", "custom_colors": "true", "hue": 229, "sat": 137, "lgt": 218 }, "feet": { "filename": "standard", "custom_colors": "true", "hue": 229, "sat": 137, "lgt": 218 }, "eyes": { "filename": "standard", "custom_colors": "false" }} } ================================================ FILE: data/skins/redbopp.json ================================================ {"skin": { "body": { "filename": "standard", "custom_colors": "true", "hue": 246, "sat": 216, "lgt": 108 }, "tattoo": { "filename": "donny", "custom_colors": "true", "hue": 2, "sat": 217, "lgt": 202, "alp": 255 }, "decoration": { "filename": "unibop", "custom_colors": "true", "hue": 246, "sat": 216, "lgt": 108 }, "hands": { "filename": "standard", "custom_colors": "true", "hue": 246, "sat": 216, "lgt": 108 }, "feet": { "filename": "standard", "custom_colors": "true", "hue": 116, "sat": 85, "lgt": 233 }, "eyes": { "filename": "standard", "custom_colors": "false" }} } ================================================ FILE: data/skins/redstripe.json ================================================ {"skin": { "body": { "filename": "standard", "custom_colors": "true", "hue": 248, "sat": 214, "lgt": 123 }, "tattoo": { "filename": "stripe", "custom_colors": "false" }, "hands": { "filename": "standard", "custom_colors": "true", "hue": 0, "sat": 0, "lgt": 184 }, "feet": { "filename": "standard", "custom_colors": "true", "hue": 149, "sat": 4, "lgt": 71 }, "eyes": { "filename": "standard", "custom_colors": "false" }} } ================================================ FILE: data/skins/saddo.json ================================================ {"skin": { "body": { "filename": "standard", "custom_colors": "true", "hue": 109, "sat": 109, "lgt": 127 }, "tattoo": { "filename": "saddo", "custom_colors": "true", "hue": 108, "sat": 54, "lgt": 68, "alp": 255 }, "hands": { "filename": "standard", "custom_colors": "true", "hue": 55, "sat": 141, "lgt": 170 }, "feet": { "filename": "standard", "custom_colors": "true", "hue": 88, "sat": 97, "lgt": 119 }, "eyes": { "filename": "standard", "custom_colors": "false" }} } ================================================ FILE: data/skins/toptri.json ================================================ {"skin": { "body": { "filename": "standard", "custom_colors": "true", "hue": 93, "sat": 95, "lgt": 163 }, "tattoo": { "filename": "toptri", "custom_colors": "false" }, "hands": { "filename": "standard", "custom_colors": "true", "hue": 55, "sat": 141, "lgt": 170 }, "feet": { "filename": "standard", "custom_colors": "true", "hue": 88, "sat": 97, "lgt": 119 }, "eyes": { "filename": "standard", "custom_colors": "false" }} } ================================================ FILE: data/skins/twinbop.json ================================================ {"skin": { "body": { "filename": "standard", "custom_colors": "true", "hue": 233, "sat": 158, "lgt": 183 }, "tattoo": { "filename": "duodonny", "custom_colors": "true", "hue": 231, "sat": 146, "lgt": 218, "alp": 255 }, "decoration": { "filename": "twinbopp", "custom_colors": "true", "hue": 233, "sat": 158, "lgt": 183 }, "hands": { "filename": "standard", "custom_colors": "true", "hue": 233, "sat": 158, "lgt": 183 }, "feet": { "filename": "standard", "custom_colors": "true", "hue": 0, "sat": 146, "lgt": 224 }, "eyes": { "filename": "standard", "custom_colors": "false" }} } ================================================ FILE: data/skins/twintri.json ================================================ {"skin": { "body": { "filename": "standard", "custom_colors": "true", "hue": 52, "sat": 156, "lgt": 124 }, "tattoo": { "filename": "twintri", "custom_colors": "true", "hue": 40, "sat": 222, "lgt": 227, "alp": 255 }, "hands": { "filename": "standard", "custom_colors": "true", "hue": 0, "sat": 0, "lgt": 185 }, "feet": { "filename": "standard", "custom_colors": "true", "hue": 147, "sat": 4, "lgt": 72 }, "eyes": { "filename": "standard", "custom_colors": "false" }} } ================================================ FILE: data/skins/warpaint.json ================================================ {"skin": { "body": { "filename": "standard", "custom_colors": "true", "hue": 29, "sat": 173, "lgt": 87 }, "tattoo": { "filename": "warpaint", "custom_colors": "false" }, "hands": { "filename": "standard", "custom_colors": "true", "hue": 11, "sat": 115, "lgt": 1 }, "feet": { "filename": "standard", "custom_colors": "true", "hue": 29, "sat": 173, "lgt": 87 }, "eyes": { "filename": "standard", "custom_colors": "false" }} } ================================================ FILE: data/skins/x_ninja.json ================================================ {"skin": { "body": { "filename": "x_ninja", "custom_colors": "true", "hue": 0, "sat": 0, "lgt": 0 }, "tattoo": { "filename": "uppy", "custom_colors": "true", "hue": 0, "sat": 0, "lgt": 255, "alp": 127 }, "hands": { "filename": "standard", "custom_colors": "false" }, "feet": { "filename": "standard", "custom_colors": "false" }, "eyes": { "filename": "x_ninja", "custom_colors": "false" }} } ================================================ FILE: datasrc/compile.py ================================================ import os, imp, sys from datatypes import * import content import network def create_enum_table(names, num): lines = [] lines += ["enum", "{"] lines += ["\t%s=0,"%names[0]] for name in names[1:]: lines += ["\t%s,"%name] lines += ["\t%s" % num, "};"] return lines def create_flags_table(names): lines = [] lines += ["enum", "{"] i = 0 for name in names: lines += ["\t%s = 1<<%d," % (name,i)] i += 1 lines += ["};"] return lines def EmitEnum(names, num): print("enum") print("{") print("\t%s=0," % names[0]) for name in names[1:]: print("\t%s," % name) print("\t%s" % num) print("};") def EmitFlags(names, num): print("enum") print("{") i = 0 for name in names: print("\t%s = 1<<%d," % (name,i)) i += 1 print("};") gen_network_header = False gen_network_source = False gen_client_content_header = False gen_client_content_source = False gen_server_content_header = False gen_server_content_source = False if "network_header" in sys.argv: gen_network_header = True if "network_source" in sys.argv: gen_network_source = True if "client_content_header" in sys.argv: gen_client_content_header = True if "client_content_source" in sys.argv: gen_client_content_source = True if "server_content_header" in sys.argv: gen_server_content_header = True if "server_content_source" in sys.argv: gen_server_content_source = True if gen_client_content_header: print("#ifndef CLIENT_CONTENT_HEADER") print("#define CLIENT_CONTENT_HEADER") if gen_server_content_header: print("#ifndef SERVER_CONTENT_HEADER") print("#define SERVER_CONTENT_HEADER") if gen_client_content_header or gen_server_content_header: # print some includes print('#include ') print('#include ') # emit the type declarations contentlines = open("datasrc/content.py", "rb").readlines() order = [] for line in contentlines: line = line.strip() if line[:6] == "class ".encode() and "(Struct)".encode() in line: order += [line.split()[1].split("(".encode())[0].decode("ascii")] for name in order: EmitTypeDeclaration(content.__dict__[name]) # the container pointer print('extern CDataContainer *g_pData;') # enums EmitEnum(["IMAGE_%s"%i.name.value.upper() for i in content.container.images.items], "NUM_IMAGES") EmitEnum(["ANIM_%s"%i.name.value.upper() for i in content.container.animations.items], "NUM_ANIMS") EmitEnum(["SPRITE_%s"%i.name.value.upper() for i in content.container.sprites.items], "NUM_SPRITES") if gen_client_content_source or gen_server_content_source: if gen_client_content_source: print('#include "client_data.h"') if gen_server_content_source: print('#include "server_data.h"') EmitDefinition(content.container, "datacontainer") print('CDataContainer *g_pData = &datacontainer;') # NETWORK if gen_network_header: print("#ifndef GAME_GENERATED_PROTOCOL_H") print("#define GAME_GENERATED_PROTOCOL_H") print(network.RawHeader) for e in network.Enums: for l in create_enum_table(["%s_%s"%(e.name, v) for v in e.values], 'NUM_%sS'%e.name): print(l) print("") for e in network.Flags: for l in create_flags_table(["%s_%s" % (e.name, v) for v in e.values]): print(l) print("") for l in create_enum_table(["NETOBJ_INVALID"]+[o.enum_name for o in network.Objects], "NUM_NETOBJTYPES"): print(l) print("") for l in create_enum_table(["NETMSG_INVALID"]+[o.enum_name for o in network.Messages], "NUM_NETMSGTYPES"): print(l) print("") for item in network.Objects + network.Messages: for line in item.emit_declaration(): print(line) print("") EmitEnum(["SOUND_%s"%i.name.value.upper() for i in content.container.sounds.items], "NUM_SOUNDS") EmitEnum(["WEAPON_%s"%i.name.value.upper() for i in content.container.weapons.id.items], "NUM_WEAPONS") print(""" class CNetObjHandler { const char *m_pMsgFailedOn; const char *m_pObjCorrectedOn; char m_aMsgData[1024]; int m_NumObjCorrections; int ClampInt(const char *pErrorMsg, int Value, int Min, int Max); int ClampFlag(const char *pErrorMsg, int Value, int Mask); static const char *ms_apObjNames[]; static int ms_aObjSizes[]; static const char *ms_apMsgNames[]; public: CNetObjHandler(); int ValidateObj(int Type, void *pData, int Size); const char *GetObjName(int Type); int GetObjSize(int Type); int NumObjCorrections(); const char *CorrectedObjOn(); const char *GetMsgName(int Type); void *SecureUnpackMsg(int Type, CUnpacker *pUnpacker); const char *FailedMsgOn(); }; """) print("#endif // GAME_GENERATED_PROTOCOL_H") if gen_network_source: # create names lines = [] lines += ['#include '] lines += ['#include '] lines += ['#include "protocol.h"'] lines += ['CNetObjHandler::CNetObjHandler()'] lines += ['{'] lines += ['\tm_pMsgFailedOn = "";'] lines += ['\tm_pObjCorrectedOn = "";'] lines += ['\tm_NumObjCorrections = 0;'] lines += ['}'] lines += [''] lines += ['int CNetObjHandler::NumObjCorrections() { return m_NumObjCorrections; }'] lines += ['const char *CNetObjHandler::CorrectedObjOn() { return m_pObjCorrectedOn; }'] lines += ['const char *CNetObjHandler::FailedMsgOn() { return m_pMsgFailedOn; }'] lines += [''] lines += [''] lines += [''] lines += [''] lines += [''] lines += ['static const int max_int = 0x7fffffff;'] lines += [''] lines += ['int CNetObjHandler::ClampInt(const char *pErrorMsg, int Value, int Min, int Max)'] lines += ['{'] lines += ['\tif(Value < Min) { m_pObjCorrectedOn = pErrorMsg; m_NumObjCorrections++; return Min; }'] lines += ['\tif(Value > Max) { m_pObjCorrectedOn = pErrorMsg; m_NumObjCorrections++; return Max; }'] lines += ['\treturn Value;'] lines += ['}'] lines += [''] lines += ['int CNetObjHandler::ClampFlag(const char *pErrorMsg, int Value, int Mask)'] lines += ['{'] lines += ['\tif((Value&Mask) != Value) { m_pObjCorrectedOn = pErrorMsg; m_NumObjCorrections++; return (Value&Mask); }'] lines += ['\treturn Value;'] lines += ['}'] lines += [''] lines += ["const char *CNetObjHandler::ms_apObjNames[] = {"] lines += ['\t"invalid",'] lines += ['\t"%s",' % o.name for o in network.Objects] lines += ['\t""', "};", ""] lines += ["int CNetObjHandler::ms_aObjSizes[] = {"] lines += ['\t0,'] lines += ['\tsizeof(%s),' % o.struct_name for o in network.Objects] lines += ['\t0', "};", ""] lines += ['const char *CNetObjHandler::ms_apMsgNames[] = {'] lines += ['\t"invalid",'] for msg in network.Messages: lines += ['\t"%s",' % msg.name] lines += ['\t""'] lines += ['};'] lines += [''] lines += ['const char *CNetObjHandler::GetObjName(int Type)'] lines += ['{'] lines += ['\tif(Type < 0 || Type >= NUM_NETOBJTYPES) return "(out of range)";'] lines += ['\treturn ms_apObjNames[Type];'] lines += ['};'] lines += [''] lines += ['int CNetObjHandler::GetObjSize(int Type)'] lines += ['{'] lines += ['\tif(Type < 0 || Type >= NUM_NETOBJTYPES) return 0;'] lines += ['\treturn ms_aObjSizes[Type];'] lines += ['};'] lines += [''] lines += ['const char *CNetObjHandler::GetMsgName(int Type)'] lines += ['{'] lines += ['\tif(Type < 0 || Type >= NUM_NETMSGTYPES) return "(out of range)";'] lines += ['\treturn ms_apMsgNames[Type];'] lines += ['};'] lines += [''] for l in lines: print(l) if 0: for item in network.Objects: for line in item.emit_validate(): print(line) print("") # create validate tables lines = [] lines += ['static int validate_invalid(void *data, int size) { return -1; }'] lines += ["typedef int(*VALIDATEFUNC)(void *data, int size);"] lines += ["static VALIDATEFUNC validate_funcs[] = {"] lines += ['\tvalidate_invalid,'] lines += ['\tvalidate_%s,' % o.name for o in network.Objects] lines += ["\t0x0", "};", ""] lines += ["int netobj_validate(int type, void *data, int size)"] lines += ["{"] lines += ["\tif(type < 0 || type >= NUM_NETOBJTYPES) return -1;"] lines += ["\treturn validate_funcs[type](data, size);"] lines += ["};", ""] lines = [] lines += ['int CNetObjHandler::ValidateObj(int Type, void *pData, int Size)'] lines += ['{'] lines += ['\tswitch(Type)'] lines += ['\t{'] for item in network.Objects: for line in item.emit_validate(): lines += ["\t" + line] lines += ['\t'] lines += ['\t}'] lines += ['\treturn -1;'] lines += ['};'] lines += [''] #int Validate(int Type, void *pData, int Size); if 0: for item in network.Messages: for line in item.emit_unpack(): print(line) print("") lines += ['static void *secure_unpack_invalid(CUnpacker *pUnpacker) { return 0; }'] lines += ['typedef void *(*SECUREUNPACKFUNC)(CUnpacker *pUnpacker);'] lines += ['static SECUREUNPACKFUNC secure_unpack_funcs[] = {'] lines += ['\tsecure_unpack_invalid,'] for msg in network.Messages: lines += ['\tsecure_unpack_%s,' % msg.name] lines += ['\t0x0'] lines += ['};'] # lines += ['void *CNetObjHandler::SecureUnpackMsg(int Type, CUnpacker *pUnpacker)'] lines += ['{'] lines += ['\tm_pMsgFailedOn = 0;'] lines += ['\tswitch(Type)'] lines += ['\t{'] for item in network.Messages: for line in item.emit_unpack(): lines += ["\t" + line] lines += ['\t'] lines += ['\tdefault:'] lines += ['\t\tm_pMsgFailedOn = "(type out of range)";'] lines += ['\t\tbreak;'] lines += ['\t}'] lines += ['\t'] lines += ['\tif(pUnpacker->Error())'] lines += ['\t\tm_pMsgFailedOn = "(unpack error)";'] lines += ['\t'] lines += ['\tif(m_pMsgFailedOn)'] lines += ['\t\treturn 0;'] lines += ['\tm_pMsgFailedOn = "";'] lines += ['\treturn m_aMsgData;'] lines += ['};'] lines += [''] for l in lines: print(l) if gen_client_content_header or gen_server_content_header: print("#endif") ================================================ FILE: datasrc/content.py ================================================ import copy from datatypes import * class Sound(Struct): def __init__(self, filename=""): Struct.__init__(self, "CDataSound") self.id = SampleHandle() self.filename = String(filename) class SoundSet(Struct): def __init__(self, name="", files=[]): Struct.__init__(self, "CDataSoundset") self.name = String(name) self.sounds = Array(Sound()) self.last = Int(-1) for name in files: self.sounds.Add(Sound(name)) class Image(Struct): def __init__(self, name="", filename=""): Struct.__init__(self, "CDataImage") self.name = String(name) self.filename = String(filename) self.id = TextureHandle() class SpriteSet(Struct): def __init__(self, name="", image=None, gridx=0, gridy=0): Struct.__init__(self, "CDataSpriteset") self.image = Pointer(Image, image) # TODO self.gridx = Int(gridx) self.gridy = Int(gridy) class Sprite(Struct): def __init__(self, name="", Set=None, x=0, y=0, w=0, h=0): Struct.__init__(self, "CDataSprite") self.name = String(name) self.set = Pointer(SpriteSet, Set) # TODO self.x = Int(x) self.y = Int(y) self.w = Int(w) self.h = Int(h) class Pickup(Struct): def __init__(self, name="", respawntime=15, spawndelay=0): Struct.__init__(self, "CDataPickupspec") self.name = String(name) self.respawntime = Int(respawntime) self.spawndelay = Int(spawndelay) class AnimKeyframe(Struct): def __init__(self, time=0, x=0, y=0, angle=0): Struct.__init__(self, "CAnimKeyframe") self.time = Float(time) self.x = Float(x) self.y = Float(y) self.angle = Float(angle) class AnimSequence(Struct): def __init__(self): Struct.__init__(self, "CAnimSequence") self.frames = Array(AnimKeyframe()) class Animation(Struct): def __init__(self, name=""): Struct.__init__(self, "CAnimation") self.name = String(name) self.body = AnimSequence() self.back_foot = AnimSequence() self.front_foot = AnimSequence() self.attach = AnimSequence() class WeaponSpec(Struct): def __init__(self, container=None, name=""): Struct.__init__(self, "CDataWeaponspec") self.name = String(name) self.sprite_body = Pointer(Sprite, Sprite()) self.sprite_cursor = Pointer(Sprite, Sprite()) self.sprite_proj = Pointer(Sprite, Sprite()) self.sprite_muzzles = Array(Pointer(Sprite, Sprite())) self.visual_size = Int(96) self.firedelay = Int(500) self.maxammo = Int(10) self.ammoregentime = Int(0) self.damage = Int(1) self.offsetx = Float(0) self.offsety = Float(0) self.muzzleoffsetx = Float(0) self.muzzleoffsety = Float(0) self.muzzleduration = Float(5) # dig out sprites if we have a container if container: for sprite in container.sprites.items: if sprite.name.value == "weapon_"+name+"_body": self.sprite_body.Set(sprite) elif sprite.name.value == "weapon_"+name+"_cursor": self.sprite_cursor.Set(sprite) elif sprite.name.value == "weapon_"+name+"_proj": self.sprite_proj.Set(sprite) elif "weapon_"+name+"_muzzle" in sprite.name.value: self.sprite_muzzles.Add(Pointer(Sprite, sprite)) class Weapon_Hammer(Struct): def __init__(self): Struct.__init__(self, "CDataWeaponspecHammer") self.base = Pointer(WeaponSpec, WeaponSpec()) class Weapon_Gun(Struct): def __init__(self): Struct.__init__(self, "CDataWeaponspecGun") self.base = Pointer(WeaponSpec, WeaponSpec()) self.curvature = Float(1.25) self.speed = Float(2200) self.lifetime = Float(2.0) class Weapon_Shotgun(Struct): def __init__(self): Struct.__init__(self, "CDataWeaponspecShotgun") self.base = Pointer(WeaponSpec, WeaponSpec()) self.curvature = Float(1.25) self.speed = Float(2200) self.speeddiff = Float(0.8) self.lifetime = Float(0.25) class Weapon_Grenade(Struct): def __init__(self): Struct.__init__(self, "CDataWeaponspecGrenade") self.base = Pointer(WeaponSpec, WeaponSpec()) self.curvature = Float(7.0) self.speed = Float(1000) self.lifetime = Float(2.0) class Weapon_Laser(Struct): def __init__(self): Struct.__init__(self, "CDataWeaponspecLaser") self.base = Pointer(WeaponSpec, WeaponSpec()) self.reach = Float(800.0) self.bounce_delay = Int(150) self.bounce_num = Int(1) self.bounce_cost = Float(0) class Weapon_Ninja(Struct): def __init__(self): Struct.__init__(self, "CDataWeaponspecNinja") self.base = Pointer(WeaponSpec, WeaponSpec()) self.duration = Int(15000) self.movetime = Int(200) self.velocity = Int(50) class Weapons(Struct): def __init__(self): Struct.__init__(self, "CDataWeaponspecs") self.hammer = Weapon_Hammer() self.gun = Weapon_Gun() self.shotgun = Weapon_Shotgun() self.grenade = Weapon_Grenade() self.laser = Weapon_Laser() self.ninja = Weapon_Ninja() self.id = Array(WeaponSpec()) class DataContainer(Struct): def __init__(self): Struct.__init__(self, "CDataContainer") self.sounds = Array(SoundSet()) self.images = Array(Image()) self.pickups = Array(Pickup()) self.spritesets = Array(SpriteSet()) self.sprites = Array(Sprite()) self.animations = Array(Animation()) self.weapons = Weapons() def FileList(format, num): return [format%(x+1) for x in range(0,num)] container = DataContainer() container.sounds.Add(SoundSet("gun_fire", FileList("audio/wp_gun_fire-%02d.wv", 3))) container.sounds.Add(SoundSet("shotgun_fire", FileList("audio/wp_shotty_fire-%02d.wv", 3))) container.sounds.Add(SoundSet("grenade_fire", FileList("audio/wp_flump_launch-%02d.wv", 3))) container.sounds.Add(SoundSet("hammer_fire", FileList("audio/wp_hammer_swing-%02d.wv", 3))) container.sounds.Add(SoundSet("hammer_hit", FileList("audio/wp_hammer_hit-%02d.wv", 3))) container.sounds.Add(SoundSet("ninja_fire", FileList("audio/wp_ninja_attack-%02d.wv", 3))) container.sounds.Add(SoundSet("grenade_explode", FileList("audio/wp_flump_explo-%02d.wv", 3))) container.sounds.Add(SoundSet("ninja_hit", FileList("audio/wp_ninja_hit-%02d.wv", 3))) container.sounds.Add(SoundSet("laser_fire", FileList("audio/wp_laser_fire-%02d.wv", 3))) container.sounds.Add(SoundSet("laser_bounce", FileList("audio/wp_laser_bnce-%02d.wv", 3))) container.sounds.Add(SoundSet("weapon_switch", FileList("audio/wp_switch-%02d.wv", 3))) container.sounds.Add(SoundSet("player_pain_short", FileList("audio/vo_teefault_pain_short-%02d.wv", 12))) container.sounds.Add(SoundSet("player_pain_long", FileList("audio/vo_teefault_pain_long-%02d.wv", 2))) container.sounds.Add(SoundSet("body_land", FileList("audio/foley_land-%02d.wv", 4))) container.sounds.Add(SoundSet("player_airjump", FileList("audio/foley_dbljump-%02d.wv", 3))) container.sounds.Add(SoundSet("player_jump", FileList("audio/foley_foot_left-%02d.wv", 4) + FileList("audio/foley_foot_right-%02d.wv", 4))) container.sounds.Add(SoundSet("player_die", FileList("audio/foley_body_splat-%02d.wv", 3))) container.sounds.Add(SoundSet("player_spawn", FileList("audio/vo_teefault_spawn-%02d.wv", 7))) container.sounds.Add(SoundSet("player_skid", FileList("audio/sfx_skid-%02d.wv", 4))) container.sounds.Add(SoundSet("tee_cry", FileList("audio/vo_teefault_cry-%02d.wv", 2))) container.sounds.Add(SoundSet("hook_loop", FileList("audio/hook_loop-%02d.wv", 2))) container.sounds.Add(SoundSet("hook_attach_ground", FileList("audio/hook_attach-%02d.wv", 3))) container.sounds.Add(SoundSet("hook_attach_player", FileList("audio/foley_body_impact-%02d.wv", 3))) container.sounds.Add(SoundSet("hook_noattach", FileList("audio/hook_noattach-%02d.wv", 2))) container.sounds.Add(SoundSet("pickup_health", FileList("audio/sfx_pickup_hrt-%02d.wv", 2))) container.sounds.Add(SoundSet("pickup_armor", FileList("audio/sfx_pickup_arm-%02d.wv", 4))) container.sounds.Add(SoundSet("pickup_grenade", ["audio/sfx_pickup_launcher.wv"])) container.sounds.Add(SoundSet("pickup_shotgun", ["audio/sfx_pickup_sg.wv"])) container.sounds.Add(SoundSet("pickup_ninja", ["audio/sfx_pickup_ninja.wv"])) container.sounds.Add(SoundSet("weapon_spawn", FileList("audio/sfx_spawn_wpn-%02d.wv", 3))) container.sounds.Add(SoundSet("weapon_noammo", FileList("audio/wp_noammo-%02d.wv", 5))) container.sounds.Add(SoundSet("hit", FileList("audio/sfx_hit_weak-%02d.wv", 2))) container.sounds.Add(SoundSet("chat_server", ["audio/sfx_msg-server.wv"])) container.sounds.Add(SoundSet("chat_client", ["audio/sfx_msg-client.wv"])) container.sounds.Add(SoundSet("chat_highlight", ["audio/sfx_msg-highlight.wv"])) container.sounds.Add(SoundSet("ctf_drop", ["audio/sfx_ctf_drop.wv"])) container.sounds.Add(SoundSet("ctf_return", ["audio/sfx_ctf_rtn.wv"])) container.sounds.Add(SoundSet("ctf_grab_pl", ["audio/sfx_ctf_grab_pl.wv"])) container.sounds.Add(SoundSet("ctf_grab_en", ["audio/sfx_ctf_grab_en.wv"])) container.sounds.Add(SoundSet("ctf_capture", ["audio/sfx_ctf_cap_pl.wv"])) container.sounds.Add(SoundSet("menu", ["audio/music_menu.wv"])) image_null = Image("null", "") image_particles = Image("particles", "particles.png") image_game = Image("game", "game.png") image_browseicons = Image("browseicons", "icons/browse.png") image_emoticons = Image("emoticons", "emoticons.png") image_demobuttons = Image("demobuttons", "demo_buttons.png") image_fileicons = Image("fileicons", "file_icons.png") image_guibuttons = Image("guibuttons", "gui_buttons.png") image_guiicons = Image("guiicons", "gui_icons.png") image_menuicons = Image("menuicons", "icons/menu.png") image_toolicons = Image("toolicons", "icons/tools.png") image_infoicons = Image("infoicons", "icons/info.png") container.images.Add(image_null) container.images.Add(image_game) container.images.Add(Image("deadtee", "deadtee.png")) container.images.Add(image_particles) container.images.Add(Image("cursor", "gui_cursor.png")) container.images.Add(Image("banner", "gui_logo.png")) container.images.Add(image_emoticons) container.images.Add(image_browseicons) container.images.Add(Image("console_bg", "console.png")) container.images.Add(Image("console_bar", "console_bar.png")) container.images.Add(image_demobuttons) container.images.Add(image_fileicons) container.images.Add(image_guibuttons) container.images.Add(image_guiicons) container.images.Add(Image("no_skinpart", "no_skinpart.png")) container.images.Add(image_menuicons) container.images.Add(image_toolicons) container.images.Add(image_infoicons) container.pickups.Add(Pickup("health")) container.pickups.Add(Pickup("armor")) container.pickups.Add(Pickup("grenade")) container.pickups.Add(Pickup("shotgun")) container.pickups.Add(Pickup("laser")) container.pickups.Add(Pickup("ninja", 90, 90)) set_particles = SpriteSet("particles", image_particles, 8, 8) set_game = SpriteSet("game", image_game, 32, 16) set_tee_body = SpriteSet("tee_body", image_null, 2, 2) set_tee_tattoos = SpriteSet("tee_tattoos", image_null, 1, 1) set_tee_decoration = SpriteSet("tee_decoration", image_null, 2, 1) set_tee_hands = SpriteSet("tee_hands", image_null, 2, 1) set_tee_feet = SpriteSet("tee_feet", image_null, 2, 1) set_tee_eyes = SpriteSet("tee_eyes", image_null, 2, 4) set_browseicons = SpriteSet("browseicons", image_browseicons, 4, 2) set_emoticons = SpriteSet("emoticons", image_emoticons, 4, 4) set_demobuttons = SpriteSet("demobuttons", image_demobuttons, 5, 1) set_fileicons = SpriteSet("fileicons", image_fileicons, 8, 1) set_guibuttons = SpriteSet("guibuttons", image_guibuttons, 12, 4) set_guiicons = SpriteSet("guiicons", image_guiicons, 8, 2) set_menuicons = SpriteSet("menuicons", image_menuicons, 2, 2) set_toolicons = SpriteSet("toolicons", image_toolicons, 4, 2) set_infoicons = SpriteSet("infoicons", image_infoicons, 1, 2) container.spritesets.Add(set_particles) container.spritesets.Add(set_game) container.spritesets.Add(set_tee_body) container.spritesets.Add(set_tee_tattoos) container.spritesets.Add(set_tee_decoration) container.spritesets.Add(set_tee_hands) container.spritesets.Add(set_tee_feet) container.spritesets.Add(set_tee_eyes) container.spritesets.Add(set_browseicons) container.spritesets.Add(set_emoticons) container.spritesets.Add(set_demobuttons) container.spritesets.Add(set_fileicons) container.spritesets.Add(set_guibuttons) container.spritesets.Add(set_guiicons) container.spritesets.Add(set_menuicons) container.spritesets.Add(set_toolicons) container.spritesets.Add(set_infoicons) container.sprites.Add(Sprite("part_slice", set_particles, 0,0,1,1)) container.sprites.Add(Sprite("part_ball", set_particles, 1,0,1,1)) container.sprites.Add(Sprite("part_splat01", set_particles, 2,0,1,1)) container.sprites.Add(Sprite("part_splat02", set_particles, 3,0,1,1)) container.sprites.Add(Sprite("part_splat03", set_particles, 4,0,1,1)) container.sprites.Add(Sprite("part_smoke", set_particles, 0,1,1,1)) container.sprites.Add(Sprite("part_shell", set_particles, 0,2,2,2)) container.sprites.Add(Sprite("part_expl01", set_particles, 0,4,4,4)) container.sprites.Add(Sprite("part_airjump", set_particles, 2,2,2,2)) container.sprites.Add(Sprite("part_hit01", set_particles, 4,1,2,2)) container.sprites.Add(Sprite("health_full", set_game, 21,0,2,2)) container.sprites.Add(Sprite("health_empty", set_game, 23,0,2,2)) container.sprites.Add(Sprite("armor_full", set_game, 21,2,2,2)) container.sprites.Add(Sprite("armor_empty", set_game, 23,2,2,2)) container.sprites.Add(Sprite("star1", set_game, 15,0,2,2)) container.sprites.Add(Sprite("star2", set_game, 17,0,2,2)) container.sprites.Add(Sprite("star3", set_game, 19,0,2,2)) container.sprites.Add(Sprite("part1", set_game, 6,0,1,1)) container.sprites.Add(Sprite("part2", set_game, 6,1,1,1)) container.sprites.Add(Sprite("part3", set_game, 7,0,1,1)) container.sprites.Add(Sprite("part4", set_game, 7,1,1,1)) container.sprites.Add(Sprite("part5", set_game, 8,0,1,1)) container.sprites.Add(Sprite("part6", set_game, 8,1,1,1)) container.sprites.Add(Sprite("part7", set_game, 9,0,2,2)) container.sprites.Add(Sprite("part8", set_game, 11,0,2,2)) container.sprites.Add(Sprite("part9", set_game, 13,0,2,2)) container.sprites.Add(Sprite("weapon_gun_body", set_game, 2,4,4,2)) container.sprites.Add(Sprite("weapon_gun_cursor", set_game, 0,4,2,2)) container.sprites.Add(Sprite("weapon_gun_proj", set_game, 6,4,2,2)) container.sprites.Add(Sprite("weapon_gun_muzzle1", set_game, 8,4,3,2)) container.sprites.Add(Sprite("weapon_gun_muzzle2", set_game, 12,4,3,2)) container.sprites.Add(Sprite("weapon_gun_muzzle3", set_game, 16,4,3,2)) container.sprites.Add(Sprite("weapon_shotgun_body", set_game, 2,6,8,2)) container.sprites.Add(Sprite("weapon_shotgun_cursor", set_game, 0,6,2,2)) container.sprites.Add(Sprite("weapon_shotgun_proj", set_game, 10,6,2,2)) container.sprites.Add(Sprite("weapon_shotgun_muzzle1", set_game, 12,6,3,2)) container.sprites.Add(Sprite("weapon_shotgun_muzzle2", set_game, 16,6,3,2)) container.sprites.Add(Sprite("weapon_shotgun_muzzle3", set_game, 20,6,3,2)) container.sprites.Add(Sprite("weapon_grenade_body", set_game, 2,8,7,2)) container.sprites.Add(Sprite("weapon_grenade_cursor", set_game, 0,8,2,2)) container.sprites.Add(Sprite("weapon_grenade_proj", set_game, 10,8,2,2)) container.sprites.Add(Sprite("weapon_hammer_body", set_game, 2,1,4,3)) container.sprites.Add(Sprite("weapon_hammer_cursor", set_game, 0,0,2,2)) container.sprites.Add(Sprite("weapon_hammer_proj", set_game, 0,0,0,0)) container.sprites.Add(Sprite("weapon_ninja_body", set_game, 2,10,8,2)) container.sprites.Add(Sprite("weapon_ninja_cursor", set_game, 0,10,2,2)) container.sprites.Add(Sprite("weapon_ninja_proj", set_game, 0,0,0,0)) container.sprites.Add(Sprite("weapon_laser_body", set_game, 2,12,7,3)) container.sprites.Add(Sprite("weapon_laser_cursor", set_game, 0,12,2,2)) container.sprites.Add(Sprite("weapon_laser_proj", set_game, 10,12,2,2)) container.sprites.Add(Sprite("hook_chain", set_game, 2,0,1,1)) container.sprites.Add(Sprite("hook_head", set_game, 3,0,2,1)) container.sprites.Add(Sprite("weapon_ninja_muzzle1", set_game, 25,0,7,4)) container.sprites.Add(Sprite("weapon_ninja_muzzle2", set_game, 25,4,7,4)) container.sprites.Add(Sprite("weapon_ninja_muzzle3", set_game, 25,8,7,4)) container.sprites.Add(Sprite("pickup_health", set_game, 10,2,2,2)) container.sprites.Add(Sprite("pickup_armor", set_game, 12,2,2,2)) container.sprites.Add(Sprite("pickup_grenade", set_game, 2,8,7,2)) container.sprites.Add(Sprite("pickup_shotgun", set_game, 2,6,8,2)) container.sprites.Add(Sprite("pickup_laser", set_game, 2,12,7,3)) container.sprites.Add(Sprite("pickup_ninja", set_game, 2,10,8,2)) container.sprites.Add(Sprite("flag_blue", set_game, 12,8,4,8)) container.sprites.Add(Sprite("flag_red", set_game, 16,8,4,8)) container.sprites.Add(Sprite("tee_body_outline", set_tee_body, 0,0,1,1)) container.sprites.Add(Sprite("tee_body", set_tee_body, 1,0,1,1)) container.sprites.Add(Sprite("tee_body_shadow", set_tee_body, 0,1,1,1)) container.sprites.Add(Sprite("tee_body_upper_outline", set_tee_body, 1,1,1,1)) container.sprites.Add(Sprite("tee_tattoo", set_tee_tattoos, 0,0,1,1)) container.sprites.Add(Sprite("tee_decoration", set_tee_decoration, 0,0,1,1)) container.sprites.Add(Sprite("tee_decoration_outline", set_tee_decoration, 1,0,1,1)) container.sprites.Add(Sprite("tee_hand", set_tee_hands, 0,0,1,1)) container.sprites.Add(Sprite("tee_hand_outline", set_tee_hands, 1,0,1,1)) container.sprites.Add(Sprite("tee_foot", set_tee_feet, 0,0,1,1)) container.sprites.Add(Sprite("tee_foot_outline", set_tee_feet, 1,0,1,1)) container.sprites.Add(Sprite("tee_eyes_normal", set_tee_eyes, 0,0,1,1)) container.sprites.Add(Sprite("tee_eyes_angry", set_tee_eyes, 1,0,1,1)) container.sprites.Add(Sprite("tee_eyes_pain", set_tee_eyes, 0,1,1,1)) container.sprites.Add(Sprite("tee_eyes_happy", set_tee_eyes, 1,1,1,1)) container.sprites.Add(Sprite("tee_eyes_surprise", set_tee_eyes, 0,2,1,1)) container.sprites.Add(Sprite("oop", set_emoticons, 0, 0, 1, 1)) container.sprites.Add(Sprite("exclamation", set_emoticons, 1, 0, 1, 1)) container.sprites.Add(Sprite("hearts", set_emoticons, 2, 0, 1, 1)) container.sprites.Add(Sprite("drop", set_emoticons, 3, 0, 1, 1)) container.sprites.Add(Sprite("dotdot", set_emoticons, 0, 1, 1, 1)) container.sprites.Add(Sprite("music", set_emoticons, 1, 1, 1, 1)) container.sprites.Add(Sprite("sorry", set_emoticons, 2, 1, 1, 1)) container.sprites.Add(Sprite("ghost", set_emoticons, 3, 1, 1, 1)) container.sprites.Add(Sprite("sushi", set_emoticons, 0, 2, 1, 1)) container.sprites.Add(Sprite("splattee", set_emoticons, 1, 2, 1, 1)) container.sprites.Add(Sprite("deviltee", set_emoticons, 2, 2, 1, 1)) container.sprites.Add(Sprite("zomg", set_emoticons, 3, 2, 1, 1)) container.sprites.Add(Sprite("zzz", set_emoticons, 0, 3, 1, 1)) container.sprites.Add(Sprite("wtf", set_emoticons, 1, 3, 1, 1)) container.sprites.Add(Sprite("eyes", set_emoticons, 2, 3, 1, 1)) container.sprites.Add(Sprite("question", set_emoticons, 3, 3, 1, 1)) container.sprites.Add(Sprite("browse_lock_a", set_browseicons, 0,0,1,1)) container.sprites.Add(Sprite("browse_lock_b", set_browseicons, 0,1,1,1)) #container.sprites.Add(Sprite("browse_lock_c", set_browseicons, 2,0,1,1)) container.sprites.Add(Sprite("browse_unpure_a", set_browseicons, 1,0,1,1)) container.sprites.Add(Sprite("browse_unpure_b", set_browseicons, 1,1,1,1)) #container.sprites.Add(Sprite("browse_unpure_c", set_browseicons, 2,1,1,1)) container.sprites.Add(Sprite("browse_star_a", set_browseicons, 2,0,1,1)) container.sprites.Add(Sprite("browse_star_b", set_browseicons, 2,1,1,1)) #container.sprites.Add(Sprite("browse_star_c", set_browseicons, 2,2,1,1)) container.sprites.Add(Sprite("browse_heart_a", set_browseicons, 3,0,1,1)) container.sprites.Add(Sprite("browse_heart_b", set_browseicons, 3,1,1,1)) #container.sprites.Add(Sprite("browse_heart_c", set_browseicons, 2,3,1,1)) container.sprites.Add(Sprite("demobutton_play", set_demobuttons, 0,0,1,1)) container.sprites.Add(Sprite("demobutton_pause", set_demobuttons, 1,0,1,1)) container.sprites.Add(Sprite("demobutton_stop", set_demobuttons, 2,0,1,1)) container.sprites.Add(Sprite("demobutton_slower", set_demobuttons, 3,0,1,1)) container.sprites.Add(Sprite("demobutton_faster", set_demobuttons, 4,0,1,1)) container.sprites.Add(Sprite("file_demo1", set_fileicons, 0,0,1,1)) container.sprites.Add(Sprite("file_demo2", set_fileicons, 1,0,1,1)) container.sprites.Add(Sprite("file_folder", set_fileicons, 2,0,1,1)) container.sprites.Add(Sprite("file_map1", set_fileicons, 5,0,1,1)) container.sprites.Add(Sprite("file_map2", set_fileicons, 6,0,1,1)) container.sprites.Add(Sprite("guibutton_off", set_guibuttons, 0,0,4,4)) container.sprites.Add(Sprite("guibutton_on", set_guibuttons, 4,0,4,4)) container.sprites.Add(Sprite("guibutton_hover", set_guibuttons, 8,0,4,4)) container.sprites.Add(Sprite("guiicon_mute", set_guiicons, 0,0,4,2)) container.sprites.Add(Sprite("guiicon_friend", set_guiicons, 4,0,4,2)) container.sprites.Add(Sprite("menu_checkbox_active", set_menuicons, 0,0,1,1)) container.sprites.Add(Sprite("menu_checkbox_inactive", set_menuicons, 0,1,1,1)) container.sprites.Add(Sprite("menu_collapsed", set_menuicons, 1,0,1,1)) container.sprites.Add(Sprite("menu_expanded", set_menuicons, 1,1,1,1)) container.sprites.Add(Sprite("tool_up_a", set_toolicons, 0,0,1,1)) container.sprites.Add(Sprite("tool_up_b", set_toolicons, 0,1,1,1)) container.sprites.Add(Sprite("tool_down_a", set_toolicons, 1,0,1,1)) container.sprites.Add(Sprite("tool_down_b", set_toolicons, 1,1,1,1)) container.sprites.Add(Sprite("tool_edit_a", set_toolicons, 2,0,1,1)) container.sprites.Add(Sprite("tool_edit_b", set_toolicons, 2,1,1,1)) container.sprites.Add(Sprite("tool_x_a", set_toolicons, 3,0,1,1)) container.sprites.Add(Sprite("tool_x_b", set_toolicons, 3,1,1,1)) container.sprites.Add(Sprite("info_a", set_infoicons, 0,0,1,1)) container.sprites.Add(Sprite("info_b", set_infoicons, 0,1,1,1)) anim = Animation("base") anim.body.frames.Add(AnimKeyframe(0, 0, -4, 0)) anim.back_foot.frames.Add(AnimKeyframe(0, 0, 10, 0)) anim.front_foot.frames.Add(AnimKeyframe(0, 0, 10, 0)) container.animations.Add(anim) anim = Animation("idle") anim.back_foot.frames.Add(AnimKeyframe(0, -7, 0, 0)) anim.front_foot.frames.Add(AnimKeyframe(0, 7, 0, 0)) container.animations.Add(anim) anim = Animation("inair") anim.back_foot.frames.Add(AnimKeyframe(0, -3, 0, -0.1)) anim.front_foot.frames.Add(AnimKeyframe(0, 3, 0, -0.1)) container.animations.Add(anim) anim = Animation("walk") anim.body.frames.Add(AnimKeyframe(0.0, 0, 0, 0)) anim.body.frames.Add(AnimKeyframe(0.2, 0,-1, 0)) anim.body.frames.Add(AnimKeyframe(0.4, 0, 0, 0)) anim.body.frames.Add(AnimKeyframe(0.6, 0, 0, 0)) anim.body.frames.Add(AnimKeyframe(0.8, 0,-1, 0)) anim.body.frames.Add(AnimKeyframe(1.0, 0, 0, 0)) anim.back_foot.frames.Add(AnimKeyframe(0.0, 8, 0, 0)) anim.back_foot.frames.Add(AnimKeyframe(0.2, -8, 0, 0)) anim.back_foot.frames.Add(AnimKeyframe(0.4,-10,-4, 0.2)) anim.back_foot.frames.Add(AnimKeyframe(0.6, -8,-8, 0.3)) anim.back_foot.frames.Add(AnimKeyframe(0.8, 4,-4,-0.2)) anim.back_foot.frames.Add(AnimKeyframe(1.0, 8, 0, 0)) anim.front_foot.frames.Add(AnimKeyframe(0.0,-10,-4, 0.2)) anim.front_foot.frames.Add(AnimKeyframe(0.2, -8,-8, 0.3)) anim.front_foot.frames.Add(AnimKeyframe(0.4, 4,-4,-0.2)) anim.front_foot.frames.Add(AnimKeyframe(0.6, 8, 0, 0)) anim.front_foot.frames.Add(AnimKeyframe(0.8, 8, 0, 0)) anim.front_foot.frames.Add(AnimKeyframe(1.0,-10,-4, 0.2)) container.animations.Add(anim) anim = Animation("hammer_swing") anim.attach.frames.Add(AnimKeyframe(0.0, 0, 0, -0.10)) anim.attach.frames.Add(AnimKeyframe(0.3, 0, 0, 0.25)) anim.attach.frames.Add(AnimKeyframe(0.4, 0, 0, 0.30)) anim.attach.frames.Add(AnimKeyframe(0.5, 0, 0, 0.25)) anim.attach.frames.Add(AnimKeyframe(1.0, 0, 0, -0.10)) container.animations.Add(anim) anim = Animation("ninja_swing") anim.attach.frames.Add(AnimKeyframe(0.00, 0, 0, -0.25)) anim.attach.frames.Add(AnimKeyframe(0.10, 0, 0, -0.05)) anim.attach.frames.Add(AnimKeyframe(0.15, 0, 0, 0.35)) anim.attach.frames.Add(AnimKeyframe(0.42, 0, 0, 0.40)) anim.attach.frames.Add(AnimKeyframe(0.50, 0, 0, 0.35)) anim.attach.frames.Add(AnimKeyframe(1.00, 0, 0, -0.25)) container.animations.Add(anim) weapon = WeaponSpec(container, "hammer") weapon.firedelay.Set(125) weapon.damage.Set(3) weapon.visual_size.Set(96) weapon.offsetx.Set(4) weapon.offsety.Set(-20) container.weapons.hammer.base.Set(weapon) container.weapons.id.Add(weapon) weapon = WeaponSpec(container, "gun") weapon.firedelay.Set(125) weapon.ammoregentime.Set(500) weapon.visual_size.Set(64) weapon.offsetx.Set(32) weapon.offsety.Set(4) weapon.muzzleoffsetx.Set(50) weapon.muzzleoffsety.Set(6) container.weapons.gun.base.Set(weapon) container.weapons.id.Add(weapon) weapon = WeaponSpec(container, "shotgun") weapon.firedelay.Set(500) weapon.visual_size.Set(96) weapon.offsetx.Set(24) weapon.offsety.Set(-2) weapon.muzzleoffsetx.Set(70) weapon.muzzleoffsety.Set(6) container.weapons.shotgun.base.Set(weapon) container.weapons.id.Add(weapon) weapon = WeaponSpec(container, "grenade") weapon.firedelay.Set(500) # TODO: fix this weapon.visual_size.Set(96) weapon.offsetx.Set(24) weapon.offsety.Set(-2) container.weapons.grenade.base.Set(weapon) container.weapons.id.Add(weapon) weapon = WeaponSpec(container, "laser") weapon.firedelay.Set(800) weapon.visual_size.Set(92) weapon.damage.Set(5) weapon.offsetx.Set(24) weapon.offsety.Set(-2) container.weapons.laser.base.Set(weapon) container.weapons.id.Add(weapon) weapon = WeaponSpec(container, "ninja") weapon.firedelay.Set(800) weapon.damage.Set(9) weapon.visual_size.Set(96) weapon.offsetx.Set(0) weapon.offsety.Set(0) weapon.muzzleoffsetx.Set(40) weapon.muzzleoffsety.Set(-4) container.weapons.ninja.base.Set(weapon) container.weapons.id.Add(weapon) ================================================ FILE: datasrc/datatypes.py ================================================ import sys GlobalIdCounter = 0 def GetID(): global GlobalIdCounter GlobalIdCounter += 1 return GlobalIdCounter def GetUID(): return "x%d"%GetID() def FixCasing(Str): NewStr = "" NextUpperCase = True for c in Str: if NextUpperCase: NextUpperCase = False NewStr += c.upper() else: if c == "_": NextUpperCase = True else: NewStr += c.lower() return NewStr def FormatName(type, name): if "*" in type: return "m_p" + FixCasing(name) if "[]" in type: return "m_a" + FixCasing(name) return "m_" + FixCasing(name) class BaseType: def __init__(self, type_name): self._type_name = type_name self._target_name = "INVALID" self._id = GetID() # this is used to remember what order the members have in structures etc def Identifyer(self): return "x"+str(self._id) def TargetName(self): return self._target_name def TypeName(self): return self._type_name def ID(self): return self._id; def EmitDeclaration(self, name): return ["%s %s;"%(self.TypeName(), FormatName(self.TypeName(), name))] def EmitPreDefinition(self, target_name): self._target_name = target_name return [] def EmitDefinition(self, name): return [] class MemberType: def __init__(self, name, var): self.name = name self.var = var class Struct(BaseType): def __init__(self, type_name): BaseType.__init__(self, type_name) def Members(self): def sorter(a): return a.var.ID() m = [] for name in self.__dict__: if name[0] == "_": continue m += [MemberType(name, self.__dict__[name])] try: m.sort(key = sorter) except: for v in m: print(v.name, v.var) sys.exit(-1) return m def EmitTypeDeclaration(self, name): lines = [] lines += ["struct " + self.TypeName()] lines += ["{"] for member in self.Members(): lines += ["\t"+l for l in member.var.EmitDeclaration(member.name)] lines += ["};"] return lines def EmitPreDefinition(self, target_name): BaseType.EmitPreDefinition(self, target_name) lines = [] for member in self.Members(): lines += member.var.EmitPreDefinition(target_name+"."+member.name) return lines def EmitDefinition(self, name): lines = ["/* %s */ {" % self.TargetName()] for member in self.Members(): lines += ["\t" + " ".join(member.var.EmitDefinition("")) + ","] lines += ["}"] return lines class Array(BaseType): def __init__(self, type): BaseType.__init__(self, type.TypeName()) self.type = type self.items = [] def Add(self, instance): if instance.TypeName() != self.type.TypeName(): error("bah") self.items += [instance] def EmitDeclaration(self, name): return ["int m_Num%s;"%(FixCasing(name)), "%s *%s;"%(self.TypeName(), FormatName("[]", name))] def EmitPreDefinition(self, target_name): BaseType.EmitPreDefinition(self, target_name) lines = [] i = 0 for item in self.items: lines += item.EmitPreDefinition("%s[%d]"%(self.Identifyer(), i)) i += 1 if len(self.items): lines += ["static %s %s[] = {"%(self.TypeName(), self.Identifyer())] for item in self.items: itemlines = item.EmitDefinition("") lines += ["\t" + " ".join(itemlines).replace("\t", " ") + ","] lines += ["};"] else: lines += ["static %s *%s = 0;"%(self.TypeName(), self.Identifyer())] return lines def EmitDefinition(self, name): return [str(len(self.items))+","+self.Identifyer()] # Basic Types class Int(BaseType): def __init__(self, value): BaseType.__init__(self, "int") self.value = value def Set(self, value): self.value = value def EmitDefinition(self, name): return ["%d"%self.value] #return ["%d /* %s */"%(self.value, self._target_name)] class Float(BaseType): def __init__(self, value): BaseType.__init__(self, "float") self.value = value def Set(self, value): self.value = value def EmitDefinition(self, name): return ["%f"%self.value] #return ["%d /* %s */"%(self.value, self._target_name)] class String(BaseType): def __init__(self, value): BaseType.__init__(self, "const char*") self.value = value def Set(self, value): self.value = value def EmitDefinition(self, name): return ['"'+self.value+'"'] class Pointer(BaseType): def __init__(self, type, target): BaseType.__init__(self, "%s*"%type().TypeName()) self.target = target def Set(self, target): self.target = target def EmitDefinition(self, name): return ["&"+self.target.TargetName()] class TextureHandle(BaseType): def __init__(self): BaseType.__init__(self, "IGraphics::CTextureHandle") def EmitDefinition(self, name): return ["IGraphics::CTextureHandle()"] class SampleHandle(BaseType): def __init__(self): BaseType.__init__(self, "ISound::CSampleHandle") def EmitDefinition(self, name): return ["ISound::CSampleHandle()"] # helper functions def EmitTypeDeclaration(root): for l in root().EmitTypeDeclaration(""): print(l) def EmitDefinition(root, name): for l in root.EmitPreDefinition(name): print(l) print("%s %s = " % (root.TypeName(), name)) for l in root.EmitDefinition(name): print(l) print(";") # Network stuff after this class Object: pass class Enum: def __init__(self, name, values): self.name = name self.values = values class Flags: def __init__(self, name, values): self.name = name self.values = values class NetObject: def __init__(self, name, variables): l = name.split(":") self.name = l[0] self.base = "" if len(l) > 1: self.base = l[1] self.base_struct_name = "CNetObj_%s" % self.base self.struct_name = "CNetObj_%s" % self.name self.enum_name = "NETOBJTYPE_%s" % self.name.upper() self.variables = variables def emit_declaration(self): if self.base: lines = ["struct %s : public %s"%(self.struct_name,self.base_struct_name), "{"] else: lines = ["struct %s"%self.struct_name, "{"] for v in self.variables: lines += ["\t"+line for line in v.emit_declaration()] lines += ["};"] return lines def emit_validate(self): lines = ["case %s:" % self.enum_name] lines += ["{"] lines += ["\t%s *pObj = (%s *)pData;"%(self.struct_name, self.struct_name)] lines += ["\tif(sizeof(*pObj) != Size) return -1;"] for v in self.variables: lines += ["\t"+line for line in v.emit_validate()] lines += ["\treturn 0;"] lines += ["}"] return lines class NetEvent(NetObject): def __init__(self, name, variables): NetObject.__init__(self, name, variables) self.base_struct_name = "CNetEvent_%s" % self.base self.struct_name = "CNetEvent_%s" % self.name self.enum_name = "NETEVENTTYPE_%s" % self.name.upper() class NetMessage(NetObject): def __init__(self, name, variables): NetObject.__init__(self, name, variables) self.base_struct_name = "CNetMsg_%s" % self.base self.struct_name = "CNetMsg_%s" % self.name self.enum_name = "NETMSGTYPE_%s" % self.name.upper() def emit_unpack(self): lines = [] lines += ["case %s:" % self.enum_name] lines += ["{"] lines += ["\t%s *pMsg = (%s *)m_aMsgData;" % (self.struct_name, self.struct_name)] lines += ["\t(void)pMsg;"] for v in self.variables: lines += ["\t"+line for line in v.emit_unpack()] for v in self.variables: lines += ["\t"+line for line in v.emit_unpack_check()] lines += ["} break;"] return lines def emit_declaration(self): extra = [] extra += ["\tint MsgID() const { return %s; }" % self.enum_name] extra += ["\t"] extra += ["\tbool Pack(CMsgPacker *pPacker)"] extra += ["\t{"] #extra += ["\t\tmsg_pack_start(%s, flags);"%self.enum_name] for v in self.variables: extra += ["\t\t"+line for line in v.emit_pack()] extra += ["\t\treturn pPacker->Error() != 0;"] extra += ["\t}"] lines = NetObject.emit_declaration(self) lines = lines[:-1] + extra + lines[-1:] return lines class NetVariable: def __init__(self, name): self.name = name def emit_declaration(self): return [] def emit_validate(self): return [] def emit_pack(self): return [] def emit_unpack(self): return [] def emit_unpack_check(self): return [] class NetString(NetVariable): def emit_declaration(self): return ["const char *%s;"%self.name] def emit_unpack(self): return ["pMsg->%s = pUnpacker->GetString();" % self.name] def emit_pack(self): return ["pPacker->AddString(%s, -1);" % self.name] class NetStringStrict(NetVariable): def emit_declaration(self): return ["const char *%s;"%self.name] def emit_unpack(self): return ["pMsg->%s = pUnpacker->GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES);" % self.name] def emit_pack(self): return ["pPacker->AddString(%s, -1);" % self.name] class NetIntAny(NetVariable): def emit_declaration(self): return ["int %s;"%self.name] def emit_unpack(self): return ["pMsg->%s = pUnpacker->GetInt();" % self.name] def emit_pack(self): return ["pPacker->AddInt(%s);" % self.name] class NetIntRange(NetIntAny): def __init__(self, name, min, max): NetIntAny.__init__(self,name) self.min = str(min) self.max = str(max) def emit_validate(self): return ["ClampInt(\"%s\", pObj->%s, %s, %s);"%(self.name,self.name, self.min, self.max)] def emit_unpack_check(self): return ["if(pMsg->%s < %s || pMsg->%s > %s) { m_pMsgFailedOn = \"%s\"; break; }" % (self.name, self.min, self.name, self.max, self.name)] class NetEnum(NetIntRange): def __init__(self, name, enum): NetIntRange.__init__(self, name, 0, len(enum.values)) class NetFlag(NetIntAny): def __init__(self, name, flag): NetIntAny.__init__(self, name) if len(flag.values) > 0: self.mask = "%s_%s" % (flag.name, flag.values[0]) for i in flag.values[1:]: self.mask += "|%s_%s" % (flag.name, i) else: self.mask = "0" def emit_validate(self): return ["ClampFlag(\"%s\", pObj->%s, %s);"%(self.name, self.name, self.mask)] def emit_unpack_check(self): return ["if((pMsg->%s & (%s)) != pMsg->%s) { m_pMsgFailedOn = \"%s\"; break; }" % (self.name, self.mask, self.name, self.name)] class NetBool(NetIntRange): def __init__(self, name): NetIntRange.__init__(self,name,0,1) class NetTick(NetIntRange): def __init__(self, name): NetIntRange.__init__(self,name,0,'max_int') class NetArray(NetVariable): def __init__(self, var, size): self.base_name = var.name self.var = var self.size = size self.name = self.base_name + "[%d]"%self.size def emit_declaration(self): self.var.name = self.name return self.var.emit_declaration() def emit_validate(self): lines = [] for i in range(self.size): self.var.name = self.base_name + "[%d]"%i lines += self.var.emit_validate() return lines def emit_unpack(self): lines = [] for i in range(self.size): self.var.name = self.base_name + "[%d]"%i lines += self.var.emit_unpack() return lines def emit_pack(self): lines = [] for i in range(self.size): self.var.name = self.base_name + "[%d]"%i lines += self.var.emit_pack() return lines def emit_unpack_check(self): lines = [] for i in range(self.size): self.var.name = self.base_name + "[%d]"%i lines += self.var.emit_unpack_check() return lines ================================================ FILE: datasrc/network.py ================================================ from datatypes import * Pickups = Enum("PICKUP", ["HEALTH", "ARMOR", "GRENADE", "SHOTGUN", "LASER", "NINJA"]) Emotes = Enum("EMOTE", ["NORMAL", "PAIN", "HAPPY", "SURPRISE", "ANGRY", "BLINK"]) Emoticons = Enum("EMOTICON", ["OOP", "EXCLAMATION", "HEARTS", "DROP", "DOTDOT", "MUSIC", "SORRY", "GHOST", "SUSHI", "SPLATTEE", "DEVILTEE", "ZOMG", "ZZZ", "WTF", "EYES", "QUESTION"]) Votes = Enum("VOTE", ["UNKNOWN", "START_OP", "START_KICK", "START_SPEC", "END_ABORT", "END_PASS", "END_FAIL"]) PlayerFlags = Flags("PLAYERFLAG", ["ADMIN", "CHATTING", "SCOREBOARD", "READY", "DEAD", "WATCHING"]) GameFlags = Flags("GAMEFLAG", ["TEAMS", "FLAGS", "SURVIVAL"]) GameStateFlags = Flags("GAMESTATEFLAG", ["WARMUP", "SUDDENDEATH", "ROUNDOVER", "GAMEOVER", "PAUSED", "STARTCOUNTDOWN"]) CoreEventFlags = Flags("COREEVENTFLAG", ["GROUND_JUMP", "AIR_JUMP", "HOOK_ATTACH_PLAYER", "HOOK_ATTACH_GROUND", "HOOK_HIT_NOHOOK"]) GameMsgIDs = Enum("GAMEMSG", ["TEAM_SWAP", "SPEC_INVALIDID", "TEAM_SHUFFLE", "TEAM_BALANCE", "CTF_DROP", "CTF_RETURN", "TEAM_ALL", "TEAM_BALANCE_VICTIM", "CTF_GRAB", "CTF_CAPTURE"]) RawHeader = ''' #include enum { INPUT_STATE_MASK=0x3f }; enum { TEAM_SPECTATORS=-1, TEAM_RED, TEAM_BLUE, NUM_TEAMS, FLAG_MISSING=-3, FLAG_ATSTAND, FLAG_TAKEN, SPEC_FREEVIEW=-1, }; ''' RawSource = ''' #include #include "protocol.h" ''' Enums = [ Pickups, Emotes, Emoticons, Votes, GameMsgIDs, ] Flags = [ PlayerFlags, GameFlags, GameStateFlags, CoreEventFlags, ] Objects = [ NetObject("PlayerInput", [ NetIntRange("m_Direction", -1, 1), NetIntAny("m_TargetX"), NetIntAny("m_TargetY"), NetBool("m_Jump"), NetIntAny("m_Fire"), NetBool("m_Hook"), NetFlag("m_PlayerFlags", PlayerFlags), NetIntRange("m_WantedWeapon", 0, 'NUM_WEAPONS-1'), NetIntAny("m_NextWeapon"), NetIntAny("m_PrevWeapon"), ]), NetObject("Projectile", [ NetIntAny("m_X"), NetIntAny("m_Y"), NetIntAny("m_VelX"), NetIntAny("m_VelY"), NetIntRange("m_Type", 0, 'NUM_WEAPONS-1'), NetTick("m_StartTick"), ]), NetObject("Laser", [ NetIntAny("m_X"), NetIntAny("m_Y"), NetIntAny("m_FromX"), NetIntAny("m_FromY"), NetTick("m_StartTick"), ]), NetObject("Pickup", [ NetIntAny("m_X"), NetIntAny("m_Y"), NetEnum("m_Type", Pickups), ]), NetObject("Flag", [ NetIntAny("m_X"), NetIntAny("m_Y"), NetIntRange("m_Team", 'TEAM_RED', 'TEAM_BLUE') ]), NetObject("GameData", [ NetTick("m_GameStartTick"), NetFlag("m_GameStateFlags", GameStateFlags), NetTick("m_GameStateEndTick"), ]), NetObject("GameDataTeam", [ NetIntAny("m_TeamscoreRed"), NetIntAny("m_TeamscoreBlue"), ]), NetObject("GameDataFlag", [ NetIntRange("m_FlagCarrierRed", 'FLAG_MISSING', 'MAX_CLIENTS-1'), NetIntRange("m_FlagCarrierBlue", 'FLAG_MISSING', 'MAX_CLIENTS-1'), NetTick("m_FlagDropTickRed"), NetTick("m_FlagDropTickBlue"), ]), NetObject("CharacterCore", [ NetTick("m_Tick"), NetIntAny("m_X"), NetIntAny("m_Y"), NetIntAny("m_VelX"), NetIntAny("m_VelY"), NetIntAny("m_Angle"), NetIntRange("m_Direction", -1, 1), NetIntRange("m_Jumped", 0, 3), NetIntRange("m_HookedPlayer", 0, 'MAX_CLIENTS-1'), NetIntRange("m_HookState", -1, 5), NetTick("m_HookTick"), NetIntAny("m_HookX"), NetIntAny("m_HookY"), ]), NetObject("Character:CharacterCore", [ NetIntRange("m_Health", 0, 10), NetIntRange("m_Armor", 0, 10), NetIntAny("m_AmmoCount"), NetIntRange("m_Weapon", 0, 'NUM_WEAPONS-1'), NetEnum("m_Emote", Emotes), NetTick("m_AttackTick"), NetFlag("m_TriggeredEvents", CoreEventFlags), ]), NetObject("PlayerInfo", [ NetFlag("m_PlayerFlags", PlayerFlags), NetIntAny("m_Score"), NetIntAny("m_Latency"), ]), NetObject("SpectatorInfo", [ NetIntRange("m_SpectatorID", 'SPEC_FREEVIEW', 'MAX_CLIENTS-1'), NetIntAny("m_X"), NetIntAny("m_Y"), ]), ## Demo NetObject("De_ClientInfo", [ NetBool("m_Local"), NetIntRange("m_Team", 'TEAM_SPECTATORS', 'TEAM_BLUE'), NetArray(NetIntAny("m_aName"), 4), NetArray(NetIntAny("m_aClan"), 3), NetIntAny("m_Country"), NetArray(NetArray(NetIntAny("m_aaSkinPartNames"), 6), 6), NetArray(NetBool("m_aUseCustomColors"), 6), NetArray(NetIntAny("m_aSkinPartColors"), 6), ]), NetObject("De_GameInfo", [ NetFlag("m_GameFlags", GameFlags), NetIntRange("m_ScoreLimit", 0, 'max_int'), NetIntRange("m_TimeLimit", 0, 'max_int'), NetIntRange("m_MatchNum", 0, 'max_int'), NetIntRange("m_MatchCurrent", 0, 'max_int'), ]), NetObject("De_TuneParams", [ # todo: should be done differently NetArray(NetIntAny("m_aTuneParams"), 33), ]), ## Events NetEvent("Common", [ NetIntAny("m_X"), NetIntAny("m_Y"), ]), NetEvent("Explosion:Common", []), NetEvent("Spawn:Common", []), NetEvent("HammerHit:Common", []), NetEvent("Death:Common", [ NetIntRange("m_ClientID", 0, 'MAX_CLIENTS-1'), ]), NetEvent("SoundWorld:Common", [ NetIntRange("m_SoundID", 0, 'NUM_SOUNDS-1'), ]), NetEvent("DamageInd:Common", [ NetIntAny("m_Angle"), ]), ] Messages = [ ### Server messages NetMessage("Sv_Motd", [ NetString("m_pMessage"), ]), NetMessage("Sv_Chat", [ NetIntRange("m_Team", 'TEAM_SPECTATORS', 'TEAM_BLUE'), NetIntRange("m_ClientID", -1, 'MAX_CLIENTS-1'), NetString("m_pMessage"), ]), NetMessage("Sv_Team", [ NetIntRange("m_ClientID", -1, 'MAX_CLIENTS-1'), NetIntRange("m_Team", 'TEAM_SPECTATORS', 'TEAM_BLUE'), NetBool("m_Silent"), NetTick("m_CooldownTick"), ]), NetMessage("Sv_KillMsg", [ NetIntRange("m_Killer", 0, 'MAX_CLIENTS-1'), NetIntRange("m_Victim", 0, 'MAX_CLIENTS-1'), NetIntRange("m_Weapon", -3, 'NUM_WEAPONS-1'), NetIntAny("m_ModeSpecial"), ]), NetMessage("Sv_TuneParams", []), NetMessage("Sv_ExtraProjectile", []), NetMessage("Sv_ReadyToEnter", []), NetMessage("Sv_WeaponPickup", [ NetIntRange("m_Weapon", 0, 'NUM_WEAPONS-1'), ]), NetMessage("Sv_Emoticon", [ NetIntRange("m_ClientID", 0, 'MAX_CLIENTS-1'), NetEnum("m_Emoticon", Emoticons), ]), NetMessage("Sv_VoteClearOptions", []), NetMessage("Sv_VoteOptionListAdd", []), NetMessage("Sv_VoteOptionAdd", [ NetStringStrict("m_pDescription"), ]), NetMessage("Sv_VoteOptionRemove", [ NetStringStrict("m_pDescription"), ]), NetMessage("Sv_VoteSet", [ NetIntRange("m_ClientID", -1, 'MAX_CLIENTS-1'), NetEnum("m_Type", Votes), NetIntRange("m_Timeout", 0, 60), NetStringStrict("m_pDescription"), NetStringStrict("m_pReason"), ]), NetMessage("Sv_VoteStatus", [ NetIntRange("m_Yes", 0, 'MAX_CLIENTS'), NetIntRange("m_No", 0, 'MAX_CLIENTS'), NetIntRange("m_Pass", 0, 'MAX_CLIENTS'), NetIntRange("m_Total", 0, 'MAX_CLIENTS'), ]), NetMessage("Sv_ServerSettings", [ NetBool("m_KickVote"), NetIntRange("m_KickMin", 0, 'MAX_CLIENTS'), NetBool("m_SpecVote"), NetBool("m_TeamLock"), NetBool("m_TeamBalance"), NetIntRange("m_PlayerSlots", 0, 'MAX_CLIENTS'), ]), NetMessage("Sv_ClientInfo", [ NetIntRange("m_ClientID", 0, 'MAX_CLIENTS-1'), NetBool("m_Local"), NetIntRange("m_Team", 'TEAM_SPECTATORS', 'TEAM_BLUE'), NetStringStrict("m_pName"), NetStringStrict("m_pClan"), NetIntAny("m_Country"), NetArray(NetStringStrict("m_apSkinPartNames"), 6), NetArray(NetBool("m_aUseCustomColors"), 6), NetArray(NetIntAny("m_aSkinPartColors"), 6), ]), NetMessage("Sv_GameInfo", [ NetFlag("m_GameFlags", GameFlags), NetIntRange("m_ScoreLimit", 0, 'max_int'), NetIntRange("m_TimeLimit", 0, 'max_int'), NetIntRange("m_MatchNum", 0, 'max_int'), NetIntRange("m_MatchCurrent", 0, 'max_int'), ]), NetMessage("Sv_ClientDrop", [ NetIntRange("m_ClientID", 0, 'MAX_CLIENTS-1'), NetStringStrict("m_pReason"), ]), NetMessage("Sv_GameMsg", []), ## Demo messages NetMessage("De_ClientEnter", [ NetStringStrict("m_pName"), NetIntRange("m_Team", 'TEAM_SPECTATORS', 'TEAM_BLUE'), ]), NetMessage("De_ClientLeave", [ NetStringStrict("m_pName"), NetStringStrict("m_pReason"), ]), ### Client messages NetMessage("Cl_Say", [ NetBool("m_Team"), NetString("m_pMessage"), ]), NetMessage("Cl_SetTeam", [ NetIntRange("m_Team", 'TEAM_SPECTATORS', 'TEAM_BLUE'), ]), NetMessage("Cl_SetSpectatorMode", [ NetIntRange("m_SpectatorID", 'SPEC_FREEVIEW', 'MAX_CLIENTS-1'), ]), NetMessage("Cl_StartInfo", [ NetStringStrict("m_pName"), NetStringStrict("m_pClan"), NetIntAny("m_Country"), NetArray(NetStringStrict("m_apSkinPartNames"), 6), NetArray(NetBool("m_aUseCustomColors"), 6), NetArray(NetIntAny("m_aSkinPartColors"), 6), ]), NetMessage("Cl_Kill", []), NetMessage("Cl_ReadyChange", []), NetMessage("Cl_Emoticon", [ NetEnum("m_Emoticon", Emoticons), ]), NetMessage("Cl_Vote", [ NetIntRange("m_Vote", -1, 1), ]), NetMessage("Cl_CallVote", [ NetStringStrict("m_Type"), NetStringStrict("m_Value"), NetStringStrict("m_Reason"), NetBool("m_Force"), ]), ] ================================================ FILE: license.txt ================================================ Copyright (C) 2007-2013 Magnus Auvinen This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ------------------------------------------------------------------------ All content under 'data' except the font (which has its own license) is released under CC-BY-SA 3.0 (http://creativecommons.org/licenses/by-sa/3.0/). ------------------------------------------------------------------------ IMPORTANT NOTE! The source under src/engine/external are stripped libraries with their own licenses. Mostly BSD or zlib/libpng license but check the individual libraries. ------------------------------------------------------------------------ With that being said, contact us if there is anything you want to do that the license does not permit. ================================================ FILE: other/config_directory.bat ================================================ @start explorer %APPDATA%\Teeworlds ================================================ FILE: other/freetype/VERSION ================================================ 2.4.8 ================================================ FILE: other/freetype/freetype.lua ================================================ FreeType = { basepath = PathDir(ModuleFilename()), OptFind = function (name, required) local check = function(option, settings) option.value = false option.use_ftconfig = false option.use_winlib = 0 option.lib_path = nil if ExecuteSilent("freetype-config") > 0 and ExecuteSilent("freetype-config --cflags") == 0 then option.value = true option.use_ftconfig = true end if platform == "win32" then option.value = true option.use_winlib = 32 elseif platform == "win64" then option.value = true option.use_winlib = 64 end end local apply = function(option, settings) -- include path settings.cc.includes:Add(FreeType.basepath .. "/include") if option.use_ftconfig == true then settings.cc.flags:Add("`freetype-config --cflags`") settings.link.flags:Add("`freetype-config --libs`") elseif option.use_winlib > 0 then if option.use_winlib == 32 then settings.link.libpath:Add(FreeType.basepath .. "/lib32") else settings.link.libpath:Add(FreeType.basepath .. "/lib64") end settings.link.libs:Add("freetype") end end local save = function(option, output) output:option(option, "value") output:option(option, "use_ftconfig") output:option(option, "use_winlib") end local display = function(option) if option.value == true then if option.use_ftconfig == true then return "using freetype-config" end if option.use_winlib == 32 then return "using supplied win32 libraries" end if option.use_winlib == 64 then return "using supplied win64 libraries" end return "using unknown method" else if option.required then return "not found (required)" else return "not found (optional)" end end end local o = MakeOption(name, 0, check, save, display) o.Apply = apply o.include_path = nil o.lib_path = nil o.required = required return o end } ================================================ FILE: other/freetype/include/freetype/config/ftconfig.h ================================================ /***************************************************************************/ /* */ /* ftconfig.h */ /* */ /* ANSI-specific configuration file (specification only). */ /* */ /* Copyright 1996-2004, 2006-2008, 2010-2011 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /*************************************************************************/ /* */ /* This header file contains a number of macro definitions that are used */ /* by the rest of the engine. Most of the macros here are automatically */ /* determined at compile time, and you should not need to change it to */ /* port FreeType, except to compile the library with a non-ANSI */ /* compiler. */ /* */ /* Note however that if some specific modifications are needed, we */ /* advise you to place a modified copy in your build directory. */ /* */ /* The build directory is usually `freetype/builds/', and */ /* contains system-specific files that are always included first when */ /* building the library. */ /* */ /* This ANSI version should stay in `include/freetype/config'. */ /* */ /*************************************************************************/ #ifndef __FTCONFIG_H__ #define __FTCONFIG_H__ #include #include FT_CONFIG_OPTIONS_H #include FT_CONFIG_STANDARD_LIBRARY_H FT_BEGIN_HEADER /*************************************************************************/ /* */ /* PLATFORM-SPECIFIC CONFIGURATION MACROS */ /* */ /* These macros can be toggled to suit a specific system. The current */ /* ones are defaults used to compile FreeType in an ANSI C environment */ /* (16bit compilers are also supported). Copy this file to your own */ /* `freetype/builds/' directory, and edit it to port the engine. */ /* */ /*************************************************************************/ /* There are systems (like the Texas Instruments 'C54x) where a `char' */ /* has 16 bits. ANSI C says that sizeof(char) is always 1. Since an */ /* `int' has 16 bits also for this system, sizeof(int) gives 1 which */ /* is probably unexpected. */ /* */ /* `CHAR_BIT' (defined in limits.h) gives the number of bits in a */ /* `char' type. */ #ifndef FT_CHAR_BIT #define FT_CHAR_BIT CHAR_BIT #endif /* The size of an `int' type. */ #if FT_UINT_MAX == 0xFFFFUL #define FT_SIZEOF_INT (16 / FT_CHAR_BIT) #elif FT_UINT_MAX == 0xFFFFFFFFUL #define FT_SIZEOF_INT (32 / FT_CHAR_BIT) #elif FT_UINT_MAX > 0xFFFFFFFFUL && FT_UINT_MAX == 0xFFFFFFFFFFFFFFFFUL #define FT_SIZEOF_INT (64 / FT_CHAR_BIT) #else #error "Unsupported size of `int' type!" #endif /* The size of a `long' type. A five-byte `long' (as used e.g. on the */ /* DM642) is recognized but avoided. */ #if FT_ULONG_MAX == 0xFFFFFFFFUL #define FT_SIZEOF_LONG (32 / FT_CHAR_BIT) #elif FT_ULONG_MAX > 0xFFFFFFFFUL && FT_ULONG_MAX == 0xFFFFFFFFFFUL #define FT_SIZEOF_LONG (32 / FT_CHAR_BIT) #elif FT_ULONG_MAX > 0xFFFFFFFFUL && FT_ULONG_MAX == 0xFFFFFFFFFFFFFFFFUL #define FT_SIZEOF_LONG (64 / FT_CHAR_BIT) #else #error "Unsupported size of `long' type!" #endif /* FT_UNUSED is a macro used to indicate that a given parameter is not */ /* used -- this is only used to get rid of unpleasant compiler warnings */ #ifndef FT_UNUSED #define FT_UNUSED( arg ) ( (arg) = (arg) ) #endif /*************************************************************************/ /* */ /* AUTOMATIC CONFIGURATION MACROS */ /* */ /* These macros are computed from the ones defined above. Don't touch */ /* their definition, unless you know precisely what you are doing. No */ /* porter should need to mess with them. */ /* */ /*************************************************************************/ /*************************************************************************/ /* */ /* Mac support */ /* */ /* This is the only necessary change, so it is defined here instead */ /* providing a new configuration file. */ /* */ #if ( defined( __APPLE__ ) && !defined( DARWIN_NO_CARBON ) ) || \ ( defined( __MWERKS__ ) && defined( macintosh ) ) /* no Carbon frameworks for 64bit 10.4.x */ /* AvailabilityMacros.h is available since Mac OS X 10.2, */ /* so guess the system version by maximum errno before inclusion */ #include #ifdef ECANCELED /* defined since 10.2 */ #include "AvailabilityMacros.h" #endif #if defined( __LP64__ ) && \ ( MAC_OS_X_VERSION_MIN_REQUIRED <= MAC_OS_X_VERSION_10_4 ) #define DARWIN_NO_CARBON 1 #else #define FT_MACINTOSH 1 #endif #elif defined( __SC__ ) || defined( __MRC__ ) /* Classic MacOS compilers */ #include "ConditionalMacros.h" #if TARGET_OS_MAC #define FT_MACINTOSH 1 #endif #endif /*************************************************************************/ /* */ /*
*/ /* basic_types */ /* */ /*************************************************************************/ /*************************************************************************/ /* */ /* */ /* FT_Int16 */ /* */ /* */ /* A typedef for a 16bit signed integer type. */ /* */ typedef signed short FT_Int16; /*************************************************************************/ /* */ /* */ /* FT_UInt16 */ /* */ /* */ /* A typedef for a 16bit unsigned integer type. */ /* */ typedef unsigned short FT_UInt16; /* */ /* this #if 0 ... #endif clause is for documentation purposes */ #if 0 /*************************************************************************/ /* */ /* */ /* FT_Int32 */ /* */ /* */ /* A typedef for a 32bit signed integer type. The size depends on */ /* the configuration. */ /* */ typedef signed XXX FT_Int32; /*************************************************************************/ /* */ /* */ /* FT_UInt32 */ /* */ /* A typedef for a 32bit unsigned integer type. The size depends on */ /* the configuration. */ /* */ typedef unsigned XXX FT_UInt32; /* */ #endif #if FT_SIZEOF_INT == (32 / FT_CHAR_BIT) typedef signed int FT_Int32; typedef unsigned int FT_UInt32; #elif FT_SIZEOF_LONG == (32 / FT_CHAR_BIT) typedef signed long FT_Int32; typedef unsigned long FT_UInt32; #else #error "no 32bit type found -- please check your configuration files" #endif /* look up an integer type that is at least 32 bits */ #if FT_SIZEOF_INT >= (32 / FT_CHAR_BIT) typedef int FT_Fast; typedef unsigned int FT_UFast; #elif FT_SIZEOF_LONG >= (32 / FT_CHAR_BIT) typedef long FT_Fast; typedef unsigned long FT_UFast; #endif /* determine whether we have a 64-bit int type for platforms without */ /* Autoconf */ #if FT_SIZEOF_LONG == (64 / FT_CHAR_BIT) /* FT_LONG64 must be defined if a 64-bit type is available */ #define FT_LONG64 #define FT_INT64 long #elif defined( _MSC_VER ) && _MSC_VER >= 900 /* Visual C++ (and Intel C++) */ /* this compiler provides the __int64 type */ #define FT_LONG64 #define FT_INT64 __int64 #elif defined( __BORLANDC__ ) /* Borland C++ */ /* XXXX: We should probably check the value of __BORLANDC__ in order */ /* to test the compiler version. */ /* this compiler provides the __int64 type */ #define FT_LONG64 #define FT_INT64 __int64 #elif defined( __WATCOMC__ ) /* Watcom C++ */ /* Watcom doesn't provide 64-bit data types */ #elif defined( __MWERKS__ ) /* Metrowerks CodeWarrior */ #define FT_LONG64 #define FT_INT64 long long int #elif defined( __GNUC__ ) /* GCC provides the `long long' type */ #define FT_LONG64 #define FT_INT64 long long int #endif /* FT_SIZEOF_LONG == (64 / FT_CHAR_BIT) */ /*************************************************************************/ /* */ /* A 64-bit data type will create compilation problems if you compile */ /* in strict ANSI mode. To avoid them, we disable its use if __STDC__ */ /* is defined. You can however ignore this rule by defining the */ /* FT_CONFIG_OPTION_FORCE_INT64 configuration macro. */ /* */ #if defined( FT_LONG64 ) && !defined( FT_CONFIG_OPTION_FORCE_INT64 ) #ifdef __STDC__ /* undefine the 64-bit macros in strict ANSI compilation mode */ #undef FT_LONG64 #undef FT_INT64 #endif /* __STDC__ */ #endif /* FT_LONG64 && !FT_CONFIG_OPTION_FORCE_INT64 */ #define FT_BEGIN_STMNT do { #define FT_END_STMNT } while ( 0 ) #define FT_DUMMY_STMNT FT_BEGIN_STMNT FT_END_STMNT #ifndef FT_CONFIG_OPTION_NO_ASSEMBLER /* Provide assembler fragments for performance-critical functions. */ /* These must be defined `static __inline__' with GCC. */ #if defined( __CC_ARM ) || defined( __ARMCC__ ) /* RVCT */ #define FT_MULFIX_ASSEMBLER FT_MulFix_arm /* documentation is in freetype.h */ static __inline FT_Int32 FT_MulFix_arm( FT_Int32 a, FT_Int32 b ) { register FT_Int32 t, t2; __asm { smull t2, t, b, a /* (lo=t2,hi=t) = a*b */ mov a, t, asr #31 /* a = (hi >> 31) */ add a, a, #0x8000 /* a += 0x8000 */ adds t2, t2, a /* t2 += a */ adc t, t, #0 /* t += carry */ mov a, t2, lsr #16 /* a = t2 >> 16 */ orr a, a, t, lsl #16 /* a |= t << 16 */ } return a; } #endif /* __CC_ARM || __ARMCC__ */ #ifdef __GNUC__ #if defined( __arm__ ) && !defined( __thumb__ ) && \ !( defined( __CC_ARM ) || defined( __ARMCC__ ) ) #define FT_MULFIX_ASSEMBLER FT_MulFix_arm /* documentation is in freetype.h */ static __inline__ FT_Int32 FT_MulFix_arm( FT_Int32 a, FT_Int32 b ) { register FT_Int32 t, t2; __asm__ __volatile__ ( "smull %1, %2, %4, %3\n\t" /* (lo=%1,hi=%2) = a*b */ "mov %0, %2, asr #31\n\t" /* %0 = (hi >> 31) */ "add %0, %0, #0x8000\n\t" /* %0 += 0x8000 */ "adds %1, %1, %0\n\t" /* %1 += %0 */ "adc %2, %2, #0\n\t" /* %2 += carry */ "mov %0, %1, lsr #16\n\t" /* %0 = %1 >> 16 */ "orr %0, %0, %2, lsl #16\n\t" /* %0 |= %2 << 16 */ : "=r"(a), "=&r"(t2), "=&r"(t) : "r"(a), "r"(b) ); return a; } #endif /* __arm__ && !__thumb__ && !( __CC_ARM || __ARMCC__ ) */ #if defined( __i386__ ) #define FT_MULFIX_ASSEMBLER FT_MulFix_i386 /* documentation is in freetype.h */ static __inline__ FT_Int32 FT_MulFix_i386( FT_Int32 a, FT_Int32 b ) { register FT_Int32 result; __asm__ __volatile__ ( "imul %%edx\n" "movl %%edx, %%ecx\n" "sarl $31, %%ecx\n" "addl $0x8000, %%ecx\n" "addl %%ecx, %%eax\n" "adcl $0, %%edx\n" "shrl $16, %%eax\n" "shll $16, %%edx\n" "addl %%edx, %%eax\n" : "=a"(result), "=d"(b) : "a"(a), "d"(b) : "%ecx", "cc" ); return result; } #endif /* i386 */ #endif /* __GNUC__ */ #ifdef _MSC_VER /* Visual C++ */ #ifdef _M_IX86 #define FT_MULFIX_ASSEMBLER FT_MulFix_i386 /* documentation is in freetype.h */ static __inline FT_Int32 FT_MulFix_i386( FT_Int32 a, FT_Int32 b ) { register FT_Int32 result; __asm { mov eax, a mov edx, b imul edx mov ecx, edx sar ecx, 31 add ecx, 8000h add eax, ecx adc edx, 0 shr eax, 16 shl edx, 16 add eax, edx mov result, eax } return result; } #endif /* _M_IX86 */ #endif /* _MSC_VER */ #endif /* !FT_CONFIG_OPTION_NO_ASSEMBLER */ #ifdef FT_CONFIG_OPTION_INLINE_MULFIX #ifdef FT_MULFIX_ASSEMBLER #define FT_MULFIX_INLINED FT_MULFIX_ASSEMBLER #endif #endif #ifdef FT_MAKE_OPTION_SINGLE_OBJECT #define FT_LOCAL( x ) static x #define FT_LOCAL_DEF( x ) static x #else #ifdef __cplusplus #define FT_LOCAL( x ) extern "C" x #define FT_LOCAL_DEF( x ) extern "C" x #else #define FT_LOCAL( x ) extern x #define FT_LOCAL_DEF( x ) x #endif #endif /* FT_MAKE_OPTION_SINGLE_OBJECT */ #ifndef FT_BASE #ifdef __cplusplus #define FT_BASE( x ) extern "C" x #else #define FT_BASE( x ) extern x #endif #endif /* !FT_BASE */ #ifndef FT_BASE_DEF #ifdef __cplusplus #define FT_BASE_DEF( x ) x #else #define FT_BASE_DEF( x ) x #endif #endif /* !FT_BASE_DEF */ #ifndef FT_EXPORT #ifdef __cplusplus #define FT_EXPORT( x ) extern "C" x #else #define FT_EXPORT( x ) extern x #endif #endif /* !FT_EXPORT */ #ifndef FT_EXPORT_DEF #ifdef __cplusplus #define FT_EXPORT_DEF( x ) extern "C" x #else #define FT_EXPORT_DEF( x ) extern x #endif #endif /* !FT_EXPORT_DEF */ #ifndef FT_EXPORT_VAR #ifdef __cplusplus #define FT_EXPORT_VAR( x ) extern "C" x #else #define FT_EXPORT_VAR( x ) extern x #endif #endif /* !FT_EXPORT_VAR */ /* The following macros are needed to compile the library with a */ /* C++ compiler and with 16bit compilers. */ /* */ /* This is special. Within C++, you must specify `extern "C"' for */ /* functions which are used via function pointers, and you also */ /* must do that for structures which contain function pointers to */ /* assure C linkage -- it's not possible to have (local) anonymous */ /* functions which are accessed by (global) function pointers. */ /* */ /* */ /* FT_CALLBACK_DEF is used to _define_ a callback function. */ /* */ /* FT_CALLBACK_TABLE is used to _declare_ a constant variable that */ /* contains pointers to callback functions. */ /* */ /* FT_CALLBACK_TABLE_DEF is used to _define_ a constant variable */ /* that contains pointers to callback functions. */ /* */ /* */ /* Some 16bit compilers have to redefine these macros to insert */ /* the infamous `_cdecl' or `__fastcall' declarations. */ /* */ #ifndef FT_CALLBACK_DEF #ifdef __cplusplus #define FT_CALLBACK_DEF( x ) extern "C" x #else #define FT_CALLBACK_DEF( x ) static x #endif #endif /* FT_CALLBACK_DEF */ #ifndef FT_CALLBACK_TABLE #ifdef __cplusplus #define FT_CALLBACK_TABLE extern "C" #define FT_CALLBACK_TABLE_DEF extern "C" #else #define FT_CALLBACK_TABLE extern #define FT_CALLBACK_TABLE_DEF /* nothing */ #endif #endif /* FT_CALLBACK_TABLE */ FT_END_HEADER #endif /* __FTCONFIG_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/config/ftheader.h ================================================ /***************************************************************************/ /* */ /* ftheader.h */ /* */ /* Build macros of the FreeType 2 library. */ /* */ /* Copyright 1996-2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2010 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __FT_HEADER_H__ #define __FT_HEADER_H__ /*@***********************************************************************/ /* */ /* */ /* FT_BEGIN_HEADER */ /* */ /* */ /* This macro is used in association with @FT_END_HEADER in header */ /* files to ensure that the declarations within are properly */ /* encapsulated in an `extern "C" { .. }' block when included from a */ /* C++ compiler. */ /* */ #ifdef __cplusplus #define FT_BEGIN_HEADER extern "C" { #else #define FT_BEGIN_HEADER /* nothing */ #endif /*@***********************************************************************/ /* */ /* */ /* FT_END_HEADER */ /* */ /* */ /* This macro is used in association with @FT_BEGIN_HEADER in header */ /* files to ensure that the declarations within are properly */ /* encapsulated in an `extern "C" { .. }' block when included from a */ /* C++ compiler. */ /* */ #ifdef __cplusplus #define FT_END_HEADER } #else #define FT_END_HEADER /* nothing */ #endif /*************************************************************************/ /* */ /* Aliases for the FreeType 2 public and configuration files. */ /* */ /*************************************************************************/ /*************************************************************************/ /* */ /*
*/ /* header_file_macros */ /* */ /* */ /* Header File Macros */ /* */ /* <Abstract> */ /* Macro definitions used to #include specific header files. */ /* */ /* <Description> */ /* The following macros are defined to the name of specific */ /* FreeType~2 header files. They can be used directly in #include */ /* statements as in: */ /* */ /* { */ /* #include FT_FREETYPE_H */ /* #include FT_MULTIPLE_MASTERS_H */ /* #include FT_GLYPH_H */ /* } */ /* */ /* There are several reasons why we are now using macros to name */ /* public header files. The first one is that such macros are not */ /* limited to the infamous 8.3~naming rule required by DOS (and */ /* `FT_MULTIPLE_MASTERS_H' is a lot more meaningful than `ftmm.h'). */ /* */ /* The second reason is that it allows for more flexibility in the */ /* way FreeType~2 is installed on a given system. */ /* */ /*************************************************************************/ /* configuration files */ /************************************************************************* * * @macro: * FT_CONFIG_CONFIG_H * * @description: * A macro used in #include statements to name the file containing * FreeType~2 configuration data. * */ #ifndef FT_CONFIG_CONFIG_H #define FT_CONFIG_CONFIG_H <freetype/config/ftconfig.h> #endif /************************************************************************* * * @macro: * FT_CONFIG_STANDARD_LIBRARY_H * * @description: * A macro used in #include statements to name the file containing * FreeType~2 interface to the standard C library functions. * */ #ifndef FT_CONFIG_STANDARD_LIBRARY_H #define FT_CONFIG_STANDARD_LIBRARY_H <freetype/config/ftstdlib.h> #endif /************************************************************************* * * @macro: * FT_CONFIG_OPTIONS_H * * @description: * A macro used in #include statements to name the file containing * FreeType~2 project-specific configuration options. * */ #ifndef FT_CONFIG_OPTIONS_H #define FT_CONFIG_OPTIONS_H <freetype/config/ftoption.h> #endif /************************************************************************* * * @macro: * FT_CONFIG_MODULES_H * * @description: * A macro used in #include statements to name the file containing the * list of FreeType~2 modules that are statically linked to new library * instances in @FT_Init_FreeType. * */ #ifndef FT_CONFIG_MODULES_H #define FT_CONFIG_MODULES_H <freetype/config/ftmodule.h> #endif /* */ /* public headers */ /************************************************************************* * * @macro: * FT_FREETYPE_H * * @description: * A macro used in #include statements to name the file containing the * base FreeType~2 API. * */ #define FT_FREETYPE_H <freetype/freetype.h> /************************************************************************* * * @macro: * FT_ERRORS_H * * @description: * A macro used in #include statements to name the file containing the * list of FreeType~2 error codes (and messages). * * It is included by @FT_FREETYPE_H. * */ #define FT_ERRORS_H <freetype/fterrors.h> /************************************************************************* * * @macro: * FT_MODULE_ERRORS_H * * @description: * A macro used in #include statements to name the file containing the * list of FreeType~2 module error offsets (and messages). * */ #define FT_MODULE_ERRORS_H <freetype/ftmoderr.h> /************************************************************************* * * @macro: * FT_SYSTEM_H * * @description: * A macro used in #include statements to name the file containing the * FreeType~2 interface to low-level operations (i.e., memory management * and stream i/o). * * It is included by @FT_FREETYPE_H. * */ #define FT_SYSTEM_H <freetype/ftsystem.h> /************************************************************************* * * @macro: * FT_IMAGE_H * * @description: * A macro used in #include statements to name the file containing type * definitions related to glyph images (i.e., bitmaps, outlines, * scan-converter parameters). * * It is included by @FT_FREETYPE_H. * */ #define FT_IMAGE_H <freetype/ftimage.h> /************************************************************************* * * @macro: * FT_TYPES_H * * @description: * A macro used in #include statements to name the file containing the * basic data types defined by FreeType~2. * * It is included by @FT_FREETYPE_H. * */ #define FT_TYPES_H <freetype/fttypes.h> /************************************************************************* * * @macro: * FT_LIST_H * * @description: * A macro used in #include statements to name the file containing the * list management API of FreeType~2. * * (Most applications will never need to include this file.) * */ #define FT_LIST_H <freetype/ftlist.h> /************************************************************************* * * @macro: * FT_OUTLINE_H * * @description: * A macro used in #include statements to name the file containing the * scalable outline management API of FreeType~2. * */ #define FT_OUTLINE_H <freetype/ftoutln.h> /************************************************************************* * * @macro: * FT_SIZES_H * * @description: * A macro used in #include statements to name the file containing the * API which manages multiple @FT_Size objects per face. * */ #define FT_SIZES_H <freetype/ftsizes.h> /************************************************************************* * * @macro: * FT_MODULE_H * * @description: * A macro used in #include statements to name the file containing the * module management API of FreeType~2. * */ #define FT_MODULE_H <freetype/ftmodapi.h> /************************************************************************* * * @macro: * FT_RENDER_H * * @description: * A macro used in #include statements to name the file containing the * renderer module management API of FreeType~2. * */ #define FT_RENDER_H <freetype/ftrender.h> /************************************************************************* * * @macro: * FT_TYPE1_TABLES_H * * @description: * A macro used in #include statements to name the file containing the * types and API specific to the Type~1 format. * */ #define FT_TYPE1_TABLES_H <freetype/t1tables.h> /************************************************************************* * * @macro: * FT_TRUETYPE_IDS_H * * @description: * A macro used in #include statements to name the file containing the * enumeration values which identify name strings, languages, encodings, * etc. This file really contains a _large_ set of constant macro * definitions, taken from the TrueType and OpenType specifications. * */ #define FT_TRUETYPE_IDS_H <freetype/ttnameid.h> /************************************************************************* * * @macro: * FT_TRUETYPE_TABLES_H * * @description: * A macro used in #include statements to name the file containing the * types and API specific to the TrueType (as well as OpenType) format. * */ #define FT_TRUETYPE_TABLES_H <freetype/tttables.h> /************************************************************************* * * @macro: * FT_TRUETYPE_TAGS_H * * @description: * A macro used in #include statements to name the file containing the * definitions of TrueType four-byte `tags' which identify blocks in * SFNT-based font formats (i.e., TrueType and OpenType). * */ #define FT_TRUETYPE_TAGS_H <freetype/tttags.h> /************************************************************************* * * @macro: * FT_BDF_H * * @description: * A macro used in #include statements to name the file containing the * definitions of an API which accesses BDF-specific strings from a * face. * */ #define FT_BDF_H <freetype/ftbdf.h> /************************************************************************* * * @macro: * FT_CID_H * * @description: * A macro used in #include statements to name the file containing the * definitions of an API which access CID font information from a * face. * */ #define FT_CID_H <freetype/ftcid.h> /************************************************************************* * * @macro: * FT_GZIP_H * * @description: * A macro used in #include statements to name the file containing the * definitions of an API which supports gzip-compressed files. * */ #define FT_GZIP_H <freetype/ftgzip.h> /************************************************************************* * * @macro: * FT_LZW_H * * @description: * A macro used in #include statements to name the file containing the * definitions of an API which supports LZW-compressed files. * */ #define FT_LZW_H <freetype/ftlzw.h> /************************************************************************* * * @macro: * FT_BZIP2_H * * @description: * A macro used in #include statements to name the file containing the * definitions of an API which supports bzip2-compressed files. * */ #define FT_BZIP2_H <freetype/ftbzip2.h> /************************************************************************* * * @macro: * FT_WINFONTS_H * * @description: * A macro used in #include statements to name the file containing the * definitions of an API which supports Windows FNT files. * */ #define FT_WINFONTS_H <freetype/ftwinfnt.h> /************************************************************************* * * @macro: * FT_GLYPH_H * * @description: * A macro used in #include statements to name the file containing the * API of the optional glyph management component. * */ #define FT_GLYPH_H <freetype/ftglyph.h> /************************************************************************* * * @macro: * FT_BITMAP_H * * @description: * A macro used in #include statements to name the file containing the * API of the optional bitmap conversion component. * */ #define FT_BITMAP_H <freetype/ftbitmap.h> /************************************************************************* * * @macro: * FT_BBOX_H * * @description: * A macro used in #include statements to name the file containing the * API of the optional exact bounding box computation routines. * */ #define FT_BBOX_H <freetype/ftbbox.h> /************************************************************************* * * @macro: * FT_CACHE_H * * @description: * A macro used in #include statements to name the file containing the * API of the optional FreeType~2 cache sub-system. * */ #define FT_CACHE_H <freetype/ftcache.h> /************************************************************************* * * @macro: * FT_CACHE_IMAGE_H * * @description: * A macro used in #include statements to name the file containing the * `glyph image' API of the FreeType~2 cache sub-system. * * It is used to define a cache for @FT_Glyph elements. You can also * use the API defined in @FT_CACHE_SMALL_BITMAPS_H if you only need to * store small glyph bitmaps, as it will use less memory. * * This macro is deprecated. Simply include @FT_CACHE_H to have all * glyph image-related cache declarations. * */ #define FT_CACHE_IMAGE_H FT_CACHE_H /************************************************************************* * * @macro: * FT_CACHE_SMALL_BITMAPS_H * * @description: * A macro used in #include statements to name the file containing the * `small bitmaps' API of the FreeType~2 cache sub-system. * * It is used to define a cache for small glyph bitmaps in a relatively * memory-efficient way. You can also use the API defined in * @FT_CACHE_IMAGE_H if you want to cache arbitrary glyph images, * including scalable outlines. * * This macro is deprecated. Simply include @FT_CACHE_H to have all * small bitmaps-related cache declarations. * */ #define FT_CACHE_SMALL_BITMAPS_H FT_CACHE_H /************************************************************************* * * @macro: * FT_CACHE_CHARMAP_H * * @description: * A macro used in #include statements to name the file containing the * `charmap' API of the FreeType~2 cache sub-system. * * This macro is deprecated. Simply include @FT_CACHE_H to have all * charmap-based cache declarations. * */ #define FT_CACHE_CHARMAP_H FT_CACHE_H /************************************************************************* * * @macro: * FT_MAC_H * * @description: * A macro used in #include statements to name the file containing the * Macintosh-specific FreeType~2 API. The latter is used to access * fonts embedded in resource forks. * * This header file must be explicitly included by client applications * compiled on the Mac (note that the base API still works though). * */ #define FT_MAC_H <freetype/ftmac.h> /************************************************************************* * * @macro: * FT_MULTIPLE_MASTERS_H * * @description: * A macro used in #include statements to name the file containing the * optional multiple-masters management API of FreeType~2. * */ #define FT_MULTIPLE_MASTERS_H <freetype/ftmm.h> /************************************************************************* * * @macro: * FT_SFNT_NAMES_H * * @description: * A macro used in #include statements to name the file containing the * optional FreeType~2 API which accesses embedded `name' strings in * SFNT-based font formats (i.e., TrueType and OpenType). * */ #define FT_SFNT_NAMES_H <freetype/ftsnames.h> /************************************************************************* * * @macro: * FT_OPENTYPE_VALIDATE_H * * @description: * A macro used in #include statements to name the file containing the * optional FreeType~2 API which validates OpenType tables (BASE, GDEF, * GPOS, GSUB, JSTF). * */ #define FT_OPENTYPE_VALIDATE_H <freetype/ftotval.h> /************************************************************************* * * @macro: * FT_GX_VALIDATE_H * * @description: * A macro used in #include statements to name the file containing the * optional FreeType~2 API which validates TrueTypeGX/AAT tables (feat, * mort, morx, bsln, just, kern, opbd, trak, prop). * */ #define FT_GX_VALIDATE_H <freetype/ftgxval.h> /************************************************************************* * * @macro: * FT_PFR_H * * @description: * A macro used in #include statements to name the file containing the * FreeType~2 API which accesses PFR-specific data. * */ #define FT_PFR_H <freetype/ftpfr.h> /************************************************************************* * * @macro: * FT_STROKER_H * * @description: * A macro used in #include statements to name the file containing the * FreeType~2 API which provides functions to stroke outline paths. */ #define FT_STROKER_H <freetype/ftstroke.h> /************************************************************************* * * @macro: * FT_SYNTHESIS_H * * @description: * A macro used in #include statements to name the file containing the * FreeType~2 API which performs artificial obliquing and emboldening. */ #define FT_SYNTHESIS_H <freetype/ftsynth.h> /************************************************************************* * * @macro: * FT_XFREE86_H * * @description: * A macro used in #include statements to name the file containing the * FreeType~2 API which provides functions specific to the XFree86 and * X.Org X11 servers. */ #define FT_XFREE86_H <freetype/ftxf86.h> /************************************************************************* * * @macro: * FT_TRIGONOMETRY_H * * @description: * A macro used in #include statements to name the file containing the * FreeType~2 API which performs trigonometric computations (e.g., * cosines and arc tangents). */ #define FT_TRIGONOMETRY_H <freetype/fttrigon.h> /************************************************************************* * * @macro: * FT_LCD_FILTER_H * * @description: * A macro used in #include statements to name the file containing the * FreeType~2 API which performs color filtering for subpixel rendering. */ #define FT_LCD_FILTER_H <freetype/ftlcdfil.h> /************************************************************************* * * @macro: * FT_UNPATENTED_HINTING_H * * @description: * A macro used in #include statements to name the file containing the * FreeType~2 API which performs color filtering for subpixel rendering. */ #define FT_UNPATENTED_HINTING_H <freetype/ttunpat.h> /************************************************************************* * * @macro: * FT_INCREMENTAL_H * * @description: * A macro used in #include statements to name the file containing the * FreeType~2 API which performs color filtering for subpixel rendering. */ #define FT_INCREMENTAL_H <freetype/ftincrem.h> /************************************************************************* * * @macro: * FT_GASP_H * * @description: * A macro used in #include statements to name the file containing the * FreeType~2 API which returns entries from the TrueType GASP table. */ #define FT_GASP_H <freetype/ftgasp.h> /************************************************************************* * * @macro: * FT_ADVANCES_H * * @description: * A macro used in #include statements to name the file containing the * FreeType~2 API which returns individual and ranged glyph advances. */ #define FT_ADVANCES_H <freetype/ftadvanc.h> /* */ #define FT_ERROR_DEFINITIONS_H <freetype/fterrdef.h> /* The internals of the cache sub-system are no longer exposed. We */ /* default to FT_CACHE_H at the moment just in case, but we know of */ /* no rogue client that uses them. */ /* */ #define FT_CACHE_MANAGER_H <freetype/ftcache.h> #define FT_CACHE_INTERNAL_MRU_H <freetype/ftcache.h> #define FT_CACHE_INTERNAL_MANAGER_H <freetype/ftcache.h> #define FT_CACHE_INTERNAL_CACHE_H <freetype/ftcache.h> #define FT_CACHE_INTERNAL_GLYPH_H <freetype/ftcache.h> #define FT_CACHE_INTERNAL_IMAGE_H <freetype/ftcache.h> #define FT_CACHE_INTERNAL_SBITS_H <freetype/ftcache.h> #define FT_INCREMENTAL_H <freetype/ftincrem.h> #define FT_TRUETYPE_UNPATENTED_H <freetype/ttunpat.h> /* * Include internal headers definitions from <freetype/internal/...> * only when building the library. */ #ifdef FT2_BUILD_LIBRARY #define FT_INTERNAL_INTERNAL_H <freetype/internal/internal.h> #include FT_INTERNAL_INTERNAL_H #endif /* FT2_BUILD_LIBRARY */ #endif /* __FT2_BUILD_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/config/ftmodule.h ================================================ /* * This file registers the FreeType modules compiled into the library. * * If you use GNU make, this file IS NOT USED! Instead, it is created in * the objects directory (normally `<topdir>/objs/') based on information * from `<topdir>/modules.cfg'. * * Please read `docs/INSTALL.ANY' and `docs/CUSTOMIZE' how to compile * FreeType without GNU make. * */ FT_USE_MODULE( FT_Module_Class, autofit_module_class ) FT_USE_MODULE( FT_Driver_ClassRec, tt_driver_class ) FT_USE_MODULE( FT_Driver_ClassRec, t1_driver_class ) FT_USE_MODULE( FT_Driver_ClassRec, cff_driver_class ) FT_USE_MODULE( FT_Driver_ClassRec, t1cid_driver_class ) FT_USE_MODULE( FT_Driver_ClassRec, pfr_driver_class ) FT_USE_MODULE( FT_Driver_ClassRec, t42_driver_class ) FT_USE_MODULE( FT_Driver_ClassRec, winfnt_driver_class ) FT_USE_MODULE( FT_Driver_ClassRec, pcf_driver_class ) FT_USE_MODULE( FT_Module_Class, psaux_module_class ) FT_USE_MODULE( FT_Module_Class, psnames_module_class ) FT_USE_MODULE( FT_Module_Class, pshinter_module_class ) FT_USE_MODULE( FT_Renderer_Class, ft_raster1_renderer_class ) FT_USE_MODULE( FT_Module_Class, sfnt_module_class ) FT_USE_MODULE( FT_Renderer_Class, ft_smooth_renderer_class ) FT_USE_MODULE( FT_Renderer_Class, ft_smooth_lcd_renderer_class ) FT_USE_MODULE( FT_Renderer_Class, ft_smooth_lcdv_renderer_class ) FT_USE_MODULE( FT_Driver_ClassRec, bdf_driver_class ) /* EOF */ ================================================ FILE: other/freetype/include/freetype/config/ftoption.h ================================================ /***************************************************************************/ /* */ /* ftoption.h */ /* */ /* User-selectable configuration macros (specification only). */ /* */ /* Copyright 1996-2011 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __FTOPTION_H__ #define __FTOPTION_H__ #include <ft2build.h> FT_BEGIN_HEADER /*************************************************************************/ /* */ /* USER-SELECTABLE CONFIGURATION MACROS */ /* */ /* This file contains the default configuration macro definitions for */ /* a standard build of the FreeType library. There are three ways to */ /* use this file to build project-specific versions of the library: */ /* */ /* - You can modify this file by hand, but this is not recommended in */ /* cases where you would like to build several versions of the */ /* library from a single source directory. */ /* */ /* - You can put a copy of this file in your build directory, more */ /* precisely in `$BUILD/freetype/config/ftoption.h', where `$BUILD' */ /* is the name of a directory that is included _before_ the FreeType */ /* include path during compilation. */ /* */ /* The default FreeType Makefiles and Jamfiles use the build */ /* directory `builds/<system>' by default, but you can easily change */ /* that for your own projects. */ /* */ /* - Copy the file <ft2build.h> to `$BUILD/ft2build.h' and modify it */ /* slightly to pre-define the macro FT_CONFIG_OPTIONS_H used to */ /* locate this file during the build. For example, */ /* */ /* #define FT_CONFIG_OPTIONS_H <myftoptions.h> */ /* #include <freetype/config/ftheader.h> */ /* */ /* will use `$BUILD/myftoptions.h' instead of this file for macro */ /* definitions. */ /* */ /* Note also that you can similarly pre-define the macro */ /* FT_CONFIG_MODULES_H used to locate the file listing of the modules */ /* that are statically linked to the library at compile time. By */ /* default, this file is <freetype/config/ftmodule.h>. */ /* */ /* We highly recommend using the third method whenever possible. */ /* */ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /**** ****/ /**** G E N E R A L F R E E T Y P E 2 C O N F I G U R A T I O N ****/ /**** ****/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /* */ /* Uncomment the line below if you want to activate sub-pixel rendering */ /* (a.k.a. LCD rendering, or ClearType) in this build of the library. */ /* */ /* Note that this feature is covered by several Microsoft patents */ /* and should not be activated in any default build of the library. */ /* */ /* This macro has no impact on the FreeType API, only on its */ /* _implementation_. For example, using FT_RENDER_MODE_LCD when calling */ /* FT_Render_Glyph still generates a bitmap that is 3 times wider than */ /* the original size in case this macro isn't defined; however, each */ /* triplet of subpixels has R=G=B. */ /* */ /* This is done to allow FreeType clients to run unmodified, forcing */ /* them to display normal gray-level anti-aliased glyphs. */ /* */ /* #define FT_CONFIG_OPTION_SUBPIXEL_RENDERING */ /*************************************************************************/ /* */ /* Many compilers provide a non-ANSI 64-bit data type that can be used */ /* by FreeType to speed up some computations. However, this will create */ /* some problems when compiling the library in strict ANSI mode. */ /* */ /* For this reason, the use of 64-bit integers is normally disabled when */ /* the __STDC__ macro is defined. You can however disable this by */ /* defining the macro FT_CONFIG_OPTION_FORCE_INT64 here. */ /* */ /* For most compilers, this will only create compilation warnings when */ /* building the library. */ /* */ /* ObNote: The compiler-specific 64-bit integers are detected in the */ /* file `ftconfig.h' either statically or through the */ /* `configure' script on supported platforms. */ /* */ #undef FT_CONFIG_OPTION_FORCE_INT64 /*************************************************************************/ /* */ /* If this macro is defined, do not try to use an assembler version of */ /* performance-critical functions (e.g. FT_MulFix). You should only do */ /* that to verify that the assembler function works properly, or to */ /* execute benchmark tests of the various implementations. */ /* #define FT_CONFIG_OPTION_NO_ASSEMBLER */ /*************************************************************************/ /* */ /* If this macro is defined, try to use an inlined assembler version of */ /* the `FT_MulFix' function, which is a `hotspot' when loading and */ /* hinting glyphs, and which should be executed as fast as possible. */ /* */ /* Note that if your compiler or CPU is not supported, this will default */ /* to the standard and portable implementation found in `ftcalc.c'. */ /* */ #define FT_CONFIG_OPTION_INLINE_MULFIX /*************************************************************************/ /* */ /* LZW-compressed file support. */ /* */ /* FreeType now handles font files that have been compressed with the */ /* `compress' program. This is mostly used to parse many of the PCF */ /* files that come with various X11 distributions. The implementation */ /* uses NetBSD's `zopen' to partially uncompress the file on the fly */ /* (see src/lzw/ftgzip.c). */ /* */ /* Define this macro if you want to enable this `feature'. */ /* */ #define FT_CONFIG_OPTION_USE_LZW /*************************************************************************/ /* */ /* Gzip-compressed file support. */ /* */ /* FreeType now handles font files that have been compressed with the */ /* `gzip' program. This is mostly used to parse many of the PCF files */ /* that come with XFree86. The implementation uses `zlib' to */ /* partially uncompress the file on the fly (see src/gzip/ftgzip.c). */ /* */ /* Define this macro if you want to enable this `feature'. See also */ /* the macro FT_CONFIG_OPTION_SYSTEM_ZLIB below. */ /* */ #define FT_CONFIG_OPTION_USE_ZLIB /*************************************************************************/ /* */ /* ZLib library selection */ /* */ /* This macro is only used when FT_CONFIG_OPTION_USE_ZLIB is defined. */ /* It allows FreeType's `ftgzip' component to link to the system's */ /* installation of the ZLib library. This is useful on systems like */ /* Unix or VMS where it generally is already available. */ /* */ /* If you let it undefined, the component will use its own copy */ /* of the zlib sources instead. These have been modified to be */ /* included directly within the component and *not* export external */ /* function names. This allows you to link any program with FreeType */ /* _and_ ZLib without linking conflicts. */ /* */ /* Do not #undef this macro here since the build system might define */ /* it for certain configurations only. */ /* */ /* #define FT_CONFIG_OPTION_SYSTEM_ZLIB */ /*************************************************************************/ /* */ /* Bzip2-compressed file support. */ /* */ /* FreeType now handles font files that have been compressed with the */ /* `bzip2' program. This is mostly used to parse many of the PCF */ /* files that come with XFree86. The implementation uses `libbz2' to */ /* partially uncompress the file on the fly (see src/bzip2/ftbzip2.c). */ /* Contrary to gzip, bzip2 currently is not included and need to use */ /* the system available bzip2 implementation. */ /* */ /* Define this macro if you want to enable this `feature'. */ /* */ /* #define FT_CONFIG_OPTION_USE_BZIP2 */ /*************************************************************************/ /* */ /* Define to disable the use of file stream functions and types, FILE, */ /* fopen() etc. Enables the use of smaller system libraries on embedded */ /* systems that have multiple system libraries, some with or without */ /* file stream support, in the cases where file stream support is not */ /* necessary such as memory loading of font files. */ /* */ /* #define FT_CONFIG_OPTION_DISABLE_STREAM_SUPPORT */ /*************************************************************************/ /* */ /* DLL export compilation */ /* */ /* When compiling FreeType as a DLL, some systems/compilers need a */ /* special keyword in front OR after the return type of function */ /* declarations. */ /* */ /* Two macros are used within the FreeType source code to define */ /* exported library functions: FT_EXPORT and FT_EXPORT_DEF. */ /* */ /* FT_EXPORT( return_type ) */ /* */ /* is used in a function declaration, as in */ /* */ /* FT_EXPORT( FT_Error ) */ /* FT_Init_FreeType( FT_Library* alibrary ); */ /* */ /* */ /* FT_EXPORT_DEF( return_type ) */ /* */ /* is used in a function definition, as in */ /* */ /* FT_EXPORT_DEF( FT_Error ) */ /* FT_Init_FreeType( FT_Library* alibrary ) */ /* { */ /* ... some code ... */ /* return FT_Err_Ok; */ /* } */ /* */ /* You can provide your own implementation of FT_EXPORT and */ /* FT_EXPORT_DEF here if you want. If you leave them undefined, they */ /* will be later automatically defined as `extern return_type' to */ /* allow normal compilation. */ /* */ /* Do not #undef these macros here since the build system might define */ /* them for certain configurations only. */ /* */ /* #define FT_EXPORT(x) extern x */ /* #define FT_EXPORT_DEF(x) x */ #define FT_EXPORT(x) __declspec(dllexport) x #define FT_EXPORT_DEF(x) __declspec(dllexport) x /*************************************************************************/ /* */ /* Glyph Postscript Names handling */ /* */ /* By default, FreeType 2 is compiled with the `psnames' module. This */ /* module is in charge of converting a glyph name string into a */ /* Unicode value, or return a Macintosh standard glyph name for the */ /* use with the TrueType `post' table. */ /* */ /* Undefine this macro if you do not want `psnames' compiled in your */ /* build of FreeType. This has the following effects: */ /* */ /* - The TrueType driver will provide its own set of glyph names, */ /* if you build it to support postscript names in the TrueType */ /* `post' table. */ /* */ /* - The Type 1 driver will not be able to synthesize a Unicode */ /* charmap out of the glyphs found in the fonts. */ /* */ /* You would normally undefine this configuration macro when building */ /* a version of FreeType that doesn't contain a Type 1 or CFF driver. */ /* */ #define FT_CONFIG_OPTION_POSTSCRIPT_NAMES /*************************************************************************/ /* */ /* Postscript Names to Unicode Values support */ /* */ /* By default, FreeType 2 is built with the `PSNames' module compiled */ /* in. Among other things, the module is used to convert a glyph name */ /* into a Unicode value. This is especially useful in order to */ /* synthesize on the fly a Unicode charmap from the CFF/Type 1 driver */ /* through a big table named the `Adobe Glyph List' (AGL). */ /* */ /* Undefine this macro if you do not want the Adobe Glyph List */ /* compiled in your `PSNames' module. The Type 1 driver will not be */ /* able to synthesize a Unicode charmap out of the glyphs found in the */ /* fonts. */ /* */ #define FT_CONFIG_OPTION_ADOBE_GLYPH_LIST /*************************************************************************/ /* */ /* Support for Mac fonts */ /* */ /* Define this macro if you want support for outline fonts in Mac */ /* format (mac dfont, mac resource, macbinary containing a mac */ /* resource) on non-Mac platforms. */ /* */ /* Note that the `FOND' resource isn't checked. */ /* */ #define FT_CONFIG_OPTION_MAC_FONTS /*************************************************************************/ /* */ /* Guessing methods to access embedded resource forks */ /* */ /* Enable extra Mac fonts support on non-Mac platforms (e.g. */ /* GNU/Linux). */ /* */ /* Resource forks which include fonts data are stored sometimes in */ /* locations which users or developers don't expected. In some cases, */ /* resource forks start with some offset from the head of a file. In */ /* other cases, the actual resource fork is stored in file different */ /* from what the user specifies. If this option is activated, */ /* FreeType tries to guess whether such offsets or different file */ /* names must be used. */ /* */ /* Note that normal, direct access of resource forks is controlled via */ /* the FT_CONFIG_OPTION_MAC_FONTS option. */ /* */ #ifdef FT_CONFIG_OPTION_MAC_FONTS #define FT_CONFIG_OPTION_GUESSING_EMBEDDED_RFORK #endif /*************************************************************************/ /* */ /* Allow the use of FT_Incremental_Interface to load typefaces that */ /* contain no glyph data, but supply it via a callback function. */ /* This is required by clients supporting document formats which */ /* supply font data incrementally as the document is parsed, such */ /* as the Ghostscript interpreter for the PostScript language. */ /* */ #define FT_CONFIG_OPTION_INCREMENTAL /*************************************************************************/ /* */ /* The size in bytes of the render pool used by the scan-line converter */ /* to do all of its work. */ /* */ /* This must be greater than 4KByte if you use FreeType to rasterize */ /* glyphs; otherwise, you may set it to zero to avoid unnecessary */ /* allocation of the render pool. */ /* */ #define FT_RENDER_POOL_SIZE 16384L /*************************************************************************/ /* */ /* FT_MAX_MODULES */ /* */ /* The maximum number of modules that can be registered in a single */ /* FreeType library object. 32 is the default. */ /* */ #define FT_MAX_MODULES 32 /*************************************************************************/ /* */ /* Debug level */ /* */ /* FreeType can be compiled in debug or trace mode. In debug mode, */ /* errors are reported through the `ftdebug' component. In trace */ /* mode, additional messages are sent to the standard output during */ /* execution. */ /* */ /* Define FT_DEBUG_LEVEL_ERROR to build the library in debug mode. */ /* Define FT_DEBUG_LEVEL_TRACE to build it in trace mode. */ /* */ /* Don't define any of these macros to compile in `release' mode! */ /* */ /* Do not #undef these macros here since the build system might define */ /* them for certain configurations only. */ /* */ /* #define FT_DEBUG_LEVEL_ERROR */ /* #define FT_DEBUG_LEVEL_TRACE */ /*************************************************************************/ /* */ /* Autofitter debugging */ /* */ /* If FT_DEBUG_AUTOFIT is defined, FreeType provides some means to */ /* control the autofitter behaviour for debugging purposes with global */ /* boolean variables (consequently, you should *never* enable this */ /* while compiling in `release' mode): */ /* */ /* _af_debug_disable_horz_hints */ /* _af_debug_disable_vert_hints */ /* _af_debug_disable_blue_hints */ /* */ /* Additionally, the following functions provide dumps of various */ /* internal autofit structures to stdout (using `printf'): */ /* */ /* af_glyph_hints_dump_points */ /* af_glyph_hints_dump_segments */ /* af_glyph_hints_dump_edges */ /* */ /* As an argument, they use another global variable: */ /* */ /* _af_debug_hints */ /* */ /* Please have a look at the `ftgrid' demo program to see how those */ /* variables and macros should be used. */ /* */ /* Do not #undef these macros here since the build system might define */ /* them for certain configurations only. */ /* */ /* #define FT_DEBUG_AUTOFIT */ /*************************************************************************/ /* */ /* Memory Debugging */ /* */ /* FreeType now comes with an integrated memory debugger that is */ /* capable of detecting simple errors like memory leaks or double */ /* deletes. To compile it within your build of the library, you */ /* should define FT_DEBUG_MEMORY here. */ /* */ /* Note that the memory debugger is only activated at runtime when */ /* when the _environment_ variable `FT2_DEBUG_MEMORY' is defined also! */ /* */ /* Do not #undef this macro here since the build system might define */ /* it for certain configurations only. */ /* */ /* #define FT_DEBUG_MEMORY */ /*************************************************************************/ /* */ /* Module errors */ /* */ /* If this macro is set (which is _not_ the default), the higher byte */ /* of an error code gives the module in which the error has occurred, */ /* while the lower byte is the real error code. */ /* */ /* Setting this macro makes sense for debugging purposes only, since */ /* it would break source compatibility of certain programs that use */ /* FreeType 2. */ /* */ /* More details can be found in the files ftmoderr.h and fterrors.h. */ /* */ #undef FT_CONFIG_OPTION_USE_MODULE_ERRORS /*************************************************************************/ /* */ /* Position Independent Code */ /* */ /* If this macro is set (which is _not_ the default), FreeType2 will */ /* avoid creating constants that require address fixups. Instead the */ /* constants will be moved into a struct and additional intialization */ /* code will be used. */ /* */ /* Setting this macro is needed for systems that prohibit address */ /* fixups, such as BREW. */ /* */ /* #define FT_CONFIG_OPTION_PIC */ /*************************************************************************/ /*************************************************************************/ /**** ****/ /**** S F N T D R I V E R C O N F I G U R A T I O N ****/ /**** ****/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /* */ /* Define TT_CONFIG_OPTION_EMBEDDED_BITMAPS if you want to support */ /* embedded bitmaps in all formats using the SFNT module (namely */ /* TrueType & OpenType). */ /* */ #define TT_CONFIG_OPTION_EMBEDDED_BITMAPS /*************************************************************************/ /* */ /* Define TT_CONFIG_OPTION_POSTSCRIPT_NAMES if you want to be able to */ /* load and enumerate the glyph Postscript names in a TrueType or */ /* OpenType file. */ /* */ /* Note that when you do not compile the `PSNames' module by undefining */ /* the above FT_CONFIG_OPTION_POSTSCRIPT_NAMES, the `sfnt' module will */ /* contain additional code used to read the PS Names table from a font. */ /* */ /* (By default, the module uses `PSNames' to extract glyph names.) */ /* */ #define TT_CONFIG_OPTION_POSTSCRIPT_NAMES /*************************************************************************/ /* */ /* Define TT_CONFIG_OPTION_SFNT_NAMES if your applications need to */ /* access the internal name table in a SFNT-based format like TrueType */ /* or OpenType. The name table contains various strings used to */ /* describe the font, like family name, copyright, version, etc. It */ /* does not contain any glyph name though. */ /* */ /* Accessing SFNT names is done through the functions declared in */ /* `freetype/ftsnames.h'. */ /* */ #define TT_CONFIG_OPTION_SFNT_NAMES /*************************************************************************/ /* */ /* TrueType CMap support */ /* */ /* Here you can fine-tune which TrueType CMap table format shall be */ /* supported. */ #define TT_CONFIG_CMAP_FORMAT_0 #define TT_CONFIG_CMAP_FORMAT_2 #define TT_CONFIG_CMAP_FORMAT_4 #define TT_CONFIG_CMAP_FORMAT_6 #define TT_CONFIG_CMAP_FORMAT_8 #define TT_CONFIG_CMAP_FORMAT_10 #define TT_CONFIG_CMAP_FORMAT_12 #define TT_CONFIG_CMAP_FORMAT_13 #define TT_CONFIG_CMAP_FORMAT_14 /*************************************************************************/ /*************************************************************************/ /**** ****/ /**** T R U E T Y P E D R I V E R C O N F I G U R A T I O N ****/ /**** ****/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /* */ /* Define TT_CONFIG_OPTION_BYTECODE_INTERPRETER if you want to compile */ /* a bytecode interpreter in the TrueType driver. */ /* */ /* By undefining this, you will only compile the code necessary to load */ /* TrueType glyphs without hinting. */ /* */ /* Do not #undef this macro here, since the build system might */ /* define it for certain configurations only. */ /* */ #define TT_CONFIG_OPTION_BYTECODE_INTERPRETER /*************************************************************************/ /* */ /* If you define TT_CONFIG_OPTION_UNPATENTED_HINTING, a special version */ /* of the TrueType bytecode interpreter is used that doesn't implement */ /* any of the patented opcodes and algorithms. The patents related to */ /* TrueType hinting have expired worldwide since May 2010; this option */ /* is now deprecated. */ /* */ /* Note that the TT_CONFIG_OPTION_UNPATENTED_HINTING macro is *ignored* */ /* if you define TT_CONFIG_OPTION_BYTECODE_INTERPRETER; in other words, */ /* either define TT_CONFIG_OPTION_BYTECODE_INTERPRETER or */ /* TT_CONFIG_OPTION_UNPATENTED_HINTING but not both at the same time. */ /* */ /* This macro is only useful for a small number of font files (mostly */ /* for Asian scripts) that require bytecode interpretation to properly */ /* load glyphs. For all other fonts, this produces unpleasant results, */ /* thus the unpatented interpreter is never used to load glyphs from */ /* TrueType fonts unless one of the following two options is used. */ /* */ /* - The unpatented interpreter is explicitly activated by the user */ /* through the FT_PARAM_TAG_UNPATENTED_HINTING parameter tag */ /* when opening the FT_Face. */ /* */ /* - FreeType detects that the FT_Face corresponds to one of the */ /* `trick' fonts (e.g., `Mingliu') it knows about. The font engine */ /* contains a hard-coded list of font names and other matching */ /* parameters (see function `tt_face_init' in file */ /* `src/truetype/ttobjs.c'). */ /* */ /* Here a sample code snippet for using FT_PARAM_TAG_UNPATENTED_HINTING. */ /* */ /* { */ /* FT_Parameter parameter; */ /* FT_Open_Args open_args; */ /* */ /* */ /* parameter.tag = FT_PARAM_TAG_UNPATENTED_HINTING; */ /* */ /* open_args.flags = FT_OPEN_PATHNAME | FT_OPEN_PARAMS; */ /* open_args.pathname = my_font_pathname; */ /* open_args.num_params = 1; */ /* open_args.params = ¶meter; */ /* */ /* error = FT_Open_Face( library, &open_args, index, &face ); */ /* ... */ /* } */ /* */ /* #define TT_CONFIG_OPTION_UNPATENTED_HINTING */ /*************************************************************************/ /* */ /* Define TT_CONFIG_OPTION_INTERPRETER_SWITCH to compile the TrueType */ /* bytecode interpreter with a huge switch statement, rather than a call */ /* table. This results in smaller and faster code for a number of */ /* architectures. */ /* */ /* Note however that on some compiler/processor combinations, undefining */ /* this macro will generate faster, though larger, code. */ /* */ #define TT_CONFIG_OPTION_INTERPRETER_SWITCH /*************************************************************************/ /* */ /* Define TT_CONFIG_OPTION_COMPONENT_OFFSET_SCALED to compile the */ /* TrueType glyph loader to use Apple's definition of how to handle */ /* component offsets in composite glyphs. */ /* */ /* Apple and MS disagree on the default behavior of component offsets */ /* in composites. Apple says that they should be scaled by the scaling */ /* factors in the transformation matrix (roughly, it's more complex) */ /* while MS says they should not. OpenType defines two bits in the */ /* composite flags array which can be used to disambiguate, but old */ /* fonts will not have them. */ /* */ /* http://www.microsoft.com/typography/otspec/glyf.htm */ /* http://fonts.apple.com/TTRefMan/RM06/Chap6glyf.html */ /* */ #undef TT_CONFIG_OPTION_COMPONENT_OFFSET_SCALED /*************************************************************************/ /* */ /* Define TT_CONFIG_OPTION_GX_VAR_SUPPORT if you want to include */ /* support for Apple's distortable font technology (fvar, gvar, cvar, */ /* and avar tables). This has many similarities to Type 1 Multiple */ /* Masters support. */ /* */ #define TT_CONFIG_OPTION_GX_VAR_SUPPORT /*************************************************************************/ /* */ /* Define TT_CONFIG_OPTION_BDF if you want to include support for */ /* an embedded `BDF ' table within SFNT-based bitmap formats. */ /* */ #define TT_CONFIG_OPTION_BDF /*************************************************************************/ /*************************************************************************/ /**** ****/ /**** T Y P E 1 D R I V E R C O N F I G U R A T I O N ****/ /**** ****/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /* */ /* T1_MAX_DICT_DEPTH is the maximal depth of nest dictionaries and */ /* arrays in the Type 1 stream (see t1load.c). A minimum of 4 is */ /* required. */ /* */ #define T1_MAX_DICT_DEPTH 5 /*************************************************************************/ /* */ /* T1_MAX_SUBRS_CALLS details the maximum number of nested sub-routine */ /* calls during glyph loading. */ /* */ #define T1_MAX_SUBRS_CALLS 16 /*************************************************************************/ /* */ /* T1_MAX_CHARSTRING_OPERANDS is the charstring stack's capacity. A */ /* minimum of 16 is required. */ /* */ /* The Chinese font MingTiEG-Medium (CNS 11643 character set) needs 256. */ /* */ #define T1_MAX_CHARSTRINGS_OPERANDS 256 /*************************************************************************/ /* */ /* Define this configuration macro if you want to prevent the */ /* compilation of `t1afm', which is in charge of reading Type 1 AFM */ /* files into an existing face. Note that if set, the T1 driver will be */ /* unable to produce kerning distances. */ /* */ #undef T1_CONFIG_OPTION_NO_AFM /*************************************************************************/ /* */ /* Define this configuration macro if you want to prevent the */ /* compilation of the Multiple Masters font support in the Type 1 */ /* driver. */ /* */ #undef T1_CONFIG_OPTION_NO_MM_SUPPORT /*************************************************************************/ /*************************************************************************/ /**** ****/ /**** A U T O F I T M O D U L E C O N F I G U R A T I O N ****/ /**** ****/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /* */ /* Compile autofit module with CJK (Chinese, Japanese, Korean) script */ /* support. */ /* */ #define AF_CONFIG_OPTION_CJK /*************************************************************************/ /* */ /* Compile autofit module with Indic script support. */ /* */ #define AF_CONFIG_OPTION_INDIC /*************************************************************************/ /* */ /* Compile autofit module with warp hinting. The idea of the warping */ /* code is to slightly scale and shift a glyph within a single dimension */ /* so that as much of its segments are aligned (more or less) on the */ /* grid. To find out the optimal scaling and shifting value, various */ /* parameter combinations are tried and scored. */ /* */ /* This experimental option is only active if the render mode is */ /* FT_RENDER_MODE_LIGHT. */ /* */ /* #define AF_CONFIG_OPTION_USE_WARPER */ /* */ /* * Define this variable if you want to keep the layout of internal * structures that was used prior to FreeType 2.2. This also compiles in * a few obsolete functions to avoid linking problems on typical Unix * distributions. * * For embedded systems or building a new distribution from scratch, it * is recommended to disable the macro since it reduces the library's code * size and activates a few memory-saving optimizations as well. */ #define FT_CONFIG_OPTION_OLD_INTERNALS /* * To detect legacy cache-lookup call from a rogue client (<= 2.1.7), * we restrict the number of charmaps in a font. The current API of * FTC_CMapCache_Lookup() takes cmap_index & charcode, but old API * takes charcode only. To determine the passed value is for cmap_index * or charcode, the possible cmap_index is restricted not to exceed * the minimum possible charcode by a rogue client. It is also very * unlikely that a rogue client is interested in Unicode values 0 to 15. * * NOTE: The original threshold was 4 deduced from popular number of * cmap subtables in UCS-4 TrueType fonts, but now it is not * irregular for OpenType fonts to have more than 4 subtables, * because variation selector subtables are available for Apple * and Microsoft platforms. */ #ifdef FT_CONFIG_OPTION_OLD_INTERNALS #define FT_MAX_CHARMAP_CACHEABLE 15 #endif /* * This macro is defined if either unpatented or native TrueType * hinting is requested by the definitions above. */ #ifdef TT_CONFIG_OPTION_BYTECODE_INTERPRETER #define TT_USE_BYTECODE_INTERPRETER #undef TT_CONFIG_OPTION_UNPATENTED_HINTING #elif defined TT_CONFIG_OPTION_UNPATENTED_HINTING #define TT_USE_BYTECODE_INTERPRETER #endif FT_END_HEADER #endif /* __FTOPTION_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/config/ftstdlib.h ================================================ /***************************************************************************/ /* */ /* ftstdlib.h */ /* */ /* ANSI-specific library and header configuration file (specification */ /* only). */ /* */ /* Copyright 2002-2007, 2009, 2011 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /*************************************************************************/ /* */ /* This file is used to group all #includes to the ANSI C library that */ /* FreeType normally requires. It also defines macros to rename the */ /* standard functions within the FreeType source code. */ /* */ /* Load a file which defines __FTSTDLIB_H__ before this one to override */ /* it. */ /* */ /*************************************************************************/ #ifndef __FTSTDLIB_H__ #define __FTSTDLIB_H__ #include <stddef.h> #define ft_ptrdiff_t ptrdiff_t /**********************************************************************/ /* */ /* integer limits */ /* */ /* UINT_MAX and ULONG_MAX are used to automatically compute the size */ /* of `int' and `long' in bytes at compile-time. So far, this works */ /* for all platforms the library has been tested on. */ /* */ /* Note that on the extremely rare platforms that do not provide */ /* integer types that are _exactly_ 16 and 32 bits wide (e.g. some */ /* old Crays where `int' is 36 bits), we do not make any guarantee */ /* about the correct behaviour of FT2 with all fonts. */ /* */ /* In these case, `ftconfig.h' will refuse to compile anyway with a */ /* message like `couldn't find 32-bit type' or something similar. */ /* */ /**********************************************************************/ #include <limits.h> #define FT_CHAR_BIT CHAR_BIT #define FT_USHORT_MAX USHRT_MAX #define FT_INT_MAX INT_MAX #define FT_INT_MIN INT_MIN #define FT_UINT_MAX UINT_MAX #define FT_ULONG_MAX ULONG_MAX /**********************************************************************/ /* */ /* character and string processing */ /* */ /**********************************************************************/ #include <string.h> #define ft_memchr memchr #define ft_memcmp memcmp #define ft_memcpy memcpy #define ft_memmove memmove #define ft_memset memset #define ft_strcat strcat #define ft_strcmp strcmp #define ft_strcpy strcpy #define ft_strlen strlen #define ft_strncmp strncmp #define ft_strncpy strncpy #define ft_strrchr strrchr #define ft_strstr strstr /**********************************************************************/ /* */ /* file handling */ /* */ /**********************************************************************/ #include <stdio.h> #define FT_FILE FILE #define ft_fclose fclose #define ft_fopen fopen #define ft_fread fread #define ft_fseek fseek #define ft_ftell ftell #define ft_sprintf sprintf /**********************************************************************/ /* */ /* sorting */ /* */ /**********************************************************************/ #include <stdlib.h> #define ft_qsort qsort /**********************************************************************/ /* */ /* memory allocation */ /* */ /**********************************************************************/ #define ft_scalloc calloc #define ft_sfree free #define ft_smalloc malloc #define ft_srealloc realloc /**********************************************************************/ /* */ /* miscellaneous */ /* */ /**********************************************************************/ #define ft_atol atol #define ft_labs labs /**********************************************************************/ /* */ /* execution control */ /* */ /**********************************************************************/ #include <setjmp.h> #define ft_jmp_buf jmp_buf /* note: this cannot be a typedef since */ /* jmp_buf is defined as a macro */ /* on certain platforms */ #define ft_longjmp longjmp #define ft_setjmp( b ) setjmp( *(jmp_buf*) &(b) ) /* same thing here */ /* the following is only used for debugging purposes, i.e., if */ /* FT_DEBUG_LEVEL_ERROR or FT_DEBUG_LEVEL_TRACE are defined */ #include <stdarg.h> #endif /* __FTSTDLIB_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/freetype.h ================================================ /***************************************************************************/ /* */ /* freetype.h */ /* */ /* FreeType high-level API and common types (specification only). */ /* */ /* Copyright 1996-2011 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef FT_FREETYPE_H #error "`ft2build.h' hasn't been included yet!" #error "Please always use macros to include FreeType header files." #error "Example:" #error " #include <ft2build.h>" #error " #include FT_FREETYPE_H" #endif #ifndef __FREETYPE_H__ #define __FREETYPE_H__ #include <ft2build.h> #include FT_CONFIG_CONFIG_H #include FT_ERRORS_H #include FT_TYPES_H FT_BEGIN_HEADER /*************************************************************************/ /* */ /* <Section> */ /* user_allocation */ /* */ /* <Title> */ /* User allocation */ /* */ /* <Abstract> */ /* How client applications should allocate FreeType data structures. */ /* */ /* <Description> */ /* FreeType assumes that structures allocated by the user and passed */ /* as arguments are zeroed out except for the actual data. In other */ /* words, it is recommended to use `calloc' (or variants of it) */ /* instead of `malloc' for allocation. */ /* */ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /* */ /* B A S I C T Y P E S */ /* */ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /* */ /* <Section> */ /* base_interface */ /* */ /* <Title> */ /* Base Interface */ /* */ /* <Abstract> */ /* The FreeType~2 base font interface. */ /* */ /* <Description> */ /* This section describes the public high-level API of FreeType~2. */ /* */ /* <Order> */ /* FT_Library */ /* FT_Face */ /* FT_Size */ /* FT_GlyphSlot */ /* FT_CharMap */ /* FT_Encoding */ /* */ /* FT_FaceRec */ /* */ /* FT_FACE_FLAG_SCALABLE */ /* FT_FACE_FLAG_FIXED_SIZES */ /* FT_FACE_FLAG_FIXED_WIDTH */ /* FT_FACE_FLAG_HORIZONTAL */ /* FT_FACE_FLAG_VERTICAL */ /* FT_FACE_FLAG_SFNT */ /* FT_FACE_FLAG_KERNING */ /* FT_FACE_FLAG_MULTIPLE_MASTERS */ /* FT_FACE_FLAG_GLYPH_NAMES */ /* FT_FACE_FLAG_EXTERNAL_STREAM */ /* FT_FACE_FLAG_FAST_GLYPHS */ /* FT_FACE_FLAG_HINTER */ /* */ /* FT_STYLE_FLAG_BOLD */ /* FT_STYLE_FLAG_ITALIC */ /* */ /* FT_SizeRec */ /* FT_Size_Metrics */ /* */ /* FT_GlyphSlotRec */ /* FT_Glyph_Metrics */ /* FT_SubGlyph */ /* */ /* FT_Bitmap_Size */ /* */ /* FT_Init_FreeType */ /* FT_Done_FreeType */ /* */ /* FT_New_Face */ /* FT_Done_Face */ /* FT_New_Memory_Face */ /* FT_Open_Face */ /* FT_Open_Args */ /* FT_Parameter */ /* FT_Attach_File */ /* FT_Attach_Stream */ /* */ /* FT_Set_Char_Size */ /* FT_Set_Pixel_Sizes */ /* FT_Request_Size */ /* FT_Select_Size */ /* FT_Size_Request_Type */ /* FT_Size_Request */ /* FT_Set_Transform */ /* FT_Load_Glyph */ /* FT_Get_Char_Index */ /* FT_Get_Name_Index */ /* FT_Load_Char */ /* */ /* FT_OPEN_MEMORY */ /* FT_OPEN_STREAM */ /* FT_OPEN_PATHNAME */ /* FT_OPEN_DRIVER */ /* FT_OPEN_PARAMS */ /* */ /* FT_LOAD_DEFAULT */ /* FT_LOAD_RENDER */ /* FT_LOAD_MONOCHROME */ /* FT_LOAD_LINEAR_DESIGN */ /* FT_LOAD_NO_SCALE */ /* FT_LOAD_NO_HINTING */ /* FT_LOAD_NO_BITMAP */ /* FT_LOAD_CROP_BITMAP */ /* */ /* FT_LOAD_VERTICAL_LAYOUT */ /* FT_LOAD_IGNORE_TRANSFORM */ /* FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH */ /* FT_LOAD_FORCE_AUTOHINT */ /* FT_LOAD_NO_RECURSE */ /* FT_LOAD_PEDANTIC */ /* */ /* FT_LOAD_TARGET_NORMAL */ /* FT_LOAD_TARGET_LIGHT */ /* FT_LOAD_TARGET_MONO */ /* FT_LOAD_TARGET_LCD */ /* FT_LOAD_TARGET_LCD_V */ /* */ /* FT_Render_Glyph */ /* FT_Render_Mode */ /* FT_Get_Kerning */ /* FT_Kerning_Mode */ /* FT_Get_Track_Kerning */ /* FT_Get_Glyph_Name */ /* FT_Get_Postscript_Name */ /* */ /* FT_CharMapRec */ /* FT_Select_Charmap */ /* FT_Set_Charmap */ /* FT_Get_Charmap_Index */ /* */ /* FT_FSTYPE_INSTALLABLE_EMBEDDING */ /* FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING */ /* FT_FSTYPE_PREVIEW_AND_PRINT_EMBEDDING */ /* FT_FSTYPE_EDITABLE_EMBEDDING */ /* FT_FSTYPE_NO_SUBSETTING */ /* FT_FSTYPE_BITMAP_EMBEDDING_ONLY */ /* */ /* FT_Get_FSType_Flags */ /* */ /*************************************************************************/ /*************************************************************************/ /* */ /* <Struct> */ /* FT_Glyph_Metrics */ /* */ /* <Description> */ /* A structure used to model the metrics of a single glyph. The */ /* values are expressed in 26.6 fractional pixel format; if the flag */ /* @FT_LOAD_NO_SCALE has been used while loading the glyph, values */ /* are expressed in font units instead. */ /* */ /* <Fields> */ /* width :: */ /* The glyph's width. */ /* */ /* height :: */ /* The glyph's height. */ /* */ /* horiBearingX :: */ /* Left side bearing for horizontal layout. */ /* */ /* horiBearingY :: */ /* Top side bearing for horizontal layout. */ /* */ /* horiAdvance :: */ /* Advance width for horizontal layout. */ /* */ /* vertBearingX :: */ /* Left side bearing for vertical layout. */ /* */ /* vertBearingY :: */ /* Top side bearing for vertical layout. Larger positive values */ /* mean further below the vertical glyph origin. */ /* */ /* vertAdvance :: */ /* Advance height for vertical layout. Positive values mean the */ /* glyph has a positive advance downward. */ /* */ /* <Note> */ /* If not disabled with @FT_LOAD_NO_HINTING, the values represent */ /* dimensions of the hinted glyph (in case hinting is applicable). */ /* */ typedef struct FT_Glyph_Metrics_ { FT_Pos width; FT_Pos height; FT_Pos horiBearingX; FT_Pos horiBearingY; FT_Pos horiAdvance; FT_Pos vertBearingX; FT_Pos vertBearingY; FT_Pos vertAdvance; } FT_Glyph_Metrics; /*************************************************************************/ /* */ /* <Struct> */ /* FT_Bitmap_Size */ /* */ /* <Description> */ /* This structure models the metrics of a bitmap strike (i.e., a set */ /* of glyphs for a given point size and resolution) in a bitmap font. */ /* It is used for the `available_sizes' field of @FT_Face. */ /* */ /* <Fields> */ /* height :: The vertical distance, in pixels, between two */ /* consecutive baselines. It is always positive. */ /* */ /* width :: The average width, in pixels, of all glyphs in the */ /* strike. */ /* */ /* size :: The nominal size of the strike in 26.6 fractional */ /* points. This field is not very useful. */ /* */ /* x_ppem :: The horizontal ppem (nominal width) in 26.6 fractional */ /* pixels. */ /* */ /* y_ppem :: The vertical ppem (nominal height) in 26.6 fractional */ /* pixels. */ /* */ /* <Note> */ /* Windows FNT: */ /* The nominal size given in a FNT font is not reliable. Thus when */ /* the driver finds it incorrect, it sets `size' to some calculated */ /* values and sets `x_ppem' and `y_ppem' to the pixel width and */ /* height given in the font, respectively. */ /* */ /* TrueType embedded bitmaps: */ /* `size', `width', and `height' values are not contained in the */ /* bitmap strike itself. They are computed from the global font */ /* parameters. */ /* */ typedef struct FT_Bitmap_Size_ { FT_Short height; FT_Short width; FT_Pos size; FT_Pos x_ppem; FT_Pos y_ppem; } FT_Bitmap_Size; /*************************************************************************/ /*************************************************************************/ /* */ /* O B J E C T C L A S S E S */ /* */ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /* */ /* <Type> */ /* FT_Library */ /* */ /* <Description> */ /* A handle to a FreeType library instance. Each `library' is */ /* completely independent from the others; it is the `root' of a set */ /* of objects like fonts, faces, sizes, etc. */ /* */ /* It also embeds a memory manager (see @FT_Memory), as well as a */ /* scan-line converter object (see @FT_Raster). */ /* */ /* For multi-threading applications each thread should have its own */ /* FT_Library object. */ /* */ /* <Note> */ /* Library objects are normally created by @FT_Init_FreeType, and */ /* destroyed with @FT_Done_FreeType. */ /* */ typedef struct FT_LibraryRec_ *FT_Library; /*************************************************************************/ /* */ /* <Type> */ /* FT_Module */ /* */ /* <Description> */ /* A handle to a given FreeType module object. Each module can be a */ /* font driver, a renderer, or anything else that provides services */ /* to the formers. */ /* */ typedef struct FT_ModuleRec_* FT_Module; /*************************************************************************/ /* */ /* <Type> */ /* FT_Driver */ /* */ /* <Description> */ /* A handle to a given FreeType font driver object. Each font driver */ /* is a special module capable of creating faces from font files. */ /* */ typedef struct FT_DriverRec_* FT_Driver; /*************************************************************************/ /* */ /* <Type> */ /* FT_Renderer */ /* */ /* <Description> */ /* A handle to a given FreeType renderer. A renderer is a special */ /* module in charge of converting a glyph image to a bitmap, when */ /* necessary. Each renderer supports a given glyph image format, and */ /* one or more target surface depths. */ /* */ typedef struct FT_RendererRec_* FT_Renderer; /*************************************************************************/ /* */ /* <Type> */ /* FT_Face */ /* */ /* <Description> */ /* A handle to a given typographic face object. A face object models */ /* a given typeface, in a given style. */ /* */ /* <Note> */ /* Each face object also owns a single @FT_GlyphSlot object, as well */ /* as one or more @FT_Size objects. */ /* */ /* Use @FT_New_Face or @FT_Open_Face to create a new face object from */ /* a given filepathname or a custom input stream. */ /* */ /* Use @FT_Done_Face to destroy it (along with its slot and sizes). */ /* */ /* <Also> */ /* See @FT_FaceRec for the publicly accessible fields of a given face */ /* object. */ /* */ typedef struct FT_FaceRec_* FT_Face; /*************************************************************************/ /* */ /* <Type> */ /* FT_Size */ /* */ /* <Description> */ /* A handle to an object used to model a face scaled to a given */ /* character size. */ /* */ /* <Note> */ /* Each @FT_Face has an _active_ @FT_Size object that is used by */ /* functions like @FT_Load_Glyph to determine the scaling */ /* transformation which is used to load and hint glyphs and metrics. */ /* */ /* You can use @FT_Set_Char_Size, @FT_Set_Pixel_Sizes, */ /* @FT_Request_Size or even @FT_Select_Size to change the content */ /* (i.e., the scaling values) of the active @FT_Size. */ /* */ /* You can use @FT_New_Size to create additional size objects for a */ /* given @FT_Face, but they won't be used by other functions until */ /* you activate it through @FT_Activate_Size. Only one size can be */ /* activated at any given time per face. */ /* */ /* <Also> */ /* See @FT_SizeRec for the publicly accessible fields of a given size */ /* object. */ /* */ typedef struct FT_SizeRec_* FT_Size; /*************************************************************************/ /* */ /* <Type> */ /* FT_GlyphSlot */ /* */ /* <Description> */ /* A handle to a given `glyph slot'. A slot is a container where it */ /* is possible to load any of the glyphs contained in its parent */ /* face. */ /* */ /* In other words, each time you call @FT_Load_Glyph or */ /* @FT_Load_Char, the slot's content is erased by the new glyph data, */ /* i.e., the glyph's metrics, its image (bitmap or outline), and */ /* other control information. */ /* */ /* <Also> */ /* See @FT_GlyphSlotRec for the publicly accessible glyph fields. */ /* */ typedef struct FT_GlyphSlotRec_* FT_GlyphSlot; /*************************************************************************/ /* */ /* <Type> */ /* FT_CharMap */ /* */ /* <Description> */ /* A handle to a given character map. A charmap is used to translate */ /* character codes in a given encoding into glyph indexes for its */ /* parent's face. Some font formats may provide several charmaps per */ /* font. */ /* */ /* Each face object owns zero or more charmaps, but only one of them */ /* can be `active' and used by @FT_Get_Char_Index or @FT_Load_Char. */ /* */ /* The list of available charmaps in a face is available through the */ /* `face->num_charmaps' and `face->charmaps' fields of @FT_FaceRec. */ /* */ /* The currently active charmap is available as `face->charmap'. */ /* You should call @FT_Set_Charmap to change it. */ /* */ /* <Note> */ /* When a new face is created (either through @FT_New_Face or */ /* @FT_Open_Face), the library looks for a Unicode charmap within */ /* the list and automatically activates it. */ /* */ /* <Also> */ /* See @FT_CharMapRec for the publicly accessible fields of a given */ /* character map. */ /* */ typedef struct FT_CharMapRec_* FT_CharMap; /*************************************************************************/ /* */ /* <Macro> */ /* FT_ENC_TAG */ /* */ /* <Description> */ /* This macro converts four-letter tags into an unsigned long. It is */ /* used to define `encoding' identifiers (see @FT_Encoding). */ /* */ /* <Note> */ /* Since many 16-bit compilers don't like 32-bit enumerations, you */ /* should redefine this macro in case of problems to something like */ /* this: */ /* */ /* { */ /* #define FT_ENC_TAG( value, a, b, c, d ) value */ /* } */ /* */ /* to get a simple enumeration without assigning special numbers. */ /* */ #ifndef FT_ENC_TAG #define FT_ENC_TAG( value, a, b, c, d ) \ value = ( ( (FT_UInt32)(a) << 24 ) | \ ( (FT_UInt32)(b) << 16 ) | \ ( (FT_UInt32)(c) << 8 ) | \ (FT_UInt32)(d) ) #endif /* FT_ENC_TAG */ /*************************************************************************/ /* */ /* <Enum> */ /* FT_Encoding */ /* */ /* <Description> */ /* An enumeration used to specify character sets supported by */ /* charmaps. Used in the @FT_Select_Charmap API function. */ /* */ /* <Note> */ /* Despite the name, this enumeration lists specific character */ /* repertories (i.e., charsets), and not text encoding methods (e.g., */ /* UTF-8, UTF-16, etc.). */ /* */ /* Other encodings might be defined in the future. */ /* */ /* <Values> */ /* FT_ENCODING_NONE :: */ /* The encoding value~0 is reserved. */ /* */ /* FT_ENCODING_UNICODE :: */ /* Corresponds to the Unicode character set. This value covers */ /* all versions of the Unicode repertoire, including ASCII and */ /* Latin-1. Most fonts include a Unicode charmap, but not all */ /* of them. */ /* */ /* For example, if you want to access Unicode value U+1F028 (and */ /* the font contains it), use value 0x1F028 as the input value for */ /* @FT_Get_Char_Index. */ /* */ /* FT_ENCODING_MS_SYMBOL :: */ /* Corresponds to the Microsoft Symbol encoding, used to encode */ /* mathematical symbols in the 32..255 character code range. For */ /* more information, see `http://www.ceviz.net/symbol.htm'. */ /* */ /* FT_ENCODING_SJIS :: */ /* Corresponds to Japanese SJIS encoding. More info at */ /* at `http://langsupport.japanreference.com/encoding.shtml'. */ /* See note on multi-byte encodings below. */ /* */ /* FT_ENCODING_GB2312 :: */ /* Corresponds to an encoding system for Simplified Chinese as used */ /* used in mainland China. */ /* */ /* FT_ENCODING_BIG5 :: */ /* Corresponds to an encoding system for Traditional Chinese as */ /* used in Taiwan and Hong Kong. */ /* */ /* FT_ENCODING_WANSUNG :: */ /* Corresponds to the Korean encoding system known as Wansung. */ /* For more information see */ /* `http://www.microsoft.com/typography/unicode/949.txt'. */ /* */ /* FT_ENCODING_JOHAB :: */ /* The Korean standard character set (KS~C 5601-1992), which */ /* corresponds to MS Windows code page 1361. This character set */ /* includes all possible Hangeul character combinations. */ /* */ /* FT_ENCODING_ADOBE_LATIN_1 :: */ /* Corresponds to a Latin-1 encoding as defined in a Type~1 */ /* PostScript font. It is limited to 256 character codes. */ /* */ /* FT_ENCODING_ADOBE_STANDARD :: */ /* Corresponds to the Adobe Standard encoding, as found in Type~1, */ /* CFF, and OpenType/CFF fonts. It is limited to 256 character */ /* codes. */ /* */ /* FT_ENCODING_ADOBE_EXPERT :: */ /* Corresponds to the Adobe Expert encoding, as found in Type~1, */ /* CFF, and OpenType/CFF fonts. It is limited to 256 character */ /* codes. */ /* */ /* FT_ENCODING_ADOBE_CUSTOM :: */ /* Corresponds to a custom encoding, as found in Type~1, CFF, and */ /* OpenType/CFF fonts. It is limited to 256 character codes. */ /* */ /* FT_ENCODING_APPLE_ROMAN :: */ /* Corresponds to the 8-bit Apple roman encoding. Many TrueType */ /* and OpenType fonts contain a charmap for this encoding, since */ /* older versions of Mac OS are able to use it. */ /* */ /* FT_ENCODING_OLD_LATIN_2 :: */ /* This value is deprecated and was never used nor reported by */ /* FreeType. Don't use or test for it. */ /* */ /* FT_ENCODING_MS_SJIS :: */ /* Same as FT_ENCODING_SJIS. Deprecated. */ /* */ /* FT_ENCODING_MS_GB2312 :: */ /* Same as FT_ENCODING_GB2312. Deprecated. */ /* */ /* FT_ENCODING_MS_BIG5 :: */ /* Same as FT_ENCODING_BIG5. Deprecated. */ /* */ /* FT_ENCODING_MS_WANSUNG :: */ /* Same as FT_ENCODING_WANSUNG. Deprecated. */ /* */ /* FT_ENCODING_MS_JOHAB :: */ /* Same as FT_ENCODING_JOHAB. Deprecated. */ /* */ /* <Note> */ /* By default, FreeType automatically synthesizes a Unicode charmap */ /* for PostScript fonts, using their glyph names dictionaries. */ /* However, it also reports the encodings defined explicitly in the */ /* font file, for the cases when they are needed, with the Adobe */ /* values as well. */ /* */ /* FT_ENCODING_NONE is set by the BDF and PCF drivers if the charmap */ /* is neither Unicode nor ISO-8859-1 (otherwise it is set to */ /* FT_ENCODING_UNICODE). Use @FT_Get_BDF_Charset_ID to find out */ /* which encoding is really present. If, for example, the */ /* `cs_registry' field is `KOI8' and the `cs_encoding' field is `R', */ /* the font is encoded in KOI8-R. */ /* */ /* FT_ENCODING_NONE is always set (with a single exception) by the */ /* winfonts driver. Use @FT_Get_WinFNT_Header and examine the */ /* `charset' field of the @FT_WinFNT_HeaderRec structure to find out */ /* which encoding is really present. For example, */ /* @FT_WinFNT_ID_CP1251 (204) means Windows code page 1251 (for */ /* Russian). */ /* */ /* FT_ENCODING_NONE is set if `platform_id' is @TT_PLATFORM_MACINTOSH */ /* and `encoding_id' is not @TT_MAC_ID_ROMAN (otherwise it is set to */ /* FT_ENCODING_APPLE_ROMAN). */ /* */ /* If `platform_id' is @TT_PLATFORM_MACINTOSH, use the function */ /* @FT_Get_CMap_Language_ID to query the Mac language ID which may */ /* be needed to be able to distinguish Apple encoding variants. See */ /* */ /* http://www.unicode.org/Public/MAPPINGS/VENDORS/APPLE/README.TXT */ /* */ /* to get an idea how to do that. Basically, if the language ID */ /* is~0, don't use it, otherwise subtract 1 from the language ID. */ /* Then examine `encoding_id'. If, for example, `encoding_id' is */ /* @TT_MAC_ID_ROMAN and the language ID (minus~1) is */ /* `TT_MAC_LANGID_GREEK', it is the Greek encoding, not Roman. */ /* @TT_MAC_ID_ARABIC with `TT_MAC_LANGID_FARSI' means the Farsi */ /* variant the Arabic encoding. */ /* */ typedef enum FT_Encoding_ { FT_ENC_TAG( FT_ENCODING_NONE, 0, 0, 0, 0 ), FT_ENC_TAG( FT_ENCODING_MS_SYMBOL, 's', 'y', 'm', 'b' ), FT_ENC_TAG( FT_ENCODING_UNICODE, 'u', 'n', 'i', 'c' ), FT_ENC_TAG( FT_ENCODING_SJIS, 's', 'j', 'i', 's' ), FT_ENC_TAG( FT_ENCODING_GB2312, 'g', 'b', ' ', ' ' ), FT_ENC_TAG( FT_ENCODING_BIG5, 'b', 'i', 'g', '5' ), FT_ENC_TAG( FT_ENCODING_WANSUNG, 'w', 'a', 'n', 's' ), FT_ENC_TAG( FT_ENCODING_JOHAB, 'j', 'o', 'h', 'a' ), /* for backwards compatibility */ FT_ENCODING_MS_SJIS = FT_ENCODING_SJIS, FT_ENCODING_MS_GB2312 = FT_ENCODING_GB2312, FT_ENCODING_MS_BIG5 = FT_ENCODING_BIG5, FT_ENCODING_MS_WANSUNG = FT_ENCODING_WANSUNG, FT_ENCODING_MS_JOHAB = FT_ENCODING_JOHAB, FT_ENC_TAG( FT_ENCODING_ADOBE_STANDARD, 'A', 'D', 'O', 'B' ), FT_ENC_TAG( FT_ENCODING_ADOBE_EXPERT, 'A', 'D', 'B', 'E' ), FT_ENC_TAG( FT_ENCODING_ADOBE_CUSTOM, 'A', 'D', 'B', 'C' ), FT_ENC_TAG( FT_ENCODING_ADOBE_LATIN_1, 'l', 'a', 't', '1' ), FT_ENC_TAG( FT_ENCODING_OLD_LATIN_2, 'l', 'a', 't', '2' ), FT_ENC_TAG( FT_ENCODING_APPLE_ROMAN, 'a', 'r', 'm', 'n' ) } FT_Encoding; /*************************************************************************/ /* */ /* <Enum> */ /* ft_encoding_xxx */ /* */ /* <Description> */ /* These constants are deprecated; use the corresponding @FT_Encoding */ /* values instead. */ /* */ #define ft_encoding_none FT_ENCODING_NONE #define ft_encoding_unicode FT_ENCODING_UNICODE #define ft_encoding_symbol FT_ENCODING_MS_SYMBOL #define ft_encoding_latin_1 FT_ENCODING_ADOBE_LATIN_1 #define ft_encoding_latin_2 FT_ENCODING_OLD_LATIN_2 #define ft_encoding_sjis FT_ENCODING_SJIS #define ft_encoding_gb2312 FT_ENCODING_GB2312 #define ft_encoding_big5 FT_ENCODING_BIG5 #define ft_encoding_wansung FT_ENCODING_WANSUNG #define ft_encoding_johab FT_ENCODING_JOHAB #define ft_encoding_adobe_standard FT_ENCODING_ADOBE_STANDARD #define ft_encoding_adobe_expert FT_ENCODING_ADOBE_EXPERT #define ft_encoding_adobe_custom FT_ENCODING_ADOBE_CUSTOM #define ft_encoding_apple_roman FT_ENCODING_APPLE_ROMAN /*************************************************************************/ /* */ /* <Struct> */ /* FT_CharMapRec */ /* */ /* <Description> */ /* The base charmap structure. */ /* */ /* <Fields> */ /* face :: A handle to the parent face object. */ /* */ /* encoding :: An @FT_Encoding tag identifying the charmap. Use */ /* this with @FT_Select_Charmap. */ /* */ /* platform_id :: An ID number describing the platform for the */ /* following encoding ID. This comes directly from */ /* the TrueType specification and should be emulated */ /* for other formats. */ /* */ /* encoding_id :: A platform specific encoding number. This also */ /* comes from the TrueType specification and should be */ /* emulated similarly. */ /* */ typedef struct FT_CharMapRec_ { FT_Face face; FT_Encoding encoding; FT_UShort platform_id; FT_UShort encoding_id; } FT_CharMapRec; /*************************************************************************/ /*************************************************************************/ /* */ /* B A S E O B J E C T C L A S S E S */ /* */ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /* */ /* <Type> */ /* FT_Face_Internal */ /* */ /* <Description> */ /* An opaque handle to an `FT_Face_InternalRec' structure, used to */ /* model private data of a given @FT_Face object. */ /* */ /* This structure might change between releases of FreeType~2 and is */ /* not generally available to client applications. */ /* */ typedef struct FT_Face_InternalRec_* FT_Face_Internal; /*************************************************************************/ /* */ /* <Struct> */ /* FT_FaceRec */ /* */ /* <Description> */ /* FreeType root face class structure. A face object models a */ /* typeface in a font file. */ /* */ /* <Fields> */ /* num_faces :: The number of faces in the font file. Some */ /* font formats can have multiple faces in */ /* a font file. */ /* */ /* face_index :: The index of the face in the font file. It */ /* is set to~0 if there is only one face in */ /* the font file. */ /* */ /* face_flags :: A set of bit flags that give important */ /* information about the face; see */ /* @FT_FACE_FLAG_XXX for the details. */ /* */ /* style_flags :: A set of bit flags indicating the style of */ /* the face; see @FT_STYLE_FLAG_XXX for the */ /* details. */ /* */ /* num_glyphs :: The number of glyphs in the face. If the */ /* face is scalable and has sbits (see */ /* `num_fixed_sizes'), it is set to the number */ /* of outline glyphs. */ /* */ /* For CID-keyed fonts, this value gives the */ /* highest CID used in the font. */ /* */ /* family_name :: The face's family name. This is an ASCII */ /* string, usually in English, which describes */ /* the typeface's family (like `Times New */ /* Roman', `Bodoni', `Garamond', etc). This */ /* is a least common denominator used to list */ /* fonts. Some formats (TrueType & OpenType) */ /* provide localized and Unicode versions of */ /* this string. Applications should use the */ /* format specific interface to access them. */ /* Can be NULL (e.g., in fonts embedded in a */ /* PDF file). */ /* */ /* style_name :: The face's style name. This is an ASCII */ /* string, usually in English, which describes */ /* the typeface's style (like `Italic', */ /* `Bold', `Condensed', etc). Not all font */ /* formats provide a style name, so this field */ /* is optional, and can be set to NULL. As */ /* for `family_name', some formats provide */ /* localized and Unicode versions of this */ /* string. Applications should use the format */ /* specific interface to access them. */ /* */ /* num_fixed_sizes :: The number of bitmap strikes in the face. */ /* Even if the face is scalable, there might */ /* still be bitmap strikes, which are called */ /* `sbits' in that case. */ /* */ /* available_sizes :: An array of @FT_Bitmap_Size for all bitmap */ /* strikes in the face. It is set to NULL if */ /* there is no bitmap strike. */ /* */ /* num_charmaps :: The number of charmaps in the face. */ /* */ /* charmaps :: An array of the charmaps of the face. */ /* */ /* generic :: A field reserved for client uses. See the */ /* @FT_Generic type description. */ /* */ /* bbox :: The font bounding box. Coordinates are */ /* expressed in font units (see */ /* `units_per_EM'). The box is large enough */ /* to contain any glyph from the font. Thus, */ /* `bbox.yMax' can be seen as the `maximal */ /* ascender', and `bbox.yMin' as the `minimal */ /* descender'. Only relevant for scalable */ /* formats. */ /* */ /* Note that the bounding box might be off by */ /* (at least) one pixel for hinted fonts. See */ /* @FT_Size_Metrics for further discussion. */ /* */ /* units_per_EM :: The number of font units per EM square for */ /* this face. This is typically 2048 for */ /* TrueType fonts, and 1000 for Type~1 fonts. */ /* Only relevant for scalable formats. */ /* */ /* ascender :: The typographic ascender of the face, */ /* expressed in font units. For font formats */ /* not having this information, it is set to */ /* `bbox.yMax'. Only relevant for scalable */ /* formats. */ /* */ /* descender :: The typographic descender of the face, */ /* expressed in font units. For font formats */ /* not having this information, it is set to */ /* `bbox.yMin'. Note that this field is */ /* usually negative. Only relevant for */ /* scalable formats. */ /* */ /* height :: The height is the vertical distance */ /* between two consecutive baselines, */ /* expressed in font units. It is always */ /* positive. Only relevant for scalable */ /* formats. */ /* */ /* max_advance_width :: The maximal advance width, in font units, */ /* for all glyphs in this face. This can be */ /* used to make word wrapping computations */ /* faster. Only relevant for scalable */ /* formats. */ /* */ /* max_advance_height :: The maximal advance height, in font units, */ /* for all glyphs in this face. This is only */ /* relevant for vertical layouts, and is set */ /* to `height' for fonts that do not provide */ /* vertical metrics. Only relevant for */ /* scalable formats. */ /* */ /* underline_position :: The position, in font units, of the */ /* underline line for this face. It is the */ /* center of the underlining stem. Only */ /* relevant for scalable formats. */ /* */ /* underline_thickness :: The thickness, in font units, of the */ /* underline for this face. Only relevant for */ /* scalable formats. */ /* */ /* glyph :: The face's associated glyph slot(s). */ /* */ /* size :: The current active size for this face. */ /* */ /* charmap :: The current active charmap for this face. */ /* */ /* <Note> */ /* Fields may be changed after a call to @FT_Attach_File or */ /* @FT_Attach_Stream. */ /* */ typedef struct FT_FaceRec_ { FT_Long num_faces; FT_Long face_index; FT_Long face_flags; FT_Long style_flags; FT_Long num_glyphs; FT_String* family_name; FT_String* style_name; FT_Int num_fixed_sizes; FT_Bitmap_Size* available_sizes; FT_Int num_charmaps; FT_CharMap* charmaps; FT_Generic generic; /*# The following member variables (down to `underline_thickness') */ /*# are only relevant to scalable outlines; cf. @FT_Bitmap_Size */ /*# for bitmap fonts. */ FT_BBox bbox; FT_UShort units_per_EM; FT_Short ascender; FT_Short descender; FT_Short height; FT_Short max_advance_width; FT_Short max_advance_height; FT_Short underline_position; FT_Short underline_thickness; FT_GlyphSlot glyph; FT_Size size; FT_CharMap charmap; /*@private begin */ FT_Driver driver; FT_Memory memory; FT_Stream stream; FT_ListRec sizes_list; FT_Generic autohint; void* extensions; FT_Face_Internal internal; /*@private end */ } FT_FaceRec; /*************************************************************************/ /* */ /* <Enum> */ /* FT_FACE_FLAG_XXX */ /* */ /* <Description> */ /* A list of bit flags used in the `face_flags' field of the */ /* @FT_FaceRec structure. They inform client applications of */ /* properties of the corresponding face. */ /* */ /* <Values> */ /* FT_FACE_FLAG_SCALABLE :: */ /* Indicates that the face contains outline glyphs. This doesn't */ /* prevent bitmap strikes, i.e., a face can have both this and */ /* and @FT_FACE_FLAG_FIXED_SIZES set. */ /* */ /* FT_FACE_FLAG_FIXED_SIZES :: */ /* Indicates that the face contains bitmap strikes. See also the */ /* `num_fixed_sizes' and `available_sizes' fields of @FT_FaceRec. */ /* */ /* FT_FACE_FLAG_FIXED_WIDTH :: */ /* Indicates that the face contains fixed-width characters (like */ /* Courier, Lucido, MonoType, etc.). */ /* */ /* FT_FACE_FLAG_SFNT :: */ /* Indicates that the face uses the `sfnt' storage scheme. For */ /* now, this means TrueType and OpenType. */ /* */ /* FT_FACE_FLAG_HORIZONTAL :: */ /* Indicates that the face contains horizontal glyph metrics. This */ /* should be set for all common formats. */ /* */ /* FT_FACE_FLAG_VERTICAL :: */ /* Indicates that the face contains vertical glyph metrics. This */ /* is only available in some formats, not all of them. */ /* */ /* FT_FACE_FLAG_KERNING :: */ /* Indicates that the face contains kerning information. If set, */ /* the kerning distance can be retrieved through the function */ /* @FT_Get_Kerning. Otherwise the function always return the */ /* vector (0,0). Note that FreeType doesn't handle kerning data */ /* from the `GPOS' table (as present in some OpenType fonts). */ /* */ /* FT_FACE_FLAG_FAST_GLYPHS :: */ /* THIS FLAG IS DEPRECATED. DO NOT USE OR TEST IT. */ /* */ /* FT_FACE_FLAG_MULTIPLE_MASTERS :: */ /* Indicates that the font contains multiple masters and is capable */ /* of interpolating between them. See the multiple-masters */ /* specific API for details. */ /* */ /* FT_FACE_FLAG_GLYPH_NAMES :: */ /* Indicates that the font contains glyph names that can be */ /* retrieved through @FT_Get_Glyph_Name. Note that some TrueType */ /* fonts contain broken glyph name tables. Use the function */ /* @FT_Has_PS_Glyph_Names when needed. */ /* */ /* FT_FACE_FLAG_EXTERNAL_STREAM :: */ /* Used internally by FreeType to indicate that a face's stream was */ /* provided by the client application and should not be destroyed */ /* when @FT_Done_Face is called. Don't read or test this flag. */ /* */ /* FT_FACE_FLAG_HINTER :: */ /* Set if the font driver has a hinting machine of its own. For */ /* example, with TrueType fonts, it makes sense to use data from */ /* the SFNT `gasp' table only if the native TrueType hinting engine */ /* (with the bytecode interpreter) is available and active. */ /* */ /* FT_FACE_FLAG_CID_KEYED :: */ /* Set if the font is CID-keyed. In that case, the font is not */ /* accessed by glyph indices but by CID values. For subsetted */ /* CID-keyed fonts this has the consequence that not all index */ /* values are a valid argument to FT_Load_Glyph. Only the CID */ /* values for which corresponding glyphs in the subsetted font */ /* exist make FT_Load_Glyph return successfully; in all other cases */ /* you get an `FT_Err_Invalid_Argument' error. */ /* */ /* Note that CID-keyed fonts which are in an SFNT wrapper don't */ /* have this flag set since the glyphs are accessed in the normal */ /* way (using contiguous indices); the `CID-ness' isn't visible to */ /* the application. */ /* */ /* FT_FACE_FLAG_TRICKY :: */ /* Set if the font is `tricky', this is, it always needs the */ /* font format's native hinting engine to get a reasonable result. */ /* A typical example is the Chinese font `mingli.ttf' which uses */ /* TrueType bytecode instructions to move and scale all of its */ /* subglyphs. */ /* */ /* It is not possible to autohint such fonts using */ /* @FT_LOAD_FORCE_AUTOHINT; it will also ignore */ /* @FT_LOAD_NO_HINTING. You have to set both @FT_LOAD_NO_HINTING */ /* and @FT_LOAD_NO_AUTOHINT to really disable hinting; however, you */ /* probably never want this except for demonstration purposes. */ /* */ /* Currently, there are about a dozen TrueType fonts in the list of */ /* tricky fonts; they are hard-coded in file `ttobjs.c'. */ /* */ #define FT_FACE_FLAG_SCALABLE ( 1L << 0 ) #define FT_FACE_FLAG_FIXED_SIZES ( 1L << 1 ) #define FT_FACE_FLAG_FIXED_WIDTH ( 1L << 2 ) #define FT_FACE_FLAG_SFNT ( 1L << 3 ) #define FT_FACE_FLAG_HORIZONTAL ( 1L << 4 ) #define FT_FACE_FLAG_VERTICAL ( 1L << 5 ) #define FT_FACE_FLAG_KERNING ( 1L << 6 ) #define FT_FACE_FLAG_FAST_GLYPHS ( 1L << 7 ) #define FT_FACE_FLAG_MULTIPLE_MASTERS ( 1L << 8 ) #define FT_FACE_FLAG_GLYPH_NAMES ( 1L << 9 ) #define FT_FACE_FLAG_EXTERNAL_STREAM ( 1L << 10 ) #define FT_FACE_FLAG_HINTER ( 1L << 11 ) #define FT_FACE_FLAG_CID_KEYED ( 1L << 12 ) #define FT_FACE_FLAG_TRICKY ( 1L << 13 ) /************************************************************************* * * @macro: * FT_HAS_HORIZONTAL( face ) * * @description: * A macro that returns true whenever a face object contains * horizontal metrics (this is true for all font formats though). * * @also: * @FT_HAS_VERTICAL can be used to check for vertical metrics. * */ #define FT_HAS_HORIZONTAL( face ) \ ( face->face_flags & FT_FACE_FLAG_HORIZONTAL ) /************************************************************************* * * @macro: * FT_HAS_VERTICAL( face ) * * @description: * A macro that returns true whenever a face object contains vertical * metrics. * */ #define FT_HAS_VERTICAL( face ) \ ( face->face_flags & FT_FACE_FLAG_VERTICAL ) /************************************************************************* * * @macro: * FT_HAS_KERNING( face ) * * @description: * A macro that returns true whenever a face object contains kerning * data that can be accessed with @FT_Get_Kerning. * */ #define FT_HAS_KERNING( face ) \ ( face->face_flags & FT_FACE_FLAG_KERNING ) /************************************************************************* * * @macro: * FT_IS_SCALABLE( face ) * * @description: * A macro that returns true whenever a face object contains a scalable * font face (true for TrueType, Type~1, Type~42, CID, OpenType/CFF, * and PFR font formats. * */ #define FT_IS_SCALABLE( face ) \ ( face->face_flags & FT_FACE_FLAG_SCALABLE ) /************************************************************************* * * @macro: * FT_IS_SFNT( face ) * * @description: * A macro that returns true whenever a face object contains a font * whose format is based on the SFNT storage scheme. This usually * means: TrueType fonts, OpenType fonts, as well as SFNT-based embedded * bitmap fonts. * * If this macro is true, all functions defined in @FT_SFNT_NAMES_H and * @FT_TRUETYPE_TABLES_H are available. * */ #define FT_IS_SFNT( face ) \ ( face->face_flags & FT_FACE_FLAG_SFNT ) /************************************************************************* * * @macro: * FT_IS_FIXED_WIDTH( face ) * * @description: * A macro that returns true whenever a face object contains a font face * that contains fixed-width (or `monospace', `fixed-pitch', etc.) * glyphs. * */ #define FT_IS_FIXED_WIDTH( face ) \ ( face->face_flags & FT_FACE_FLAG_FIXED_WIDTH ) /************************************************************************* * * @macro: * FT_HAS_FIXED_SIZES( face ) * * @description: * A macro that returns true whenever a face object contains some * embedded bitmaps. See the `available_sizes' field of the * @FT_FaceRec structure. * */ #define FT_HAS_FIXED_SIZES( face ) \ ( face->face_flags & FT_FACE_FLAG_FIXED_SIZES ) /************************************************************************* * * @macro: * FT_HAS_FAST_GLYPHS( face ) * * @description: * Deprecated. * */ #define FT_HAS_FAST_GLYPHS( face ) 0 /************************************************************************* * * @macro: * FT_HAS_GLYPH_NAMES( face ) * * @description: * A macro that returns true whenever a face object contains some glyph * names that can be accessed through @FT_Get_Glyph_Name. * */ #define FT_HAS_GLYPH_NAMES( face ) \ ( face->face_flags & FT_FACE_FLAG_GLYPH_NAMES ) /************************************************************************* * * @macro: * FT_HAS_MULTIPLE_MASTERS( face ) * * @description: * A macro that returns true whenever a face object contains some * multiple masters. The functions provided by @FT_MULTIPLE_MASTERS_H * are then available to choose the exact design you want. * */ #define FT_HAS_MULTIPLE_MASTERS( face ) \ ( face->face_flags & FT_FACE_FLAG_MULTIPLE_MASTERS ) /************************************************************************* * * @macro: * FT_IS_CID_KEYED( face ) * * @description: * A macro that returns true whenever a face object contains a CID-keyed * font. See the discussion of @FT_FACE_FLAG_CID_KEYED for more * details. * * If this macro is true, all functions defined in @FT_CID_H are * available. * */ #define FT_IS_CID_KEYED( face ) \ ( face->face_flags & FT_FACE_FLAG_CID_KEYED ) /************************************************************************* * * @macro: * FT_IS_TRICKY( face ) * * @description: * A macro that returns true whenever a face represents a `tricky' font. * See the discussion of @FT_FACE_FLAG_TRICKY for more details. * */ #define FT_IS_TRICKY( face ) \ ( face->face_flags & FT_FACE_FLAG_TRICKY ) /*************************************************************************/ /* */ /* <Const> */ /* FT_STYLE_FLAG_XXX */ /* */ /* <Description> */ /* A list of bit-flags used to indicate the style of a given face. */ /* These are used in the `style_flags' field of @FT_FaceRec. */ /* */ /* <Values> */ /* FT_STYLE_FLAG_ITALIC :: */ /* Indicates that a given face style is italic or oblique. */ /* */ /* FT_STYLE_FLAG_BOLD :: */ /* Indicates that a given face is bold. */ /* */ /* <Note> */ /* The style information as provided by FreeType is very basic. More */ /* details are beyond the scope and should be done on a higher level */ /* (for example, by analyzing various fields of the `OS/2' table in */ /* SFNT based fonts). */ /* */ #define FT_STYLE_FLAG_ITALIC ( 1 << 0 ) #define FT_STYLE_FLAG_BOLD ( 1 << 1 ) /*************************************************************************/ /* */ /* <Type> */ /* FT_Size_Internal */ /* */ /* <Description> */ /* An opaque handle to an `FT_Size_InternalRec' structure, used to */ /* model private data of a given @FT_Size object. */ /* */ typedef struct FT_Size_InternalRec_* FT_Size_Internal; /*************************************************************************/ /* */ /* <Struct> */ /* FT_Size_Metrics */ /* */ /* <Description> */ /* The size metrics structure gives the metrics of a size object. */ /* */ /* <Fields> */ /* x_ppem :: The width of the scaled EM square in pixels, hence */ /* the term `ppem' (pixels per EM). It is also */ /* referred to as `nominal width'. */ /* */ /* y_ppem :: The height of the scaled EM square in pixels, */ /* hence the term `ppem' (pixels per EM). It is also */ /* referred to as `nominal height'. */ /* */ /* x_scale :: A 16.16 fractional scaling value used to convert */ /* horizontal metrics from font units to 26.6 */ /* fractional pixels. Only relevant for scalable */ /* font formats. */ /* */ /* y_scale :: A 16.16 fractional scaling value used to convert */ /* vertical metrics from font units to 26.6 */ /* fractional pixels. Only relevant for scalable */ /* font formats. */ /* */ /* ascender :: The ascender in 26.6 fractional pixels. See */ /* @FT_FaceRec for the details. */ /* */ /* descender :: The descender in 26.6 fractional pixels. See */ /* @FT_FaceRec for the details. */ /* */ /* height :: The height in 26.6 fractional pixels. See */ /* @FT_FaceRec for the details. */ /* */ /* max_advance :: The maximal advance width in 26.6 fractional */ /* pixels. See @FT_FaceRec for the details. */ /* */ /* <Note> */ /* The scaling values, if relevant, are determined first during a */ /* size changing operation. The remaining fields are then set by the */ /* driver. For scalable formats, they are usually set to scaled */ /* values of the corresponding fields in @FT_FaceRec. */ /* */ /* Note that due to glyph hinting, these values might not be exact */ /* for certain fonts. Thus they must be treated as unreliable */ /* with an error margin of at least one pixel! */ /* */ /* Indeed, the only way to get the exact metrics is to render _all_ */ /* glyphs. As this would be a definite performance hit, it is up to */ /* client applications to perform such computations. */ /* */ /* The FT_Size_Metrics structure is valid for bitmap fonts also. */ /* */ typedef struct FT_Size_Metrics_ { FT_UShort x_ppem; /* horizontal pixels per EM */ FT_UShort y_ppem; /* vertical pixels per EM */ FT_Fixed x_scale; /* scaling values used to convert font */ FT_Fixed y_scale; /* units to 26.6 fractional pixels */ FT_Pos ascender; /* ascender in 26.6 frac. pixels */ FT_Pos descender; /* descender in 26.6 frac. pixels */ FT_Pos height; /* text height in 26.6 frac. pixels */ FT_Pos max_advance; /* max horizontal advance, in 26.6 pixels */ } FT_Size_Metrics; /*************************************************************************/ /* */ /* <Struct> */ /* FT_SizeRec */ /* */ /* <Description> */ /* FreeType root size class structure. A size object models a face */ /* object at a given size. */ /* */ /* <Fields> */ /* face :: Handle to the parent face object. */ /* */ /* generic :: A typeless pointer, which is unused by the FreeType */ /* library or any of its drivers. It can be used by */ /* client applications to link their own data to each size */ /* object. */ /* */ /* metrics :: Metrics for this size object. This field is read-only. */ /* */ typedef struct FT_SizeRec_ { FT_Face face; /* parent face object */ FT_Generic generic; /* generic pointer for client uses */ FT_Size_Metrics metrics; /* size metrics */ FT_Size_Internal internal; } FT_SizeRec; /*************************************************************************/ /* */ /* <Struct> */ /* FT_SubGlyph */ /* */ /* <Description> */ /* The subglyph structure is an internal object used to describe */ /* subglyphs (for example, in the case of composites). */ /* */ /* <Note> */ /* The subglyph implementation is not part of the high-level API, */ /* hence the forward structure declaration. */ /* */ /* You can however retrieve subglyph information with */ /* @FT_Get_SubGlyph_Info. */ /* */ typedef struct FT_SubGlyphRec_* FT_SubGlyph; /*************************************************************************/ /* */ /* <Type> */ /* FT_Slot_Internal */ /* */ /* <Description> */ /* An opaque handle to an `FT_Slot_InternalRec' structure, used to */ /* model private data of a given @FT_GlyphSlot object. */ /* */ typedef struct FT_Slot_InternalRec_* FT_Slot_Internal; /*************************************************************************/ /* */ /* <Struct> */ /* FT_GlyphSlotRec */ /* */ /* <Description> */ /* FreeType root glyph slot class structure. A glyph slot is a */ /* container where individual glyphs can be loaded, be they in */ /* outline or bitmap format. */ /* */ /* <Fields> */ /* library :: A handle to the FreeType library instance */ /* this slot belongs to. */ /* */ /* face :: A handle to the parent face object. */ /* */ /* next :: In some cases (like some font tools), several */ /* glyph slots per face object can be a good */ /* thing. As this is rare, the glyph slots are */ /* listed through a direct, single-linked list */ /* using its `next' field. */ /* */ /* generic :: A typeless pointer which is unused by the */ /* FreeType library or any of its drivers. It */ /* can be used by client applications to link */ /* their own data to each glyph slot object. */ /* */ /* metrics :: The metrics of the last loaded glyph in the */ /* slot. The returned values depend on the last */ /* load flags (see the @FT_Load_Glyph API */ /* function) and can be expressed either in 26.6 */ /* fractional pixels or font units. */ /* */ /* Note that even when the glyph image is */ /* transformed, the metrics are not. */ /* */ /* linearHoriAdvance :: The advance width of the unhinted glyph. */ /* Its value is expressed in 16.16 fractional */ /* pixels, unless @FT_LOAD_LINEAR_DESIGN is set */ /* when loading the glyph. This field can be */ /* important to perform correct WYSIWYG layout. */ /* Only relevant for outline glyphs. */ /* */ /* linearVertAdvance :: The advance height of the unhinted glyph. */ /* Its value is expressed in 16.16 fractional */ /* pixels, unless @FT_LOAD_LINEAR_DESIGN is set */ /* when loading the glyph. This field can be */ /* important to perform correct WYSIWYG layout. */ /* Only relevant for outline glyphs. */ /* */ /* advance :: This shorthand is, depending on */ /* @FT_LOAD_IGNORE_TRANSFORM, the transformed */ /* advance width for the glyph (in 26.6 */ /* fractional pixel format). As specified with */ /* @FT_LOAD_VERTICAL_LAYOUT, it uses either the */ /* `horiAdvance' or the `vertAdvance' value of */ /* `metrics' field. */ /* */ /* format :: This field indicates the format of the image */ /* contained in the glyph slot. Typically */ /* @FT_GLYPH_FORMAT_BITMAP, */ /* @FT_GLYPH_FORMAT_OUTLINE, or */ /* @FT_GLYPH_FORMAT_COMPOSITE, but others are */ /* possible. */ /* */ /* bitmap :: This field is used as a bitmap descriptor */ /* when the slot format is */ /* @FT_GLYPH_FORMAT_BITMAP. Note that the */ /* address and content of the bitmap buffer can */ /* change between calls of @FT_Load_Glyph and a */ /* few other functions. */ /* */ /* bitmap_left :: This is the bitmap's left bearing expressed */ /* in integer pixels. Of course, this is only */ /* valid if the format is */ /* @FT_GLYPH_FORMAT_BITMAP. */ /* */ /* bitmap_top :: This is the bitmap's top bearing expressed in */ /* integer pixels. Remember that this is the */ /* distance from the baseline to the top-most */ /* glyph scanline, upwards y~coordinates being */ /* *positive*. */ /* */ /* outline :: The outline descriptor for the current glyph */ /* image if its format is */ /* @FT_GLYPH_FORMAT_OUTLINE. Once a glyph is */ /* loaded, `outline' can be transformed, */ /* distorted, embolded, etc. However, it must */ /* not be freed. */ /* */ /* num_subglyphs :: The number of subglyphs in a composite glyph. */ /* This field is only valid for the composite */ /* glyph format that should normally only be */ /* loaded with the @FT_LOAD_NO_RECURSE flag. */ /* For now this is internal to FreeType. */ /* */ /* subglyphs :: An array of subglyph descriptors for */ /* composite glyphs. There are `num_subglyphs' */ /* elements in there. Currently internal to */ /* FreeType. */ /* */ /* control_data :: Certain font drivers can also return the */ /* control data for a given glyph image (e.g. */ /* TrueType bytecode, Type~1 charstrings, etc.). */ /* This field is a pointer to such data. */ /* */ /* control_len :: This is the length in bytes of the control */ /* data. */ /* */ /* other :: Really wicked formats can use this pointer to */ /* present their own glyph image to client */ /* applications. Note that the application */ /* needs to know about the image format. */ /* */ /* lsb_delta :: The difference between hinted and unhinted */ /* left side bearing while autohinting is */ /* active. Zero otherwise. */ /* */ /* rsb_delta :: The difference between hinted and unhinted */ /* right side bearing while autohinting is */ /* active. Zero otherwise. */ /* */ /* <Note> */ /* If @FT_Load_Glyph is called with default flags (see */ /* @FT_LOAD_DEFAULT) the glyph image is loaded in the glyph slot in */ /* its native format (e.g., an outline glyph for TrueType and Type~1 */ /* formats). */ /* */ /* This image can later be converted into a bitmap by calling */ /* @FT_Render_Glyph. This function finds the current renderer for */ /* the native image's format, then invokes it. */ /* */ /* The renderer is in charge of transforming the native image through */ /* the slot's face transformation fields, then converting it into a */ /* bitmap that is returned in `slot->bitmap'. */ /* */ /* Note that `slot->bitmap_left' and `slot->bitmap_top' are also used */ /* to specify the position of the bitmap relative to the current pen */ /* position (e.g., coordinates (0,0) on the baseline). Of course, */ /* `slot->format' is also changed to @FT_GLYPH_FORMAT_BITMAP. */ /* */ /* <Note> */ /* Here a small pseudo code fragment which shows how to use */ /* `lsb_delta' and `rsb_delta': */ /* */ /* { */ /* FT_Pos origin_x = 0; */ /* FT_Pos prev_rsb_delta = 0; */ /* */ /* */ /* for all glyphs do */ /* <compute kern between current and previous glyph and add it to */ /* `origin_x'> */ /* */ /* <load glyph with `FT_Load_Glyph'> */ /* */ /* if ( prev_rsb_delta - face->glyph->lsb_delta >= 32 ) */ /* origin_x -= 64; */ /* else if ( prev_rsb_delta - face->glyph->lsb_delta < -32 ) */ /* origin_x += 64; */ /* */ /* prev_rsb_delta = face->glyph->rsb_delta; */ /* */ /* <save glyph image, or render glyph, or ...> */ /* */ /* origin_x += face->glyph->advance.x; */ /* endfor */ /* } */ /* */ typedef struct FT_GlyphSlotRec_ { FT_Library library; FT_Face face; FT_GlyphSlot next; FT_UInt reserved; /* retained for binary compatibility */ FT_Generic generic; FT_Glyph_Metrics metrics; FT_Fixed linearHoriAdvance; FT_Fixed linearVertAdvance; FT_Vector advance; FT_Glyph_Format format; FT_Bitmap bitmap; FT_Int bitmap_left; FT_Int bitmap_top; FT_Outline outline; FT_UInt num_subglyphs; FT_SubGlyph subglyphs; void* control_data; long control_len; FT_Pos lsb_delta; FT_Pos rsb_delta; void* other; FT_Slot_Internal internal; } FT_GlyphSlotRec; /*************************************************************************/ /*************************************************************************/ /* */ /* F U N C T I O N S */ /* */ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /* */ /* <Function> */ /* FT_Init_FreeType */ /* */ /* <Description> */ /* Initialize a new FreeType library object. The set of modules */ /* that are registered by this function is determined at build time. */ /* */ /* <Output> */ /* alibrary :: A handle to a new library object. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ /* <Note> */ /* In case you want to provide your own memory allocating routines, */ /* use @FT_New_Library instead, followed by a call to */ /* @FT_Add_Default_Modules (or a series of calls to @FT_Add_Module). */ /* */ FT_EXPORT( FT_Error ) FT_Init_FreeType( FT_Library *alibrary ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Done_FreeType */ /* */ /* <Description> */ /* Destroy a given FreeType library object and all of its children, */ /* including resources, drivers, faces, sizes, etc. */ /* */ /* <Input> */ /* library :: A handle to the target library object. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ FT_EXPORT( FT_Error ) FT_Done_FreeType( FT_Library library ); /*************************************************************************/ /* */ /* <Enum> */ /* FT_OPEN_XXX */ /* */ /* <Description> */ /* A list of bit-field constants used within the `flags' field of the */ /* @FT_Open_Args structure. */ /* */ /* <Values> */ /* FT_OPEN_MEMORY :: This is a memory-based stream. */ /* */ /* FT_OPEN_STREAM :: Copy the stream from the `stream' field. */ /* */ /* FT_OPEN_PATHNAME :: Create a new input stream from a C~path */ /* name. */ /* */ /* FT_OPEN_DRIVER :: Use the `driver' field. */ /* */ /* FT_OPEN_PARAMS :: Use the `num_params' and `params' fields. */ /* */ /* ft_open_memory :: Deprecated; use @FT_OPEN_MEMORY instead. */ /* */ /* ft_open_stream :: Deprecated; use @FT_OPEN_STREAM instead. */ /* */ /* ft_open_pathname :: Deprecated; use @FT_OPEN_PATHNAME instead. */ /* */ /* ft_open_driver :: Deprecated; use @FT_OPEN_DRIVER instead. */ /* */ /* ft_open_params :: Deprecated; use @FT_OPEN_PARAMS instead. */ /* */ /* <Note> */ /* The `FT_OPEN_MEMORY', `FT_OPEN_STREAM', and `FT_OPEN_PATHNAME' */ /* flags are mutually exclusive. */ /* */ #define FT_OPEN_MEMORY 0x1 #define FT_OPEN_STREAM 0x2 #define FT_OPEN_PATHNAME 0x4 #define FT_OPEN_DRIVER 0x8 #define FT_OPEN_PARAMS 0x10 #define ft_open_memory FT_OPEN_MEMORY /* deprecated */ #define ft_open_stream FT_OPEN_STREAM /* deprecated */ #define ft_open_pathname FT_OPEN_PATHNAME /* deprecated */ #define ft_open_driver FT_OPEN_DRIVER /* deprecated */ #define ft_open_params FT_OPEN_PARAMS /* deprecated */ /*************************************************************************/ /* */ /* <Struct> */ /* FT_Parameter */ /* */ /* <Description> */ /* A simple structure used to pass more or less generic parameters to */ /* @FT_Open_Face. */ /* */ /* <Fields> */ /* tag :: A four-byte identification tag. */ /* */ /* data :: A pointer to the parameter data. */ /* */ /* <Note> */ /* The ID and function of parameters are driver-specific. See the */ /* various FT_PARAM_TAG_XXX flags for more information. */ /* */ typedef struct FT_Parameter_ { FT_ULong tag; FT_Pointer data; } FT_Parameter; /*************************************************************************/ /* */ /* <Struct> */ /* FT_Open_Args */ /* */ /* <Description> */ /* A structure used to indicate how to open a new font file or */ /* stream. A pointer to such a structure can be used as a parameter */ /* for the functions @FT_Open_Face and @FT_Attach_Stream. */ /* */ /* <Fields> */ /* flags :: A set of bit flags indicating how to use the */ /* structure. */ /* */ /* memory_base :: The first byte of the file in memory. */ /* */ /* memory_size :: The size in bytes of the file in memory. */ /* */ /* pathname :: A pointer to an 8-bit file pathname. */ /* */ /* stream :: A handle to a source stream object. */ /* */ /* driver :: This field is exclusively used by @FT_Open_Face; */ /* it simply specifies the font driver to use to open */ /* the face. If set to~0, FreeType tries to load the */ /* face with each one of the drivers in its list. */ /* */ /* num_params :: The number of extra parameters. */ /* */ /* params :: Extra parameters passed to the font driver when */ /* opening a new face. */ /* */ /* <Note> */ /* The stream type is determined by the contents of `flags' which */ /* are tested in the following order by @FT_Open_Face: */ /* */ /* If the `FT_OPEN_MEMORY' bit is set, assume that this is a */ /* memory file of `memory_size' bytes, located at `memory_address'. */ /* The data are are not copied, and the client is responsible for */ /* releasing and destroying them _after_ the corresponding call to */ /* @FT_Done_Face. */ /* */ /* Otherwise, if the `FT_OPEN_STREAM' bit is set, assume that a */ /* custom input stream `stream' is used. */ /* */ /* Otherwise, if the `FT_OPEN_PATHNAME' bit is set, assume that this */ /* is a normal file and use `pathname' to open it. */ /* */ /* If the `FT_OPEN_DRIVER' bit is set, @FT_Open_Face only tries to */ /* open the file with the driver whose handler is in `driver'. */ /* */ /* If the `FT_OPEN_PARAMS' bit is set, the parameters given by */ /* `num_params' and `params' is used. They are ignored otherwise. */ /* */ /* Ideally, both the `pathname' and `params' fields should be tagged */ /* as `const'; this is missing for API backwards compatibility. In */ /* other words, applications should treat them as read-only. */ /* */ typedef struct FT_Open_Args_ { FT_UInt flags; const FT_Byte* memory_base; FT_Long memory_size; FT_String* pathname; FT_Stream stream; FT_Module driver; FT_Int num_params; FT_Parameter* params; } FT_Open_Args; /*************************************************************************/ /* */ /* <Function> */ /* FT_New_Face */ /* */ /* <Description> */ /* This function calls @FT_Open_Face to open a font by its pathname. */ /* */ /* <InOut> */ /* library :: A handle to the library resource. */ /* */ /* <Input> */ /* pathname :: A path to the font file. */ /* */ /* face_index :: The index of the face within the font. The first */ /* face has index~0. */ /* */ /* <Output> */ /* aface :: A handle to a new face object. If `face_index' is */ /* greater than or equal to zero, it must be non-NULL. */ /* See @FT_Open_Face for more details. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ FT_EXPORT( FT_Error ) FT_New_Face( FT_Library library, const char* filepathname, FT_Long face_index, FT_Face *aface ); /*************************************************************************/ /* */ /* <Function> */ /* FT_New_Memory_Face */ /* */ /* <Description> */ /* This function calls @FT_Open_Face to open a font which has been */ /* loaded into memory. */ /* */ /* <InOut> */ /* library :: A handle to the library resource. */ /* */ /* <Input> */ /* file_base :: A pointer to the beginning of the font data. */ /* */ /* file_size :: The size of the memory chunk used by the font data. */ /* */ /* face_index :: The index of the face within the font. The first */ /* face has index~0. */ /* */ /* <Output> */ /* aface :: A handle to a new face object. If `face_index' is */ /* greater than or equal to zero, it must be non-NULL. */ /* See @FT_Open_Face for more details. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ /* <Note> */ /* You must not deallocate the memory before calling @FT_Done_Face. */ /* */ FT_EXPORT( FT_Error ) FT_New_Memory_Face( FT_Library library, const FT_Byte* file_base, FT_Long file_size, FT_Long face_index, FT_Face *aface ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Open_Face */ /* */ /* <Description> */ /* Create a face object from a given resource described by */ /* @FT_Open_Args. */ /* */ /* <InOut> */ /* library :: A handle to the library resource. */ /* */ /* <Input> */ /* args :: A pointer to an `FT_Open_Args' structure which must */ /* be filled by the caller. */ /* */ /* face_index :: The index of the face within the font. The first */ /* face has index~0. */ /* */ /* <Output> */ /* aface :: A handle to a new face object. If `face_index' is */ /* greater than or equal to zero, it must be non-NULL. */ /* See note below. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ /* <Note> */ /* Unlike FreeType 1.x, this function automatically creates a glyph */ /* slot for the face object which can be accessed directly through */ /* `face->glyph'. */ /* */ /* FT_Open_Face can be used to quickly check whether the font */ /* format of a given font resource is supported by FreeType. If the */ /* `face_index' field is negative, the function's return value is~0 */ /* if the font format is recognized, or non-zero otherwise; */ /* the function returns a more or less empty face handle in `*aface' */ /* (if `aface' isn't NULL). The only useful field in this special */ /* case is `face->num_faces' which gives the number of faces within */ /* the font file. After examination, the returned @FT_Face structure */ /* should be deallocated with a call to @FT_Done_Face. */ /* */ /* Each new face object created with this function also owns a */ /* default @FT_Size object, accessible as `face->size'. */ /* */ /* See the discussion of reference counters in the description of */ /* @FT_Reference_Face. */ /* */ FT_EXPORT( FT_Error ) FT_Open_Face( FT_Library library, const FT_Open_Args* args, FT_Long face_index, FT_Face *aface ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Attach_File */ /* */ /* <Description> */ /* This function calls @FT_Attach_Stream to attach a file. */ /* */ /* <InOut> */ /* face :: The target face object. */ /* */ /* <Input> */ /* filepathname :: The pathname. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ FT_EXPORT( FT_Error ) FT_Attach_File( FT_Face face, const char* filepathname ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Attach_Stream */ /* */ /* <Description> */ /* `Attach' data to a face object. Normally, this is used to read */ /* additional information for the face object. For example, you can */ /* attach an AFM file that comes with a Type~1 font to get the */ /* kerning values and other metrics. */ /* */ /* <InOut> */ /* face :: The target face object. */ /* */ /* <Input> */ /* parameters :: A pointer to @FT_Open_Args which must be filled by */ /* the caller. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ /* <Note> */ /* The meaning of the `attach' (i.e., what really happens when the */ /* new file is read) is not fixed by FreeType itself. It really */ /* depends on the font format (and thus the font driver). */ /* */ /* Client applications are expected to know what they are doing */ /* when invoking this function. Most drivers simply do not implement */ /* file attachments. */ /* */ FT_EXPORT( FT_Error ) FT_Attach_Stream( FT_Face face, FT_Open_Args* parameters ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Reference_Face */ /* */ /* <Description> */ /* A counter gets initialized to~1 at the time an @FT_Face structure */ /* is created. This function increments the counter. @FT_Done_Face */ /* then only destroys a face if the counter is~1, otherwise it simply */ /* decrements the counter. */ /* */ /* This function helps in managing life-cycles of structures which */ /* reference @FT_Face objects. */ /* */ /* <Input> */ /* face :: A handle to a target face object. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ /* <Since> */ /* 2.4.2 */ /* */ FT_EXPORT( FT_Error ) FT_Reference_Face( FT_Face face ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Done_Face */ /* */ /* <Description> */ /* Discard a given face object, as well as all of its child slots and */ /* sizes. */ /* */ /* <Input> */ /* face :: A handle to a target face object. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ /* <Note> */ /* See the discussion of reference counters in the description of */ /* @FT_Reference_Face. */ /* */ FT_EXPORT( FT_Error ) FT_Done_Face( FT_Face face ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Select_Size */ /* */ /* <Description> */ /* Select a bitmap strike. */ /* */ /* <InOut> */ /* face :: A handle to a target face object. */ /* */ /* <Input> */ /* strike_index :: The index of the bitmap strike in the */ /* `available_sizes' field of @FT_FaceRec structure. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ FT_EXPORT( FT_Error ) FT_Select_Size( FT_Face face, FT_Int strike_index ); /*************************************************************************/ /* */ /* <Enum> */ /* FT_Size_Request_Type */ /* */ /* <Description> */ /* An enumeration type that lists the supported size request types. */ /* */ /* <Values> */ /* FT_SIZE_REQUEST_TYPE_NOMINAL :: */ /* The nominal size. The `units_per_EM' field of @FT_FaceRec is */ /* used to determine both scaling values. */ /* */ /* FT_SIZE_REQUEST_TYPE_REAL_DIM :: */ /* The real dimension. The sum of the the `ascender' and (minus */ /* of) the `descender' fields of @FT_FaceRec are used to determine */ /* both scaling values. */ /* */ /* FT_SIZE_REQUEST_TYPE_BBOX :: */ /* The font bounding box. The width and height of the `bbox' field */ /* of @FT_FaceRec are used to determine the horizontal and vertical */ /* scaling value, respectively. */ /* */ /* FT_SIZE_REQUEST_TYPE_CELL :: */ /* The `max_advance_width' field of @FT_FaceRec is used to */ /* determine the horizontal scaling value; the vertical scaling */ /* value is determined the same way as */ /* @FT_SIZE_REQUEST_TYPE_REAL_DIM does. Finally, both scaling */ /* values are set to the smaller one. This type is useful if you */ /* want to specify the font size for, say, a window of a given */ /* dimension and 80x24 cells. */ /* */ /* FT_SIZE_REQUEST_TYPE_SCALES :: */ /* Specify the scaling values directly. */ /* */ /* <Note> */ /* The above descriptions only apply to scalable formats. For bitmap */ /* formats, the behaviour is up to the driver. */ /* */ /* See the note section of @FT_Size_Metrics if you wonder how size */ /* requesting relates to scaling values. */ /* */ typedef enum FT_Size_Request_Type_ { FT_SIZE_REQUEST_TYPE_NOMINAL, FT_SIZE_REQUEST_TYPE_REAL_DIM, FT_SIZE_REQUEST_TYPE_BBOX, FT_SIZE_REQUEST_TYPE_CELL, FT_SIZE_REQUEST_TYPE_SCALES, FT_SIZE_REQUEST_TYPE_MAX } FT_Size_Request_Type; /*************************************************************************/ /* */ /* <Struct> */ /* FT_Size_RequestRec */ /* */ /* <Description> */ /* A structure used to model a size request. */ /* */ /* <Fields> */ /* type :: See @FT_Size_Request_Type. */ /* */ /* width :: The desired width. */ /* */ /* height :: The desired height. */ /* */ /* horiResolution :: The horizontal resolution. If set to zero, */ /* `width' is treated as a 26.6 fractional pixel */ /* value. */ /* */ /* vertResolution :: The vertical resolution. If set to zero, */ /* `height' is treated as a 26.6 fractional pixel */ /* value. */ /* */ /* <Note> */ /* If `width' is zero, then the horizontal scaling value is set equal */ /* to the vertical scaling value, and vice versa. */ /* */ typedef struct FT_Size_RequestRec_ { FT_Size_Request_Type type; FT_Long width; FT_Long height; FT_UInt horiResolution; FT_UInt vertResolution; } FT_Size_RequestRec; /*************************************************************************/ /* */ /* <Struct> */ /* FT_Size_Request */ /* */ /* <Description> */ /* A handle to a size request structure. */ /* */ typedef struct FT_Size_RequestRec_ *FT_Size_Request; /*************************************************************************/ /* */ /* <Function> */ /* FT_Request_Size */ /* */ /* <Description> */ /* Resize the scale of the active @FT_Size object in a face. */ /* */ /* <InOut> */ /* face :: A handle to a target face object. */ /* */ /* <Input> */ /* req :: A pointer to a @FT_Size_RequestRec. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ /* <Note> */ /* Although drivers may select the bitmap strike matching the */ /* request, you should not rely on this if you intend to select a */ /* particular bitmap strike. Use @FT_Select_Size instead in that */ /* case. */ /* */ FT_EXPORT( FT_Error ) FT_Request_Size( FT_Face face, FT_Size_Request req ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Set_Char_Size */ /* */ /* <Description> */ /* This function calls @FT_Request_Size to request the nominal size */ /* (in points). */ /* */ /* <InOut> */ /* face :: A handle to a target face object. */ /* */ /* <Input> */ /* char_width :: The nominal width, in 26.6 fractional points. */ /* */ /* char_height :: The nominal height, in 26.6 fractional points. */ /* */ /* horz_resolution :: The horizontal resolution in dpi. */ /* */ /* vert_resolution :: The vertical resolution in dpi. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ /* <Note> */ /* If either the character width or height is zero, it is set equal */ /* to the other value. */ /* */ /* If either the horizontal or vertical resolution is zero, it is set */ /* equal to the other value. */ /* */ /* A character width or height smaller than 1pt is set to 1pt; if */ /* both resolution values are zero, they are set to 72dpi. */ /* */ /* Don't use this function if you are using the FreeType cache API. */ /* */ FT_EXPORT( FT_Error ) FT_Set_Char_Size( FT_Face face, FT_F26Dot6 char_width, FT_F26Dot6 char_height, FT_UInt horz_resolution, FT_UInt vert_resolution ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Set_Pixel_Sizes */ /* */ /* <Description> */ /* This function calls @FT_Request_Size to request the nominal size */ /* (in pixels). */ /* */ /* <InOut> */ /* face :: A handle to the target face object. */ /* */ /* <Input> */ /* pixel_width :: The nominal width, in pixels. */ /* */ /* pixel_height :: The nominal height, in pixels. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ FT_EXPORT( FT_Error ) FT_Set_Pixel_Sizes( FT_Face face, FT_UInt pixel_width, FT_UInt pixel_height ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Load_Glyph */ /* */ /* <Description> */ /* A function used to load a single glyph into the glyph slot of a */ /* face object. */ /* */ /* <InOut> */ /* face :: A handle to the target face object where the glyph */ /* is loaded. */ /* */ /* <Input> */ /* glyph_index :: The index of the glyph in the font file. For */ /* CID-keyed fonts (either in PS or in CFF format) */ /* this argument specifies the CID value. */ /* */ /* load_flags :: A flag indicating what to load for this glyph. The */ /* @FT_LOAD_XXX constants can be used to control the */ /* glyph loading process (e.g., whether the outline */ /* should be scaled, whether to load bitmaps or not, */ /* whether to hint the outline, etc). */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ /* <Note> */ /* The loaded glyph may be transformed. See @FT_Set_Transform for */ /* the details. */ /* */ /* For subsetted CID-keyed fonts, `FT_Err_Invalid_Argument' is */ /* returned for invalid CID values (this is, for CID values which */ /* don't have a corresponding glyph in the font). See the discussion */ /* of the @FT_FACE_FLAG_CID_KEYED flag for more details. */ /* */ FT_EXPORT( FT_Error ) FT_Load_Glyph( FT_Face face, FT_UInt glyph_index, FT_Int32 load_flags ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Load_Char */ /* */ /* <Description> */ /* A function used to load a single glyph into the glyph slot of a */ /* face object, according to its character code. */ /* */ /* <InOut> */ /* face :: A handle to a target face object where the glyph */ /* is loaded. */ /* */ /* <Input> */ /* char_code :: The glyph's character code, according to the */ /* current charmap used in the face. */ /* */ /* load_flags :: A flag indicating what to load for this glyph. The */ /* @FT_LOAD_XXX constants can be used to control the */ /* glyph loading process (e.g., whether the outline */ /* should be scaled, whether to load bitmaps or not, */ /* whether to hint the outline, etc). */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ /* <Note> */ /* This function simply calls @FT_Get_Char_Index and @FT_Load_Glyph. */ /* */ FT_EXPORT( FT_Error ) FT_Load_Char( FT_Face face, FT_ULong char_code, FT_Int32 load_flags ); /************************************************************************* * * @enum: * FT_LOAD_XXX * * @description: * A list of bit-field constants used with @FT_Load_Glyph to indicate * what kind of operations to perform during glyph loading. * * @values: * FT_LOAD_DEFAULT :: * Corresponding to~0, this value is used as the default glyph load * operation. In this case, the following happens: * * 1. FreeType looks for a bitmap for the glyph corresponding to the * face's current size. If one is found, the function returns. * The bitmap data can be accessed from the glyph slot (see note * below). * * 2. If no embedded bitmap is searched or found, FreeType looks for a * scalable outline. If one is found, it is loaded from the font * file, scaled to device pixels, then `hinted' to the pixel grid * in order to optimize it. The outline data can be accessed from * the glyph slot (see note below). * * Note that by default, the glyph loader doesn't render outlines into * bitmaps. The following flags are used to modify this default * behaviour to more specific and useful cases. * * FT_LOAD_NO_SCALE :: * Don't scale the outline glyph loaded, but keep it in font units. * * This flag implies @FT_LOAD_NO_HINTING and @FT_LOAD_NO_BITMAP, and * unsets @FT_LOAD_RENDER. * * FT_LOAD_NO_HINTING :: * Disable hinting. This generally generates `blurrier' bitmap glyph * when the glyph is rendered in any of the anti-aliased modes. See * also the note below. * * This flag is implied by @FT_LOAD_NO_SCALE. * * FT_LOAD_RENDER :: * Call @FT_Render_Glyph after the glyph is loaded. By default, the * glyph is rendered in @FT_RENDER_MODE_NORMAL mode. This can be * overridden by @FT_LOAD_TARGET_XXX or @FT_LOAD_MONOCHROME. * * This flag is unset by @FT_LOAD_NO_SCALE. * * FT_LOAD_NO_BITMAP :: * Ignore bitmap strikes when loading. Bitmap-only fonts ignore this * flag. * * @FT_LOAD_NO_SCALE always sets this flag. * * FT_LOAD_VERTICAL_LAYOUT :: * Load the glyph for vertical text layout. _Don't_ use it as it is * problematic currently. * * FT_LOAD_FORCE_AUTOHINT :: * Indicates that the auto-hinter is preferred over the font's native * hinter. See also the note below. * * FT_LOAD_CROP_BITMAP :: * Indicates that the font driver should crop the loaded bitmap glyph * (i.e., remove all space around its black bits). Not all drivers * implement this. * * FT_LOAD_PEDANTIC :: * Indicates that the font driver should perform pedantic verifications * during glyph loading. This is mostly used to detect broken glyphs * in fonts. By default, FreeType tries to handle broken fonts also. * * FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH :: * Ignored. Deprecated. * * FT_LOAD_NO_RECURSE :: * This flag is only used internally. It merely indicates that the * font driver should not load composite glyphs recursively. Instead, * it should set the `num_subglyph' and `subglyphs' values of the * glyph slot accordingly, and set `glyph->format' to * @FT_GLYPH_FORMAT_COMPOSITE. * * The description of sub-glyphs is not available to client * applications for now. * * This flag implies @FT_LOAD_NO_SCALE and @FT_LOAD_IGNORE_TRANSFORM. * * FT_LOAD_IGNORE_TRANSFORM :: * Indicates that the transform matrix set by @FT_Set_Transform should * be ignored. * * FT_LOAD_MONOCHROME :: * This flag is used with @FT_LOAD_RENDER to indicate that you want to * render an outline glyph to a 1-bit monochrome bitmap glyph, with * 8~pixels packed into each byte of the bitmap data. * * Note that this has no effect on the hinting algorithm used. You * should rather use @FT_LOAD_TARGET_MONO so that the * monochrome-optimized hinting algorithm is used. * * FT_LOAD_LINEAR_DESIGN :: * Indicates that the `linearHoriAdvance' and `linearVertAdvance' * fields of @FT_GlyphSlotRec should be kept in font units. See * @FT_GlyphSlotRec for details. * * FT_LOAD_NO_AUTOHINT :: * Disable auto-hinter. See also the note below. * * @note: * By default, hinting is enabled and the font's native hinter (see * @FT_FACE_FLAG_HINTER) is preferred over the auto-hinter. You can * disable hinting by setting @FT_LOAD_NO_HINTING or change the * precedence by setting @FT_LOAD_FORCE_AUTOHINT. You can also set * @FT_LOAD_NO_AUTOHINT in case you don't want the auto-hinter to be * used at all. * * See the description of @FT_FACE_FLAG_TRICKY for a special exception * (affecting only a handful of Asian fonts). * * Besides deciding which hinter to use, you can also decide which * hinting algorithm to use. See @FT_LOAD_TARGET_XXX for details. * */ #define FT_LOAD_DEFAULT 0x0 #define FT_LOAD_NO_SCALE 0x1 #define FT_LOAD_NO_HINTING 0x2 #define FT_LOAD_RENDER 0x4 #define FT_LOAD_NO_BITMAP 0x8 #define FT_LOAD_VERTICAL_LAYOUT 0x10 #define FT_LOAD_FORCE_AUTOHINT 0x20 #define FT_LOAD_CROP_BITMAP 0x40 #define FT_LOAD_PEDANTIC 0x80 #define FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH 0x200 #define FT_LOAD_NO_RECURSE 0x400 #define FT_LOAD_IGNORE_TRANSFORM 0x800 #define FT_LOAD_MONOCHROME 0x1000 #define FT_LOAD_LINEAR_DESIGN 0x2000 #define FT_LOAD_NO_AUTOHINT 0x8000U /* */ /* used internally only by certain font drivers! */ #define FT_LOAD_ADVANCE_ONLY 0x100 #define FT_LOAD_SBITS_ONLY 0x4000 /************************************************************************** * * @enum: * FT_LOAD_TARGET_XXX * * @description: * A list of values that are used to select a specific hinting algorithm * to use by the hinter. You should OR one of these values to your * `load_flags' when calling @FT_Load_Glyph. * * Note that font's native hinters may ignore the hinting algorithm you * have specified (e.g., the TrueType bytecode interpreter). You can set * @FT_LOAD_FORCE_AUTOHINT to ensure that the auto-hinter is used. * * Also note that @FT_LOAD_TARGET_LIGHT is an exception, in that it * always implies @FT_LOAD_FORCE_AUTOHINT. * * @values: * FT_LOAD_TARGET_NORMAL :: * This corresponds to the default hinting algorithm, optimized for * standard gray-level rendering. For monochrome output, use * @FT_LOAD_TARGET_MONO instead. * * FT_LOAD_TARGET_LIGHT :: * A lighter hinting algorithm for non-monochrome modes. Many * generated glyphs are more fuzzy but better resemble its original * shape. A bit like rendering on Mac OS~X. * * As a special exception, this target implies @FT_LOAD_FORCE_AUTOHINT. * * FT_LOAD_TARGET_MONO :: * Strong hinting algorithm that should only be used for monochrome * output. The result is probably unpleasant if the glyph is rendered * in non-monochrome modes. * * FT_LOAD_TARGET_LCD :: * A variant of @FT_LOAD_TARGET_NORMAL optimized for horizontally * decimated LCD displays. * * FT_LOAD_TARGET_LCD_V :: * A variant of @FT_LOAD_TARGET_NORMAL optimized for vertically * decimated LCD displays. * * @note: * You should use only _one_ of the FT_LOAD_TARGET_XXX values in your * `load_flags'. They can't be ORed. * * If @FT_LOAD_RENDER is also set, the glyph is rendered in the * corresponding mode (i.e., the mode which matches the used algorithm * best) unless @FT_LOAD_MONOCHROME is set. * * You can use a hinting algorithm that doesn't correspond to the same * rendering mode. As an example, it is possible to use the `light' * hinting algorithm and have the results rendered in horizontal LCD * pixel mode, with code like * * { * FT_Load_Glyph( face, glyph_index, * load_flags | FT_LOAD_TARGET_LIGHT ); * * FT_Render_Glyph( face->glyph, FT_RENDER_MODE_LCD ); * } * */ #define FT_LOAD_TARGET_( x ) ( (FT_Int32)( (x) & 15 ) << 16 ) #define FT_LOAD_TARGET_NORMAL FT_LOAD_TARGET_( FT_RENDER_MODE_NORMAL ) #define FT_LOAD_TARGET_LIGHT FT_LOAD_TARGET_( FT_RENDER_MODE_LIGHT ) #define FT_LOAD_TARGET_MONO FT_LOAD_TARGET_( FT_RENDER_MODE_MONO ) #define FT_LOAD_TARGET_LCD FT_LOAD_TARGET_( FT_RENDER_MODE_LCD ) #define FT_LOAD_TARGET_LCD_V FT_LOAD_TARGET_( FT_RENDER_MODE_LCD_V ) /************************************************************************** * * @macro: * FT_LOAD_TARGET_MODE * * @description: * Return the @FT_Render_Mode corresponding to a given * @FT_LOAD_TARGET_XXX value. * */ #define FT_LOAD_TARGET_MODE( x ) ( (FT_Render_Mode)( ( (x) >> 16 ) & 15 ) ) /*************************************************************************/ /* */ /* <Function> */ /* FT_Set_Transform */ /* */ /* <Description> */ /* A function used to set the transformation that is applied to glyph */ /* images when they are loaded into a glyph slot through */ /* @FT_Load_Glyph. */ /* */ /* <InOut> */ /* face :: A handle to the source face object. */ /* */ /* <Input> */ /* matrix :: A pointer to the transformation's 2x2 matrix. Use~0 for */ /* the identity matrix. */ /* delta :: A pointer to the translation vector. Use~0 for the null */ /* vector. */ /* */ /* <Note> */ /* The transformation is only applied to scalable image formats after */ /* the glyph has been loaded. It means that hinting is unaltered by */ /* the transformation and is performed on the character size given in */ /* the last call to @FT_Set_Char_Size or @FT_Set_Pixel_Sizes. */ /* */ /* Note that this also transforms the `face.glyph.advance' field, but */ /* *not* the values in `face.glyph.metrics'. */ /* */ FT_EXPORT( void ) FT_Set_Transform( FT_Face face, FT_Matrix* matrix, FT_Vector* delta ); /*************************************************************************/ /* */ /* <Enum> */ /* FT_Render_Mode */ /* */ /* <Description> */ /* An enumeration type that lists the render modes supported by */ /* FreeType~2. Each mode corresponds to a specific type of scanline */ /* conversion performed on the outline. */ /* */ /* For bitmap fonts and embedded bitmaps the `bitmap->pixel_mode' */ /* field in the @FT_GlyphSlotRec structure gives the format of the */ /* returned bitmap. */ /* */ /* All modes except @FT_RENDER_MODE_MONO use 256 levels of opacity. */ /* */ /* <Values> */ /* FT_RENDER_MODE_NORMAL :: */ /* This is the default render mode; it corresponds to 8-bit */ /* anti-aliased bitmaps. */ /* */ /* FT_RENDER_MODE_LIGHT :: */ /* This is equivalent to @FT_RENDER_MODE_NORMAL. It is only */ /* defined as a separate value because render modes are also used */ /* indirectly to define hinting algorithm selectors. See */ /* @FT_LOAD_TARGET_XXX for details. */ /* */ /* FT_RENDER_MODE_MONO :: */ /* This mode corresponds to 1-bit bitmaps (with 2~levels of */ /* opacity). */ /* */ /* FT_RENDER_MODE_LCD :: */ /* This mode corresponds to horizontal RGB and BGR sub-pixel */ /* displays like LCD screens. It produces 8-bit bitmaps that are */ /* 3~times the width of the original glyph outline in pixels, and */ /* which use the @FT_PIXEL_MODE_LCD mode. */ /* */ /* FT_RENDER_MODE_LCD_V :: */ /* This mode corresponds to vertical RGB and BGR sub-pixel displays */ /* (like PDA screens, rotated LCD displays, etc.). It produces */ /* 8-bit bitmaps that are 3~times the height of the original */ /* glyph outline in pixels and use the @FT_PIXEL_MODE_LCD_V mode. */ /* */ /* <Note> */ /* The LCD-optimized glyph bitmaps produced by FT_Render_Glyph can be */ /* filtered to reduce color-fringes by using @FT_Library_SetLcdFilter */ /* (not active in the default builds). It is up to the caller to */ /* either call @FT_Library_SetLcdFilter (if available) or do the */ /* filtering itself. */ /* */ /* The selected render mode only affects vector glyphs of a font. */ /* Embedded bitmaps often have a different pixel mode like */ /* @FT_PIXEL_MODE_MONO. You can use @FT_Bitmap_Convert to transform */ /* them into 8-bit pixmaps. */ /* */ typedef enum FT_Render_Mode_ { FT_RENDER_MODE_NORMAL = 0, FT_RENDER_MODE_LIGHT, FT_RENDER_MODE_MONO, FT_RENDER_MODE_LCD, FT_RENDER_MODE_LCD_V, FT_RENDER_MODE_MAX } FT_Render_Mode; /*************************************************************************/ /* */ /* <Enum> */ /* ft_render_mode_xxx */ /* */ /* <Description> */ /* These constants are deprecated. Use the corresponding */ /* @FT_Render_Mode values instead. */ /* */ /* <Values> */ /* ft_render_mode_normal :: see @FT_RENDER_MODE_NORMAL */ /* ft_render_mode_mono :: see @FT_RENDER_MODE_MONO */ /* */ #define ft_render_mode_normal FT_RENDER_MODE_NORMAL #define ft_render_mode_mono FT_RENDER_MODE_MONO /*************************************************************************/ /* */ /* <Function> */ /* FT_Render_Glyph */ /* */ /* <Description> */ /* Convert a given glyph image to a bitmap. It does so by inspecting */ /* the glyph image format, finding the relevant renderer, and */ /* invoking it. */ /* */ /* <InOut> */ /* slot :: A handle to the glyph slot containing the image to */ /* convert. */ /* */ /* <Input> */ /* render_mode :: This is the render mode used to render the glyph */ /* image into a bitmap. See @FT_Render_Mode for a */ /* list of possible values. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ FT_EXPORT( FT_Error ) FT_Render_Glyph( FT_GlyphSlot slot, FT_Render_Mode render_mode ); /*************************************************************************/ /* */ /* <Enum> */ /* FT_Kerning_Mode */ /* */ /* <Description> */ /* An enumeration used to specify which kerning values to return in */ /* @FT_Get_Kerning. */ /* */ /* <Values> */ /* FT_KERNING_DEFAULT :: Return scaled and grid-fitted kerning */ /* distances (value is~0). */ /* */ /* FT_KERNING_UNFITTED :: Return scaled but un-grid-fitted kerning */ /* distances. */ /* */ /* FT_KERNING_UNSCALED :: Return the kerning vector in original font */ /* units. */ /* */ typedef enum FT_Kerning_Mode_ { FT_KERNING_DEFAULT = 0, FT_KERNING_UNFITTED, FT_KERNING_UNSCALED } FT_Kerning_Mode; /*************************************************************************/ /* */ /* <Const> */ /* ft_kerning_default */ /* */ /* <Description> */ /* This constant is deprecated. Please use @FT_KERNING_DEFAULT */ /* instead. */ /* */ #define ft_kerning_default FT_KERNING_DEFAULT /*************************************************************************/ /* */ /* <Const> */ /* ft_kerning_unfitted */ /* */ /* <Description> */ /* This constant is deprecated. Please use @FT_KERNING_UNFITTED */ /* instead. */ /* */ #define ft_kerning_unfitted FT_KERNING_UNFITTED /*************************************************************************/ /* */ /* <Const> */ /* ft_kerning_unscaled */ /* */ /* <Description> */ /* This constant is deprecated. Please use @FT_KERNING_UNSCALED */ /* instead. */ /* */ #define ft_kerning_unscaled FT_KERNING_UNSCALED /*************************************************************************/ /* */ /* <Function> */ /* FT_Get_Kerning */ /* */ /* <Description> */ /* Return the kerning vector between two glyphs of a same face. */ /* */ /* <Input> */ /* face :: A handle to a source face object. */ /* */ /* left_glyph :: The index of the left glyph in the kern pair. */ /* */ /* right_glyph :: The index of the right glyph in the kern pair. */ /* */ /* kern_mode :: See @FT_Kerning_Mode for more information. */ /* Determines the scale and dimension of the returned */ /* kerning vector. */ /* */ /* <Output> */ /* akerning :: The kerning vector. This is either in font units */ /* or in pixels (26.6 format) for scalable formats, */ /* and in pixels for fixed-sizes formats. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ /* <Note> */ /* Only horizontal layouts (left-to-right & right-to-left) are */ /* supported by this method. Other layouts, or more sophisticated */ /* kernings, are out of the scope of this API function -- they can be */ /* implemented through format-specific interfaces. */ /* */ FT_EXPORT( FT_Error ) FT_Get_Kerning( FT_Face face, FT_UInt left_glyph, FT_UInt right_glyph, FT_UInt kern_mode, FT_Vector *akerning ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Get_Track_Kerning */ /* */ /* <Description> */ /* Return the track kerning for a given face object at a given size. */ /* */ /* <Input> */ /* face :: A handle to a source face object. */ /* */ /* point_size :: The point size in 16.16 fractional points. */ /* */ /* degree :: The degree of tightness. */ /* */ /* <Output> */ /* akerning :: The kerning in 16.16 fractional points. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ FT_EXPORT( FT_Error ) FT_Get_Track_Kerning( FT_Face face, FT_Fixed point_size, FT_Int degree, FT_Fixed* akerning ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Get_Glyph_Name */ /* */ /* <Description> */ /* Retrieve the ASCII name of a given glyph in a face. This only */ /* works for those faces where @FT_HAS_GLYPH_NAMES(face) returns~1. */ /* */ /* <Input> */ /* face :: A handle to a source face object. */ /* */ /* glyph_index :: The glyph index. */ /* */ /* buffer_max :: The maximal number of bytes available in the */ /* buffer. */ /* */ /* <Output> */ /* buffer :: A pointer to a target buffer where the name is */ /* copied to. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ /* <Note> */ /* An error is returned if the face doesn't provide glyph names or if */ /* the glyph index is invalid. In all cases of failure, the first */ /* byte of `buffer' is set to~0 to indicate an empty name. */ /* */ /* The glyph name is truncated to fit within the buffer if it is too */ /* long. The returned string is always zero-terminated. */ /* */ /* Be aware that FreeType reorders glyph indices internally so that */ /* glyph index~0 always corresponds to the `missing glyph' (called */ /* `.notdef'). */ /* */ /* This function is not compiled within the library if the config */ /* macro `FT_CONFIG_OPTION_NO_GLYPH_NAMES' is defined in */ /* `include/freetype/config/ftoptions.h'. */ /* */ FT_EXPORT( FT_Error ) FT_Get_Glyph_Name( FT_Face face, FT_UInt glyph_index, FT_Pointer buffer, FT_UInt buffer_max ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Get_Postscript_Name */ /* */ /* <Description> */ /* Retrieve the ASCII PostScript name of a given face, if available. */ /* This only works with PostScript and TrueType fonts. */ /* */ /* <Input> */ /* face :: A handle to the source face object. */ /* */ /* <Return> */ /* A pointer to the face's PostScript name. NULL if unavailable. */ /* */ /* <Note> */ /* The returned pointer is owned by the face and is destroyed with */ /* it. */ /* */ FT_EXPORT( const char* ) FT_Get_Postscript_Name( FT_Face face ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Select_Charmap */ /* */ /* <Description> */ /* Select a given charmap by its encoding tag (as listed in */ /* `freetype.h'). */ /* */ /* <InOut> */ /* face :: A handle to the source face object. */ /* */ /* <Input> */ /* encoding :: A handle to the selected encoding. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ /* <Note> */ /* This function returns an error if no charmap in the face */ /* corresponds to the encoding queried here. */ /* */ /* Because many fonts contain more than a single cmap for Unicode */ /* encoding, this function has some special code to select the one */ /* which covers Unicode best (`best' in the sense that a UCS-4 cmap */ /* is preferred to a UCS-2 cmap). It is thus preferable to */ /* @FT_Set_Charmap in this case. */ /* */ FT_EXPORT( FT_Error ) FT_Select_Charmap( FT_Face face, FT_Encoding encoding ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Set_Charmap */ /* */ /* <Description> */ /* Select a given charmap for character code to glyph index mapping. */ /* */ /* <InOut> */ /* face :: A handle to the source face object. */ /* */ /* <Input> */ /* charmap :: A handle to the selected charmap. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ /* <Note> */ /* This function returns an error if the charmap is not part of */ /* the face (i.e., if it is not listed in the `face->charmaps' */ /* table). */ /* */ /* It also fails if a type~14 charmap is selected. */ /* */ FT_EXPORT( FT_Error ) FT_Set_Charmap( FT_Face face, FT_CharMap charmap ); /************************************************************************* * * @function: * FT_Get_Charmap_Index * * @description: * Retrieve index of a given charmap. * * @input: * charmap :: * A handle to a charmap. * * @return: * The index into the array of character maps within the face to which * `charmap' belongs. If an error occurs, -1 is returned. * */ FT_EXPORT( FT_Int ) FT_Get_Charmap_Index( FT_CharMap charmap ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Get_Char_Index */ /* */ /* <Description> */ /* Return the glyph index of a given character code. This function */ /* uses a charmap object to do the mapping. */ /* */ /* <Input> */ /* face :: A handle to the source face object. */ /* */ /* charcode :: The character code. */ /* */ /* <Return> */ /* The glyph index. 0~means `undefined character code'. */ /* */ /* <Note> */ /* If you use FreeType to manipulate the contents of font files */ /* directly, be aware that the glyph index returned by this function */ /* doesn't always correspond to the internal indices used within */ /* the file. This is done to ensure that value~0 always corresponds */ /* to the `missing glyph'. */ /* */ FT_EXPORT( FT_UInt ) FT_Get_Char_Index( FT_Face face, FT_ULong charcode ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Get_First_Char */ /* */ /* <Description> */ /* This function is used to return the first character code in the */ /* current charmap of a given face. It also returns the */ /* corresponding glyph index. */ /* */ /* <Input> */ /* face :: A handle to the source face object. */ /* */ /* <Output> */ /* agindex :: Glyph index of first character code. 0~if charmap is */ /* empty. */ /* */ /* <Return> */ /* The charmap's first character code. */ /* */ /* <Note> */ /* You should use this function with @FT_Get_Next_Char to be able to */ /* parse all character codes available in a given charmap. The code */ /* should look like this: */ /* */ /* { */ /* FT_ULong charcode; */ /* FT_UInt gindex; */ /* */ /* */ /* charcode = FT_Get_First_Char( face, &gindex ); */ /* while ( gindex != 0 ) */ /* { */ /* ... do something with (charcode,gindex) pair ... */ /* */ /* charcode = FT_Get_Next_Char( face, charcode, &gindex ); */ /* } */ /* } */ /* */ /* Note that `*agindex' is set to~0 if the charmap is empty. The */ /* result itself can be~0 in two cases: if the charmap is empty or */ /* if the value~0 is the first valid character code. */ /* */ FT_EXPORT( FT_ULong ) FT_Get_First_Char( FT_Face face, FT_UInt *agindex ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Get_Next_Char */ /* */ /* <Description> */ /* This function is used to return the next character code in the */ /* current charmap of a given face following the value `char_code', */ /* as well as the corresponding glyph index. */ /* */ /* <Input> */ /* face :: A handle to the source face object. */ /* char_code :: The starting character code. */ /* */ /* <Output> */ /* agindex :: Glyph index of next character code. 0~if charmap */ /* is empty. */ /* */ /* <Return> */ /* The charmap's next character code. */ /* */ /* <Note> */ /* You should use this function with @FT_Get_First_Char to walk */ /* over all character codes available in a given charmap. See the */ /* note for this function for a simple code example. */ /* */ /* Note that `*agindex' is set to~0 when there are no more codes in */ /* the charmap. */ /* */ FT_EXPORT( FT_ULong ) FT_Get_Next_Char( FT_Face face, FT_ULong char_code, FT_UInt *agindex ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Get_Name_Index */ /* */ /* <Description> */ /* Return the glyph index of a given glyph name. This function uses */ /* driver specific objects to do the translation. */ /* */ /* <Input> */ /* face :: A handle to the source face object. */ /* */ /* glyph_name :: The glyph name. */ /* */ /* <Return> */ /* The glyph index. 0~means `undefined character code'. */ /* */ FT_EXPORT( FT_UInt ) FT_Get_Name_Index( FT_Face face, FT_String* glyph_name ); /************************************************************************* * * @macro: * FT_SUBGLYPH_FLAG_XXX * * @description: * A list of constants used to describe subglyphs. Please refer to the * TrueType specification for the meaning of the various flags. * * @values: * FT_SUBGLYPH_FLAG_ARGS_ARE_WORDS :: * FT_SUBGLYPH_FLAG_ARGS_ARE_XY_VALUES :: * FT_SUBGLYPH_FLAG_ROUND_XY_TO_GRID :: * FT_SUBGLYPH_FLAG_SCALE :: * FT_SUBGLYPH_FLAG_XY_SCALE :: * FT_SUBGLYPH_FLAG_2X2 :: * FT_SUBGLYPH_FLAG_USE_MY_METRICS :: * */ #define FT_SUBGLYPH_FLAG_ARGS_ARE_WORDS 1 #define FT_SUBGLYPH_FLAG_ARGS_ARE_XY_VALUES 2 #define FT_SUBGLYPH_FLAG_ROUND_XY_TO_GRID 4 #define FT_SUBGLYPH_FLAG_SCALE 8 #define FT_SUBGLYPH_FLAG_XY_SCALE 0x40 #define FT_SUBGLYPH_FLAG_2X2 0x80 #define FT_SUBGLYPH_FLAG_USE_MY_METRICS 0x200 /************************************************************************* * * @func: * FT_Get_SubGlyph_Info * * @description: * Retrieve a description of a given subglyph. Only use it if * `glyph->format' is @FT_GLYPH_FORMAT_COMPOSITE; an error is * returned otherwise. * * @input: * glyph :: * The source glyph slot. * * sub_index :: * The index of the subglyph. Must be less than * `glyph->num_subglyphs'. * * @output: * p_index :: * The glyph index of the subglyph. * * p_flags :: * The subglyph flags, see @FT_SUBGLYPH_FLAG_XXX. * * p_arg1 :: * The subglyph's first argument (if any). * * p_arg2 :: * The subglyph's second argument (if any). * * p_transform :: * The subglyph transformation (if any). * * @return: * FreeType error code. 0~means success. * * @note: * The values of `*p_arg1', `*p_arg2', and `*p_transform' must be * interpreted depending on the flags returned in `*p_flags'. See the * TrueType specification for details. * */ FT_EXPORT( FT_Error ) FT_Get_SubGlyph_Info( FT_GlyphSlot glyph, FT_UInt sub_index, FT_Int *p_index, FT_UInt *p_flags, FT_Int *p_arg1, FT_Int *p_arg2, FT_Matrix *p_transform ); /*************************************************************************/ /* */ /* <Enum> */ /* FT_FSTYPE_XXX */ /* */ /* <Description> */ /* A list of bit flags used in the `fsType' field of the OS/2 table */ /* in a TrueType or OpenType font and the `FSType' entry in a */ /* PostScript font. These bit flags are returned by */ /* @FT_Get_FSType_Flags; they inform client applications of embedding */ /* and subsetting restrictions associated with a font. */ /* */ /* See http://www.adobe.com/devnet/acrobat/pdfs/FontPolicies.pdf for */ /* more details. */ /* */ /* <Values> */ /* FT_FSTYPE_INSTALLABLE_EMBEDDING :: */ /* Fonts with no fsType bit set may be embedded and permanently */ /* installed on the remote system by an application. */ /* */ /* FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING :: */ /* Fonts that have only this bit set must not be modified, embedded */ /* or exchanged in any manner without first obtaining permission of */ /* the font software copyright owner. */ /* */ /* FT_FSTYPE_PREVIEW_AND_PRINT_EMBEDDING :: */ /* If this bit is set, the font may be embedded and temporarily */ /* loaded on the remote system. Documents containing Preview & */ /* Print fonts must be opened `read-only'; no edits can be applied */ /* to the document. */ /* */ /* FT_FSTYPE_EDITABLE_EMBEDDING :: */ /* If this bit is set, the font may be embedded but must only be */ /* installed temporarily on other systems. In contrast to Preview */ /* & Print fonts, documents containing editable fonts may be opened */ /* for reading, editing is permitted, and changes may be saved. */ /* */ /* FT_FSTYPE_NO_SUBSETTING :: */ /* If this bit is set, the font may not be subsetted prior to */ /* embedding. */ /* */ /* FT_FSTYPE_BITMAP_EMBEDDING_ONLY :: */ /* If this bit is set, only bitmaps contained in the font may be */ /* embedded; no outline data may be embedded. If there are no */ /* bitmaps available in the font, then the font is unembeddable. */ /* */ /* <Note> */ /* While the fsType flags can indicate that a font may be embedded, a */ /* license with the font vendor may be separately required to use the */ /* font in this way. */ /* */ #define FT_FSTYPE_INSTALLABLE_EMBEDDING 0x0000 #define FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING 0x0002 #define FT_FSTYPE_PREVIEW_AND_PRINT_EMBEDDING 0x0004 #define FT_FSTYPE_EDITABLE_EMBEDDING 0x0008 #define FT_FSTYPE_NO_SUBSETTING 0x0100 #define FT_FSTYPE_BITMAP_EMBEDDING_ONLY 0x0200 /*************************************************************************/ /* */ /* <Function> */ /* FT_Get_FSType_Flags */ /* */ /* <Description> */ /* Return the fsType flags for a font. */ /* */ /* <Input> */ /* face :: A handle to the source face object. */ /* */ /* <Return> */ /* The fsType flags, @FT_FSTYPE_XXX. */ /* */ /* <Note> */ /* Use this function rather than directly reading the `fs_type' field */ /* in the @PS_FontInfoRec structure which is only guaranteed to */ /* return the correct results for Type~1 fonts. */ /* */ /* <Since> */ /* 2.3.8 */ /* */ FT_EXPORT( FT_UShort ) FT_Get_FSType_Flags( FT_Face face ); /*************************************************************************/ /* */ /* <Section> */ /* glyph_variants */ /* */ /* <Title> */ /* Glyph Variants */ /* */ /* <Abstract> */ /* The FreeType~2 interface to Unicode Ideographic Variation */ /* Sequences (IVS), using the SFNT cmap format~14. */ /* */ /* <Description> */ /* Many CJK characters have variant forms. They are a sort of grey */ /* area somewhere between being totally irrelevant and semantically */ /* distinct; for this reason, the Unicode consortium decided to */ /* introduce Ideographic Variation Sequences (IVS), consisting of a */ /* Unicode base character and one of 240 variant selectors */ /* (U+E0100-U+E01EF), instead of further extending the already huge */ /* code range for CJK characters. */ /* */ /* An IVS is registered and unique; for further details please refer */ /* to Unicode Technical Report #37, the Ideographic Variation */ /* Database. To date (October 2007), the character with the most */ /* variants is U+908A, having 8~such IVS. */ /* */ /* Adobe and MS decided to support IVS with a new cmap subtable */ /* (format~14). It is an odd subtable because it is not a mapping of */ /* input code points to glyphs, but contains lists of all variants */ /* supported by the font. */ /* */ /* A variant may be either `default' or `non-default'. A default */ /* variant is the one you will get for that code point if you look it */ /* up in the standard Unicode cmap. A non-default variant is a */ /* different glyph. */ /* */ /*************************************************************************/ /*************************************************************************/ /* */ /* <Function> */ /* FT_Face_GetCharVariantIndex */ /* */ /* <Description> */ /* Return the glyph index of a given character code as modified by */ /* the variation selector. */ /* */ /* <Input> */ /* face :: */ /* A handle to the source face object. */ /* */ /* charcode :: */ /* The character code point in Unicode. */ /* */ /* variantSelector :: */ /* The Unicode code point of the variation selector. */ /* */ /* <Return> */ /* The glyph index. 0~means either `undefined character code', or */ /* `undefined selector code', or `no variation selector cmap */ /* subtable', or `current CharMap is not Unicode'. */ /* */ /* <Note> */ /* If you use FreeType to manipulate the contents of font files */ /* directly, be aware that the glyph index returned by this function */ /* doesn't always correspond to the internal indices used within */ /* the file. This is done to ensure that value~0 always corresponds */ /* to the `missing glyph'. */ /* */ /* This function is only meaningful if */ /* a) the font has a variation selector cmap sub table, */ /* and */ /* b) the current charmap has a Unicode encoding. */ /* */ /* <Since> */ /* 2.3.6 */ /* */ FT_EXPORT( FT_UInt ) FT_Face_GetCharVariantIndex( FT_Face face, FT_ULong charcode, FT_ULong variantSelector ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Face_GetCharVariantIsDefault */ /* */ /* <Description> */ /* Check whether this variant of this Unicode character is the one to */ /* be found in the `cmap'. */ /* */ /* <Input> */ /* face :: */ /* A handle to the source face object. */ /* */ /* charcode :: */ /* The character codepoint in Unicode. */ /* */ /* variantSelector :: */ /* The Unicode codepoint of the variation selector. */ /* */ /* <Return> */ /* 1~if found in the standard (Unicode) cmap, 0~if found in the */ /* variation selector cmap, or -1 if it is not a variant. */ /* */ /* <Note> */ /* This function is only meaningful if the font has a variation */ /* selector cmap subtable. */ /* */ /* <Since> */ /* 2.3.6 */ /* */ FT_EXPORT( FT_Int ) FT_Face_GetCharVariantIsDefault( FT_Face face, FT_ULong charcode, FT_ULong variantSelector ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Face_GetVariantSelectors */ /* */ /* <Description> */ /* Return a zero-terminated list of Unicode variant selectors found */ /* in the font. */ /* */ /* <Input> */ /* face :: */ /* A handle to the source face object. */ /* */ /* <Return> */ /* A pointer to an array of selector code points, or NULL if there is */ /* no valid variant selector cmap subtable. */ /* */ /* <Note> */ /* The last item in the array is~0; the array is owned by the */ /* @FT_Face object but can be overwritten or released on the next */ /* call to a FreeType function. */ /* */ /* <Since> */ /* 2.3.6 */ /* */ FT_EXPORT( FT_UInt32* ) FT_Face_GetVariantSelectors( FT_Face face ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Face_GetVariantsOfChar */ /* */ /* <Description> */ /* Return a zero-terminated list of Unicode variant selectors found */ /* for the specified character code. */ /* */ /* <Input> */ /* face :: */ /* A handle to the source face object. */ /* */ /* charcode :: */ /* The character codepoint in Unicode. */ /* */ /* <Return> */ /* A pointer to an array of variant selector code points which are */ /* active for the given character, or NULL if the corresponding list */ /* is empty. */ /* */ /* <Note> */ /* The last item in the array is~0; the array is owned by the */ /* @FT_Face object but can be overwritten or released on the next */ /* call to a FreeType function. */ /* */ /* <Since> */ /* 2.3.6 */ /* */ FT_EXPORT( FT_UInt32* ) FT_Face_GetVariantsOfChar( FT_Face face, FT_ULong charcode ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Face_GetCharsOfVariant */ /* */ /* <Description> */ /* Return a zero-terminated list of Unicode character codes found for */ /* the specified variant selector. */ /* */ /* <Input> */ /* face :: */ /* A handle to the source face object. */ /* */ /* variantSelector :: */ /* The variant selector code point in Unicode. */ /* */ /* <Return> */ /* A list of all the code points which are specified by this selector */ /* (both default and non-default codes are returned) or NULL if there */ /* is no valid cmap or the variant selector is invalid. */ /* */ /* <Note> */ /* The last item in the array is~0; the array is owned by the */ /* @FT_Face object but can be overwritten or released on the next */ /* call to a FreeType function. */ /* */ /* <Since> */ /* 2.3.6 */ /* */ FT_EXPORT( FT_UInt32* ) FT_Face_GetCharsOfVariant( FT_Face face, FT_ULong variantSelector ); /*************************************************************************/ /* */ /* <Section> */ /* computations */ /* */ /* <Title> */ /* Computations */ /* */ /* <Abstract> */ /* Crunching fixed numbers and vectors. */ /* */ /* <Description> */ /* This section contains various functions used to perform */ /* computations on 16.16 fixed-float numbers or 2d vectors. */ /* */ /* <Order> */ /* FT_MulDiv */ /* FT_MulFix */ /* FT_DivFix */ /* FT_RoundFix */ /* FT_CeilFix */ /* FT_FloorFix */ /* FT_Vector_Transform */ /* FT_Matrix_Multiply */ /* FT_Matrix_Invert */ /* */ /*************************************************************************/ /*************************************************************************/ /* */ /* <Function> */ /* FT_MulDiv */ /* */ /* <Description> */ /* A very simple function used to perform the computation `(a*b)/c' */ /* with maximal accuracy (it uses a 64-bit intermediate integer */ /* whenever necessary). */ /* */ /* This function isn't necessarily as fast as some processor specific */ /* operations, but is at least completely portable. */ /* */ /* <Input> */ /* a :: The first multiplier. */ /* b :: The second multiplier. */ /* c :: The divisor. */ /* */ /* <Return> */ /* The result of `(a*b)/c'. This function never traps when trying to */ /* divide by zero; it simply returns `MaxInt' or `MinInt' depending */ /* on the signs of `a' and `b'. */ /* */ FT_EXPORT( FT_Long ) FT_MulDiv( FT_Long a, FT_Long b, FT_Long c ); /* */ /* The following #if 0 ... #endif is for the documentation formatter, */ /* hiding the internal `FT_MULFIX_INLINED' macro. */ #if 0 /*************************************************************************/ /* */ /* <Function> */ /* FT_MulFix */ /* */ /* <Description> */ /* A very simple function used to perform the computation */ /* `(a*b)/0x10000' with maximal accuracy. Most of the time this is */ /* used to multiply a given value by a 16.16 fixed float factor. */ /* */ /* <Input> */ /* a :: The first multiplier. */ /* b :: The second multiplier. Use a 16.16 factor here whenever */ /* possible (see note below). */ /* */ /* <Return> */ /* The result of `(a*b)/0x10000'. */ /* */ /* <Note> */ /* This function has been optimized for the case where the absolute */ /* value of `a' is less than 2048, and `b' is a 16.16 scaling factor. */ /* As this happens mainly when scaling from notional units to */ /* fractional pixels in FreeType, it resulted in noticeable speed */ /* improvements between versions 2.x and 1.x. */ /* */ /* As a conclusion, always try to place a 16.16 factor as the */ /* _second_ argument of this function; this can make a great */ /* difference. */ /* */ FT_EXPORT( FT_Long ) FT_MulFix( FT_Long a, FT_Long b ); /* */ #endif #ifdef FT_MULFIX_INLINED #define FT_MulFix( a, b ) FT_MULFIX_INLINED( a, b ) #else FT_EXPORT( FT_Long ) FT_MulFix( FT_Long a, FT_Long b ); #endif /*************************************************************************/ /* */ /* <Function> */ /* FT_DivFix */ /* */ /* <Description> */ /* A very simple function used to perform the computation */ /* `(a*0x10000)/b' with maximal accuracy. Most of the time, this is */ /* used to divide a given value by a 16.16 fixed float factor. */ /* */ /* <Input> */ /* a :: The first multiplier. */ /* b :: The second multiplier. Use a 16.16 factor here whenever */ /* possible (see note below). */ /* */ /* <Return> */ /* The result of `(a*0x10000)/b'. */ /* */ /* <Note> */ /* The optimization for FT_DivFix() is simple: If (a~<<~16) fits in */ /* 32~bits, then the division is computed directly. Otherwise, we */ /* use a specialized version of @FT_MulDiv. */ /* */ FT_EXPORT( FT_Long ) FT_DivFix( FT_Long a, FT_Long b ); /*************************************************************************/ /* */ /* <Function> */ /* FT_RoundFix */ /* */ /* <Description> */ /* A very simple function used to round a 16.16 fixed number. */ /* */ /* <Input> */ /* a :: The number to be rounded. */ /* */ /* <Return> */ /* The result of `(a + 0x8000) & -0x10000'. */ /* */ FT_EXPORT( FT_Fixed ) FT_RoundFix( FT_Fixed a ); /*************************************************************************/ /* */ /* <Function> */ /* FT_CeilFix */ /* */ /* <Description> */ /* A very simple function used to compute the ceiling function of a */ /* 16.16 fixed number. */ /* */ /* <Input> */ /* a :: The number for which the ceiling function is to be computed. */ /* */ /* <Return> */ /* The result of `(a + 0x10000 - 1) & -0x10000'. */ /* */ FT_EXPORT( FT_Fixed ) FT_CeilFix( FT_Fixed a ); /*************************************************************************/ /* */ /* <Function> */ /* FT_FloorFix */ /* */ /* <Description> */ /* A very simple function used to compute the floor function of a */ /* 16.16 fixed number. */ /* */ /* <Input> */ /* a :: The number for which the floor function is to be computed. */ /* */ /* <Return> */ /* The result of `a & -0x10000'. */ /* */ FT_EXPORT( FT_Fixed ) FT_FloorFix( FT_Fixed a ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Vector_Transform */ /* */ /* <Description> */ /* Transform a single vector through a 2x2 matrix. */ /* */ /* <InOut> */ /* vector :: The target vector to transform. */ /* */ /* <Input> */ /* matrix :: A pointer to the source 2x2 matrix. */ /* */ /* <Note> */ /* The result is undefined if either `vector' or `matrix' is invalid. */ /* */ FT_EXPORT( void ) FT_Vector_Transform( FT_Vector* vec, const FT_Matrix* matrix ); /*************************************************************************/ /* */ /* <Section> */ /* version */ /* */ /* <Title> */ /* FreeType Version */ /* */ /* <Abstract> */ /* Functions and macros related to FreeType versions. */ /* */ /* <Description> */ /* Note that those functions and macros are of limited use because */ /* even a new release of FreeType with only documentation changes */ /* increases the version number. */ /* */ /*************************************************************************/ /************************************************************************* * * @enum: * FREETYPE_XXX * * @description: * These three macros identify the FreeType source code version. * Use @FT_Library_Version to access them at runtime. * * @values: * FREETYPE_MAJOR :: The major version number. * FREETYPE_MINOR :: The minor version number. * FREETYPE_PATCH :: The patch level. * * @note: * The version number of FreeType if built as a dynamic link library * with the `libtool' package is _not_ controlled by these three * macros. * */ #define FREETYPE_MAJOR 2 #define FREETYPE_MINOR 4 #define FREETYPE_PATCH 8 /*************************************************************************/ /* */ /* <Function> */ /* FT_Library_Version */ /* */ /* <Description> */ /* Return the version of the FreeType library being used. This is */ /* useful when dynamically linking to the library, since one cannot */ /* use the macros @FREETYPE_MAJOR, @FREETYPE_MINOR, and */ /* @FREETYPE_PATCH. */ /* */ /* <Input> */ /* library :: A source library handle. */ /* */ /* <Output> */ /* amajor :: The major version number. */ /* */ /* aminor :: The minor version number. */ /* */ /* apatch :: The patch version number. */ /* */ /* <Note> */ /* The reason why this function takes a `library' argument is because */ /* certain programs implement library initialization in a custom way */ /* that doesn't use @FT_Init_FreeType. */ /* */ /* In such cases, the library version might not be available before */ /* the library object has been created. */ /* */ FT_EXPORT( void ) FT_Library_Version( FT_Library library, FT_Int *amajor, FT_Int *aminor, FT_Int *apatch ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Face_CheckTrueTypePatents */ /* */ /* <Description> */ /* Parse all bytecode instructions of a TrueType font file to check */ /* whether any of the patented opcodes are used. This is only useful */ /* if you want to be able to use the unpatented hinter with */ /* fonts that do *not* use these opcodes. */ /* */ /* Note that this function parses *all* glyph instructions in the */ /* font file, which may be slow. */ /* */ /* <Input> */ /* face :: A face handle. */ /* */ /* <Return> */ /* 1~if this is a TrueType font that uses one of the patented */ /* opcodes, 0~otherwise. */ /* */ /* <Note> */ /* Since May 2010, TrueType hinting is no longer patented. */ /* */ /* <Since> */ /* 2.3.5 */ /* */ FT_EXPORT( FT_Bool ) FT_Face_CheckTrueTypePatents( FT_Face face ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Face_SetUnpatentedHinting */ /* */ /* <Description> */ /* Enable or disable the unpatented hinter for a given face. */ /* Only enable it if you have determined that the face doesn't */ /* use any patented opcodes (see @FT_Face_CheckTrueTypePatents). */ /* */ /* <Input> */ /* face :: A face handle. */ /* */ /* value :: New boolean setting. */ /* */ /* <Return> */ /* The old setting value. This will always be false if this is not */ /* an SFNT font, or if the unpatented hinter is not compiled in this */ /* instance of the library. */ /* */ /* <Note> */ /* Since May 2010, TrueType hinting is no longer patented. */ /* */ /* <Since> */ /* 2.3.5 */ /* */ FT_EXPORT( FT_Bool ) FT_Face_SetUnpatentedHinting( FT_Face face, FT_Bool value ); /* */ FT_END_HEADER #endif /* __FREETYPE_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/ftadvanc.h ================================================ /***************************************************************************/ /* */ /* ftadvanc.h */ /* */ /* Quick computation of advance widths (specification only). */ /* */ /* Copyright 2008 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __FTADVANC_H__ #define __FTADVANC_H__ #include <ft2build.h> #include FT_FREETYPE_H #ifdef FREETYPE_H #error "freetype.h of FreeType 1 has been loaded!" #error "Please fix the directory search order for header files" #error "so that freetype.h of FreeType 2 is found first." #endif FT_BEGIN_HEADER /************************************************************************** * * @section: * quick_advance * * @title: * Quick retrieval of advance values * * @abstract: * Retrieve horizontal and vertical advance values without processing * glyph outlines, if possible. * * @description: * This section contains functions to quickly extract advance values * without handling glyph outlines, if possible. */ /*************************************************************************/ /* */ /* <Const> */ /* FT_ADVANCE_FLAG_FAST_ONLY */ /* */ /* <Description> */ /* A bit-flag to be OR-ed with the `flags' parameter of the */ /* @FT_Get_Advance and @FT_Get_Advances functions. */ /* */ /* If set, it indicates that you want these functions to fail if the */ /* corresponding hinting mode or font driver doesn't allow for very */ /* quick advance computation. */ /* */ /* Typically, glyphs which are either unscaled, unhinted, bitmapped, */ /* or light-hinted can have their advance width computed very */ /* quickly. */ /* */ /* Normal and bytecode hinted modes, which require loading, scaling, */ /* and hinting of the glyph outline, are extremely slow by */ /* comparison. */ /* */ #define FT_ADVANCE_FLAG_FAST_ONLY 0x20000000UL /*************************************************************************/ /* */ /* <Function> */ /* FT_Get_Advance */ /* */ /* <Description> */ /* Retrieve the advance value of a given glyph outline in an */ /* @FT_Face. By default, the unhinted advance is returned in font */ /* units. */ /* */ /* <Input> */ /* face :: The source @FT_Face handle. */ /* */ /* gindex :: The glyph index. */ /* */ /* load_flags :: A set of bit flags similar to those used when */ /* calling @FT_Load_Glyph, used to determine what kind */ /* of advances you need. */ /* <Output> */ /* padvance :: The advance value, in either font units or 16.16 */ /* format. */ /* */ /* If @FT_LOAD_VERTICAL_LAYOUT is set, this is the */ /* vertical advance corresponding to a vertical layout. */ /* Otherwise, it is the horizontal advance in a */ /* horizontal layout. */ /* */ /* <Return> */ /* FreeType error code. 0 means success. */ /* */ /* <Note> */ /* This function may fail if you use @FT_ADVANCE_FLAG_FAST_ONLY and */ /* if the corresponding font backend doesn't have a quick way to */ /* retrieve the advances. */ /* */ /* A scaled advance is returned in 16.16 format but isn't transformed */ /* by the affine transformation specified by @FT_Set_Transform. */ /* */ FT_EXPORT( FT_Error ) FT_Get_Advance( FT_Face face, FT_UInt gindex, FT_Int32 load_flags, FT_Fixed *padvance ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Get_Advances */ /* */ /* <Description> */ /* Retrieve the advance values of several glyph outlines in an */ /* @FT_Face. By default, the unhinted advances are returned in font */ /* units. */ /* */ /* <Input> */ /* face :: The source @FT_Face handle. */ /* */ /* start :: The first glyph index. */ /* */ /* count :: The number of advance values you want to retrieve. */ /* */ /* load_flags :: A set of bit flags similar to those used when */ /* calling @FT_Load_Glyph. */ /* */ /* <Output> */ /* padvance :: The advances, in either font units or 16.16 format. */ /* This array must contain at least `count' elements. */ /* */ /* If @FT_LOAD_VERTICAL_LAYOUT is set, these are the */ /* vertical advances corresponding to a vertical layout. */ /* Otherwise, they are the horizontal advances in a */ /* horizontal layout. */ /* */ /* <Return> */ /* FreeType error code. 0 means success. */ /* */ /* <Note> */ /* This function may fail if you use @FT_ADVANCE_FLAG_FAST_ONLY and */ /* if the corresponding font backend doesn't have a quick way to */ /* retrieve the advances. */ /* */ /* Scaled advances are returned in 16.16 format but aren't */ /* transformed by the affine transformation specified by */ /* @FT_Set_Transform. */ /* */ FT_EXPORT( FT_Error ) FT_Get_Advances( FT_Face face, FT_UInt start, FT_UInt count, FT_Int32 load_flags, FT_Fixed *padvances ); /* */ FT_END_HEADER #endif /* __FTADVANC_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/ftbbox.h ================================================ /***************************************************************************/ /* */ /* ftbbox.h */ /* */ /* FreeType exact bbox computation (specification). */ /* */ /* Copyright 1996-2001, 2003, 2007, 2011 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /*************************************************************************/ /* */ /* This component has a _single_ role: to compute exact outline bounding */ /* boxes. */ /* */ /* It is separated from the rest of the engine for various technical */ /* reasons. It may well be integrated in `ftoutln' later. */ /* */ /*************************************************************************/ #ifndef __FTBBOX_H__ #define __FTBBOX_H__ #include <ft2build.h> #include FT_FREETYPE_H #ifdef FREETYPE_H #error "freetype.h of FreeType 1 has been loaded!" #error "Please fix the directory search order for header files" #error "so that freetype.h of FreeType 2 is found first." #endif FT_BEGIN_HEADER /*************************************************************************/ /* */ /* <Section> */ /* outline_processing */ /* */ /*************************************************************************/ /*************************************************************************/ /* */ /* <Function> */ /* FT_Outline_Get_BBox */ /* */ /* <Description> */ /* Compute the exact bounding box of an outline. This is slower */ /* than computing the control box. However, it uses an advanced */ /* algorithm which returns _very_ quickly when the two boxes */ /* coincide. Otherwise, the outline Bézier arcs are traversed to */ /* extract their extrema. */ /* */ /* <Input> */ /* outline :: A pointer to the source outline. */ /* */ /* <Output> */ /* abbox :: The outline's exact bounding box. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ /* <Note> */ /* If the font is tricky and the glyph has been loaded with */ /* @FT_LOAD_NO_SCALE, the resulting BBox is meaningless. To get */ /* reasonable values for the BBox it is necessary to load the glyph */ /* at a large ppem value (so that the hinting instructions can */ /* properly shift and scale the subglyphs), then extracting the BBox */ /* which can be eventually converted back to font units. */ /* */ FT_EXPORT( FT_Error ) FT_Outline_Get_BBox( FT_Outline* outline, FT_BBox *abbox ); /* */ FT_END_HEADER #endif /* __FTBBOX_H__ */ /* END */ /* Local Variables: */ /* coding: utf-8 */ /* End: */ ================================================ FILE: other/freetype/include/freetype/ftbdf.h ================================================ /***************************************************************************/ /* */ /* ftbdf.h */ /* */ /* FreeType API for accessing BDF-specific strings (specification). */ /* */ /* Copyright 2002, 2003, 2004, 2006, 2009 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __FTBDF_H__ #define __FTBDF_H__ #include <ft2build.h> #include FT_FREETYPE_H #ifdef FREETYPE_H #error "freetype.h of FreeType 1 has been loaded!" #error "Please fix the directory search order for header files" #error "so that freetype.h of FreeType 2 is found first." #endif FT_BEGIN_HEADER /*************************************************************************/ /* */ /* <Section> */ /* bdf_fonts */ /* */ /* <Title> */ /* BDF and PCF Files */ /* */ /* <Abstract> */ /* BDF and PCF specific API. */ /* */ /* <Description> */ /* This section contains the declaration of functions specific to BDF */ /* and PCF fonts. */ /* */ /*************************************************************************/ /********************************************************************** * * @enum: * FT_PropertyType * * @description: * A list of BDF property types. * * @values: * BDF_PROPERTY_TYPE_NONE :: * Value~0 is used to indicate a missing property. * * BDF_PROPERTY_TYPE_ATOM :: * Property is a string atom. * * BDF_PROPERTY_TYPE_INTEGER :: * Property is a 32-bit signed integer. * * BDF_PROPERTY_TYPE_CARDINAL :: * Property is a 32-bit unsigned integer. */ typedef enum BDF_PropertyType_ { BDF_PROPERTY_TYPE_NONE = 0, BDF_PROPERTY_TYPE_ATOM = 1, BDF_PROPERTY_TYPE_INTEGER = 2, BDF_PROPERTY_TYPE_CARDINAL = 3 } BDF_PropertyType; /********************************************************************** * * @type: * BDF_Property * * @description: * A handle to a @BDF_PropertyRec structure to model a given * BDF/PCF property. */ typedef struct BDF_PropertyRec_* BDF_Property; /********************************************************************** * * @struct: * BDF_PropertyRec * * @description: * This structure models a given BDF/PCF property. * * @fields: * type :: * The property type. * * u.atom :: * The atom string, if type is @BDF_PROPERTY_TYPE_ATOM. * * u.integer :: * A signed integer, if type is @BDF_PROPERTY_TYPE_INTEGER. * * u.cardinal :: * An unsigned integer, if type is @BDF_PROPERTY_TYPE_CARDINAL. */ typedef struct BDF_PropertyRec_ { BDF_PropertyType type; union { const char* atom; FT_Int32 integer; FT_UInt32 cardinal; } u; } BDF_PropertyRec; /********************************************************************** * * @function: * FT_Get_BDF_Charset_ID * * @description: * Retrieve a BDF font character set identity, according to * the BDF specification. * * @input: * face :: * A handle to the input face. * * @output: * acharset_encoding :: * Charset encoding, as a C~string, owned by the face. * * acharset_registry :: * Charset registry, as a C~string, owned by the face. * * @return: * FreeType error code. 0~means success. * * @note: * This function only works with BDF faces, returning an error otherwise. */ FT_EXPORT( FT_Error ) FT_Get_BDF_Charset_ID( FT_Face face, const char* *acharset_encoding, const char* *acharset_registry ); /********************************************************************** * * @function: * FT_Get_BDF_Property * * @description: * Retrieve a BDF property from a BDF or PCF font file. * * @input: * face :: A handle to the input face. * * name :: The property name. * * @output: * aproperty :: The property. * * @return: * FreeType error code. 0~means success. * * @note: * This function works with BDF _and_ PCF fonts. It returns an error * otherwise. It also returns an error if the property is not in the * font. * * A `property' is a either key-value pair within the STARTPROPERTIES * ... ENDPROPERTIES block of a BDF font or a key-value pair from the * `info->props' array within a `FontRec' structure of a PCF font. * * Integer properties are always stored as `signed' within PCF fonts; * consequently, @BDF_PROPERTY_TYPE_CARDINAL is a possible return value * for BDF fonts only. * * In case of error, `aproperty->type' is always set to * @BDF_PROPERTY_TYPE_NONE. */ FT_EXPORT( FT_Error ) FT_Get_BDF_Property( FT_Face face, const char* prop_name, BDF_PropertyRec *aproperty ); /* */ FT_END_HEADER #endif /* __FTBDF_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/ftbitmap.h ================================================ /***************************************************************************/ /* */ /* ftbitmap.h */ /* */ /* FreeType utility functions for bitmaps (specification). */ /* */ /* Copyright 2004, 2005, 2006, 2008 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __FTBITMAP_H__ #define __FTBITMAP_H__ #include <ft2build.h> #include FT_FREETYPE_H #ifdef FREETYPE_H #error "freetype.h of FreeType 1 has been loaded!" #error "Please fix the directory search order for header files" #error "so that freetype.h of FreeType 2 is found first." #endif FT_BEGIN_HEADER /*************************************************************************/ /* */ /* <Section> */ /* bitmap_handling */ /* */ /* <Title> */ /* Bitmap Handling */ /* */ /* <Abstract> */ /* Handling FT_Bitmap objects. */ /* */ /* <Description> */ /* This section contains functions for converting FT_Bitmap objects. */ /* */ /*************************************************************************/ /*************************************************************************/ /* */ /* <Function> */ /* FT_Bitmap_New */ /* */ /* <Description> */ /* Initialize a pointer to an @FT_Bitmap structure. */ /* */ /* <InOut> */ /* abitmap :: A pointer to the bitmap structure. */ /* */ FT_EXPORT( void ) FT_Bitmap_New( FT_Bitmap *abitmap ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Bitmap_Copy */ /* */ /* <Description> */ /* Copy a bitmap into another one. */ /* */ /* <Input> */ /* library :: A handle to a library object. */ /* */ /* source :: A handle to the source bitmap. */ /* */ /* <Output> */ /* target :: A handle to the target bitmap. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ FT_EXPORT( FT_Error ) FT_Bitmap_Copy( FT_Library library, const FT_Bitmap *source, FT_Bitmap *target); /*************************************************************************/ /* */ /* <Function> */ /* FT_Bitmap_Embolden */ /* */ /* <Description> */ /* Embolden a bitmap. The new bitmap will be about `xStrength' */ /* pixels wider and `yStrength' pixels higher. The left and bottom */ /* borders are kept unchanged. */ /* */ /* <Input> */ /* library :: A handle to a library object. */ /* */ /* xStrength :: How strong the glyph is emboldened horizontally. */ /* Expressed in 26.6 pixel format. */ /* */ /* yStrength :: How strong the glyph is emboldened vertically. */ /* Expressed in 26.6 pixel format. */ /* */ /* <InOut> */ /* bitmap :: A handle to the target bitmap. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ /* <Note> */ /* The current implementation restricts `xStrength' to be less than */ /* or equal to~8 if bitmap is of pixel_mode @FT_PIXEL_MODE_MONO. */ /* */ /* If you want to embolden the bitmap owned by a @FT_GlyphSlotRec, */ /* you should call @FT_GlyphSlot_Own_Bitmap on the slot first. */ /* */ FT_EXPORT( FT_Error ) FT_Bitmap_Embolden( FT_Library library, FT_Bitmap* bitmap, FT_Pos xStrength, FT_Pos yStrength ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Bitmap_Convert */ /* */ /* <Description> */ /* Convert a bitmap object with depth 1bpp, 2bpp, 4bpp, or 8bpp to a */ /* bitmap object with depth 8bpp, making the number of used bytes per */ /* line (a.k.a. the `pitch') a multiple of `alignment'. */ /* */ /* <Input> */ /* library :: A handle to a library object. */ /* */ /* source :: The source bitmap. */ /* */ /* alignment :: The pitch of the bitmap is a multiple of this */ /* parameter. Common values are 1, 2, or 4. */ /* */ /* <Output> */ /* target :: The target bitmap. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ /* <Note> */ /* It is possible to call @FT_Bitmap_Convert multiple times without */ /* calling @FT_Bitmap_Done (the memory is simply reallocated). */ /* */ /* Use @FT_Bitmap_Done to finally remove the bitmap object. */ /* */ /* The `library' argument is taken to have access to FreeType's */ /* memory handling functions. */ /* */ FT_EXPORT( FT_Error ) FT_Bitmap_Convert( FT_Library library, const FT_Bitmap *source, FT_Bitmap *target, FT_Int alignment ); /*************************************************************************/ /* */ /* <Function> */ /* FT_GlyphSlot_Own_Bitmap */ /* */ /* <Description> */ /* Make sure that a glyph slot owns `slot->bitmap'. */ /* */ /* <Input> */ /* slot :: The glyph slot. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ /* <Note> */ /* This function is to be used in combination with */ /* @FT_Bitmap_Embolden. */ /* */ FT_EXPORT( FT_Error ) FT_GlyphSlot_Own_Bitmap( FT_GlyphSlot slot ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Bitmap_Done */ /* */ /* <Description> */ /* Destroy a bitmap object created with @FT_Bitmap_New. */ /* */ /* <Input> */ /* library :: A handle to a library object. */ /* */ /* bitmap :: The bitmap object to be freed. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ /* <Note> */ /* The `library' argument is taken to have access to FreeType's */ /* memory handling functions. */ /* */ FT_EXPORT( FT_Error ) FT_Bitmap_Done( FT_Library library, FT_Bitmap *bitmap ); /* */ FT_END_HEADER #endif /* __FTBITMAP_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/ftbzip2.h ================================================ /***************************************************************************/ /* */ /* ftbzip2.h */ /* */ /* Bzip2-compressed stream support. */ /* */ /* Copyright 2010 by */ /* Joel Klinghed. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __FTBZIP2_H__ #define __FTBZIP2_H__ #include <ft2build.h> #include FT_FREETYPE_H #ifdef FREETYPE_H #error "freetype.h of FreeType 1 has been loaded!" #error "Please fix the directory search order for header files" #error "so that freetype.h of FreeType 2 is found first." #endif FT_BEGIN_HEADER /*************************************************************************/ /* */ /* <Section> */ /* bzip2 */ /* */ /* <Title> */ /* BZIP2 Streams */ /* */ /* <Abstract> */ /* Using bzip2-compressed font files. */ /* */ /* <Description> */ /* This section contains the declaration of Bzip2-specific functions. */ /* */ /*************************************************************************/ /************************************************************************ * * @function: * FT_Stream_OpenBzip2 * * @description: * Open a new stream to parse bzip2-compressed font files. This is * mainly used to support the compressed `*.pcf.bz2' fonts that come * with XFree86. * * @input: * stream :: * The target embedding stream. * * source :: * The source stream. * * @return: * FreeType error code. 0~means success. * * @note: * The source stream must be opened _before_ calling this function. * * Calling the internal function `FT_Stream_Close' on the new stream will * *not* call `FT_Stream_Close' on the source stream. None of the stream * objects will be released to the heap. * * The stream implementation is very basic and resets the decompression * process each time seeking backwards is needed within the stream. * * In certain builds of the library, bzip2 compression recognition is * automatically handled when calling @FT_New_Face or @FT_Open_Face. * This means that if no font driver is capable of handling the raw * compressed file, the library will try to open a bzip2 compressed stream * from it and re-open the face with it. * * This function may return `FT_Err_Unimplemented_Feature' if your build * of FreeType was not compiled with bzip2 support. */ FT_EXPORT( FT_Error ) FT_Stream_OpenBzip2( FT_Stream stream, FT_Stream source ); /* */ FT_END_HEADER #endif /* __FTBZIP2_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/ftcache.h ================================================ /***************************************************************************/ /* */ /* ftcache.h */ /* */ /* FreeType Cache subsystem (specification). */ /* */ /* Copyright 1996-2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2010 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __FTCACHE_H__ #define __FTCACHE_H__ #include <ft2build.h> #include FT_GLYPH_H FT_BEGIN_HEADER /************************************************************************* * * <Section> * cache_subsystem * * <Title> * Cache Sub-System * * <Abstract> * How to cache face, size, and glyph data with FreeType~2. * * <Description> * This section describes the FreeType~2 cache sub-system, which is used * to limit the number of concurrently opened @FT_Face and @FT_Size * objects, as well as caching information like character maps and glyph * images while limiting their maximum memory usage. * * Note that all types and functions begin with the `FTC_' prefix. * * The cache is highly portable and thus doesn't know anything about the * fonts installed on your system, or how to access them. This implies * the following scheme: * * First, available or installed font faces are uniquely identified by * @FTC_FaceID values, provided to the cache by the client. Note that * the cache only stores and compares these values, and doesn't try to * interpret them in any way. * * Second, the cache calls, only when needed, a client-provided function * to convert an @FTC_FaceID into a new @FT_Face object. The latter is * then completely managed by the cache, including its termination * through @FT_Done_Face. To monitor termination of face objects, the * finalizer callback in the `generic' field of the @FT_Face object can * be used, which might also be used to store the @FTC_FaceID of the * face. * * Clients are free to map face IDs to anything else. The most simple * usage is to associate them to a (pathname,face_index) pair that is * used to call @FT_New_Face. However, more complex schemes are also * possible. * * Note that for the cache to work correctly, the face ID values must be * *persistent*, which means that the contents they point to should not * change at runtime, or that their value should not become invalid. * * If this is unavoidable (e.g., when a font is uninstalled at runtime), * you should call @FTC_Manager_RemoveFaceID as soon as possible, to let * the cache get rid of any references to the old @FTC_FaceID it may * keep internally. Failure to do so will lead to incorrect behaviour * or even crashes. * * To use the cache, start with calling @FTC_Manager_New to create a new * @FTC_Manager object, which models a single cache instance. You can * then look up @FT_Face and @FT_Size objects with * @FTC_Manager_LookupFace and @FTC_Manager_LookupSize, respectively. * * If you want to use the charmap caching, call @FTC_CMapCache_New, then * later use @FTC_CMapCache_Lookup to perform the equivalent of * @FT_Get_Char_Index, only much faster. * * If you want to use the @FT_Glyph caching, call @FTC_ImageCache, then * later use @FTC_ImageCache_Lookup to retrieve the corresponding * @FT_Glyph objects from the cache. * * If you need lots of small bitmaps, it is much more memory efficient * to call @FTC_SBitCache_New followed by @FTC_SBitCache_Lookup. This * returns @FTC_SBitRec structures, which are used to store small * bitmaps directly. (A small bitmap is one whose metrics and * dimensions all fit into 8-bit integers). * * We hope to also provide a kerning cache in the near future. * * * <Order> * FTC_Manager * FTC_FaceID * FTC_Face_Requester * * FTC_Manager_New * FTC_Manager_Reset * FTC_Manager_Done * FTC_Manager_LookupFace * FTC_Manager_LookupSize * FTC_Manager_RemoveFaceID * * FTC_Node * FTC_Node_Unref * * FTC_ImageCache * FTC_ImageCache_New * FTC_ImageCache_Lookup * * FTC_SBit * FTC_SBitCache * FTC_SBitCache_New * FTC_SBitCache_Lookup * * FTC_CMapCache * FTC_CMapCache_New * FTC_CMapCache_Lookup * *************************************************************************/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** BASIC TYPE DEFINITIONS *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /************************************************************************* * * @type: FTC_FaceID * * @description: * An opaque pointer type that is used to identity face objects. The * contents of such objects is application-dependent. * * These pointers are typically used to point to a user-defined * structure containing a font file path, and face index. * * @note: * Never use NULL as a valid @FTC_FaceID. * * Face IDs are passed by the client to the cache manager, which calls, * when needed, the @FTC_Face_Requester to translate them into new * @FT_Face objects. * * If the content of a given face ID changes at runtime, or if the value * becomes invalid (e.g., when uninstalling a font), you should * immediately call @FTC_Manager_RemoveFaceID before any other cache * function. * * Failure to do so will result in incorrect behaviour or even * memory leaks and crashes. */ typedef FT_Pointer FTC_FaceID; /************************************************************************ * * @functype: * FTC_Face_Requester * * @description: * A callback function provided by client applications. It is used by * the cache manager to translate a given @FTC_FaceID into a new valid * @FT_Face object, on demand. * * <Input> * face_id :: * The face ID to resolve. * * library :: * A handle to a FreeType library object. * * req_data :: * Application-provided request data (see note below). * * <Output> * aface :: * A new @FT_Face handle. * * <Return> * FreeType error code. 0~means success. * * <Note> * The third parameter `req_data' is the same as the one passed by the * client when @FTC_Manager_New is called. * * The face requester should not perform funny things on the returned * face object, like creating a new @FT_Size for it, or setting a * transformation through @FT_Set_Transform! */ typedef FT_Error (*FTC_Face_Requester)( FTC_FaceID face_id, FT_Library library, FT_Pointer request_data, FT_Face* aface ); /* */ #ifdef FT_CONFIG_OPTION_OLD_INTERNALS /* these macros are incompatible with LLP64, should not be used */ #define FT_POINTER_TO_ULONG( p ) ( (FT_ULong)(FT_Pointer)(p) ) #define FTC_FACE_ID_HASH( i ) \ ((FT_UInt32)(( FT_POINTER_TO_ULONG( i ) >> 3 ) ^ \ ( FT_POINTER_TO_ULONG( i ) << 7 ) ) ) #endif /* FT_CONFIG_OPTION_OLD_INTERNALS */ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** CACHE MANAGER OBJECT *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /* */ /* <Type> */ /* FTC_Manager */ /* */ /* <Description> */ /* This object corresponds to one instance of the cache-subsystem. */ /* It is used to cache one or more @FT_Face objects, along with */ /* corresponding @FT_Size objects. */ /* */ /* The manager intentionally limits the total number of opened */ /* @FT_Face and @FT_Size objects to control memory usage. See the */ /* `max_faces' and `max_sizes' parameters of @FTC_Manager_New. */ /* */ /* The manager is also used to cache `nodes' of various types while */ /* limiting their total memory usage. */ /* */ /* All limitations are enforced by keeping lists of managed objects */ /* in most-recently-used order, and flushing old nodes to make room */ /* for new ones. */ /* */ typedef struct FTC_ManagerRec_* FTC_Manager; /*************************************************************************/ /* */ /* <Type> */ /* FTC_Node */ /* */ /* <Description> */ /* An opaque handle to a cache node object. Each cache node is */ /* reference-counted. A node with a count of~0 might be flushed */ /* out of a full cache whenever a lookup request is performed. */ /* */ /* If you look up nodes, you have the ability to `acquire' them, */ /* i.e., to increment their reference count. This will prevent the */ /* node from being flushed out of the cache until you explicitly */ /* `release' it (see @FTC_Node_Unref). */ /* */ /* See also @FTC_SBitCache_Lookup and @FTC_ImageCache_Lookup. */ /* */ typedef struct FTC_NodeRec_* FTC_Node; /*************************************************************************/ /* */ /* <Function> */ /* FTC_Manager_New */ /* */ /* <Description> */ /* Create a new cache manager. */ /* */ /* <Input> */ /* library :: The parent FreeType library handle to use. */ /* */ /* max_faces :: Maximum number of opened @FT_Face objects managed by */ /* this cache instance. Use~0 for defaults. */ /* */ /* max_sizes :: Maximum number of opened @FT_Size objects managed by */ /* this cache instance. Use~0 for defaults. */ /* */ /* max_bytes :: Maximum number of bytes to use for cached data nodes. */ /* Use~0 for defaults. Note that this value does not */ /* account for managed @FT_Face and @FT_Size objects. */ /* */ /* requester :: An application-provided callback used to translate */ /* face IDs into real @FT_Face objects. */ /* */ /* req_data :: A generic pointer that is passed to the requester */ /* each time it is called (see @FTC_Face_Requester). */ /* */ /* <Output> */ /* amanager :: A handle to a new manager object. 0~in case of */ /* failure. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ FT_EXPORT( FT_Error ) FTC_Manager_New( FT_Library library, FT_UInt max_faces, FT_UInt max_sizes, FT_ULong max_bytes, FTC_Face_Requester requester, FT_Pointer req_data, FTC_Manager *amanager ); /*************************************************************************/ /* */ /* <Function> */ /* FTC_Manager_Reset */ /* */ /* <Description> */ /* Empty a given cache manager. This simply gets rid of all the */ /* currently cached @FT_Face and @FT_Size objects within the manager. */ /* */ /* <InOut> */ /* manager :: A handle to the manager. */ /* */ FT_EXPORT( void ) FTC_Manager_Reset( FTC_Manager manager ); /*************************************************************************/ /* */ /* <Function> */ /* FTC_Manager_Done */ /* */ /* <Description> */ /* Destroy a given manager after emptying it. */ /* */ /* <Input> */ /* manager :: A handle to the target cache manager object. */ /* */ FT_EXPORT( void ) FTC_Manager_Done( FTC_Manager manager ); /*************************************************************************/ /* */ /* <Function> */ /* FTC_Manager_LookupFace */ /* */ /* <Description> */ /* Retrieve the @FT_Face object that corresponds to a given face ID */ /* through a cache manager. */ /* */ /* <Input> */ /* manager :: A handle to the cache manager. */ /* */ /* face_id :: The ID of the face object. */ /* */ /* <Output> */ /* aface :: A handle to the face object. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ /* <Note> */ /* The returned @FT_Face object is always owned by the manager. You */ /* should never try to discard it yourself. */ /* */ /* The @FT_Face object doesn't necessarily have a current size object */ /* (i.e., face->size can be 0). If you need a specific `font size', */ /* use @FTC_Manager_LookupSize instead. */ /* */ /* Never change the face's transformation matrix (i.e., never call */ /* the @FT_Set_Transform function) on a returned face! If you need */ /* to transform glyphs, do it yourself after glyph loading. */ /* */ /* When you perform a lookup, out-of-memory errors are detected */ /* _within_ the lookup and force incremental flushes of the cache */ /* until enough memory is released for the lookup to succeed. */ /* */ /* If a lookup fails with `FT_Err_Out_Of_Memory' the cache has */ /* already been completely flushed, and still no memory was available */ /* for the operation. */ /* */ FT_EXPORT( FT_Error ) FTC_Manager_LookupFace( FTC_Manager manager, FTC_FaceID face_id, FT_Face *aface ); /*************************************************************************/ /* */ /* <Struct> */ /* FTC_ScalerRec */ /* */ /* <Description> */ /* A structure used to describe a given character size in either */ /* pixels or points to the cache manager. See */ /* @FTC_Manager_LookupSize. */ /* */ /* <Fields> */ /* face_id :: The source face ID. */ /* */ /* width :: The character width. */ /* */ /* height :: The character height. */ /* */ /* pixel :: A Boolean. If 1, the `width' and `height' fields are */ /* interpreted as integer pixel character sizes. */ /* Otherwise, they are expressed as 1/64th of points. */ /* */ /* x_res :: Only used when `pixel' is value~0 to indicate the */ /* horizontal resolution in dpi. */ /* */ /* y_res :: Only used when `pixel' is value~0 to indicate the */ /* vertical resolution in dpi. */ /* */ /* <Note> */ /* This type is mainly used to retrieve @FT_Size objects through the */ /* cache manager. */ /* */ typedef struct FTC_ScalerRec_ { FTC_FaceID face_id; FT_UInt width; FT_UInt height; FT_Int pixel; FT_UInt x_res; FT_UInt y_res; } FTC_ScalerRec; /*************************************************************************/ /* */ /* <Struct> */ /* FTC_Scaler */ /* */ /* <Description> */ /* A handle to an @FTC_ScalerRec structure. */ /* */ typedef struct FTC_ScalerRec_* FTC_Scaler; /*************************************************************************/ /* */ /* <Function> */ /* FTC_Manager_LookupSize */ /* */ /* <Description> */ /* Retrieve the @FT_Size object that corresponds to a given */ /* @FTC_ScalerRec pointer through a cache manager. */ /* */ /* <Input> */ /* manager :: A handle to the cache manager. */ /* */ /* scaler :: A scaler handle. */ /* */ /* <Output> */ /* asize :: A handle to the size object. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ /* <Note> */ /* The returned @FT_Size object is always owned by the manager. You */ /* should never try to discard it by yourself. */ /* */ /* You can access the parent @FT_Face object simply as `size->face' */ /* if you need it. Note that this object is also owned by the */ /* manager. */ /* */ /* <Note> */ /* When you perform a lookup, out-of-memory errors are detected */ /* _within_ the lookup and force incremental flushes of the cache */ /* until enough memory is released for the lookup to succeed. */ /* */ /* If a lookup fails with `FT_Err_Out_Of_Memory' the cache has */ /* already been completely flushed, and still no memory is available */ /* for the operation. */ /* */ FT_EXPORT( FT_Error ) FTC_Manager_LookupSize( FTC_Manager manager, FTC_Scaler scaler, FT_Size *asize ); /*************************************************************************/ /* */ /* <Function> */ /* FTC_Node_Unref */ /* */ /* <Description> */ /* Decrement a cache node's internal reference count. When the count */ /* reaches 0, it is not destroyed but becomes eligible for subsequent */ /* cache flushes. */ /* */ /* <Input> */ /* node :: The cache node handle. */ /* */ /* manager :: The cache manager handle. */ /* */ FT_EXPORT( void ) FTC_Node_Unref( FTC_Node node, FTC_Manager manager ); /************************************************************************* * * @function: * FTC_Manager_RemoveFaceID * * @description: * A special function used to indicate to the cache manager that * a given @FTC_FaceID is no longer valid, either because its * content changed, or because it was deallocated or uninstalled. * * @input: * manager :: * The cache manager handle. * * face_id :: * The @FTC_FaceID to be removed. * * @note: * This function flushes all nodes from the cache corresponding to this * `face_id', with the exception of nodes with a non-null reference * count. * * Such nodes are however modified internally so as to never appear * in later lookups with the same `face_id' value, and to be immediately * destroyed when released by all their users. * */ FT_EXPORT( void ) FTC_Manager_RemoveFaceID( FTC_Manager manager, FTC_FaceID face_id ); /*************************************************************************/ /* */ /* <Section> */ /* cache_subsystem */ /* */ /*************************************************************************/ /************************************************************************* * * @type: * FTC_CMapCache * * @description: * An opaque handle used to model a charmap cache. This cache is to * hold character codes -> glyph indices mappings. * */ typedef struct FTC_CMapCacheRec_* FTC_CMapCache; /************************************************************************* * * @function: * FTC_CMapCache_New * * @description: * Create a new charmap cache. * * @input: * manager :: * A handle to the cache manager. * * @output: * acache :: * A new cache handle. NULL in case of error. * * @return: * FreeType error code. 0~means success. * * @note: * Like all other caches, this one will be destroyed with the cache * manager. * */ FT_EXPORT( FT_Error ) FTC_CMapCache_New( FTC_Manager manager, FTC_CMapCache *acache ); /************************************************************************ * * @function: * FTC_CMapCache_Lookup * * @description: * Translate a character code into a glyph index, using the charmap * cache. * * @input: * cache :: * A charmap cache handle. * * face_id :: * The source face ID. * * cmap_index :: * The index of the charmap in the source face. Any negative value * means to use the cache @FT_Face's default charmap. * * char_code :: * The character code (in the corresponding charmap). * * @return: * Glyph index. 0~means `no glyph'. * */ FT_EXPORT( FT_UInt ) FTC_CMapCache_Lookup( FTC_CMapCache cache, FTC_FaceID face_id, FT_Int cmap_index, FT_UInt32 char_code ); /*************************************************************************/ /* */ /* <Section> */ /* cache_subsystem */ /* */ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** IMAGE CACHE OBJECT *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /************************************************************************* * * @struct: * FTC_ImageTypeRec * * @description: * A structure used to model the type of images in a glyph cache. * * @fields: * face_id :: * The face ID. * * width :: * The width in pixels. * * height :: * The height in pixels. * * flags :: * The load flags, as in @FT_Load_Glyph. * */ typedef struct FTC_ImageTypeRec_ { FTC_FaceID face_id; FT_Int width; FT_Int height; FT_Int32 flags; } FTC_ImageTypeRec; /************************************************************************* * * @type: * FTC_ImageType * * @description: * A handle to an @FTC_ImageTypeRec structure. * */ typedef struct FTC_ImageTypeRec_* FTC_ImageType; /* */ #define FTC_IMAGE_TYPE_COMPARE( d1, d2 ) \ ( (d1)->face_id == (d2)->face_id && \ (d1)->width == (d2)->width && \ (d1)->flags == (d2)->flags ) #ifdef FT_CONFIG_OPTION_OLD_INTERNALS /* this macro is incompatible with LLP64, should not be used */ #define FTC_IMAGE_TYPE_HASH( d ) \ (FT_UFast)( FTC_FACE_ID_HASH( (d)->face_id ) ^ \ ( (d)->width << 8 ) ^ (d)->height ^ \ ( (d)->flags << 4 ) ) #endif /* FT_CONFIG_OPTION_OLD_INTERNALS */ /*************************************************************************/ /* */ /* <Type> */ /* FTC_ImageCache */ /* */ /* <Description> */ /* A handle to an glyph image cache object. They are designed to */ /* hold many distinct glyph images while not exceeding a certain */ /* memory threshold. */ /* */ typedef struct FTC_ImageCacheRec_* FTC_ImageCache; /*************************************************************************/ /* */ /* <Function> */ /* FTC_ImageCache_New */ /* */ /* <Description> */ /* Create a new glyph image cache. */ /* */ /* <Input> */ /* manager :: The parent manager for the image cache. */ /* */ /* <Output> */ /* acache :: A handle to the new glyph image cache object. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ FT_EXPORT( FT_Error ) FTC_ImageCache_New( FTC_Manager manager, FTC_ImageCache *acache ); /*************************************************************************/ /* */ /* <Function> */ /* FTC_ImageCache_Lookup */ /* */ /* <Description> */ /* Retrieve a given glyph image from a glyph image cache. */ /* */ /* <Input> */ /* cache :: A handle to the source glyph image cache. */ /* */ /* type :: A pointer to a glyph image type descriptor. */ /* */ /* gindex :: The glyph index to retrieve. */ /* */ /* <Output> */ /* aglyph :: The corresponding @FT_Glyph object. 0~in case of */ /* failure. */ /* */ /* anode :: Used to return the address of of the corresponding cache */ /* node after incrementing its reference count (see note */ /* below). */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ /* <Note> */ /* The returned glyph is owned and managed by the glyph image cache. */ /* Never try to transform or discard it manually! You can however */ /* create a copy with @FT_Glyph_Copy and modify the new one. */ /* */ /* If `anode' is _not_ NULL, it receives the address of the cache */ /* node containing the glyph image, after increasing its reference */ /* count. This ensures that the node (as well as the @FT_Glyph) will */ /* always be kept in the cache until you call @FTC_Node_Unref to */ /* `release' it. */ /* */ /* If `anode' is NULL, the cache node is left unchanged, which means */ /* that the @FT_Glyph could be flushed out of the cache on the next */ /* call to one of the caching sub-system APIs. Don't assume that it */ /* is persistent! */ /* */ FT_EXPORT( FT_Error ) FTC_ImageCache_Lookup( FTC_ImageCache cache, FTC_ImageType type, FT_UInt gindex, FT_Glyph *aglyph, FTC_Node *anode ); /*************************************************************************/ /* */ /* <Function> */ /* FTC_ImageCache_LookupScaler */ /* */ /* <Description> */ /* A variant of @FTC_ImageCache_Lookup that uses an @FTC_ScalerRec */ /* to specify the face ID and its size. */ /* */ /* <Input> */ /* cache :: A handle to the source glyph image cache. */ /* */ /* scaler :: A pointer to a scaler descriptor. */ /* */ /* load_flags :: The corresponding load flags. */ /* */ /* gindex :: The glyph index to retrieve. */ /* */ /* <Output> */ /* aglyph :: The corresponding @FT_Glyph object. 0~in case of */ /* failure. */ /* */ /* anode :: Used to return the address of of the corresponding */ /* cache node after incrementing its reference count */ /* (see note below). */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ /* <Note> */ /* The returned glyph is owned and managed by the glyph image cache. */ /* Never try to transform or discard it manually! You can however */ /* create a copy with @FT_Glyph_Copy and modify the new one. */ /* */ /* If `anode' is _not_ NULL, it receives the address of the cache */ /* node containing the glyph image, after increasing its reference */ /* count. This ensures that the node (as well as the @FT_Glyph) will */ /* always be kept in the cache until you call @FTC_Node_Unref to */ /* `release' it. */ /* */ /* If `anode' is NULL, the cache node is left unchanged, which means */ /* that the @FT_Glyph could be flushed out of the cache on the next */ /* call to one of the caching sub-system APIs. Don't assume that it */ /* is persistent! */ /* */ /* Calls to @FT_Set_Char_Size and friends have no effect on cached */ /* glyphs; you should always use the FreeType cache API instead. */ /* */ FT_EXPORT( FT_Error ) FTC_ImageCache_LookupScaler( FTC_ImageCache cache, FTC_Scaler scaler, FT_ULong load_flags, FT_UInt gindex, FT_Glyph *aglyph, FTC_Node *anode ); /*************************************************************************/ /* */ /* <Type> */ /* FTC_SBit */ /* */ /* <Description> */ /* A handle to a small bitmap descriptor. See the @FTC_SBitRec */ /* structure for details. */ /* */ typedef struct FTC_SBitRec_* FTC_SBit; /*************************************************************************/ /* */ /* <Struct> */ /* FTC_SBitRec */ /* */ /* <Description> */ /* A very compact structure used to describe a small glyph bitmap. */ /* */ /* <Fields> */ /* width :: The bitmap width in pixels. */ /* */ /* height :: The bitmap height in pixels. */ /* */ /* left :: The horizontal distance from the pen position to the */ /* left bitmap border (a.k.a. `left side bearing', or */ /* `lsb'). */ /* */ /* top :: The vertical distance from the pen position (on the */ /* baseline) to the upper bitmap border (a.k.a. `top */ /* side bearing'). The distance is positive for upwards */ /* y~coordinates. */ /* */ /* format :: The format of the glyph bitmap (monochrome or gray). */ /* */ /* max_grays :: Maximum gray level value (in the range 1 to~255). */ /* */ /* pitch :: The number of bytes per bitmap line. May be positive */ /* or negative. */ /* */ /* xadvance :: The horizontal advance width in pixels. */ /* */ /* yadvance :: The vertical advance height in pixels. */ /* */ /* buffer :: A pointer to the bitmap pixels. */ /* */ typedef struct FTC_SBitRec_ { FT_Byte width; FT_Byte height; FT_Char left; FT_Char top; FT_Byte format; FT_Byte max_grays; FT_Short pitch; FT_Char xadvance; FT_Char yadvance; FT_Byte* buffer; } FTC_SBitRec; /*************************************************************************/ /* */ /* <Type> */ /* FTC_SBitCache */ /* */ /* <Description> */ /* A handle to a small bitmap cache. These are special cache objects */ /* used to store small glyph bitmaps (and anti-aliased pixmaps) in a */ /* much more efficient way than the traditional glyph image cache */ /* implemented by @FTC_ImageCache. */ /* */ typedef struct FTC_SBitCacheRec_* FTC_SBitCache; /*************************************************************************/ /* */ /* <Function> */ /* FTC_SBitCache_New */ /* */ /* <Description> */ /* Create a new cache to store small glyph bitmaps. */ /* */ /* <Input> */ /* manager :: A handle to the source cache manager. */ /* */ /* <Output> */ /* acache :: A handle to the new sbit cache. NULL in case of error. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ FT_EXPORT( FT_Error ) FTC_SBitCache_New( FTC_Manager manager, FTC_SBitCache *acache ); /*************************************************************************/ /* */ /* <Function> */ /* FTC_SBitCache_Lookup */ /* */ /* <Description> */ /* Look up a given small glyph bitmap in a given sbit cache and */ /* `lock' it to prevent its flushing from the cache until needed. */ /* */ /* <Input> */ /* cache :: A handle to the source sbit cache. */ /* */ /* type :: A pointer to the glyph image type descriptor. */ /* */ /* gindex :: The glyph index. */ /* */ /* <Output> */ /* sbit :: A handle to a small bitmap descriptor. */ /* */ /* anode :: Used to return the address of of the corresponding cache */ /* node after incrementing its reference count (see note */ /* below). */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ /* <Note> */ /* The small bitmap descriptor and its bit buffer are owned by the */ /* cache and should never be freed by the application. They might */ /* as well disappear from memory on the next cache lookup, so don't */ /* treat them as persistent data. */ /* */ /* The descriptor's `buffer' field is set to~0 to indicate a missing */ /* glyph bitmap. */ /* */ /* If `anode' is _not_ NULL, it receives the address of the cache */ /* node containing the bitmap, after increasing its reference count. */ /* This ensures that the node (as well as the image) will always be */ /* kept in the cache until you call @FTC_Node_Unref to `release' it. */ /* */ /* If `anode' is NULL, the cache node is left unchanged, which means */ /* that the bitmap could be flushed out of the cache on the next */ /* call to one of the caching sub-system APIs. Don't assume that it */ /* is persistent! */ /* */ FT_EXPORT( FT_Error ) FTC_SBitCache_Lookup( FTC_SBitCache cache, FTC_ImageType type, FT_UInt gindex, FTC_SBit *sbit, FTC_Node *anode ); /*************************************************************************/ /* */ /* <Function> */ /* FTC_SBitCache_LookupScaler */ /* */ /* <Description> */ /* A variant of @FTC_SBitCache_Lookup that uses an @FTC_ScalerRec */ /* to specify the face ID and its size. */ /* */ /* <Input> */ /* cache :: A handle to the source sbit cache. */ /* */ /* scaler :: A pointer to the scaler descriptor. */ /* */ /* load_flags :: The corresponding load flags. */ /* */ /* gindex :: The glyph index. */ /* */ /* <Output> */ /* sbit :: A handle to a small bitmap descriptor. */ /* */ /* anode :: Used to return the address of of the corresponding */ /* cache node after incrementing its reference count */ /* (see note below). */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ /* <Note> */ /* The small bitmap descriptor and its bit buffer are owned by the */ /* cache and should never be freed by the application. They might */ /* as well disappear from memory on the next cache lookup, so don't */ /* treat them as persistent data. */ /* */ /* The descriptor's `buffer' field is set to~0 to indicate a missing */ /* glyph bitmap. */ /* */ /* If `anode' is _not_ NULL, it receives the address of the cache */ /* node containing the bitmap, after increasing its reference count. */ /* This ensures that the node (as well as the image) will always be */ /* kept in the cache until you call @FTC_Node_Unref to `release' it. */ /* */ /* If `anode' is NULL, the cache node is left unchanged, which means */ /* that the bitmap could be flushed out of the cache on the next */ /* call to one of the caching sub-system APIs. Don't assume that it */ /* is persistent! */ /* */ FT_EXPORT( FT_Error ) FTC_SBitCache_LookupScaler( FTC_SBitCache cache, FTC_Scaler scaler, FT_ULong load_flags, FT_UInt gindex, FTC_SBit *sbit, FTC_Node *anode ); /* */ #ifdef FT_CONFIG_OPTION_OLD_INTERNALS /*@***********************************************************************/ /* */ /* <Struct> */ /* FTC_FontRec */ /* */ /* <Description> */ /* A simple structure used to describe a given `font' to the cache */ /* manager. Note that a `font' is the combination of a given face */ /* with a given character size. */ /* */ /* <Fields> */ /* face_id :: The ID of the face to use. */ /* */ /* pix_width :: The character width in integer pixels. */ /* */ /* pix_height :: The character height in integer pixels. */ /* */ typedef struct FTC_FontRec_ { FTC_FaceID face_id; FT_UShort pix_width; FT_UShort pix_height; } FTC_FontRec; /* */ #define FTC_FONT_COMPARE( f1, f2 ) \ ( (f1)->face_id == (f2)->face_id && \ (f1)->pix_width == (f2)->pix_width && \ (f1)->pix_height == (f2)->pix_height ) /* this macro is incompatible with LLP64, should not be used */ #define FTC_FONT_HASH( f ) \ (FT_UInt32)( FTC_FACE_ID_HASH((f)->face_id) ^ \ ((f)->pix_width << 8) ^ \ ((f)->pix_height) ) typedef FTC_FontRec* FTC_Font; FT_EXPORT( FT_Error ) FTC_Manager_Lookup_Face( FTC_Manager manager, FTC_FaceID face_id, FT_Face *aface ); FT_EXPORT( FT_Error ) FTC_Manager_Lookup_Size( FTC_Manager manager, FTC_Font font, FT_Face *aface, FT_Size *asize ); #endif /* FT_CONFIG_OPTION_OLD_INTERNALS */ /* */ FT_END_HEADER #endif /* __FTCACHE_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/ftchapters.h ================================================ /***************************************************************************/ /* */ /* This file defines the structure of the FreeType reference. */ /* It is used by the python script which generates the HTML files. */ /* */ /***************************************************************************/ /***************************************************************************/ /* */ /* <Chapter> */ /* general_remarks */ /* */ /* <Title> */ /* General Remarks */ /* */ /* <Sections> */ /* user_allocation */ /* */ /***************************************************************************/ /***************************************************************************/ /* */ /* <Chapter> */ /* core_api */ /* */ /* <Title> */ /* Core API */ /* */ /* <Sections> */ /* version */ /* basic_types */ /* base_interface */ /* glyph_variants */ /* glyph_management */ /* mac_specific */ /* sizes_management */ /* header_file_macros */ /* */ /***************************************************************************/ /***************************************************************************/ /* */ /* <Chapter> */ /* format_specific */ /* */ /* <Title> */ /* Format-Specific API */ /* */ /* <Sections> */ /* multiple_masters */ /* truetype_tables */ /* type1_tables */ /* sfnt_names */ /* bdf_fonts */ /* cid_fonts */ /* pfr_fonts */ /* winfnt_fonts */ /* font_formats */ /* gasp_table */ /* */ /***************************************************************************/ /***************************************************************************/ /* */ /* <Chapter> */ /* cache_subsystem */ /* */ /* <Title> */ /* Cache Sub-System */ /* */ /* <Sections> */ /* cache_subsystem */ /* */ /***************************************************************************/ /***************************************************************************/ /* */ /* <Chapter> */ /* support_api */ /* */ /* <Title> */ /* Support API */ /* */ /* <Sections> */ /* computations */ /* list_processing */ /* outline_processing */ /* quick_advance */ /* bitmap_handling */ /* raster */ /* glyph_stroker */ /* system_interface */ /* module_management */ /* gzip */ /* lzw */ /* bzip2 */ /* lcd_filtering */ /* */ /***************************************************************************/ ================================================ FILE: other/freetype/include/freetype/ftcid.h ================================================ /***************************************************************************/ /* */ /* ftcid.h */ /* */ /* FreeType API for accessing CID font information (specification). */ /* */ /* Copyright 2007, 2009 by Dereg Clegg, Michael Toftdal. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __FTCID_H__ #define __FTCID_H__ #include <ft2build.h> #include FT_FREETYPE_H #ifdef FREETYPE_H #error "freetype.h of FreeType 1 has been loaded!" #error "Please fix the directory search order for header files" #error "so that freetype.h of FreeType 2 is found first." #endif FT_BEGIN_HEADER /*************************************************************************/ /* */ /* <Section> */ /* cid_fonts */ /* */ /* <Title> */ /* CID Fonts */ /* */ /* <Abstract> */ /* CID-keyed font specific API. */ /* */ /* <Description> */ /* This section contains the declaration of CID-keyed font specific */ /* functions. */ /* */ /*************************************************************************/ /********************************************************************** * * @function: * FT_Get_CID_Registry_Ordering_Supplement * * @description: * Retrieve the Registry/Ordering/Supplement triple (also known as the * "R/O/S") from a CID-keyed font. * * @input: * face :: * A handle to the input face. * * @output: * registry :: * The registry, as a C~string, owned by the face. * * ordering :: * The ordering, as a C~string, owned by the face. * * supplement :: * The supplement. * * @return: * FreeType error code. 0~means success. * * @note: * This function only works with CID faces, returning an error * otherwise. * * @since: * 2.3.6 */ FT_EXPORT( FT_Error ) FT_Get_CID_Registry_Ordering_Supplement( FT_Face face, const char* *registry, const char* *ordering, FT_Int *supplement); /********************************************************************** * * @function: * FT_Get_CID_Is_Internally_CID_Keyed * * @description: * Retrieve the type of the input face, CID keyed or not. In * constrast to the @FT_IS_CID_KEYED macro this function returns * successfully also for CID-keyed fonts in an SNFT wrapper. * * @input: * face :: * A handle to the input face. * * @output: * is_cid :: * The type of the face as an @FT_Bool. * * @return: * FreeType error code. 0~means success. * * @note: * This function only works with CID faces and OpenType fonts, * returning an error otherwise. * * @since: * 2.3.9 */ FT_EXPORT( FT_Error ) FT_Get_CID_Is_Internally_CID_Keyed( FT_Face face, FT_Bool *is_cid ); /********************************************************************** * * @function: * FT_Get_CID_From_Glyph_Index * * @description: * Retrieve the CID of the input glyph index. * * @input: * face :: * A handle to the input face. * * glyph_index :: * The input glyph index. * * @output: * cid :: * The CID as an @FT_UInt. * * @return: * FreeType error code. 0~means success. * * @note: * This function only works with CID faces and OpenType fonts, * returning an error otherwise. * * @since: * 2.3.9 */ FT_EXPORT( FT_Error ) FT_Get_CID_From_Glyph_Index( FT_Face face, FT_UInt glyph_index, FT_UInt *cid ); /* */ FT_END_HEADER #endif /* __FTCID_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/fterrdef.h ================================================ /***************************************************************************/ /* */ /* fterrdef.h */ /* */ /* FreeType error codes (specification). */ /* */ /* Copyright 2002, 2004, 2006, 2007, 2010 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /*******************************************************************/ /*******************************************************************/ /***** *****/ /***** LIST OF ERROR CODES/MESSAGES *****/ /***** *****/ /*******************************************************************/ /*******************************************************************/ /* You need to define both FT_ERRORDEF_ and FT_NOERRORDEF_ before */ /* including this file. */ /* generic errors */ FT_NOERRORDEF_( Ok, 0x00, \ "no error" ) FT_ERRORDEF_( Cannot_Open_Resource, 0x01, \ "cannot open resource" ) FT_ERRORDEF_( Unknown_File_Format, 0x02, \ "unknown file format" ) FT_ERRORDEF_( Invalid_File_Format, 0x03, \ "broken file" ) FT_ERRORDEF_( Invalid_Version, 0x04, \ "invalid FreeType version" ) FT_ERRORDEF_( Lower_Module_Version, 0x05, \ "module version is too low" ) FT_ERRORDEF_( Invalid_Argument, 0x06, \ "invalid argument" ) FT_ERRORDEF_( Unimplemented_Feature, 0x07, \ "unimplemented feature" ) FT_ERRORDEF_( Invalid_Table, 0x08, \ "broken table" ) FT_ERRORDEF_( Invalid_Offset, 0x09, \ "broken offset within table" ) FT_ERRORDEF_( Array_Too_Large, 0x0A, \ "array allocation size too large" ) /* glyph/character errors */ FT_ERRORDEF_( Invalid_Glyph_Index, 0x10, \ "invalid glyph index" ) FT_ERRORDEF_( Invalid_Character_Code, 0x11, \ "invalid character code" ) FT_ERRORDEF_( Invalid_Glyph_Format, 0x12, \ "unsupported glyph image format" ) FT_ERRORDEF_( Cannot_Render_Glyph, 0x13, \ "cannot render this glyph format" ) FT_ERRORDEF_( Invalid_Outline, 0x14, \ "invalid outline" ) FT_ERRORDEF_( Invalid_Composite, 0x15, \ "invalid composite glyph" ) FT_ERRORDEF_( Too_Many_Hints, 0x16, \ "too many hints" ) FT_ERRORDEF_( Invalid_Pixel_Size, 0x17, \ "invalid pixel size" ) /* handle errors */ FT_ERRORDEF_( Invalid_Handle, 0x20, \ "invalid object handle" ) FT_ERRORDEF_( Invalid_Library_Handle, 0x21, \ "invalid library handle" ) FT_ERRORDEF_( Invalid_Driver_Handle, 0x22, \ "invalid module handle" ) FT_ERRORDEF_( Invalid_Face_Handle, 0x23, \ "invalid face handle" ) FT_ERRORDEF_( Invalid_Size_Handle, 0x24, \ "invalid size handle" ) FT_ERRORDEF_( Invalid_Slot_Handle, 0x25, \ "invalid glyph slot handle" ) FT_ERRORDEF_( Invalid_CharMap_Handle, 0x26, \ "invalid charmap handle" ) FT_ERRORDEF_( Invalid_Cache_Handle, 0x27, \ "invalid cache manager handle" ) FT_ERRORDEF_( Invalid_Stream_Handle, 0x28, \ "invalid stream handle" ) /* driver errors */ FT_ERRORDEF_( Too_Many_Drivers, 0x30, \ "too many modules" ) FT_ERRORDEF_( Too_Many_Extensions, 0x31, \ "too many extensions" ) /* memory errors */ FT_ERRORDEF_( Out_Of_Memory, 0x40, \ "out of memory" ) FT_ERRORDEF_( Unlisted_Object, 0x41, \ "unlisted object" ) /* stream errors */ FT_ERRORDEF_( Cannot_Open_Stream, 0x51, \ "cannot open stream" ) FT_ERRORDEF_( Invalid_Stream_Seek, 0x52, \ "invalid stream seek" ) FT_ERRORDEF_( Invalid_Stream_Skip, 0x53, \ "invalid stream skip" ) FT_ERRORDEF_( Invalid_Stream_Read, 0x54, \ "invalid stream read" ) FT_ERRORDEF_( Invalid_Stream_Operation, 0x55, \ "invalid stream operation" ) FT_ERRORDEF_( Invalid_Frame_Operation, 0x56, \ "invalid frame operation" ) FT_ERRORDEF_( Nested_Frame_Access, 0x57, \ "nested frame access" ) FT_ERRORDEF_( Invalid_Frame_Read, 0x58, \ "invalid frame read" ) /* raster errors */ FT_ERRORDEF_( Raster_Uninitialized, 0x60, \ "raster uninitialized" ) FT_ERRORDEF_( Raster_Corrupted, 0x61, \ "raster corrupted" ) FT_ERRORDEF_( Raster_Overflow, 0x62, \ "raster overflow" ) FT_ERRORDEF_( Raster_Negative_Height, 0x63, \ "negative height while rastering" ) /* cache errors */ FT_ERRORDEF_( Too_Many_Caches, 0x70, \ "too many registered caches" ) /* TrueType and SFNT errors */ FT_ERRORDEF_( Invalid_Opcode, 0x80, \ "invalid opcode" ) FT_ERRORDEF_( Too_Few_Arguments, 0x81, \ "too few arguments" ) FT_ERRORDEF_( Stack_Overflow, 0x82, \ "stack overflow" ) FT_ERRORDEF_( Code_Overflow, 0x83, \ "code overflow" ) FT_ERRORDEF_( Bad_Argument, 0x84, \ "bad argument" ) FT_ERRORDEF_( Divide_By_Zero, 0x85, \ "division by zero" ) FT_ERRORDEF_( Invalid_Reference, 0x86, \ "invalid reference" ) FT_ERRORDEF_( Debug_OpCode, 0x87, \ "found debug opcode" ) FT_ERRORDEF_( ENDF_In_Exec_Stream, 0x88, \ "found ENDF opcode in execution stream" ) FT_ERRORDEF_( Nested_DEFS, 0x89, \ "nested DEFS" ) FT_ERRORDEF_( Invalid_CodeRange, 0x8A, \ "invalid code range" ) FT_ERRORDEF_( Execution_Too_Long, 0x8B, \ "execution context too long" ) FT_ERRORDEF_( Too_Many_Function_Defs, 0x8C, \ "too many function definitions" ) FT_ERRORDEF_( Too_Many_Instruction_Defs, 0x8D, \ "too many instruction definitions" ) FT_ERRORDEF_( Table_Missing, 0x8E, \ "SFNT font table missing" ) FT_ERRORDEF_( Horiz_Header_Missing, 0x8F, \ "horizontal header (hhea) table missing" ) FT_ERRORDEF_( Locations_Missing, 0x90, \ "locations (loca) table missing" ) FT_ERRORDEF_( Name_Table_Missing, 0x91, \ "name table missing" ) FT_ERRORDEF_( CMap_Table_Missing, 0x92, \ "character map (cmap) table missing" ) FT_ERRORDEF_( Hmtx_Table_Missing, 0x93, \ "horizontal metrics (hmtx) table missing" ) FT_ERRORDEF_( Post_Table_Missing, 0x94, \ "PostScript (post) table missing" ) FT_ERRORDEF_( Invalid_Horiz_Metrics, 0x95, \ "invalid horizontal metrics" ) FT_ERRORDEF_( Invalid_CharMap_Format, 0x96, \ "invalid character map (cmap) format" ) FT_ERRORDEF_( Invalid_PPem, 0x97, \ "invalid ppem value" ) FT_ERRORDEF_( Invalid_Vert_Metrics, 0x98, \ "invalid vertical metrics" ) FT_ERRORDEF_( Could_Not_Find_Context, 0x99, \ "could not find context" ) FT_ERRORDEF_( Invalid_Post_Table_Format, 0x9A, \ "invalid PostScript (post) table format" ) FT_ERRORDEF_( Invalid_Post_Table, 0x9B, \ "invalid PostScript (post) table" ) /* CFF, CID, and Type 1 errors */ FT_ERRORDEF_( Syntax_Error, 0xA0, \ "opcode syntax error" ) FT_ERRORDEF_( Stack_Underflow, 0xA1, \ "argument stack underflow" ) FT_ERRORDEF_( Ignore, 0xA2, \ "ignore" ) FT_ERRORDEF_( No_Unicode_Glyph_Name, 0xA3, \ "no Unicode glyph name found" ) /* BDF errors */ FT_ERRORDEF_( Missing_Startfont_Field, 0xB0, \ "`STARTFONT' field missing" ) FT_ERRORDEF_( Missing_Font_Field, 0xB1, \ "`FONT' field missing" ) FT_ERRORDEF_( Missing_Size_Field, 0xB2, \ "`SIZE' field missing" ) FT_ERRORDEF_( Missing_Fontboundingbox_Field, 0xB3, \ "`FONTBOUNDINGBOX' field missing" ) FT_ERRORDEF_( Missing_Chars_Field, 0xB4, \ "`CHARS' field missing" ) FT_ERRORDEF_( Missing_Startchar_Field, 0xB5, \ "`STARTCHAR' field missing" ) FT_ERRORDEF_( Missing_Encoding_Field, 0xB6, \ "`ENCODING' field missing" ) FT_ERRORDEF_( Missing_Bbx_Field, 0xB7, \ "`BBX' field missing" ) FT_ERRORDEF_( Bbx_Too_Big, 0xB8, \ "`BBX' too big" ) FT_ERRORDEF_( Corrupted_Font_Header, 0xB9, \ "Font header corrupted or missing fields" ) FT_ERRORDEF_( Corrupted_Font_Glyphs, 0xBA, \ "Font glyphs corrupted or missing fields" ) /* END */ ================================================ FILE: other/freetype/include/freetype/fterrors.h ================================================ /***************************************************************************/ /* */ /* fterrors.h */ /* */ /* FreeType error code handling (specification). */ /* */ /* Copyright 1996-2001, 2002, 2004, 2007 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /*************************************************************************/ /* */ /* This special header file is used to define the handling of FT2 */ /* enumeration constants. It can also be used to generate error message */ /* strings with a small macro trick explained below. */ /* */ /* I - Error Formats */ /* ----------------- */ /* */ /* The configuration macro FT_CONFIG_OPTION_USE_MODULE_ERRORS can be */ /* defined in ftoption.h in order to make the higher byte indicate */ /* the module where the error has happened (this is not compatible */ /* with standard builds of FreeType 2). You can then use the macro */ /* FT_ERROR_BASE macro to extract the generic error code from an */ /* FT_Error value. */ /* */ /* */ /* II - Error Message strings */ /* -------------------------- */ /* */ /* The error definitions below are made through special macros that */ /* allow client applications to build a table of error message strings */ /* if they need it. The strings are not included in a normal build of */ /* FreeType 2 to save space (most client applications do not use */ /* them). */ /* */ /* To do so, you have to define the following macros before including */ /* this file: */ /* */ /* FT_ERROR_START_LIST :: */ /* This macro is called before anything else to define the start of */ /* the error list. It is followed by several FT_ERROR_DEF calls */ /* (see below). */ /* */ /* FT_ERROR_DEF( e, v, s ) :: */ /* This macro is called to define one single error. */ /* `e' is the error code identifier (e.g. FT_Err_Invalid_Argument). */ /* `v' is the error numerical value. */ /* `s' is the corresponding error string. */ /* */ /* FT_ERROR_END_LIST :: */ /* This macro ends the list. */ /* */ /* Additionally, you have to undefine __FTERRORS_H__ before #including */ /* this file. */ /* */ /* Here is a simple example: */ /* */ /* { */ /* #undef __FTERRORS_H__ */ /* #define FT_ERRORDEF( e, v, s ) { e, s }, */ /* #define FT_ERROR_START_LIST { */ /* #define FT_ERROR_END_LIST { 0, 0 } }; */ /* */ /* const struct */ /* { */ /* int err_code; */ /* const char* err_msg; */ /* } ft_errors[] = */ /* */ /* #include FT_ERRORS_H */ /* } */ /* */ /*************************************************************************/ #ifndef __FTERRORS_H__ #define __FTERRORS_H__ /* include module base error codes */ #include FT_MODULE_ERRORS_H /*******************************************************************/ /*******************************************************************/ /***** *****/ /***** SETUP MACROS *****/ /***** *****/ /*******************************************************************/ /*******************************************************************/ #undef FT_NEED_EXTERN_C #undef FT_ERR_XCAT #undef FT_ERR_CAT #define FT_ERR_XCAT( x, y ) x ## y #define FT_ERR_CAT( x, y ) FT_ERR_XCAT( x, y ) /* FT_ERR_PREFIX is used as a prefix for error identifiers. */ /* By default, we use `FT_Err_'. */ /* */ #ifndef FT_ERR_PREFIX #define FT_ERR_PREFIX FT_Err_ #endif /* FT_ERR_BASE is used as the base for module-specific errors. */ /* */ #ifdef FT_CONFIG_OPTION_USE_MODULE_ERRORS #ifndef FT_ERR_BASE #define FT_ERR_BASE FT_Mod_Err_Base #endif #else #undef FT_ERR_BASE #define FT_ERR_BASE 0 #endif /* FT_CONFIG_OPTION_USE_MODULE_ERRORS */ /* If FT_ERRORDEF is not defined, we need to define a simple */ /* enumeration type. */ /* */ #ifndef FT_ERRORDEF #define FT_ERRORDEF( e, v, s ) e = v, #define FT_ERROR_START_LIST enum { #define FT_ERROR_END_LIST FT_ERR_CAT( FT_ERR_PREFIX, Max ) }; #ifdef __cplusplus #define FT_NEED_EXTERN_C extern "C" { #endif #endif /* !FT_ERRORDEF */ /* this macro is used to define an error */ #define FT_ERRORDEF_( e, v, s ) \ FT_ERRORDEF( FT_ERR_CAT( FT_ERR_PREFIX, e ), v + FT_ERR_BASE, s ) /* this is only used for <module>_Err_Ok, which must be 0! */ #define FT_NOERRORDEF_( e, v, s ) \ FT_ERRORDEF( FT_ERR_CAT( FT_ERR_PREFIX, e ), v, s ) #ifdef FT_ERROR_START_LIST FT_ERROR_START_LIST #endif /* now include the error codes */ #include FT_ERROR_DEFINITIONS_H #ifdef FT_ERROR_END_LIST FT_ERROR_END_LIST #endif /*******************************************************************/ /*******************************************************************/ /***** *****/ /***** SIMPLE CLEANUP *****/ /***** *****/ /*******************************************************************/ /*******************************************************************/ #ifdef FT_NEED_EXTERN_C } #endif #undef FT_ERROR_START_LIST #undef FT_ERROR_END_LIST #undef FT_ERRORDEF #undef FT_ERRORDEF_ #undef FT_NOERRORDEF_ #undef FT_NEED_EXTERN_C #undef FT_ERR_CONCAT #undef FT_ERR_BASE /* FT_KEEP_ERR_PREFIX is needed for ftvalid.h */ #ifndef FT_KEEP_ERR_PREFIX #undef FT_ERR_PREFIX #endif #endif /* __FTERRORS_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/ftgasp.h ================================================ /***************************************************************************/ /* */ /* ftgasp.h */ /* */ /* Access of TrueType's `gasp' table (specification). */ /* */ /* Copyright 2007, 2008, 2011 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef _FT_GASP_H_ #define _FT_GASP_H_ #include <ft2build.h> #include FT_FREETYPE_H #ifdef FREETYPE_H #error "freetype.h of FreeType 1 has been loaded!" #error "Please fix the directory search order for header files" #error "so that freetype.h of FreeType 2 is found first." #endif /*************************************************************************** * * @section: * gasp_table * * @title: * Gasp Table * * @abstract: * Retrieving TrueType `gasp' table entries. * * @description: * The function @FT_Get_Gasp can be used to query a TrueType or OpenType * font for specific entries in its `gasp' table, if any. This is * mainly useful when implementing native TrueType hinting with the * bytecode interpreter to duplicate the Windows text rendering results. */ /************************************************************************* * * @enum: * FT_GASP_XXX * * @description: * A list of values and/or bit-flags returned by the @FT_Get_Gasp * function. * * @values: * FT_GASP_NO_TABLE :: * This special value means that there is no GASP table in this face. * It is up to the client to decide what to do. * * FT_GASP_DO_GRIDFIT :: * Grid-fitting and hinting should be performed at the specified ppem. * This *really* means TrueType bytecode interpretation. If this bit * is not set, no hinting gets applied. * * FT_GASP_DO_GRAY :: * Anti-aliased rendering should be performed at the specified ppem. * If not set, do monochrome rendering. * * FT_GASP_SYMMETRIC_SMOOTHING :: * If set, smoothing along multiple axes must be used with ClearType. * * FT_GASP_SYMMETRIC_GRIDFIT :: * Grid-fitting must be used with ClearType's symmetric smoothing. * * @note: * The bit-flags `FT_GASP_DO_GRIDFIT' and `FT_GASP_DO_GRAY' are to be * used for standard font rasterization only. Independently of that, * `FT_GASP_SYMMETRIC_SMOOTHING' and `FT_GASP_SYMMETRIC_GRIDFIT' are to * be used if ClearType is enabled (and `FT_GASP_DO_GRIDFIT' and * `FT_GASP_DO_GRAY' are consequently ignored). * * `ClearType' is Microsoft's implementation of LCD rendering, partly * protected by patents. * * @since: * 2.3.0 */ #define FT_GASP_NO_TABLE -1 #define FT_GASP_DO_GRIDFIT 0x01 #define FT_GASP_DO_GRAY 0x02 #define FT_GASP_SYMMETRIC_SMOOTHING 0x08 #define FT_GASP_SYMMETRIC_GRIDFIT 0x10 /************************************************************************* * * @func: * FT_Get_Gasp * * @description: * Read the `gasp' table from a TrueType or OpenType font file and * return the entry corresponding to a given character pixel size. * * @input: * face :: The source face handle. * ppem :: The vertical character pixel size. * * @return: * Bit flags (see @FT_GASP_XXX), or @FT_GASP_NO_TABLE if there is no * `gasp' table in the face. * * @since: * 2.3.0 */ FT_EXPORT( FT_Int ) FT_Get_Gasp( FT_Face face, FT_UInt ppem ); /* */ #endif /* _FT_GASP_H_ */ /* END */ ================================================ FILE: other/freetype/include/freetype/ftglyph.h ================================================ /***************************************************************************/ /* */ /* ftglyph.h */ /* */ /* FreeType convenience functions to handle glyphs (specification). */ /* */ /* Copyright 1996-2003, 2006, 2008, 2009, 2011 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /*************************************************************************/ /* */ /* This file contains the definition of several convenience functions */ /* that can be used by client applications to easily retrieve glyph */ /* bitmaps and outlines from a given face. */ /* */ /* These functions should be optional if you are writing a font server */ /* or text layout engine on top of FreeType. However, they are pretty */ /* handy for many other simple uses of the library. */ /* */ /*************************************************************************/ #ifndef __FTGLYPH_H__ #define __FTGLYPH_H__ #include <ft2build.h> #include FT_FREETYPE_H #ifdef FREETYPE_H #error "freetype.h of FreeType 1 has been loaded!" #error "Please fix the directory search order for header files" #error "so that freetype.h of FreeType 2 is found first." #endif FT_BEGIN_HEADER /*************************************************************************/ /* */ /* <Section> */ /* glyph_management */ /* */ /* <Title> */ /* Glyph Management */ /* */ /* <Abstract> */ /* Generic interface to manage individual glyph data. */ /* */ /* <Description> */ /* This section contains definitions used to manage glyph data */ /* through generic FT_Glyph objects. Each of them can contain a */ /* bitmap, a vector outline, or even images in other formats. */ /* */ /*************************************************************************/ /* forward declaration to a private type */ typedef struct FT_Glyph_Class_ FT_Glyph_Class; /*************************************************************************/ /* */ /* <Type> */ /* FT_Glyph */ /* */ /* <Description> */ /* Handle to an object used to model generic glyph images. It is a */ /* pointer to the @FT_GlyphRec structure and can contain a glyph */ /* bitmap or pointer. */ /* */ /* <Note> */ /* Glyph objects are not owned by the library. You must thus release */ /* them manually (through @FT_Done_Glyph) _before_ calling */ /* @FT_Done_FreeType. */ /* */ typedef struct FT_GlyphRec_* FT_Glyph; /*************************************************************************/ /* */ /* <Struct> */ /* FT_GlyphRec */ /* */ /* <Description> */ /* The root glyph structure contains a given glyph image plus its */ /* advance width in 16.16 fixed float format. */ /* */ /* <Fields> */ /* library :: A handle to the FreeType library object. */ /* */ /* clazz :: A pointer to the glyph's class. Private. */ /* */ /* format :: The format of the glyph's image. */ /* */ /* advance :: A 16.16 vector that gives the glyph's advance width. */ /* */ typedef struct FT_GlyphRec_ { FT_Library library; const FT_Glyph_Class* clazz; FT_Glyph_Format format; FT_Vector advance; } FT_GlyphRec; /*************************************************************************/ /* */ /* <Type> */ /* FT_BitmapGlyph */ /* */ /* <Description> */ /* A handle to an object used to model a bitmap glyph image. This is */ /* a sub-class of @FT_Glyph, and a pointer to @FT_BitmapGlyphRec. */ /* */ typedef struct FT_BitmapGlyphRec_* FT_BitmapGlyph; /*************************************************************************/ /* */ /* <Struct> */ /* FT_BitmapGlyphRec */ /* */ /* <Description> */ /* A structure used for bitmap glyph images. This really is a */ /* `sub-class' of @FT_GlyphRec. */ /* */ /* <Fields> */ /* root :: The root @FT_Glyph fields. */ /* */ /* left :: The left-side bearing, i.e., the horizontal distance */ /* from the current pen position to the left border of the */ /* glyph bitmap. */ /* */ /* top :: The top-side bearing, i.e., the vertical distance from */ /* the current pen position to the top border of the glyph */ /* bitmap. This distance is positive for upwards~y! */ /* */ /* bitmap :: A descriptor for the bitmap. */ /* */ /* <Note> */ /* You can typecast an @FT_Glyph to @FT_BitmapGlyph if you have */ /* `glyph->format == FT_GLYPH_FORMAT_BITMAP'. This lets you access */ /* the bitmap's contents easily. */ /* */ /* The corresponding pixel buffer is always owned by @FT_BitmapGlyph */ /* and is thus created and destroyed with it. */ /* */ typedef struct FT_BitmapGlyphRec_ { FT_GlyphRec root; FT_Int left; FT_Int top; FT_Bitmap bitmap; } FT_BitmapGlyphRec; /*************************************************************************/ /* */ /* <Type> */ /* FT_OutlineGlyph */ /* */ /* <Description> */ /* A handle to an object used to model an outline glyph image. This */ /* is a sub-class of @FT_Glyph, and a pointer to @FT_OutlineGlyphRec. */ /* */ typedef struct FT_OutlineGlyphRec_* FT_OutlineGlyph; /*************************************************************************/ /* */ /* <Struct> */ /* FT_OutlineGlyphRec */ /* */ /* <Description> */ /* A structure used for outline (vectorial) glyph images. This */ /* really is a `sub-class' of @FT_GlyphRec. */ /* */ /* <Fields> */ /* root :: The root @FT_Glyph fields. */ /* */ /* outline :: A descriptor for the outline. */ /* */ /* <Note> */ /* You can typecast an @FT_Glyph to @FT_OutlineGlyph if you have */ /* `glyph->format == FT_GLYPH_FORMAT_OUTLINE'. This lets you access */ /* the outline's content easily. */ /* */ /* As the outline is extracted from a glyph slot, its coordinates are */ /* expressed normally in 26.6 pixels, unless the flag */ /* @FT_LOAD_NO_SCALE was used in @FT_Load_Glyph() or @FT_Load_Char(). */ /* */ /* The outline's tables are always owned by the object and are */ /* destroyed with it. */ /* */ typedef struct FT_OutlineGlyphRec_ { FT_GlyphRec root; FT_Outline outline; } FT_OutlineGlyphRec; /*************************************************************************/ /* */ /* <Function> */ /* FT_Get_Glyph */ /* */ /* <Description> */ /* A function used to extract a glyph image from a slot. Note that */ /* the created @FT_Glyph object must be released with @FT_Done_Glyph. */ /* */ /* <Input> */ /* slot :: A handle to the source glyph slot. */ /* */ /* <Output> */ /* aglyph :: A handle to the glyph object. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ FT_EXPORT( FT_Error ) FT_Get_Glyph( FT_GlyphSlot slot, FT_Glyph *aglyph ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Glyph_Copy */ /* */ /* <Description> */ /* A function used to copy a glyph image. Note that the created */ /* @FT_Glyph object must be released with @FT_Done_Glyph. */ /* */ /* <Input> */ /* source :: A handle to the source glyph object. */ /* */ /* <Output> */ /* target :: A handle to the target glyph object. 0~in case of */ /* error. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ FT_EXPORT( FT_Error ) FT_Glyph_Copy( FT_Glyph source, FT_Glyph *target ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Glyph_Transform */ /* */ /* <Description> */ /* Transform a glyph image if its format is scalable. */ /* */ /* <InOut> */ /* glyph :: A handle to the target glyph object. */ /* */ /* <Input> */ /* matrix :: A pointer to a 2x2 matrix to apply. */ /* */ /* delta :: A pointer to a 2d vector to apply. Coordinates are */ /* expressed in 1/64th of a pixel. */ /* */ /* <Return> */ /* FreeType error code (if not 0, the glyph format is not scalable). */ /* */ /* <Note> */ /* The 2x2 transformation matrix is also applied to the glyph's */ /* advance vector. */ /* */ FT_EXPORT( FT_Error ) FT_Glyph_Transform( FT_Glyph glyph, FT_Matrix* matrix, FT_Vector* delta ); /*************************************************************************/ /* */ /* <Enum> */ /* FT_Glyph_BBox_Mode */ /* */ /* <Description> */ /* The mode how the values of @FT_Glyph_Get_CBox are returned. */ /* */ /* <Values> */ /* FT_GLYPH_BBOX_UNSCALED :: */ /* Return unscaled font units. */ /* */ /* FT_GLYPH_BBOX_SUBPIXELS :: */ /* Return unfitted 26.6 coordinates. */ /* */ /* FT_GLYPH_BBOX_GRIDFIT :: */ /* Return grid-fitted 26.6 coordinates. */ /* */ /* FT_GLYPH_BBOX_TRUNCATE :: */ /* Return coordinates in integer pixels. */ /* */ /* FT_GLYPH_BBOX_PIXELS :: */ /* Return grid-fitted pixel coordinates. */ /* */ typedef enum FT_Glyph_BBox_Mode_ { FT_GLYPH_BBOX_UNSCALED = 0, FT_GLYPH_BBOX_SUBPIXELS = 0, FT_GLYPH_BBOX_GRIDFIT = 1, FT_GLYPH_BBOX_TRUNCATE = 2, FT_GLYPH_BBOX_PIXELS = 3 } FT_Glyph_BBox_Mode; /*************************************************************************/ /* */ /* <Enum> */ /* ft_glyph_bbox_xxx */ /* */ /* <Description> */ /* These constants are deprecated. Use the corresponding */ /* @FT_Glyph_BBox_Mode values instead. */ /* */ /* <Values> */ /* ft_glyph_bbox_unscaled :: See @FT_GLYPH_BBOX_UNSCALED. */ /* ft_glyph_bbox_subpixels :: See @FT_GLYPH_BBOX_SUBPIXELS. */ /* ft_glyph_bbox_gridfit :: See @FT_GLYPH_BBOX_GRIDFIT. */ /* ft_glyph_bbox_truncate :: See @FT_GLYPH_BBOX_TRUNCATE. */ /* ft_glyph_bbox_pixels :: See @FT_GLYPH_BBOX_PIXELS. */ /* */ #define ft_glyph_bbox_unscaled FT_GLYPH_BBOX_UNSCALED #define ft_glyph_bbox_subpixels FT_GLYPH_BBOX_SUBPIXELS #define ft_glyph_bbox_gridfit FT_GLYPH_BBOX_GRIDFIT #define ft_glyph_bbox_truncate FT_GLYPH_BBOX_TRUNCATE #define ft_glyph_bbox_pixels FT_GLYPH_BBOX_PIXELS /*************************************************************************/ /* */ /* <Function> */ /* FT_Glyph_Get_CBox */ /* */ /* <Description> */ /* Return a glyph's `control box'. The control box encloses all the */ /* outline's points, including Bézier control points. Though it */ /* coincides with the exact bounding box for most glyphs, it can be */ /* slightly larger in some situations (like when rotating an outline */ /* which contains Bézier outside arcs). */ /* */ /* Computing the control box is very fast, while getting the bounding */ /* box can take much more time as it needs to walk over all segments */ /* and arcs in the outline. To get the latter, you can use the */ /* `ftbbox' component which is dedicated to this single task. */ /* */ /* <Input> */ /* glyph :: A handle to the source glyph object. */ /* */ /* mode :: The mode which indicates how to interpret the returned */ /* bounding box values. */ /* */ /* <Output> */ /* acbox :: The glyph coordinate bounding box. Coordinates are */ /* expressed in 1/64th of pixels if it is grid-fitted. */ /* */ /* <Note> */ /* Coordinates are relative to the glyph origin, using the y~upwards */ /* convention. */ /* */ /* If the glyph has been loaded with @FT_LOAD_NO_SCALE, `bbox_mode' */ /* must be set to @FT_GLYPH_BBOX_UNSCALED to get unscaled font */ /* units in 26.6 pixel format. The value @FT_GLYPH_BBOX_SUBPIXELS */ /* is another name for this constant. */ /* */ /* If the font is tricky and the glyph has been loaded with */ /* @FT_LOAD_NO_SCALE, the resulting CBox is meaningless. To get */ /* reasonable values for the CBox it is necessary to load the glyph */ /* at a large ppem value (so that the hinting instructions can */ /* properly shift and scale the subglyphs), then extracting the CBox */ /* which can be eventually converted back to font units. */ /* */ /* Note that the maximum coordinates are exclusive, which means that */ /* one can compute the width and height of the glyph image (be it in */ /* integer or 26.6 pixels) as: */ /* */ /* { */ /* width = bbox.xMax - bbox.xMin; */ /* height = bbox.yMax - bbox.yMin; */ /* } */ /* */ /* Note also that for 26.6 coordinates, if `bbox_mode' is set to */ /* @FT_GLYPH_BBOX_GRIDFIT, the coordinates will also be grid-fitted, */ /* which corresponds to: */ /* */ /* { */ /* bbox.xMin = FLOOR(bbox.xMin); */ /* bbox.yMin = FLOOR(bbox.yMin); */ /* bbox.xMax = CEILING(bbox.xMax); */ /* bbox.yMax = CEILING(bbox.yMax); */ /* } */ /* */ /* To get the bbox in pixel coordinates, set `bbox_mode' to */ /* @FT_GLYPH_BBOX_TRUNCATE. */ /* */ /* To get the bbox in grid-fitted pixel coordinates, set `bbox_mode' */ /* to @FT_GLYPH_BBOX_PIXELS. */ /* */ FT_EXPORT( void ) FT_Glyph_Get_CBox( FT_Glyph glyph, FT_UInt bbox_mode, FT_BBox *acbox ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Glyph_To_Bitmap */ /* */ /* <Description> */ /* Convert a given glyph object to a bitmap glyph object. */ /* */ /* <InOut> */ /* the_glyph :: A pointer to a handle to the target glyph. */ /* */ /* <Input> */ /* render_mode :: An enumeration that describes how the data is */ /* rendered. */ /* */ /* origin :: A pointer to a vector used to translate the glyph */ /* image before rendering. Can be~0 (if no */ /* translation). The origin is expressed in */ /* 26.6 pixels. */ /* */ /* destroy :: A boolean that indicates that the original glyph */ /* image should be destroyed by this function. It is */ /* never destroyed in case of error. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ /* <Note> */ /* This function does nothing if the glyph format isn't scalable. */ /* */ /* The glyph image is translated with the `origin' vector before */ /* rendering. */ /* */ /* The first parameter is a pointer to an @FT_Glyph handle, that will */ /* be _replaced_ by this function (with newly allocated data). */ /* Typically, you would use (omitting error handling): */ /* */ /* */ /* { */ /* FT_Glyph glyph; */ /* FT_BitmapGlyph glyph_bitmap; */ /* */ /* */ /* // load glyph */ /* error = FT_Load_Char( face, glyph_index, FT_LOAD_DEFAUT ); */ /* */ /* // extract glyph image */ /* error = FT_Get_Glyph( face->glyph, &glyph ); */ /* */ /* // convert to a bitmap (default render mode + destroying old) */ /* if ( glyph->format != FT_GLYPH_FORMAT_BITMAP ) */ /* { */ /* error = FT_Glyph_To_Bitmap( &glyph, FT_RENDER_MODE_NORMAL, */ /* 0, 1 ); */ /* if ( error ) // `glyph' unchanged */ /* ... */ /* } */ /* */ /* // access bitmap content by typecasting */ /* glyph_bitmap = (FT_BitmapGlyph)glyph; */ /* */ /* // do funny stuff with it, like blitting/drawing */ /* ... */ /* */ /* // discard glyph image (bitmap or not) */ /* FT_Done_Glyph( glyph ); */ /* } */ /* */ /* */ /* Here another example, again without error handling: */ /* */ /* */ /* { */ /* FT_Glyph glyphs[MAX_GLYPHS] */ /* */ /* */ /* ... */ /* */ /* for ( idx = 0; i < MAX_GLYPHS; i++ ) */ /* error = FT_Load_Glyph( face, idx, FT_LOAD_DEFAULT ) || */ /* FT_Get_Glyph ( face->glyph, &glyph[idx] ); */ /* */ /* ... */ /* */ /* for ( idx = 0; i < MAX_GLYPHS; i++ ) */ /* { */ /* FT_Glyph bitmap = glyphs[idx]; */ /* */ /* */ /* ... */ /* */ /* // after this call, `bitmap' no longer points into */ /* // the `glyphs' array (and the old value isn't destroyed) */ /* FT_Glyph_To_Bitmap( &bitmap, FT_RENDER_MODE_MONO, 0, 0 ); */ /* */ /* ... */ /* */ /* FT_Done_Glyph( bitmap ); */ /* } */ /* */ /* ... */ /* */ /* for ( idx = 0; i < MAX_GLYPHS; i++ ) */ /* FT_Done_Glyph( glyphs[idx] ); */ /* } */ /* */ FT_EXPORT( FT_Error ) FT_Glyph_To_Bitmap( FT_Glyph* the_glyph, FT_Render_Mode render_mode, FT_Vector* origin, FT_Bool destroy ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Done_Glyph */ /* */ /* <Description> */ /* Destroy a given glyph. */ /* */ /* <Input> */ /* glyph :: A handle to the target glyph object. */ /* */ FT_EXPORT( void ) FT_Done_Glyph( FT_Glyph glyph ); /* */ /* other helpful functions */ /*************************************************************************/ /* */ /* <Section> */ /* computations */ /* */ /*************************************************************************/ /*************************************************************************/ /* */ /* <Function> */ /* FT_Matrix_Multiply */ /* */ /* <Description> */ /* Perform the matrix operation `b = a*b'. */ /* */ /* <Input> */ /* a :: A pointer to matrix `a'. */ /* */ /* <InOut> */ /* b :: A pointer to matrix `b'. */ /* */ /* <Note> */ /* The result is undefined if either `a' or `b' is zero. */ /* */ FT_EXPORT( void ) FT_Matrix_Multiply( const FT_Matrix* a, FT_Matrix* b ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Matrix_Invert */ /* */ /* <Description> */ /* Invert a 2x2 matrix. Return an error if it can't be inverted. */ /* */ /* <InOut> */ /* matrix :: A pointer to the target matrix. Remains untouched in */ /* case of error. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ FT_EXPORT( FT_Error ) FT_Matrix_Invert( FT_Matrix* matrix ); /* */ FT_END_HEADER #endif /* __FTGLYPH_H__ */ /* END */ /* Local Variables: */ /* coding: utf-8 */ /* End: */ ================================================ FILE: other/freetype/include/freetype/ftgxval.h ================================================ /***************************************************************************/ /* */ /* ftgxval.h */ /* */ /* FreeType API for validating TrueTypeGX/AAT tables (specification). */ /* */ /* Copyright 2004, 2005, 2006 by */ /* Masatake YAMATO, Redhat K.K, */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /***************************************************************************/ /* */ /* gxvalid is derived from both gxlayout module and otvalid module. */ /* Development of gxlayout is supported by the Information-technology */ /* Promotion Agency(IPA), Japan. */ /* */ /***************************************************************************/ #ifndef __FTGXVAL_H__ #define __FTGXVAL_H__ #include <ft2build.h> #include FT_FREETYPE_H #ifdef FREETYPE_H #error "freetype.h of FreeType 1 has been loaded!" #error "Please fix the directory search order for header files" #error "so that freetype.h of FreeType 2 is found first." #endif FT_BEGIN_HEADER /*************************************************************************/ /* */ /* <Section> */ /* gx_validation */ /* */ /* <Title> */ /* TrueTypeGX/AAT Validation */ /* */ /* <Abstract> */ /* An API to validate TrueTypeGX/AAT tables. */ /* */ /* <Description> */ /* This section contains the declaration of functions to validate */ /* some TrueTypeGX tables (feat, mort, morx, bsln, just, kern, opbd, */ /* trak, prop, lcar). */ /* */ /*************************************************************************/ /*************************************************************************/ /* */ /* */ /* Warning: Use FT_VALIDATE_XXX to validate a table. */ /* Following definitions are for gxvalid developers. */ /* */ /* */ /*************************************************************************/ #define FT_VALIDATE_feat_INDEX 0 #define FT_VALIDATE_mort_INDEX 1 #define FT_VALIDATE_morx_INDEX 2 #define FT_VALIDATE_bsln_INDEX 3 #define FT_VALIDATE_just_INDEX 4 #define FT_VALIDATE_kern_INDEX 5 #define FT_VALIDATE_opbd_INDEX 6 #define FT_VALIDATE_trak_INDEX 7 #define FT_VALIDATE_prop_INDEX 8 #define FT_VALIDATE_lcar_INDEX 9 #define FT_VALIDATE_GX_LAST_INDEX FT_VALIDATE_lcar_INDEX /************************************************************************* * * @macro: * FT_VALIDATE_GX_LENGTH * * @description: * The number of tables checked in this module. Use it as a parameter * for the `table-length' argument of function @FT_TrueTypeGX_Validate. */ #define FT_VALIDATE_GX_LENGTH (FT_VALIDATE_GX_LAST_INDEX + 1) /* */ /* Up to 0x1000 is used by otvalid. Ox2xxx is reserved for feature OT extension. */ #define FT_VALIDATE_GX_START 0x4000 #define FT_VALIDATE_GX_BITFIELD( tag ) \ ( FT_VALIDATE_GX_START << FT_VALIDATE_##tag##_INDEX ) /********************************************************************** * * @enum: * FT_VALIDATE_GXXXX * * @description: * A list of bit-field constants used with @FT_TrueTypeGX_Validate to * indicate which TrueTypeGX/AAT Type tables should be validated. * * @values: * FT_VALIDATE_feat :: * Validate `feat' table. * * FT_VALIDATE_mort :: * Validate `mort' table. * * FT_VALIDATE_morx :: * Validate `morx' table. * * FT_VALIDATE_bsln :: * Validate `bsln' table. * * FT_VALIDATE_just :: * Validate `just' table. * * FT_VALIDATE_kern :: * Validate `kern' table. * * FT_VALIDATE_opbd :: * Validate `opbd' table. * * FT_VALIDATE_trak :: * Validate `trak' table. * * FT_VALIDATE_prop :: * Validate `prop' table. * * FT_VALIDATE_lcar :: * Validate `lcar' table. * * FT_VALIDATE_GX :: * Validate all TrueTypeGX tables (feat, mort, morx, bsln, just, kern, * opbd, trak, prop and lcar). * */ #define FT_VALIDATE_feat FT_VALIDATE_GX_BITFIELD( feat ) #define FT_VALIDATE_mort FT_VALIDATE_GX_BITFIELD( mort ) #define FT_VALIDATE_morx FT_VALIDATE_GX_BITFIELD( morx ) #define FT_VALIDATE_bsln FT_VALIDATE_GX_BITFIELD( bsln ) #define FT_VALIDATE_just FT_VALIDATE_GX_BITFIELD( just ) #define FT_VALIDATE_kern FT_VALIDATE_GX_BITFIELD( kern ) #define FT_VALIDATE_opbd FT_VALIDATE_GX_BITFIELD( opbd ) #define FT_VALIDATE_trak FT_VALIDATE_GX_BITFIELD( trak ) #define FT_VALIDATE_prop FT_VALIDATE_GX_BITFIELD( prop ) #define FT_VALIDATE_lcar FT_VALIDATE_GX_BITFIELD( lcar ) #define FT_VALIDATE_GX ( FT_VALIDATE_feat | \ FT_VALIDATE_mort | \ FT_VALIDATE_morx | \ FT_VALIDATE_bsln | \ FT_VALIDATE_just | \ FT_VALIDATE_kern | \ FT_VALIDATE_opbd | \ FT_VALIDATE_trak | \ FT_VALIDATE_prop | \ FT_VALIDATE_lcar ) /* */ /********************************************************************** * * @function: * FT_TrueTypeGX_Validate * * @description: * Validate various TrueTypeGX tables to assure that all offsets and * indices are valid. The idea is that a higher-level library which * actually does the text layout can access those tables without * error checking (which can be quite time consuming). * * @input: * face :: * A handle to the input face. * * validation_flags :: * A bit field which specifies the tables to be validated. See * @FT_VALIDATE_GXXXX for possible values. * * table_length :: * The size of the `tables' array. Normally, @FT_VALIDATE_GX_LENGTH * should be passed. * * @output: * tables :: * The array where all validated sfnt tables are stored. * The array itself must be allocated by a client. * * @return: * FreeType error code. 0~means success. * * @note: * This function only works with TrueTypeGX fonts, returning an error * otherwise. * * After use, the application should deallocate the buffers pointed to by * each `tables' element, by calling @FT_TrueTypeGX_Free. A NULL value * indicates that the table either doesn't exist in the font, the * application hasn't asked for validation, or the validator doesn't have * the ability to validate the sfnt table. */ FT_EXPORT( FT_Error ) FT_TrueTypeGX_Validate( FT_Face face, FT_UInt validation_flags, FT_Bytes tables[FT_VALIDATE_GX_LENGTH], FT_UInt table_length ); /* */ /********************************************************************** * * @function: * FT_TrueTypeGX_Free * * @description: * Free the buffer allocated by TrueTypeGX validator. * * @input: * face :: * A handle to the input face. * * table :: * The pointer to the buffer allocated by * @FT_TrueTypeGX_Validate. * * @note: * This function must be used to free the buffer allocated by * @FT_TrueTypeGX_Validate only. */ FT_EXPORT( void ) FT_TrueTypeGX_Free( FT_Face face, FT_Bytes table ); /* */ /********************************************************************** * * @enum: * FT_VALIDATE_CKERNXXX * * @description: * A list of bit-field constants used with @FT_ClassicKern_Validate * to indicate the classic kern dialect or dialects. If the selected * type doesn't fit, @FT_ClassicKern_Validate regards the table as * invalid. * * @values: * FT_VALIDATE_MS :: * Handle the `kern' table as a classic Microsoft kern table. * * FT_VALIDATE_APPLE :: * Handle the `kern' table as a classic Apple kern table. * * FT_VALIDATE_CKERN :: * Handle the `kern' as either classic Apple or Microsoft kern table. */ #define FT_VALIDATE_MS ( FT_VALIDATE_GX_START << 0 ) #define FT_VALIDATE_APPLE ( FT_VALIDATE_GX_START << 1 ) #define FT_VALIDATE_CKERN ( FT_VALIDATE_MS | FT_VALIDATE_APPLE ) /* */ /********************************************************************** * * @function: * FT_ClassicKern_Validate * * @description: * Validate classic (16-bit format) kern table to assure that the offsets * and indices are valid. The idea is that a higher-level library which * actually does the text layout can access those tables without error * checking (which can be quite time consuming). * * The `kern' table validator in @FT_TrueTypeGX_Validate deals with both * the new 32-bit format and the classic 16-bit format, while * FT_ClassicKern_Validate only supports the classic 16-bit format. * * @input: * face :: * A handle to the input face. * * validation_flags :: * A bit field which specifies the dialect to be validated. See * @FT_VALIDATE_CKERNXXX for possible values. * * @output: * ckern_table :: * A pointer to the kern table. * * @return: * FreeType error code. 0~means success. * * @note: * After use, the application should deallocate the buffers pointed to by * `ckern_table', by calling @FT_ClassicKern_Free. A NULL value * indicates that the table doesn't exist in the font. */ FT_EXPORT( FT_Error ) FT_ClassicKern_Validate( FT_Face face, FT_UInt validation_flags, FT_Bytes *ckern_table ); /* */ /********************************************************************** * * @function: * FT_ClassicKern_Free * * @description: * Free the buffer allocated by classic Kern validator. * * @input: * face :: * A handle to the input face. * * table :: * The pointer to the buffer that is allocated by * @FT_ClassicKern_Validate. * * @note: * This function must be used to free the buffer allocated by * @FT_ClassicKern_Validate only. */ FT_EXPORT( void ) FT_ClassicKern_Free( FT_Face face, FT_Bytes table ); /* */ FT_END_HEADER #endif /* __FTGXVAL_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/ftgzip.h ================================================ /***************************************************************************/ /* */ /* ftgzip.h */ /* */ /* Gzip-compressed stream support. */ /* */ /* Copyright 2002, 2003, 2004, 2006 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __FTGZIP_H__ #define __FTGZIP_H__ #include <ft2build.h> #include FT_FREETYPE_H #ifdef FREETYPE_H #error "freetype.h of FreeType 1 has been loaded!" #error "Please fix the directory search order for header files" #error "so that freetype.h of FreeType 2 is found first." #endif FT_BEGIN_HEADER /*************************************************************************/ /* */ /* <Section> */ /* gzip */ /* */ /* <Title> */ /* GZIP Streams */ /* */ /* <Abstract> */ /* Using gzip-compressed font files. */ /* */ /* <Description> */ /* This section contains the declaration of Gzip-specific functions. */ /* */ /*************************************************************************/ /************************************************************************ * * @function: * FT_Stream_OpenGzip * * @description: * Open a new stream to parse gzip-compressed font files. This is * mainly used to support the compressed `*.pcf.gz' fonts that come * with XFree86. * * @input: * stream :: * The target embedding stream. * * source :: * The source stream. * * @return: * FreeType error code. 0~means success. * * @note: * The source stream must be opened _before_ calling this function. * * Calling the internal function `FT_Stream_Close' on the new stream will * *not* call `FT_Stream_Close' on the source stream. None of the stream * objects will be released to the heap. * * The stream implementation is very basic and resets the decompression * process each time seeking backwards is needed within the stream. * * In certain builds of the library, gzip compression recognition is * automatically handled when calling @FT_New_Face or @FT_Open_Face. * This means that if no font driver is capable of handling the raw * compressed file, the library will try to open a gzipped stream from * it and re-open the face with it. * * This function may return `FT_Err_Unimplemented_Feature' if your build * of FreeType was not compiled with zlib support. */ FT_EXPORT( FT_Error ) FT_Stream_OpenGzip( FT_Stream stream, FT_Stream source ); /* */ FT_END_HEADER #endif /* __FTGZIP_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/ftimage.h ================================================ /***************************************************************************/ /* */ /* ftimage.h */ /* */ /* FreeType glyph image formats and default raster interface */ /* (specification). */ /* */ /* Copyright 1996-2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, */ /* 2010 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /*************************************************************************/ /* */ /* Note: A `raster' is simply a scan-line converter, used to render */ /* FT_Outlines into FT_Bitmaps. */ /* */ /*************************************************************************/ #ifndef __FTIMAGE_H__ #define __FTIMAGE_H__ /* _STANDALONE_ is from ftgrays.c */ #ifndef _STANDALONE_ #include <ft2build.h> #endif FT_BEGIN_HEADER /*************************************************************************/ /* */ /* <Section> */ /* basic_types */ /* */ /*************************************************************************/ /*************************************************************************/ /* */ /* <Type> */ /* FT_Pos */ /* */ /* <Description> */ /* The type FT_Pos is used to store vectorial coordinates. Depending */ /* on the context, these can represent distances in integer font */ /* units, or 16.16, or 26.6 fixed float pixel coordinates. */ /* */ typedef signed long FT_Pos; /*************************************************************************/ /* */ /* <Struct> */ /* FT_Vector */ /* */ /* <Description> */ /* A simple structure used to store a 2D vector; coordinates are of */ /* the FT_Pos type. */ /* */ /* <Fields> */ /* x :: The horizontal coordinate. */ /* y :: The vertical coordinate. */ /* */ typedef struct FT_Vector_ { FT_Pos x; FT_Pos y; } FT_Vector; /*************************************************************************/ /* */ /* <Struct> */ /* FT_BBox */ /* */ /* <Description> */ /* A structure used to hold an outline's bounding box, i.e., the */ /* coordinates of its extrema in the horizontal and vertical */ /* directions. */ /* */ /* <Fields> */ /* xMin :: The horizontal minimum (left-most). */ /* */ /* yMin :: The vertical minimum (bottom-most). */ /* */ /* xMax :: The horizontal maximum (right-most). */ /* */ /* yMax :: The vertical maximum (top-most). */ /* */ /* <Note> */ /* The bounding box is specified with the coordinates of the lower */ /* left and the upper right corner. In PostScript, those values are */ /* often called (llx,lly) and (urx,ury), respectively. */ /* */ /* If `yMin' is negative, this value gives the glyph's descender. */ /* Otherwise, the glyph doesn't descend below the baseline. */ /* Similarly, if `ymax' is positive, this value gives the glyph's */ /* ascender. */ /* */ /* `xMin' gives the horizontal distance from the glyph's origin to */ /* the left edge of the glyph's bounding box. If `xMin' is negative, */ /* the glyph extends to the left of the origin. */ /* */ typedef struct FT_BBox_ { FT_Pos xMin, yMin; FT_Pos xMax, yMax; } FT_BBox; /*************************************************************************/ /* */ /* <Enum> */ /* FT_Pixel_Mode */ /* */ /* <Description> */ /* An enumeration type used to describe the format of pixels in a */ /* given bitmap. Note that additional formats may be added in the */ /* future. */ /* */ /* <Values> */ /* FT_PIXEL_MODE_NONE :: */ /* Value~0 is reserved. */ /* */ /* FT_PIXEL_MODE_MONO :: */ /* A monochrome bitmap, using 1~bit per pixel. Note that pixels */ /* are stored in most-significant order (MSB), which means that */ /* the left-most pixel in a byte has value 128. */ /* */ /* FT_PIXEL_MODE_GRAY :: */ /* An 8-bit bitmap, generally used to represent anti-aliased glyph */ /* images. Each pixel is stored in one byte. Note that the number */ /* of `gray' levels is stored in the `num_grays' field of the */ /* @FT_Bitmap structure (it generally is 256). */ /* */ /* FT_PIXEL_MODE_GRAY2 :: */ /* A 2-bit per pixel bitmap, used to represent embedded */ /* anti-aliased bitmaps in font files according to the OpenType */ /* specification. We haven't found a single font using this */ /* format, however. */ /* */ /* FT_PIXEL_MODE_GRAY4 :: */ /* A 4-bit per pixel bitmap, representing embedded anti-aliased */ /* bitmaps in font files according to the OpenType specification. */ /* We haven't found a single font using this format, however. */ /* */ /* FT_PIXEL_MODE_LCD :: */ /* An 8-bit bitmap, representing RGB or BGR decimated glyph images */ /* used for display on LCD displays; the bitmap is three times */ /* wider than the original glyph image. See also */ /* @FT_RENDER_MODE_LCD. */ /* */ /* FT_PIXEL_MODE_LCD_V :: */ /* An 8-bit bitmap, representing RGB or BGR decimated glyph images */ /* used for display on rotated LCD displays; the bitmap is three */ /* times taller than the original glyph image. See also */ /* @FT_RENDER_MODE_LCD_V. */ /* */ typedef enum FT_Pixel_Mode_ { FT_PIXEL_MODE_NONE = 0, FT_PIXEL_MODE_MONO, FT_PIXEL_MODE_GRAY, FT_PIXEL_MODE_GRAY2, FT_PIXEL_MODE_GRAY4, FT_PIXEL_MODE_LCD, FT_PIXEL_MODE_LCD_V, FT_PIXEL_MODE_MAX /* do not remove */ } FT_Pixel_Mode; /*************************************************************************/ /* */ /* <Enum> */ /* ft_pixel_mode_xxx */ /* */ /* <Description> */ /* A list of deprecated constants. Use the corresponding */ /* @FT_Pixel_Mode values instead. */ /* */ /* <Values> */ /* ft_pixel_mode_none :: See @FT_PIXEL_MODE_NONE. */ /* ft_pixel_mode_mono :: See @FT_PIXEL_MODE_MONO. */ /* ft_pixel_mode_grays :: See @FT_PIXEL_MODE_GRAY. */ /* ft_pixel_mode_pal2 :: See @FT_PIXEL_MODE_GRAY2. */ /* ft_pixel_mode_pal4 :: See @FT_PIXEL_MODE_GRAY4. */ /* */ #define ft_pixel_mode_none FT_PIXEL_MODE_NONE #define ft_pixel_mode_mono FT_PIXEL_MODE_MONO #define ft_pixel_mode_grays FT_PIXEL_MODE_GRAY #define ft_pixel_mode_pal2 FT_PIXEL_MODE_GRAY2 #define ft_pixel_mode_pal4 FT_PIXEL_MODE_GRAY4 /* */ #if 0 /*************************************************************************/ /* */ /* <Enum> */ /* FT_Palette_Mode */ /* */ /* <Description> */ /* THIS TYPE IS DEPRECATED. DO NOT USE IT! */ /* */ /* An enumeration type to describe the format of a bitmap palette, */ /* used with ft_pixel_mode_pal4 and ft_pixel_mode_pal8. */ /* */ /* <Values> */ /* ft_palette_mode_rgb :: The palette is an array of 3-byte RGB */ /* records. */ /* */ /* ft_palette_mode_rgba :: The palette is an array of 4-byte RGBA */ /* records. */ /* */ /* <Note> */ /* As ft_pixel_mode_pal2, pal4 and pal8 are currently unused by */ /* FreeType, these types are not handled by the library itself. */ /* */ typedef enum FT_Palette_Mode_ { ft_palette_mode_rgb = 0, ft_palette_mode_rgba, ft_palette_mode_max /* do not remove */ } FT_Palette_Mode; /* */ #endif /*************************************************************************/ /* */ /* <Struct> */ /* FT_Bitmap */ /* */ /* <Description> */ /* A structure used to describe a bitmap or pixmap to the raster. */ /* Note that we now manage pixmaps of various depths through the */ /* `pixel_mode' field. */ /* */ /* <Fields> */ /* rows :: The number of bitmap rows. */ /* */ /* width :: The number of pixels in bitmap row. */ /* */ /* pitch :: The pitch's absolute value is the number of bytes */ /* taken by one bitmap row, including padding. */ /* However, the pitch is positive when the bitmap has */ /* a `down' flow, and negative when it has an `up' */ /* flow. In all cases, the pitch is an offset to add */ /* to a bitmap pointer in order to go down one row. */ /* */ /* Note that `padding' means the alignment of a */ /* bitmap to a byte border, and FreeType functions */ /* normally align to the smallest possible integer */ /* value. */ /* */ /* For the B/W rasterizer, `pitch' is always an even */ /* number. */ /* */ /* To change the pitch of a bitmap (say, to make it a */ /* multiple of 4), use @FT_Bitmap_Convert. */ /* Alternatively, you might use callback functions to */ /* directly render to the application's surface; see */ /* the file `example2.cpp' in the tutorial for a */ /* demonstration. */ /* */ /* buffer :: A typeless pointer to the bitmap buffer. This */ /* value should be aligned on 32-bit boundaries in */ /* most cases. */ /* */ /* num_grays :: This field is only used with */ /* @FT_PIXEL_MODE_GRAY; it gives the number of gray */ /* levels used in the bitmap. */ /* */ /* pixel_mode :: The pixel mode, i.e., how pixel bits are stored. */ /* See @FT_Pixel_Mode for possible values. */ /* */ /* palette_mode :: This field is intended for paletted pixel modes; */ /* it indicates how the palette is stored. Not */ /* used currently. */ /* */ /* palette :: A typeless pointer to the bitmap palette; this */ /* field is intended for paletted pixel modes. Not */ /* used currently. */ /* */ /* <Note> */ /* For now, the only pixel modes supported by FreeType are mono and */ /* grays. However, drivers might be added in the future to support */ /* more `colorful' options. */ /* */ typedef struct FT_Bitmap_ { int rows; int width; int pitch; unsigned char* buffer; short num_grays; char pixel_mode; char palette_mode; void* palette; } FT_Bitmap; /*************************************************************************/ /* */ /* <Section> */ /* outline_processing */ /* */ /*************************************************************************/ /*************************************************************************/ /* */ /* <Struct> */ /* FT_Outline */ /* */ /* <Description> */ /* This structure is used to describe an outline to the scan-line */ /* converter. */ /* */ /* <Fields> */ /* n_contours :: The number of contours in the outline. */ /* */ /* n_points :: The number of points in the outline. */ /* */ /* points :: A pointer to an array of `n_points' @FT_Vector */ /* elements, giving the outline's point coordinates. */ /* */ /* tags :: A pointer to an array of `n_points' chars, giving */ /* each outline point's type. */ /* */ /* If bit~0 is unset, the point is `off' the curve, */ /* i.e., a Bézier control point, while it is `on' if */ /* set. */ /* */ /* Bit~1 is meaningful for `off' points only. If set, */ /* it indicates a third-order Bézier arc control point; */ /* and a second-order control point if unset. */ /* */ /* If bit~2 is set, bits 5-7 contain the drop-out mode */ /* (as defined in the OpenType specification; the value */ /* is the same as the argument to the SCANMODE */ /* instruction). */ /* */ /* Bits 3 and~4 are reserved for internal purposes. */ /* */ /* contours :: An array of `n_contours' shorts, giving the end */ /* point of each contour within the outline. For */ /* example, the first contour is defined by the points */ /* `0' to `contours[0]', the second one is defined by */ /* the points `contours[0]+1' to `contours[1]', etc. */ /* */ /* flags :: A set of bit flags used to characterize the outline */ /* and give hints to the scan-converter and hinter on */ /* how to convert/grid-fit it. See @FT_OUTLINE_FLAGS. */ /* */ /* <Note> */ /* The B/W rasterizer only checks bit~2 in the `tags' array for the */ /* first point of each contour. The drop-out mode as given with */ /* @FT_OUTLINE_IGNORE_DROPOUTS, @FT_OUTLINE_SMART_DROPOUTS, and */ /* @FT_OUTLINE_INCLUDE_STUBS in `flags' is then overridden. */ /* */ typedef struct FT_Outline_ { short n_contours; /* number of contours in glyph */ short n_points; /* number of points in the glyph */ FT_Vector* points; /* the outline's points */ char* tags; /* the points flags */ short* contours; /* the contour end points */ int flags; /* outline masks */ } FT_Outline; /* Following limits must be consistent with */ /* FT_Outline.{n_contours,n_points} */ #define FT_OUTLINE_CONTOURS_MAX SHRT_MAX #define FT_OUTLINE_POINTS_MAX SHRT_MAX /*************************************************************************/ /* */ /* <Enum> */ /* FT_OUTLINE_FLAGS */ /* */ /* <Description> */ /* A list of bit-field constants use for the flags in an outline's */ /* `flags' field. */ /* */ /* <Values> */ /* FT_OUTLINE_NONE :: */ /* Value~0 is reserved. */ /* */ /* FT_OUTLINE_OWNER :: */ /* If set, this flag indicates that the outline's field arrays */ /* (i.e., `points', `flags', and `contours') are `owned' by the */ /* outline object, and should thus be freed when it is destroyed. */ /* */ /* FT_OUTLINE_EVEN_ODD_FILL :: */ /* By default, outlines are filled using the non-zero winding rule. */ /* If set to 1, the outline will be filled using the even-odd fill */ /* rule (only works with the smooth rasterizer). */ /* */ /* FT_OUTLINE_REVERSE_FILL :: */ /* By default, outside contours of an outline are oriented in */ /* clock-wise direction, as defined in the TrueType specification. */ /* This flag is set if the outline uses the opposite direction */ /* (typically for Type~1 fonts). This flag is ignored by the scan */ /* converter. */ /* */ /* FT_OUTLINE_IGNORE_DROPOUTS :: */ /* By default, the scan converter will try to detect drop-outs in */ /* an outline and correct the glyph bitmap to ensure consistent */ /* shape continuity. If set, this flag hints the scan-line */ /* converter to ignore such cases. See below for more information. */ /* */ /* FT_OUTLINE_SMART_DROPOUTS :: */ /* Select smart dropout control. If unset, use simple dropout */ /* control. Ignored if @FT_OUTLINE_IGNORE_DROPOUTS is set. See */ /* below for more information. */ /* */ /* FT_OUTLINE_INCLUDE_STUBS :: */ /* If set, turn pixels on for `stubs', otherwise exclude them. */ /* Ignored if @FT_OUTLINE_IGNORE_DROPOUTS is set. See below for */ /* more information. */ /* */ /* FT_OUTLINE_HIGH_PRECISION :: */ /* This flag indicates that the scan-line converter should try to */ /* convert this outline to bitmaps with the highest possible */ /* quality. It is typically set for small character sizes. Note */ /* that this is only a hint that might be completely ignored by a */ /* given scan-converter. */ /* */ /* FT_OUTLINE_SINGLE_PASS :: */ /* This flag is set to force a given scan-converter to only use a */ /* single pass over the outline to render a bitmap glyph image. */ /* Normally, it is set for very large character sizes. It is only */ /* a hint that might be completely ignored by a given */ /* scan-converter. */ /* */ /* <Note> */ /* The flags @FT_OUTLINE_IGNORE_DROPOUTS, @FT_OUTLINE_SMART_DROPOUTS, */ /* and @FT_OUTLINE_INCLUDE_STUBS are ignored by the smooth */ /* rasterizer. */ /* */ /* There exists a second mechanism to pass the drop-out mode to the */ /* B/W rasterizer; see the `tags' field in @FT_Outline. */ /* */ /* Please refer to the description of the `SCANTYPE' instruction in */ /* the OpenType specification (in file `ttinst1.doc') how simple */ /* drop-outs, smart drop-outs, and stubs are defined. */ /* */ #define FT_OUTLINE_NONE 0x0 #define FT_OUTLINE_OWNER 0x1 #define FT_OUTLINE_EVEN_ODD_FILL 0x2 #define FT_OUTLINE_REVERSE_FILL 0x4 #define FT_OUTLINE_IGNORE_DROPOUTS 0x8 #define FT_OUTLINE_SMART_DROPOUTS 0x10 #define FT_OUTLINE_INCLUDE_STUBS 0x20 #define FT_OUTLINE_HIGH_PRECISION 0x100 #define FT_OUTLINE_SINGLE_PASS 0x200 /************************************************************************* * * @enum: * ft_outline_flags * * @description: * These constants are deprecated. Please use the corresponding * @FT_OUTLINE_FLAGS values. * * @values: * ft_outline_none :: See @FT_OUTLINE_NONE. * ft_outline_owner :: See @FT_OUTLINE_OWNER. * ft_outline_even_odd_fill :: See @FT_OUTLINE_EVEN_ODD_FILL. * ft_outline_reverse_fill :: See @FT_OUTLINE_REVERSE_FILL. * ft_outline_ignore_dropouts :: See @FT_OUTLINE_IGNORE_DROPOUTS. * ft_outline_high_precision :: See @FT_OUTLINE_HIGH_PRECISION. * ft_outline_single_pass :: See @FT_OUTLINE_SINGLE_PASS. */ #define ft_outline_none FT_OUTLINE_NONE #define ft_outline_owner FT_OUTLINE_OWNER #define ft_outline_even_odd_fill FT_OUTLINE_EVEN_ODD_FILL #define ft_outline_reverse_fill FT_OUTLINE_REVERSE_FILL #define ft_outline_ignore_dropouts FT_OUTLINE_IGNORE_DROPOUTS #define ft_outline_high_precision FT_OUTLINE_HIGH_PRECISION #define ft_outline_single_pass FT_OUTLINE_SINGLE_PASS /* */ #define FT_CURVE_TAG( flag ) ( flag & 3 ) #define FT_CURVE_TAG_ON 1 #define FT_CURVE_TAG_CONIC 0 #define FT_CURVE_TAG_CUBIC 2 #define FT_CURVE_TAG_HAS_SCANMODE 4 #define FT_CURVE_TAG_TOUCH_X 8 /* reserved for the TrueType hinter */ #define FT_CURVE_TAG_TOUCH_Y 16 /* reserved for the TrueType hinter */ #define FT_CURVE_TAG_TOUCH_BOTH ( FT_CURVE_TAG_TOUCH_X | \ FT_CURVE_TAG_TOUCH_Y ) #define FT_Curve_Tag_On FT_CURVE_TAG_ON #define FT_Curve_Tag_Conic FT_CURVE_TAG_CONIC #define FT_Curve_Tag_Cubic FT_CURVE_TAG_CUBIC #define FT_Curve_Tag_Touch_X FT_CURVE_TAG_TOUCH_X #define FT_Curve_Tag_Touch_Y FT_CURVE_TAG_TOUCH_Y /*************************************************************************/ /* */ /* <FuncType> */ /* FT_Outline_MoveToFunc */ /* */ /* <Description> */ /* A function pointer type used to describe the signature of a `move */ /* to' function during outline walking/decomposition. */ /* */ /* A `move to' is emitted to start a new contour in an outline. */ /* */ /* <Input> */ /* to :: A pointer to the target point of the `move to'. */ /* */ /* user :: A typeless pointer which is passed from the caller of the */ /* decomposition function. */ /* */ /* <Return> */ /* Error code. 0~means success. */ /* */ typedef int (*FT_Outline_MoveToFunc)( const FT_Vector* to, void* user ); #define FT_Outline_MoveTo_Func FT_Outline_MoveToFunc /*************************************************************************/ /* */ /* <FuncType> */ /* FT_Outline_LineToFunc */ /* */ /* <Description> */ /* A function pointer type used to describe the signature of a `line */ /* to' function during outline walking/decomposition. */ /* */ /* A `line to' is emitted to indicate a segment in the outline. */ /* */ /* <Input> */ /* to :: A pointer to the target point of the `line to'. */ /* */ /* user :: A typeless pointer which is passed from the caller of the */ /* decomposition function. */ /* */ /* <Return> */ /* Error code. 0~means success. */ /* */ typedef int (*FT_Outline_LineToFunc)( const FT_Vector* to, void* user ); #define FT_Outline_LineTo_Func FT_Outline_LineToFunc /*************************************************************************/ /* */ /* <FuncType> */ /* FT_Outline_ConicToFunc */ /* */ /* <Description> */ /* A function pointer type used to describe the signature of a `conic */ /* to' function during outline walking or decomposition. */ /* */ /* A `conic to' is emitted to indicate a second-order Bézier arc in */ /* the outline. */ /* */ /* <Input> */ /* control :: An intermediate control point between the last position */ /* and the new target in `to'. */ /* */ /* to :: A pointer to the target end point of the conic arc. */ /* */ /* user :: A typeless pointer which is passed from the caller of */ /* the decomposition function. */ /* */ /* <Return> */ /* Error code. 0~means success. */ /* */ typedef int (*FT_Outline_ConicToFunc)( const FT_Vector* control, const FT_Vector* to, void* user ); #define FT_Outline_ConicTo_Func FT_Outline_ConicToFunc /*************************************************************************/ /* */ /* <FuncType> */ /* FT_Outline_CubicToFunc */ /* */ /* <Description> */ /* A function pointer type used to describe the signature of a `cubic */ /* to' function during outline walking or decomposition. */ /* */ /* A `cubic to' is emitted to indicate a third-order Bézier arc. */ /* */ /* <Input> */ /* control1 :: A pointer to the first Bézier control point. */ /* */ /* control2 :: A pointer to the second Bézier control point. */ /* */ /* to :: A pointer to the target end point. */ /* */ /* user :: A typeless pointer which is passed from the caller of */ /* the decomposition function. */ /* */ /* <Return> */ /* Error code. 0~means success. */ /* */ typedef int (*FT_Outline_CubicToFunc)( const FT_Vector* control1, const FT_Vector* control2, const FT_Vector* to, void* user ); #define FT_Outline_CubicTo_Func FT_Outline_CubicToFunc /*************************************************************************/ /* */ /* <Struct> */ /* FT_Outline_Funcs */ /* */ /* <Description> */ /* A structure to hold various function pointers used during outline */ /* decomposition in order to emit segments, conic, and cubic Béziers. */ /* */ /* <Fields> */ /* move_to :: The `move to' emitter. */ /* */ /* line_to :: The segment emitter. */ /* */ /* conic_to :: The second-order Bézier arc emitter. */ /* */ /* cubic_to :: The third-order Bézier arc emitter. */ /* */ /* shift :: The shift that is applied to coordinates before they */ /* are sent to the emitter. */ /* */ /* delta :: The delta that is applied to coordinates before they */ /* are sent to the emitter, but after the shift. */ /* */ /* <Note> */ /* The point coordinates sent to the emitters are the transformed */ /* version of the original coordinates (this is important for high */ /* accuracy during scan-conversion). The transformation is simple: */ /* */ /* { */ /* x' = (x << shift) - delta */ /* y' = (x << shift) - delta */ /* } */ /* */ /* Set the values of `shift' and `delta' to~0 to get the original */ /* point coordinates. */ /* */ typedef struct FT_Outline_Funcs_ { FT_Outline_MoveToFunc move_to; FT_Outline_LineToFunc line_to; FT_Outline_ConicToFunc conic_to; FT_Outline_CubicToFunc cubic_to; int shift; FT_Pos delta; } FT_Outline_Funcs; /*************************************************************************/ /* */ /* <Section> */ /* basic_types */ /* */ /*************************************************************************/ /*************************************************************************/ /* */ /* <Macro> */ /* FT_IMAGE_TAG */ /* */ /* <Description> */ /* This macro converts four-letter tags to an unsigned long type. */ /* */ /* <Note> */ /* Since many 16-bit compilers don't like 32-bit enumerations, you */ /* should redefine this macro in case of problems to something like */ /* this: */ /* */ /* { */ /* #define FT_IMAGE_TAG( value, _x1, _x2, _x3, _x4 ) value */ /* } */ /* */ /* to get a simple enumeration without assigning special numbers. */ /* */ #ifndef FT_IMAGE_TAG #define FT_IMAGE_TAG( value, _x1, _x2, _x3, _x4 ) \ value = ( ( (unsigned long)_x1 << 24 ) | \ ( (unsigned long)_x2 << 16 ) | \ ( (unsigned long)_x3 << 8 ) | \ (unsigned long)_x4 ) #endif /* FT_IMAGE_TAG */ /*************************************************************************/ /* */ /* <Enum> */ /* FT_Glyph_Format */ /* */ /* <Description> */ /* An enumeration type used to describe the format of a given glyph */ /* image. Note that this version of FreeType only supports two image */ /* formats, even though future font drivers will be able to register */ /* their own format. */ /* */ /* <Values> */ /* FT_GLYPH_FORMAT_NONE :: */ /* The value~0 is reserved. */ /* */ /* FT_GLYPH_FORMAT_COMPOSITE :: */ /* The glyph image is a composite of several other images. This */ /* format is _only_ used with @FT_LOAD_NO_RECURSE, and is used to */ /* report compound glyphs (like accented characters). */ /* */ /* FT_GLYPH_FORMAT_BITMAP :: */ /* The glyph image is a bitmap, and can be described as an */ /* @FT_Bitmap. You generally need to access the `bitmap' field of */ /* the @FT_GlyphSlotRec structure to read it. */ /* */ /* FT_GLYPH_FORMAT_OUTLINE :: */ /* The glyph image is a vectorial outline made of line segments */ /* and Bézier arcs; it can be described as an @FT_Outline; you */ /* generally want to access the `outline' field of the */ /* @FT_GlyphSlotRec structure to read it. */ /* */ /* FT_GLYPH_FORMAT_PLOTTER :: */ /* The glyph image is a vectorial path with no inside and outside */ /* contours. Some Type~1 fonts, like those in the Hershey family, */ /* contain glyphs in this format. These are described as */ /* @FT_Outline, but FreeType isn't currently capable of rendering */ /* them correctly. */ /* */ typedef enum FT_Glyph_Format_ { FT_IMAGE_TAG( FT_GLYPH_FORMAT_NONE, 0, 0, 0, 0 ), FT_IMAGE_TAG( FT_GLYPH_FORMAT_COMPOSITE, 'c', 'o', 'm', 'p' ), FT_IMAGE_TAG( FT_GLYPH_FORMAT_BITMAP, 'b', 'i', 't', 's' ), FT_IMAGE_TAG( FT_GLYPH_FORMAT_OUTLINE, 'o', 'u', 't', 'l' ), FT_IMAGE_TAG( FT_GLYPH_FORMAT_PLOTTER, 'p', 'l', 'o', 't' ) } FT_Glyph_Format; /*************************************************************************/ /* */ /* <Enum> */ /* ft_glyph_format_xxx */ /* */ /* <Description> */ /* A list of deprecated constants. Use the corresponding */ /* @FT_Glyph_Format values instead. */ /* */ /* <Values> */ /* ft_glyph_format_none :: See @FT_GLYPH_FORMAT_NONE. */ /* ft_glyph_format_composite :: See @FT_GLYPH_FORMAT_COMPOSITE. */ /* ft_glyph_format_bitmap :: See @FT_GLYPH_FORMAT_BITMAP. */ /* ft_glyph_format_outline :: See @FT_GLYPH_FORMAT_OUTLINE. */ /* ft_glyph_format_plotter :: See @FT_GLYPH_FORMAT_PLOTTER. */ /* */ #define ft_glyph_format_none FT_GLYPH_FORMAT_NONE #define ft_glyph_format_composite FT_GLYPH_FORMAT_COMPOSITE #define ft_glyph_format_bitmap FT_GLYPH_FORMAT_BITMAP #define ft_glyph_format_outline FT_GLYPH_FORMAT_OUTLINE #define ft_glyph_format_plotter FT_GLYPH_FORMAT_PLOTTER /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** R A S T E R D E F I N I T I O N S *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /* */ /* A raster is a scan converter, in charge of rendering an outline into */ /* a a bitmap. This section contains the public API for rasters. */ /* */ /* Note that in FreeType 2, all rasters are now encapsulated within */ /* specific modules called `renderers'. See `freetype/ftrender.h' for */ /* more details on renderers. */ /* */ /*************************************************************************/ /*************************************************************************/ /* */ /* <Section> */ /* raster */ /* */ /* <Title> */ /* Scanline Converter */ /* */ /* <Abstract> */ /* How vectorial outlines are converted into bitmaps and pixmaps. */ /* */ /* <Description> */ /* This section contains technical definitions. */ /* */ /*************************************************************************/ /*************************************************************************/ /* */ /* <Type> */ /* FT_Raster */ /* */ /* <Description> */ /* A handle (pointer) to a raster object. Each object can be used */ /* independently to convert an outline into a bitmap or pixmap. */ /* */ typedef struct FT_RasterRec_* FT_Raster; /*************************************************************************/ /* */ /* <Struct> */ /* FT_Span */ /* */ /* <Description> */ /* A structure used to model a single span of gray (or black) pixels */ /* when rendering a monochrome or anti-aliased bitmap. */ /* */ /* <Fields> */ /* x :: The span's horizontal start position. */ /* */ /* len :: The span's length in pixels. */ /* */ /* coverage :: The span color/coverage, ranging from 0 (background) */ /* to 255 (foreground). Only used for anti-aliased */ /* rendering. */ /* */ /* <Note> */ /* This structure is used by the span drawing callback type named */ /* @FT_SpanFunc which takes the y~coordinate of the span as a */ /* a parameter. */ /* */ /* The coverage value is always between 0 and 255. If you want less */ /* gray values, the callback function has to reduce them. */ /* */ typedef struct FT_Span_ { short x; unsigned short len; unsigned char coverage; } FT_Span; /*************************************************************************/ /* */ /* <FuncType> */ /* FT_SpanFunc */ /* */ /* <Description> */ /* A function used as a call-back by the anti-aliased renderer in */ /* order to let client applications draw themselves the gray pixel */ /* spans on each scan line. */ /* */ /* <Input> */ /* y :: The scanline's y~coordinate. */ /* */ /* count :: The number of spans to draw on this scanline. */ /* */ /* spans :: A table of `count' spans to draw on the scanline. */ /* */ /* user :: User-supplied data that is passed to the callback. */ /* */ /* <Note> */ /* This callback allows client applications to directly render the */ /* gray spans of the anti-aliased bitmap to any kind of surfaces. */ /* */ /* This can be used to write anti-aliased outlines directly to a */ /* given background bitmap, and even perform translucency. */ /* */ /* Note that the `count' field cannot be greater than a fixed value */ /* defined by the `FT_MAX_GRAY_SPANS' configuration macro in */ /* `ftoption.h'. By default, this value is set to~32, which means */ /* that if there are more than 32~spans on a given scanline, the */ /* callback is called several times with the same `y' parameter in */ /* order to draw all callbacks. */ /* */ /* Otherwise, the callback is only called once per scan-line, and */ /* only for those scanlines that do have `gray' pixels on them. */ /* */ typedef void (*FT_SpanFunc)( int y, int count, const FT_Span* spans, void* user ); #define FT_Raster_Span_Func FT_SpanFunc /*************************************************************************/ /* */ /* <FuncType> */ /* FT_Raster_BitTest_Func */ /* */ /* <Description> */ /* THIS TYPE IS DEPRECATED. DO NOT USE IT. */ /* */ /* A function used as a call-back by the monochrome scan-converter */ /* to test whether a given target pixel is already set to the drawing */ /* `color'. These tests are crucial to implement drop-out control */ /* per-se the TrueType spec. */ /* */ /* <Input> */ /* y :: The pixel's y~coordinate. */ /* */ /* x :: The pixel's x~coordinate. */ /* */ /* user :: User-supplied data that is passed to the callback. */ /* */ /* <Return> */ /* 1~if the pixel is `set', 0~otherwise. */ /* */ typedef int (*FT_Raster_BitTest_Func)( int y, int x, void* user ); /*************************************************************************/ /* */ /* <FuncType> */ /* FT_Raster_BitSet_Func */ /* */ /* <Description> */ /* THIS TYPE IS DEPRECATED. DO NOT USE IT. */ /* */ /* A function used as a call-back by the monochrome scan-converter */ /* to set an individual target pixel. This is crucial to implement */ /* drop-out control according to the TrueType specification. */ /* */ /* <Input> */ /* y :: The pixel's y~coordinate. */ /* */ /* x :: The pixel's x~coordinate. */ /* */ /* user :: User-supplied data that is passed to the callback. */ /* */ /* <Return> */ /* 1~if the pixel is `set', 0~otherwise. */ /* */ typedef void (*FT_Raster_BitSet_Func)( int y, int x, void* user ); /*************************************************************************/ /* */ /* <Enum> */ /* FT_RASTER_FLAG_XXX */ /* */ /* <Description> */ /* A list of bit flag constants as used in the `flags' field of a */ /* @FT_Raster_Params structure. */ /* */ /* <Values> */ /* FT_RASTER_FLAG_DEFAULT :: This value is 0. */ /* */ /* FT_RASTER_FLAG_AA :: This flag is set to indicate that an */ /* anti-aliased glyph image should be */ /* generated. Otherwise, it will be */ /* monochrome (1-bit). */ /* */ /* FT_RASTER_FLAG_DIRECT :: This flag is set to indicate direct */ /* rendering. In this mode, client */ /* applications must provide their own span */ /* callback. This lets them directly */ /* draw or compose over an existing bitmap. */ /* If this bit is not set, the target */ /* pixmap's buffer _must_ be zeroed before */ /* rendering. */ /* */ /* Note that for now, direct rendering is */ /* only possible with anti-aliased glyphs. */ /* */ /* FT_RASTER_FLAG_CLIP :: This flag is only used in direct */ /* rendering mode. If set, the output will */ /* be clipped to a box specified in the */ /* `clip_box' field of the */ /* @FT_Raster_Params structure. */ /* */ /* Note that by default, the glyph bitmap */ /* is clipped to the target pixmap, except */ /* in direct rendering mode where all spans */ /* are generated if no clipping box is set. */ /* */ #define FT_RASTER_FLAG_DEFAULT 0x0 #define FT_RASTER_FLAG_AA 0x1 #define FT_RASTER_FLAG_DIRECT 0x2 #define FT_RASTER_FLAG_CLIP 0x4 /* deprecated */ #define ft_raster_flag_default FT_RASTER_FLAG_DEFAULT #define ft_raster_flag_aa FT_RASTER_FLAG_AA #define ft_raster_flag_direct FT_RASTER_FLAG_DIRECT #define ft_raster_flag_clip FT_RASTER_FLAG_CLIP /*************************************************************************/ /* */ /* <Struct> */ /* FT_Raster_Params */ /* */ /* <Description> */ /* A structure to hold the arguments used by a raster's render */ /* function. */ /* */ /* <Fields> */ /* target :: The target bitmap. */ /* */ /* source :: A pointer to the source glyph image (e.g., an */ /* @FT_Outline). */ /* */ /* flags :: The rendering flags. */ /* */ /* gray_spans :: The gray span drawing callback. */ /* */ /* black_spans :: The black span drawing callback. UNIMPLEMENTED! */ /* */ /* bit_test :: The bit test callback. UNIMPLEMENTED! */ /* */ /* bit_set :: The bit set callback. UNIMPLEMENTED! */ /* */ /* user :: User-supplied data that is passed to each drawing */ /* callback. */ /* */ /* clip_box :: An optional clipping box. It is only used in */ /* direct rendering mode. Note that coordinates here */ /* should be expressed in _integer_ pixels (and not in */ /* 26.6 fixed-point units). */ /* */ /* <Note> */ /* An anti-aliased glyph bitmap is drawn if the @FT_RASTER_FLAG_AA */ /* bit flag is set in the `flags' field, otherwise a monochrome */ /* bitmap is generated. */ /* */ /* If the @FT_RASTER_FLAG_DIRECT bit flag is set in `flags', the */ /* raster will call the `gray_spans' callback to draw gray pixel */ /* spans, in the case of an aa glyph bitmap, it will call */ /* `black_spans', and `bit_test' and `bit_set' in the case of a */ /* monochrome bitmap. This allows direct composition over a */ /* pre-existing bitmap through user-provided callbacks to perform the */ /* span drawing/composition. */ /* */ /* Note that the `bit_test' and `bit_set' callbacks are required when */ /* rendering a monochrome bitmap, as they are crucial to implement */ /* correct drop-out control as defined in the TrueType specification. */ /* */ typedef struct FT_Raster_Params_ { const FT_Bitmap* target; const void* source; int flags; FT_SpanFunc gray_spans; FT_SpanFunc black_spans; /* doesn't work! */ FT_Raster_BitTest_Func bit_test; /* doesn't work! */ FT_Raster_BitSet_Func bit_set; /* doesn't work! */ void* user; FT_BBox clip_box; } FT_Raster_Params; /*************************************************************************/ /* */ /* <FuncType> */ /* FT_Raster_NewFunc */ /* */ /* <Description> */ /* A function used to create a new raster object. */ /* */ /* <Input> */ /* memory :: A handle to the memory allocator. */ /* */ /* <Output> */ /* raster :: A handle to the new raster object. */ /* */ /* <Return> */ /* Error code. 0~means success. */ /* */ /* <Note> */ /* The `memory' parameter is a typeless pointer in order to avoid */ /* un-wanted dependencies on the rest of the FreeType code. In */ /* practice, it is an @FT_Memory object, i.e., a handle to the */ /* standard FreeType memory allocator. However, this field can be */ /* completely ignored by a given raster implementation. */ /* */ typedef int (*FT_Raster_NewFunc)( void* memory, FT_Raster* raster ); #define FT_Raster_New_Func FT_Raster_NewFunc /*************************************************************************/ /* */ /* <FuncType> */ /* FT_Raster_DoneFunc */ /* */ /* <Description> */ /* A function used to destroy a given raster object. */ /* */ /* <Input> */ /* raster :: A handle to the raster object. */ /* */ typedef void (*FT_Raster_DoneFunc)( FT_Raster raster ); #define FT_Raster_Done_Func FT_Raster_DoneFunc /*************************************************************************/ /* */ /* <FuncType> */ /* FT_Raster_ResetFunc */ /* */ /* <Description> */ /* FreeType provides an area of memory called the `render pool', */ /* available to all registered rasters. This pool can be freely used */ /* during a given scan-conversion but is shared by all rasters. Its */ /* content is thus transient. */ /* */ /* This function is called each time the render pool changes, or just */ /* after a new raster object is created. */ /* */ /* <Input> */ /* raster :: A handle to the new raster object. */ /* */ /* pool_base :: The address in memory of the render pool. */ /* */ /* pool_size :: The size in bytes of the render pool. */ /* */ /* <Note> */ /* Rasters can ignore the render pool and rely on dynamic memory */ /* allocation if they want to (a handle to the memory allocator is */ /* passed to the raster constructor). However, this is not */ /* recommended for efficiency purposes. */ /* */ typedef void (*FT_Raster_ResetFunc)( FT_Raster raster, unsigned char* pool_base, unsigned long pool_size ); #define FT_Raster_Reset_Func FT_Raster_ResetFunc /*************************************************************************/ /* */ /* <FuncType> */ /* FT_Raster_SetModeFunc */ /* */ /* <Description> */ /* This function is a generic facility to change modes or attributes */ /* in a given raster. This can be used for debugging purposes, or */ /* simply to allow implementation-specific `features' in a given */ /* raster module. */ /* */ /* <Input> */ /* raster :: A handle to the new raster object. */ /* */ /* mode :: A 4-byte tag used to name the mode or property. */ /* */ /* args :: A pointer to the new mode/property to use. */ /* */ typedef int (*FT_Raster_SetModeFunc)( FT_Raster raster, unsigned long mode, void* args ); #define FT_Raster_Set_Mode_Func FT_Raster_SetModeFunc /*************************************************************************/ /* */ /* <FuncType> */ /* FT_Raster_RenderFunc */ /* */ /* <Description> */ /* Invoke a given raster to scan-convert a given glyph image into a */ /* target bitmap. */ /* */ /* <Input> */ /* raster :: A handle to the raster object. */ /* */ /* params :: A pointer to an @FT_Raster_Params structure used to */ /* store the rendering parameters. */ /* */ /* <Return> */ /* Error code. 0~means success. */ /* */ /* <Note> */ /* The exact format of the source image depends on the raster's glyph */ /* format defined in its @FT_Raster_Funcs structure. It can be an */ /* @FT_Outline or anything else in order to support a large array of */ /* glyph formats. */ /* */ /* Note also that the render function can fail and return a */ /* `FT_Err_Unimplemented_Feature' error code if the raster used does */ /* not support direct composition. */ /* */ /* XXX: For now, the standard raster doesn't support direct */ /* composition but this should change for the final release (see */ /* the files `demos/src/ftgrays.c' and `demos/src/ftgrays2.c' */ /* for examples of distinct implementations which support direct */ /* composition). */ /* */ typedef int (*FT_Raster_RenderFunc)( FT_Raster raster, const FT_Raster_Params* params ); #define FT_Raster_Render_Func FT_Raster_RenderFunc /*************************************************************************/ /* */ /* <Struct> */ /* FT_Raster_Funcs */ /* */ /* <Description> */ /* A structure used to describe a given raster class to the library. */ /* */ /* <Fields> */ /* glyph_format :: The supported glyph format for this raster. */ /* */ /* raster_new :: The raster constructor. */ /* */ /* raster_reset :: Used to reset the render pool within the raster. */ /* */ /* raster_render :: A function to render a glyph into a given bitmap. */ /* */ /* raster_done :: The raster destructor. */ /* */ typedef struct FT_Raster_Funcs_ { FT_Glyph_Format glyph_format; FT_Raster_NewFunc raster_new; FT_Raster_ResetFunc raster_reset; FT_Raster_SetModeFunc raster_set_mode; FT_Raster_RenderFunc raster_render; FT_Raster_DoneFunc raster_done; } FT_Raster_Funcs; /* */ FT_END_HEADER #endif /* __FTIMAGE_H__ */ /* END */ /* Local Variables: */ /* coding: utf-8 */ /* End: */ ================================================ FILE: other/freetype/include/freetype/ftincrem.h ================================================ /***************************************************************************/ /* */ /* ftincrem.h */ /* */ /* FreeType incremental loading (specification). */ /* */ /* Copyright 2002, 2003, 2006, 2007, 2008, 2010 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __FTINCREM_H__ #define __FTINCREM_H__ #include <ft2build.h> #include FT_FREETYPE_H #ifdef FREETYPE_H #error "freetype.h of FreeType 1 has been loaded!" #error "Please fix the directory search order for header files" #error "so that freetype.h of FreeType 2 is found first." #endif FT_BEGIN_HEADER /*************************************************************************** * * @section: * incremental * * @title: * Incremental Loading * * @abstract: * Custom Glyph Loading. * * @description: * This section contains various functions used to perform so-called * `incremental' glyph loading. This is a mode where all glyphs loaded * from a given @FT_Face are provided by the client application, * * Apart from that, all other tables are loaded normally from the font * file. This mode is useful when FreeType is used within another * engine, e.g., a PostScript Imaging Processor. * * To enable this mode, you must use @FT_Open_Face, passing an * @FT_Parameter with the @FT_PARAM_TAG_INCREMENTAL tag and an * @FT_Incremental_Interface value. See the comments for * @FT_Incremental_InterfaceRec for an example. * */ /*************************************************************************** * * @type: * FT_Incremental * * @description: * An opaque type describing a user-provided object used to implement * `incremental' glyph loading within FreeType. This is used to support * embedded fonts in certain environments (e.g., PostScript interpreters), * where the glyph data isn't in the font file, or must be overridden by * different values. * * @note: * It is up to client applications to create and implement @FT_Incremental * objects, as long as they provide implementations for the methods * @FT_Incremental_GetGlyphDataFunc, @FT_Incremental_FreeGlyphDataFunc * and @FT_Incremental_GetGlyphMetricsFunc. * * See the description of @FT_Incremental_InterfaceRec to understand how * to use incremental objects with FreeType. * */ typedef struct FT_IncrementalRec_* FT_Incremental; /*************************************************************************** * * @struct: * FT_Incremental_MetricsRec * * @description: * A small structure used to contain the basic glyph metrics returned * by the @FT_Incremental_GetGlyphMetricsFunc method. * * @fields: * bearing_x :: * Left bearing, in font units. * * bearing_y :: * Top bearing, in font units. * * advance :: * Horizontal component of glyph advance, in font units. * * advance_v :: * Vertical component of glyph advance, in font units. * * @note: * These correspond to horizontal or vertical metrics depending on the * value of the `vertical' argument to the function * @FT_Incremental_GetGlyphMetricsFunc. * */ typedef struct FT_Incremental_MetricsRec_ { FT_Long bearing_x; FT_Long bearing_y; FT_Long advance; FT_Long advance_v; /* since 2.3.12 */ } FT_Incremental_MetricsRec; /*************************************************************************** * * @struct: * FT_Incremental_Metrics * * @description: * A handle to an @FT_Incremental_MetricsRec structure. * */ typedef struct FT_Incremental_MetricsRec_* FT_Incremental_Metrics; /*************************************************************************** * * @type: * FT_Incremental_GetGlyphDataFunc * * @description: * A function called by FreeType to access a given glyph's data bytes * during @FT_Load_Glyph or @FT_Load_Char if incremental loading is * enabled. * * Note that the format of the glyph's data bytes depends on the font * file format. For TrueType, it must correspond to the raw bytes within * the `glyf' table. For PostScript formats, it must correspond to the * *unencrypted* charstring bytes, without any `lenIV' header. It is * undefined for any other format. * * @input: * incremental :: * Handle to an opaque @FT_Incremental handle provided by the client * application. * * glyph_index :: * Index of relevant glyph. * * @output: * adata :: * A structure describing the returned glyph data bytes (which will be * accessed as a read-only byte block). * * @return: * FreeType error code. 0~means success. * * @note: * If this function returns successfully the method * @FT_Incremental_FreeGlyphDataFunc will be called later to release * the data bytes. * * Nested calls to @FT_Incremental_GetGlyphDataFunc can happen for * compound glyphs. * */ typedef FT_Error (*FT_Incremental_GetGlyphDataFunc)( FT_Incremental incremental, FT_UInt glyph_index, FT_Data* adata ); /*************************************************************************** * * @type: * FT_Incremental_FreeGlyphDataFunc * * @description: * A function used to release the glyph data bytes returned by a * successful call to @FT_Incremental_GetGlyphDataFunc. * * @input: * incremental :: * A handle to an opaque @FT_Incremental handle provided by the client * application. * * data :: * A structure describing the glyph data bytes (which will be accessed * as a read-only byte block). * */ typedef void (*FT_Incremental_FreeGlyphDataFunc)( FT_Incremental incremental, FT_Data* data ); /*************************************************************************** * * @type: * FT_Incremental_GetGlyphMetricsFunc * * @description: * A function used to retrieve the basic metrics of a given glyph index * before accessing its data. This is necessary because, in certain * formats like TrueType, the metrics are stored in a different place from * the glyph images proper. * * @input: * incremental :: * A handle to an opaque @FT_Incremental handle provided by the client * application. * * glyph_index :: * Index of relevant glyph. * * vertical :: * If true, return vertical metrics. * * ametrics :: * This parameter is used for both input and output. * The original glyph metrics, if any, in font units. If metrics are * not available all the values must be set to zero. * * @output: * ametrics :: * The replacement glyph metrics in font units. * */ typedef FT_Error (*FT_Incremental_GetGlyphMetricsFunc) ( FT_Incremental incremental, FT_UInt glyph_index, FT_Bool vertical, FT_Incremental_MetricsRec *ametrics ); /************************************************************************** * * @struct: * FT_Incremental_FuncsRec * * @description: * A table of functions for accessing fonts that load data * incrementally. Used in @FT_Incremental_InterfaceRec. * * @fields: * get_glyph_data :: * The function to get glyph data. Must not be null. * * free_glyph_data :: * The function to release glyph data. Must not be null. * * get_glyph_metrics :: * The function to get glyph metrics. May be null if the font does * not provide overriding glyph metrics. * */ typedef struct FT_Incremental_FuncsRec_ { FT_Incremental_GetGlyphDataFunc get_glyph_data; FT_Incremental_FreeGlyphDataFunc free_glyph_data; FT_Incremental_GetGlyphMetricsFunc get_glyph_metrics; } FT_Incremental_FuncsRec; /*************************************************************************** * * @struct: * FT_Incremental_InterfaceRec * * @description: * A structure to be used with @FT_Open_Face to indicate that the user * wants to support incremental glyph loading. You should use it with * @FT_PARAM_TAG_INCREMENTAL as in the following example: * * { * FT_Incremental_InterfaceRec inc_int; * FT_Parameter parameter; * FT_Open_Args open_args; * * * // set up incremental descriptor * inc_int.funcs = my_funcs; * inc_int.object = my_object; * * // set up optional parameter * parameter.tag = FT_PARAM_TAG_INCREMENTAL; * parameter.data = &inc_int; * * // set up FT_Open_Args structure * open_args.flags = FT_OPEN_PATHNAME | FT_OPEN_PARAMS; * open_args.pathname = my_font_pathname; * open_args.num_params = 1; * open_args.params = ¶meter; // we use one optional argument * * // open the font * error = FT_Open_Face( library, &open_args, index, &face ); * ... * } * */ typedef struct FT_Incremental_InterfaceRec_ { const FT_Incremental_FuncsRec* funcs; FT_Incremental object; } FT_Incremental_InterfaceRec; /*************************************************************************** * * @type: * FT_Incremental_Interface * * @description: * A pointer to an @FT_Incremental_InterfaceRec structure. * */ typedef FT_Incremental_InterfaceRec* FT_Incremental_Interface; /*************************************************************************** * * @constant: * FT_PARAM_TAG_INCREMENTAL * * @description: * A constant used as the tag of @FT_Parameter structures to indicate * an incremental loading object to be used by FreeType. * */ #define FT_PARAM_TAG_INCREMENTAL FT_MAKE_TAG( 'i', 'n', 'c', 'r' ) /* */ FT_END_HEADER #endif /* __FTINCREM_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/ftlcdfil.h ================================================ /***************************************************************************/ /* */ /* ftlcdfil.h */ /* */ /* FreeType API for color filtering of subpixel bitmap glyphs */ /* (specification). */ /* */ /* Copyright 2006, 2007, 2008, 2010 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __FT_LCD_FILTER_H__ #define __FT_LCD_FILTER_H__ #include <ft2build.h> #include FT_FREETYPE_H #ifdef FREETYPE_H #error "freetype.h of FreeType 1 has been loaded!" #error "Please fix the directory search order for header files" #error "so that freetype.h of FreeType 2 is found first." #endif FT_BEGIN_HEADER /*************************************************************************** * * @section: * lcd_filtering * * @title: * LCD Filtering * * @abstract: * Reduce color fringes of LCD-optimized bitmaps. * * @description: * The @FT_Library_SetLcdFilter API can be used to specify a low-pass * filter which is then applied to LCD-optimized bitmaps generated * through @FT_Render_Glyph. This is useful to reduce color fringes * which would occur with unfiltered rendering. * * Note that no filter is active by default, and that this function is * *not* implemented in default builds of the library. You need to * #define FT_CONFIG_OPTION_SUBPIXEL_RENDERING in your `ftoption.h' file * in order to activate it. */ /**************************************************************************** * * @enum: * FT_LcdFilter * * @description: * A list of values to identify various types of LCD filters. * * @values: * FT_LCD_FILTER_NONE :: * Do not perform filtering. When used with subpixel rendering, this * results in sometimes severe color fringes. * * FT_LCD_FILTER_DEFAULT :: * The default filter reduces color fringes considerably, at the cost * of a slight blurriness in the output. * * FT_LCD_FILTER_LIGHT :: * The light filter is a variant that produces less blurriness at the * cost of slightly more color fringes than the default one. It might * be better, depending on taste, your monitor, or your personal vision. * * FT_LCD_FILTER_LEGACY :: * This filter corresponds to the original libXft color filter. It * provides high contrast output but can exhibit really bad color * fringes if glyphs are not extremely well hinted to the pixel grid. * In other words, it only works well if the TrueType bytecode * interpreter is enabled *and* high-quality hinted fonts are used. * * This filter is only provided for comparison purposes, and might be * disabled or stay unsupported in the future. * * @since: * 2.3.0 */ typedef enum FT_LcdFilter_ { FT_LCD_FILTER_NONE = 0, FT_LCD_FILTER_DEFAULT = 1, FT_LCD_FILTER_LIGHT = 2, FT_LCD_FILTER_LEGACY = 16, FT_LCD_FILTER_MAX /* do not remove */ } FT_LcdFilter; /************************************************************************** * * @func: * FT_Library_SetLcdFilter * * @description: * This function is used to apply color filtering to LCD decimated * bitmaps, like the ones used when calling @FT_Render_Glyph with * @FT_RENDER_MODE_LCD or @FT_RENDER_MODE_LCD_V. * * @input: * library :: * A handle to the target library instance. * * filter :: * The filter type. * * You can use @FT_LCD_FILTER_NONE here to disable this feature, or * @FT_LCD_FILTER_DEFAULT to use a default filter that should work * well on most LCD screens. * * @return: * FreeType error code. 0~means success. * * @note: * This feature is always disabled by default. Clients must make an * explicit call to this function with a `filter' value other than * @FT_LCD_FILTER_NONE in order to enable it. * * Due to *PATENTS* covering subpixel rendering, this function doesn't * do anything except returning `FT_Err_Unimplemented_Feature' if the * configuration macro FT_CONFIG_OPTION_SUBPIXEL_RENDERING is not * defined in your build of the library, which should correspond to all * default builds of FreeType. * * The filter affects glyph bitmaps rendered through @FT_Render_Glyph, * @FT_Outline_Get_Bitmap, @FT_Load_Glyph, and @FT_Load_Char. * * It does _not_ affect the output of @FT_Outline_Render and * @FT_Outline_Get_Bitmap. * * If this feature is activated, the dimensions of LCD glyph bitmaps are * either larger or taller than the dimensions of the corresponding * outline with regards to the pixel grid. For example, for * @FT_RENDER_MODE_LCD, the filter adds up to 3~pixels to the left, and * up to 3~pixels to the right. * * The bitmap offset values are adjusted correctly, so clients shouldn't * need to modify their layout and glyph positioning code when enabling * the filter. * * @since: * 2.3.0 */ FT_EXPORT( FT_Error ) FT_Library_SetLcdFilter( FT_Library library, FT_LcdFilter filter ); /************************************************************************** * * @func: * FT_Library_SetLcdFilterWeights * * @description: * Use this function to override the filter weights selected by * @FT_Library_SetLcdFilter. By default, FreeType uses the quintuple * (0x00, 0x55, 0x56, 0x55, 0x00) for FT_LCD_FILTER_LIGHT, and (0x10, * 0x40, 0x70, 0x40, 0x10) for FT_LCD_FILTER_DEFAULT and * FT_LCD_FILTER_LEGACY. * * @input: * library :: * A handle to the target library instance. * * weights :: * A pointer to an array; the function copies the first five bytes and * uses them to specify the filter weights. * * @return: * FreeType error code. 0~means success. * * @note: * Due to *PATENTS* covering subpixel rendering, this function doesn't * do anything except returning `FT_Err_Unimplemented_Feature' if the * configuration macro FT_CONFIG_OPTION_SUBPIXEL_RENDERING is not * defined in your build of the library, which should correspond to all * default builds of FreeType. * * This function must be called after @FT_Library_SetLcdFilter to have * any effect. * * @since: * 2.4.0 */ FT_EXPORT( FT_Error ) FT_Library_SetLcdFilterWeights( FT_Library library, unsigned char *weights ); /* */ FT_END_HEADER #endif /* __FT_LCD_FILTER_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/ftlist.h ================================================ /***************************************************************************/ /* */ /* ftlist.h */ /* */ /* Generic list support for FreeType (specification). */ /* */ /* Copyright 1996-2001, 2003, 2007, 2010 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /*************************************************************************/ /* */ /* This file implements functions relative to list processing. Its */ /* data structures are defined in `freetype.h'. */ /* */ /*************************************************************************/ #ifndef __FTLIST_H__ #define __FTLIST_H__ #include <ft2build.h> #include FT_FREETYPE_H #ifdef FREETYPE_H #error "freetype.h of FreeType 1 has been loaded!" #error "Please fix the directory search order for header files" #error "so that freetype.h of FreeType 2 is found first." #endif FT_BEGIN_HEADER /*************************************************************************/ /* */ /* <Section> */ /* list_processing */ /* */ /* <Title> */ /* List Processing */ /* */ /* <Abstract> */ /* Simple management of lists. */ /* */ /* <Description> */ /* This section contains various definitions related to list */ /* processing using doubly-linked nodes. */ /* */ /* <Order> */ /* FT_List */ /* FT_ListNode */ /* FT_ListRec */ /* FT_ListNodeRec */ /* */ /* FT_List_Add */ /* FT_List_Insert */ /* FT_List_Find */ /* FT_List_Remove */ /* FT_List_Up */ /* FT_List_Iterate */ /* FT_List_Iterator */ /* FT_List_Finalize */ /* FT_List_Destructor */ /* */ /*************************************************************************/ /*************************************************************************/ /* */ /* <Function> */ /* FT_List_Find */ /* */ /* <Description> */ /* Find the list node for a given listed object. */ /* */ /* <Input> */ /* list :: A pointer to the parent list. */ /* data :: The address of the listed object. */ /* */ /* <Return> */ /* List node. NULL if it wasn't found. */ /* */ FT_EXPORT( FT_ListNode ) FT_List_Find( FT_List list, void* data ); /*************************************************************************/ /* */ /* <Function> */ /* FT_List_Add */ /* */ /* <Description> */ /* Append an element to the end of a list. */ /* */ /* <InOut> */ /* list :: A pointer to the parent list. */ /* node :: The node to append. */ /* */ FT_EXPORT( void ) FT_List_Add( FT_List list, FT_ListNode node ); /*************************************************************************/ /* */ /* <Function> */ /* FT_List_Insert */ /* */ /* <Description> */ /* Insert an element at the head of a list. */ /* */ /* <InOut> */ /* list :: A pointer to parent list. */ /* node :: The node to insert. */ /* */ FT_EXPORT( void ) FT_List_Insert( FT_List list, FT_ListNode node ); /*************************************************************************/ /* */ /* <Function> */ /* FT_List_Remove */ /* */ /* <Description> */ /* Remove a node from a list. This function doesn't check whether */ /* the node is in the list! */ /* */ /* <Input> */ /* node :: The node to remove. */ /* */ /* <InOut> */ /* list :: A pointer to the parent list. */ /* */ FT_EXPORT( void ) FT_List_Remove( FT_List list, FT_ListNode node ); /*************************************************************************/ /* */ /* <Function> */ /* FT_List_Up */ /* */ /* <Description> */ /* Move a node to the head/top of a list. Used to maintain LRU */ /* lists. */ /* */ /* <InOut> */ /* list :: A pointer to the parent list. */ /* node :: The node to move. */ /* */ FT_EXPORT( void ) FT_List_Up( FT_List list, FT_ListNode node ); /*************************************************************************/ /* */ /* <FuncType> */ /* FT_List_Iterator */ /* */ /* <Description> */ /* An FT_List iterator function which is called during a list parse */ /* by @FT_List_Iterate. */ /* */ /* <Input> */ /* node :: The current iteration list node. */ /* */ /* user :: A typeless pointer passed to @FT_List_Iterate. */ /* Can be used to point to the iteration's state. */ /* */ typedef FT_Error (*FT_List_Iterator)( FT_ListNode node, void* user ); /*************************************************************************/ /* */ /* <Function> */ /* FT_List_Iterate */ /* */ /* <Description> */ /* Parse a list and calls a given iterator function on each element. */ /* Note that parsing is stopped as soon as one of the iterator calls */ /* returns a non-zero value. */ /* */ /* <Input> */ /* list :: A handle to the list. */ /* iterator :: An iterator function, called on each node of the list. */ /* user :: A user-supplied field which is passed as the second */ /* argument to the iterator. */ /* */ /* <Return> */ /* The result (a FreeType error code) of the last iterator call. */ /* */ FT_EXPORT( FT_Error ) FT_List_Iterate( FT_List list, FT_List_Iterator iterator, void* user ); /*************************************************************************/ /* */ /* <FuncType> */ /* FT_List_Destructor */ /* */ /* <Description> */ /* An @FT_List iterator function which is called during a list */ /* finalization by @FT_List_Finalize to destroy all elements in a */ /* given list. */ /* */ /* <Input> */ /* system :: The current system object. */ /* */ /* data :: The current object to destroy. */ /* */ /* user :: A typeless pointer passed to @FT_List_Iterate. It can */ /* be used to point to the iteration's state. */ /* */ typedef void (*FT_List_Destructor)( FT_Memory memory, void* data, void* user ); /*************************************************************************/ /* */ /* <Function> */ /* FT_List_Finalize */ /* */ /* <Description> */ /* Destroy all elements in the list as well as the list itself. */ /* */ /* <Input> */ /* list :: A handle to the list. */ /* */ /* destroy :: A list destructor that will be applied to each element */ /* of the list. */ /* */ /* memory :: The current memory object which handles deallocation. */ /* */ /* user :: A user-supplied field which is passed as the last */ /* argument to the destructor. */ /* */ /* <Note> */ /* This function expects that all nodes added by @FT_List_Add or */ /* @FT_List_Insert have been dynamically allocated. */ /* */ FT_EXPORT( void ) FT_List_Finalize( FT_List list, FT_List_Destructor destroy, FT_Memory memory, void* user ); /* */ FT_END_HEADER #endif /* __FTLIST_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/ftlzw.h ================================================ /***************************************************************************/ /* */ /* ftlzw.h */ /* */ /* LZW-compressed stream support. */ /* */ /* Copyright 2004, 2006 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __FTLZW_H__ #define __FTLZW_H__ #include <ft2build.h> #include FT_FREETYPE_H #ifdef FREETYPE_H #error "freetype.h of FreeType 1 has been loaded!" #error "Please fix the directory search order for header files" #error "so that freetype.h of FreeType 2 is found first." #endif FT_BEGIN_HEADER /*************************************************************************/ /* */ /* <Section> */ /* lzw */ /* */ /* <Title> */ /* LZW Streams */ /* */ /* <Abstract> */ /* Using LZW-compressed font files. */ /* */ /* <Description> */ /* This section contains the declaration of LZW-specific functions. */ /* */ /*************************************************************************/ /************************************************************************ * * @function: * FT_Stream_OpenLZW * * @description: * Open a new stream to parse LZW-compressed font files. This is * mainly used to support the compressed `*.pcf.Z' fonts that come * with XFree86. * * @input: * stream :: The target embedding stream. * * source :: The source stream. * * @return: * FreeType error code. 0~means success. * * @note: * The source stream must be opened _before_ calling this function. * * Calling the internal function `FT_Stream_Close' on the new stream will * *not* call `FT_Stream_Close' on the source stream. None of the stream * objects will be released to the heap. * * The stream implementation is very basic and resets the decompression * process each time seeking backwards is needed within the stream * * In certain builds of the library, LZW compression recognition is * automatically handled when calling @FT_New_Face or @FT_Open_Face. * This means that if no font driver is capable of handling the raw * compressed file, the library will try to open a LZW stream from it * and re-open the face with it. * * This function may return `FT_Err_Unimplemented_Feature' if your build * of FreeType was not compiled with LZW support. */ FT_EXPORT( FT_Error ) FT_Stream_OpenLZW( FT_Stream stream, FT_Stream source ); /* */ FT_END_HEADER #endif /* __FTLZW_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/ftmac.h ================================================ /***************************************************************************/ /* */ /* ftmac.h */ /* */ /* Additional Mac-specific API. */ /* */ /* Copyright 1996-2001, 2004, 2006, 2007 by */ /* Just van Rossum, David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /***************************************************************************/ /* */ /* NOTE: Include this file after <freetype/freetype.h> and after any */ /* Mac-specific headers (because this header uses Mac types such as */ /* Handle, FSSpec, FSRef, etc.) */ /* */ /***************************************************************************/ #ifndef __FTMAC_H__ #define __FTMAC_H__ #include <ft2build.h> FT_BEGIN_HEADER /* gcc-3.4.1 and later can warn about functions tagged as deprecated */ #ifndef FT_DEPRECATED_ATTRIBUTE #if defined(__GNUC__) && \ ((__GNUC__ >= 4) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1))) #define FT_DEPRECATED_ATTRIBUTE __attribute__((deprecated)) #else #define FT_DEPRECATED_ATTRIBUTE #endif #endif /*************************************************************************/ /* */ /* <Section> */ /* mac_specific */ /* */ /* <Title> */ /* Mac Specific Interface */ /* */ /* <Abstract> */ /* Only available on the Macintosh. */ /* */ /* <Description> */ /* The following definitions are only available if FreeType is */ /* compiled on a Macintosh. */ /* */ /*************************************************************************/ /*************************************************************************/ /* */ /* <Function> */ /* FT_New_Face_From_FOND */ /* */ /* <Description> */ /* Create a new face object from a FOND resource. */ /* */ /* <InOut> */ /* library :: A handle to the library resource. */ /* */ /* <Input> */ /* fond :: A FOND resource. */ /* */ /* face_index :: Only supported for the -1 `sanity check' special */ /* case. */ /* */ /* <Output> */ /* aface :: A handle to a new face object. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ /* <Notes> */ /* This function can be used to create @FT_Face objects from fonts */ /* that are installed in the system as follows. */ /* */ /* { */ /* fond = GetResource( 'FOND', fontName ); */ /* error = FT_New_Face_From_FOND( library, fond, 0, &face ); */ /* } */ /* */ FT_EXPORT( FT_Error ) FT_New_Face_From_FOND( FT_Library library, Handle fond, FT_Long face_index, FT_Face *aface ) FT_DEPRECATED_ATTRIBUTE; /*************************************************************************/ /* */ /* <Function> */ /* FT_GetFile_From_Mac_Name */ /* */ /* <Description> */ /* Return an FSSpec for the disk file containing the named font. */ /* */ /* <Input> */ /* fontName :: Mac OS name of the font (e.g., Times New Roman */ /* Bold). */ /* */ /* <Output> */ /* pathSpec :: FSSpec to the file. For passing to */ /* @FT_New_Face_From_FSSpec. */ /* */ /* face_index :: Index of the face. For passing to */ /* @FT_New_Face_From_FSSpec. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ FT_EXPORT( FT_Error ) FT_GetFile_From_Mac_Name( const char* fontName, FSSpec* pathSpec, FT_Long* face_index ) FT_DEPRECATED_ATTRIBUTE; /*************************************************************************/ /* */ /* <Function> */ /* FT_GetFile_From_Mac_ATS_Name */ /* */ /* <Description> */ /* Return an FSSpec for the disk file containing the named font. */ /* */ /* <Input> */ /* fontName :: Mac OS name of the font in ATS framework. */ /* */ /* <Output> */ /* pathSpec :: FSSpec to the file. For passing to */ /* @FT_New_Face_From_FSSpec. */ /* */ /* face_index :: Index of the face. For passing to */ /* @FT_New_Face_From_FSSpec. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ FT_EXPORT( FT_Error ) FT_GetFile_From_Mac_ATS_Name( const char* fontName, FSSpec* pathSpec, FT_Long* face_index ) FT_DEPRECATED_ATTRIBUTE; /*************************************************************************/ /* */ /* <Function> */ /* FT_GetFilePath_From_Mac_ATS_Name */ /* */ /* <Description> */ /* Return a pathname of the disk file and face index for given font */ /* name which is handled by ATS framework. */ /* */ /* <Input> */ /* fontName :: Mac OS name of the font in ATS framework. */ /* */ /* <Output> */ /* path :: Buffer to store pathname of the file. For passing */ /* to @FT_New_Face. The client must allocate this */ /* buffer before calling this function. */ /* */ /* maxPathSize :: Lengths of the buffer `path' that client allocated. */ /* */ /* face_index :: Index of the face. For passing to @FT_New_Face. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ FT_EXPORT( FT_Error ) FT_GetFilePath_From_Mac_ATS_Name( const char* fontName, UInt8* path, UInt32 maxPathSize, FT_Long* face_index ) FT_DEPRECATED_ATTRIBUTE; /*************************************************************************/ /* */ /* <Function> */ /* FT_New_Face_From_FSSpec */ /* */ /* <Description> */ /* Create a new face object from a given resource and typeface index */ /* using an FSSpec to the font file. */ /* */ /* <InOut> */ /* library :: A handle to the library resource. */ /* */ /* <Input> */ /* spec :: FSSpec to the font file. */ /* */ /* face_index :: The index of the face within the resource. The */ /* first face has index~0. */ /* <Output> */ /* aface :: A handle to a new face object. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ /* <Note> */ /* @FT_New_Face_From_FSSpec is identical to @FT_New_Face except */ /* it accepts an FSSpec instead of a path. */ /* */ FT_EXPORT( FT_Error ) FT_New_Face_From_FSSpec( FT_Library library, const FSSpec *spec, FT_Long face_index, FT_Face *aface ) FT_DEPRECATED_ATTRIBUTE; /*************************************************************************/ /* */ /* <Function> */ /* FT_New_Face_From_FSRef */ /* */ /* <Description> */ /* Create a new face object from a given resource and typeface index */ /* using an FSRef to the font file. */ /* */ /* <InOut> */ /* library :: A handle to the library resource. */ /* */ /* <Input> */ /* spec :: FSRef to the font file. */ /* */ /* face_index :: The index of the face within the resource. The */ /* first face has index~0. */ /* <Output> */ /* aface :: A handle to a new face object. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ /* <Note> */ /* @FT_New_Face_From_FSRef is identical to @FT_New_Face except */ /* it accepts an FSRef instead of a path. */ /* */ FT_EXPORT( FT_Error ) FT_New_Face_From_FSRef( FT_Library library, const FSRef *ref, FT_Long face_index, FT_Face *aface ) FT_DEPRECATED_ATTRIBUTE; /* */ FT_END_HEADER #endif /* __FTMAC_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/ftmm.h ================================================ /***************************************************************************/ /* */ /* ftmm.h */ /* */ /* FreeType Multiple Master font interface (specification). */ /* */ /* Copyright 1996-2001, 2003, 2004, 2006, 2009 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __FTMM_H__ #define __FTMM_H__ #include <ft2build.h> #include FT_TYPE1_TABLES_H FT_BEGIN_HEADER /*************************************************************************/ /* */ /* <Section> */ /* multiple_masters */ /* */ /* <Title> */ /* Multiple Masters */ /* */ /* <Abstract> */ /* How to manage Multiple Masters fonts. */ /* */ /* <Description> */ /* The following types and functions are used to manage Multiple */ /* Master fonts, i.e., the selection of specific design instances by */ /* setting design axis coordinates. */ /* */ /* George Williams has extended this interface to make it work with */ /* both Type~1 Multiple Masters fonts and GX distortable (var) */ /* fonts. Some of these routines only work with MM fonts, others */ /* will work with both types. They are similar enough that a */ /* consistent interface makes sense. */ /* */ /*************************************************************************/ /*************************************************************************/ /* */ /* <Struct> */ /* FT_MM_Axis */ /* */ /* <Description> */ /* A simple structure used to model a given axis in design space for */ /* Multiple Masters fonts. */ /* */ /* This structure can't be used for GX var fonts. */ /* */ /* <Fields> */ /* name :: The axis's name. */ /* */ /* minimum :: The axis's minimum design coordinate. */ /* */ /* maximum :: The axis's maximum design coordinate. */ /* */ typedef struct FT_MM_Axis_ { FT_String* name; FT_Long minimum; FT_Long maximum; } FT_MM_Axis; /*************************************************************************/ /* */ /* <Struct> */ /* FT_Multi_Master */ /* */ /* <Description> */ /* A structure used to model the axes and space of a Multiple Masters */ /* font. */ /* */ /* This structure can't be used for GX var fonts. */ /* */ /* <Fields> */ /* num_axis :: Number of axes. Cannot exceed~4. */ /* */ /* num_designs :: Number of designs; should be normally 2^num_axis */ /* even though the Type~1 specification strangely */ /* allows for intermediate designs to be present. This */ /* number cannot exceed~16. */ /* */ /* axis :: A table of axis descriptors. */ /* */ typedef struct FT_Multi_Master_ { FT_UInt num_axis; FT_UInt num_designs; FT_MM_Axis axis[T1_MAX_MM_AXIS]; } FT_Multi_Master; /*************************************************************************/ /* */ /* <Struct> */ /* FT_Var_Axis */ /* */ /* <Description> */ /* A simple structure used to model a given axis in design space for */ /* Multiple Masters and GX var fonts. */ /* */ /* <Fields> */ /* name :: The axis's name. */ /* Not always meaningful for GX. */ /* */ /* minimum :: The axis's minimum design coordinate. */ /* */ /* def :: The axis's default design coordinate. */ /* FreeType computes meaningful default values for MM; it */ /* is then an integer value, not in 16.16 format. */ /* */ /* maximum :: The axis's maximum design coordinate. */ /* */ /* tag :: The axis's tag (the GX equivalent to `name'). */ /* FreeType provides default values for MM if possible. */ /* */ /* strid :: The entry in `name' table (another GX version of */ /* `name'). */ /* Not meaningful for MM. */ /* */ typedef struct FT_Var_Axis_ { FT_String* name; FT_Fixed minimum; FT_Fixed def; FT_Fixed maximum; FT_ULong tag; FT_UInt strid; } FT_Var_Axis; /*************************************************************************/ /* */ /* <Struct> */ /* FT_Var_Named_Style */ /* */ /* <Description> */ /* A simple structure used to model a named style in a GX var font. */ /* */ /* This structure can't be used for MM fonts. */ /* */ /* <Fields> */ /* coords :: The design coordinates for this style. */ /* This is an array with one entry for each axis. */ /* */ /* strid :: The entry in `name' table identifying this style. */ /* */ typedef struct FT_Var_Named_Style_ { FT_Fixed* coords; FT_UInt strid; } FT_Var_Named_Style; /*************************************************************************/ /* */ /* <Struct> */ /* FT_MM_Var */ /* */ /* <Description> */ /* A structure used to model the axes and space of a Multiple Masters */ /* or GX var distortable font. */ /* */ /* Some fields are specific to one format and not to the other. */ /* */ /* <Fields> */ /* num_axis :: The number of axes. The maximum value is~4 for */ /* MM; no limit in GX. */ /* */ /* num_designs :: The number of designs; should be normally */ /* 2^num_axis for MM fonts. Not meaningful for GX */ /* (where every glyph could have a different */ /* number of designs). */ /* */ /* num_namedstyles :: The number of named styles; only meaningful for */ /* GX which allows certain design coordinates to */ /* have a string ID (in the `name' table) */ /* associated with them. The font can tell the */ /* user that, for example, Weight=1.5 is `Bold'. */ /* */ /* axis :: A table of axis descriptors. */ /* GX fonts contain slightly more data than MM. */ /* */ /* namedstyles :: A table of named styles. */ /* Only meaningful with GX. */ /* */ typedef struct FT_MM_Var_ { FT_UInt num_axis; FT_UInt num_designs; FT_UInt num_namedstyles; FT_Var_Axis* axis; FT_Var_Named_Style* namedstyle; } FT_MM_Var; /* */ /*************************************************************************/ /* */ /* <Function> */ /* FT_Get_Multi_Master */ /* */ /* <Description> */ /* Retrieve the Multiple Master descriptor of a given font. */ /* */ /* This function can't be used with GX fonts. */ /* */ /* <Input> */ /* face :: A handle to the source face. */ /* */ /* <Output> */ /* amaster :: The Multiple Masters descriptor. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ FT_EXPORT( FT_Error ) FT_Get_Multi_Master( FT_Face face, FT_Multi_Master *amaster ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Get_MM_Var */ /* */ /* <Description> */ /* Retrieve the Multiple Master/GX var descriptor of a given font. */ /* */ /* <Input> */ /* face :: A handle to the source face. */ /* */ /* <Output> */ /* amaster :: The Multiple Masters/GX var descriptor. */ /* Allocates a data structure, which the user must free */ /* (a single call to FT_FREE will do it). */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ FT_EXPORT( FT_Error ) FT_Get_MM_Var( FT_Face face, FT_MM_Var* *amaster ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Set_MM_Design_Coordinates */ /* */ /* <Description> */ /* For Multiple Masters fonts, choose an interpolated font design */ /* through design coordinates. */ /* */ /* This function can't be used with GX fonts. */ /* */ /* <InOut> */ /* face :: A handle to the source face. */ /* */ /* <Input> */ /* num_coords :: The number of design coordinates (must be equal to */ /* the number of axes in the font). */ /* */ /* coords :: An array of design coordinates. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ FT_EXPORT( FT_Error ) FT_Set_MM_Design_Coordinates( FT_Face face, FT_UInt num_coords, FT_Long* coords ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Set_Var_Design_Coordinates */ /* */ /* <Description> */ /* For Multiple Master or GX Var fonts, choose an interpolated font */ /* design through design coordinates. */ /* */ /* <InOut> */ /* face :: A handle to the source face. */ /* */ /* <Input> */ /* num_coords :: The number of design coordinates (must be equal to */ /* the number of axes in the font). */ /* */ /* coords :: An array of design coordinates. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ FT_EXPORT( FT_Error ) FT_Set_Var_Design_Coordinates( FT_Face face, FT_UInt num_coords, FT_Fixed* coords ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Set_MM_Blend_Coordinates */ /* */ /* <Description> */ /* For Multiple Masters and GX var fonts, choose an interpolated font */ /* design through normalized blend coordinates. */ /* */ /* <InOut> */ /* face :: A handle to the source face. */ /* */ /* <Input> */ /* num_coords :: The number of design coordinates (must be equal to */ /* the number of axes in the font). */ /* */ /* coords :: The design coordinates array (each element must be */ /* between 0 and 1.0). */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ FT_EXPORT( FT_Error ) FT_Set_MM_Blend_Coordinates( FT_Face face, FT_UInt num_coords, FT_Fixed* coords ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Set_Var_Blend_Coordinates */ /* */ /* <Description> */ /* This is another name of @FT_Set_MM_Blend_Coordinates. */ /* */ FT_EXPORT( FT_Error ) FT_Set_Var_Blend_Coordinates( FT_Face face, FT_UInt num_coords, FT_Fixed* coords ); /* */ FT_END_HEADER #endif /* __FTMM_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/ftmodapi.h ================================================ /***************************************************************************/ /* */ /* ftmodapi.h */ /* */ /* FreeType modules public interface (specification). */ /* */ /* Copyright 1996-2001, 2002, 2003, 2006, 2008, 2009, 2010 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __FTMODAPI_H__ #define __FTMODAPI_H__ #include <ft2build.h> #include FT_FREETYPE_H #ifdef FREETYPE_H #error "freetype.h of FreeType 1 has been loaded!" #error "Please fix the directory search order for header files" #error "so that freetype.h of FreeType 2 is found first." #endif FT_BEGIN_HEADER /*************************************************************************/ /* */ /* <Section> */ /* module_management */ /* */ /* <Title> */ /* Module Management */ /* */ /* <Abstract> */ /* How to add, upgrade, and remove modules from FreeType. */ /* */ /* <Description> */ /* The definitions below are used to manage modules within FreeType. */ /* Modules can be added, upgraded, and removed at runtime. */ /* */ /*************************************************************************/ /* module bit flags */ #define FT_MODULE_FONT_DRIVER 1 /* this module is a font driver */ #define FT_MODULE_RENDERER 2 /* this module is a renderer */ #define FT_MODULE_HINTER 4 /* this module is a glyph hinter */ #define FT_MODULE_STYLER 8 /* this module is a styler */ #define FT_MODULE_DRIVER_SCALABLE 0x100 /* the driver supports */ /* scalable fonts */ #define FT_MODULE_DRIVER_NO_OUTLINES 0x200 /* the driver does not */ /* support vector outlines */ #define FT_MODULE_DRIVER_HAS_HINTER 0x400 /* the driver provides its */ /* own hinter */ /* deprecated values */ #define ft_module_font_driver FT_MODULE_FONT_DRIVER #define ft_module_renderer FT_MODULE_RENDERER #define ft_module_hinter FT_MODULE_HINTER #define ft_module_styler FT_MODULE_STYLER #define ft_module_driver_scalable FT_MODULE_DRIVER_SCALABLE #define ft_module_driver_no_outlines FT_MODULE_DRIVER_NO_OUTLINES #define ft_module_driver_has_hinter FT_MODULE_DRIVER_HAS_HINTER typedef FT_Pointer FT_Module_Interface; /*************************************************************************/ /* */ /* <FuncType> */ /* FT_Module_Constructor */ /* */ /* <Description> */ /* A function used to initialize (not create) a new module object. */ /* */ /* <Input> */ /* module :: The module to initialize. */ /* */ typedef FT_Error (*FT_Module_Constructor)( FT_Module module ); /*************************************************************************/ /* */ /* <FuncType> */ /* FT_Module_Destructor */ /* */ /* <Description> */ /* A function used to finalize (not destroy) a given module object. */ /* */ /* <Input> */ /* module :: The module to finalize. */ /* */ typedef void (*FT_Module_Destructor)( FT_Module module ); /*************************************************************************/ /* */ /* <FuncType> */ /* FT_Module_Requester */ /* */ /* <Description> */ /* A function used to query a given module for a specific interface. */ /* */ /* <Input> */ /* module :: The module to finalize. */ /* */ /* name :: The name of the interface in the module. */ /* */ typedef FT_Module_Interface (*FT_Module_Requester)( FT_Module module, const char* name ); /*************************************************************************/ /* */ /* <Struct> */ /* FT_Module_Class */ /* */ /* <Description> */ /* The module class descriptor. */ /* */ /* <Fields> */ /* module_flags :: Bit flags describing the module. */ /* */ /* module_size :: The size of one module object/instance in */ /* bytes. */ /* */ /* module_name :: The name of the module. */ /* */ /* module_version :: The version, as a 16.16 fixed number */ /* (major.minor). */ /* */ /* module_requires :: The version of FreeType this module requires, */ /* as a 16.16 fixed number (major.minor). Starts */ /* at version 2.0, i.e., 0x20000. */ /* */ /* module_init :: The initializing function. */ /* */ /* module_done :: The finalizing function. */ /* */ /* get_interface :: The interface requesting function. */ /* */ typedef struct FT_Module_Class_ { FT_ULong module_flags; FT_Long module_size; const FT_String* module_name; FT_Fixed module_version; FT_Fixed module_requires; const void* module_interface; FT_Module_Constructor module_init; FT_Module_Destructor module_done; FT_Module_Requester get_interface; } FT_Module_Class; /*************************************************************************/ /* */ /* <Function> */ /* FT_Add_Module */ /* */ /* <Description> */ /* Add a new module to a given library instance. */ /* */ /* <InOut> */ /* library :: A handle to the library object. */ /* */ /* <Input> */ /* clazz :: A pointer to class descriptor for the module. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ /* <Note> */ /* An error will be returned if a module already exists by that name, */ /* or if the module requires a version of FreeType that is too great. */ /* */ FT_EXPORT( FT_Error ) FT_Add_Module( FT_Library library, const FT_Module_Class* clazz ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Get_Module */ /* */ /* <Description> */ /* Find a module by its name. */ /* */ /* <Input> */ /* library :: A handle to the library object. */ /* */ /* module_name :: The module's name (as an ASCII string). */ /* */ /* <Return> */ /* A module handle. 0~if none was found. */ /* */ /* <Note> */ /* FreeType's internal modules aren't documented very well, and you */ /* should look up the source code for details. */ /* */ FT_EXPORT( FT_Module ) FT_Get_Module( FT_Library library, const char* module_name ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Remove_Module */ /* */ /* <Description> */ /* Remove a given module from a library instance. */ /* */ /* <InOut> */ /* library :: A handle to a library object. */ /* */ /* <Input> */ /* module :: A handle to a module object. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ /* <Note> */ /* The module object is destroyed by the function in case of success. */ /* */ FT_EXPORT( FT_Error ) FT_Remove_Module( FT_Library library, FT_Module module ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Reference_Library */ /* */ /* <Description> */ /* A counter gets initialized to~1 at the time an @FT_Library */ /* structure is created. This function increments the counter. */ /* @FT_Done_Library then only destroys a library if the counter is~1, */ /* otherwise it simply decrements the counter. */ /* */ /* This function helps in managing life-cycles of structures which */ /* reference @FT_Library objects. */ /* */ /* <Input> */ /* library :: A handle to a target library object. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ /* <Since> */ /* 2.4.2 */ /* */ FT_EXPORT( FT_Error ) FT_Reference_Library( FT_Library library ); /*************************************************************************/ /* */ /* <Function> */ /* FT_New_Library */ /* */ /* <Description> */ /* This function is used to create a new FreeType library instance */ /* from a given memory object. It is thus possible to use libraries */ /* with distinct memory allocators within the same program. */ /* */ /* Normally, you would call this function (followed by a call to */ /* @FT_Add_Default_Modules or a series of calls to @FT_Add_Module) */ /* instead of @FT_Init_FreeType to initialize the FreeType library. */ /* */ /* Don't use @FT_Done_FreeType but @FT_Done_Library to destroy a */ /* library instance. */ /* */ /* <Input> */ /* memory :: A handle to the original memory object. */ /* */ /* <Output> */ /* alibrary :: A pointer to handle of a new library object. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ /* <Note> */ /* See the discussion of reference counters in the description of */ /* @FT_Reference_Library. */ /* */ FT_EXPORT( FT_Error ) FT_New_Library( FT_Memory memory, FT_Library *alibrary ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Done_Library */ /* */ /* <Description> */ /* Discard a given library object. This closes all drivers and */ /* discards all resource objects. */ /* */ /* <Input> */ /* library :: A handle to the target library. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ /* <Note> */ /* See the discussion of reference counters in the description of */ /* @FT_Reference_Library. */ /* */ FT_EXPORT( FT_Error ) FT_Done_Library( FT_Library library ); /* */ typedef void (*FT_DebugHook_Func)( void* arg ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Set_Debug_Hook */ /* */ /* <Description> */ /* Set a debug hook function for debugging the interpreter of a font */ /* format. */ /* */ /* <InOut> */ /* library :: A handle to the library object. */ /* */ /* <Input> */ /* hook_index :: The index of the debug hook. You should use the */ /* values defined in `ftobjs.h', e.g., */ /* `FT_DEBUG_HOOK_TRUETYPE'. */ /* */ /* debug_hook :: The function used to debug the interpreter. */ /* */ /* <Note> */ /* Currently, four debug hook slots are available, but only two (for */ /* the TrueType and the Type~1 interpreter) are defined. */ /* */ /* Since the internal headers of FreeType are no longer installed, */ /* the symbol `FT_DEBUG_HOOK_TRUETYPE' isn't available publicly. */ /* This is a bug and will be fixed in a forthcoming release. */ /* */ FT_EXPORT( void ) FT_Set_Debug_Hook( FT_Library library, FT_UInt hook_index, FT_DebugHook_Func debug_hook ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Add_Default_Modules */ /* */ /* <Description> */ /* Add the set of default drivers to a given library object. */ /* This is only useful when you create a library object with */ /* @FT_New_Library (usually to plug a custom memory manager). */ /* */ /* <InOut> */ /* library :: A handle to a new library object. */ /* */ FT_EXPORT( void ) FT_Add_Default_Modules( FT_Library library ); /************************************************************************** * * @section: * truetype_engine * * @title: * The TrueType Engine * * @abstract: * TrueType bytecode support. * * @description: * This section contains a function used to query the level of TrueType * bytecode support compiled in this version of the library. * */ /************************************************************************** * * @enum: * FT_TrueTypeEngineType * * @description: * A list of values describing which kind of TrueType bytecode * engine is implemented in a given FT_Library instance. It is used * by the @FT_Get_TrueType_Engine_Type function. * * @values: * FT_TRUETYPE_ENGINE_TYPE_NONE :: * The library doesn't implement any kind of bytecode interpreter. * * FT_TRUETYPE_ENGINE_TYPE_UNPATENTED :: * The library implements a bytecode interpreter that doesn't * support the patented operations of the TrueType virtual machine. * * Its main use is to load certain Asian fonts which position and * scale glyph components with bytecode instructions. It produces * bad output for most other fonts. * * FT_TRUETYPE_ENGINE_TYPE_PATENTED :: * The library implements a bytecode interpreter that covers * the full instruction set of the TrueType virtual machine (this * was governed by patents until May 2010, hence the name). * * @since: * 2.2 * */ typedef enum FT_TrueTypeEngineType_ { FT_TRUETYPE_ENGINE_TYPE_NONE = 0, FT_TRUETYPE_ENGINE_TYPE_UNPATENTED, FT_TRUETYPE_ENGINE_TYPE_PATENTED } FT_TrueTypeEngineType; /************************************************************************** * * @func: * FT_Get_TrueType_Engine_Type * * @description: * Return an @FT_TrueTypeEngineType value to indicate which level of * the TrueType virtual machine a given library instance supports. * * @input: * library :: * A library instance. * * @return: * A value indicating which level is supported. * * @since: * 2.2 * */ FT_EXPORT( FT_TrueTypeEngineType ) FT_Get_TrueType_Engine_Type( FT_Library library ); /* */ FT_END_HEADER #endif /* __FTMODAPI_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/ftmoderr.h ================================================ /***************************************************************************/ /* */ /* ftmoderr.h */ /* */ /* FreeType module error offsets (specification). */ /* */ /* Copyright 2001, 2002, 2003, 2004, 2005, 2010 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /*************************************************************************/ /* */ /* This file is used to define the FreeType module error offsets. */ /* */ /* The lower byte gives the error code, the higher byte gives the */ /* module. The base module has error offset 0. For example, the error */ /* `FT_Err_Invalid_File_Format' has value 0x003, the error */ /* `TT_Err_Invalid_File_Format' has value 0x1103, the error */ /* `T1_Err_Invalid_File_Format' has value 0x1203, etc. */ /* */ /* Undefine the macro FT_CONFIG_OPTION_USE_MODULE_ERRORS in ftoption.h */ /* to make the higher byte always zero (disabling the module error */ /* mechanism). */ /* */ /* It can also be used to create a module error message table easily */ /* with something like */ /* */ /* { */ /* #undef __FTMODERR_H__ */ /* #define FT_MODERRDEF( e, v, s ) { FT_Mod_Err_ ## e, s }, */ /* #define FT_MODERR_START_LIST { */ /* #define FT_MODERR_END_LIST { 0, 0 } }; */ /* */ /* const struct */ /* { */ /* int mod_err_offset; */ /* const char* mod_err_msg */ /* } ft_mod_errors[] = */ /* */ /* #include FT_MODULE_ERRORS_H */ /* } */ /* */ /* To use such a table, all errors must be ANDed with 0xFF00 to remove */ /* the error code. */ /* */ /*************************************************************************/ #ifndef __FTMODERR_H__ #define __FTMODERR_H__ /*******************************************************************/ /*******************************************************************/ /***** *****/ /***** SETUP MACROS *****/ /***** *****/ /*******************************************************************/ /*******************************************************************/ #undef FT_NEED_EXTERN_C #ifndef FT_MODERRDEF #ifdef FT_CONFIG_OPTION_USE_MODULE_ERRORS #define FT_MODERRDEF( e, v, s ) FT_Mod_Err_ ## e = v, #else #define FT_MODERRDEF( e, v, s ) FT_Mod_Err_ ## e = 0, #endif #define FT_MODERR_START_LIST enum { #define FT_MODERR_END_LIST FT_Mod_Err_Max }; #ifdef __cplusplus #define FT_NEED_EXTERN_C extern "C" { #endif #endif /* !FT_MODERRDEF */ /*******************************************************************/ /*******************************************************************/ /***** *****/ /***** LIST MODULE ERROR BASES *****/ /***** *****/ /*******************************************************************/ /*******************************************************************/ #ifdef FT_MODERR_START_LIST FT_MODERR_START_LIST #endif FT_MODERRDEF( Base, 0x000, "base module" ) FT_MODERRDEF( Autofit, 0x100, "autofitter module" ) FT_MODERRDEF( BDF, 0x200, "BDF module" ) FT_MODERRDEF( Bzip2, 0x300, "Bzip2 module" ) FT_MODERRDEF( Cache, 0x400, "cache module" ) FT_MODERRDEF( CFF, 0x500, "CFF module" ) FT_MODERRDEF( CID, 0x600, "CID module" ) FT_MODERRDEF( Gzip, 0x700, "Gzip module" ) FT_MODERRDEF( LZW, 0x800, "LZW module" ) FT_MODERRDEF( OTvalid, 0x900, "OpenType validation module" ) FT_MODERRDEF( PCF, 0xA00, "PCF module" ) FT_MODERRDEF( PFR, 0xB00, "PFR module" ) FT_MODERRDEF( PSaux, 0xC00, "PS auxiliary module" ) FT_MODERRDEF( PShinter, 0xD00, "PS hinter module" ) FT_MODERRDEF( PSnames, 0xE00, "PS names module" ) FT_MODERRDEF( Raster, 0xF00, "raster module" ) FT_MODERRDEF( SFNT, 0x1000, "SFNT module" ) FT_MODERRDEF( Smooth, 0x1100, "smooth raster module" ) FT_MODERRDEF( TrueType, 0x1200, "TrueType module" ) FT_MODERRDEF( Type1, 0x1300, "Type 1 module" ) FT_MODERRDEF( Type42, 0x1400, "Type 42 module" ) FT_MODERRDEF( Winfonts, 0x1500, "Windows FON/FNT module" ) #ifdef FT_MODERR_END_LIST FT_MODERR_END_LIST #endif /*******************************************************************/ /*******************************************************************/ /***** *****/ /***** CLEANUP *****/ /***** *****/ /*******************************************************************/ /*******************************************************************/ #ifdef FT_NEED_EXTERN_C } #endif #undef FT_MODERR_START_LIST #undef FT_MODERR_END_LIST #undef FT_MODERRDEF #undef FT_NEED_EXTERN_C #endif /* __FTMODERR_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/ftotval.h ================================================ /***************************************************************************/ /* */ /* ftotval.h */ /* */ /* FreeType API for validating OpenType tables (specification). */ /* */ /* Copyright 2004, 2005, 2006, 2007 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /***************************************************************************/ /* */ /* */ /* Warning: This module might be moved to a different library in the */ /* future to avoid a tight dependency between FreeType and the */ /* OpenType specification. */ /* */ /* */ /***************************************************************************/ #ifndef __FTOTVAL_H__ #define __FTOTVAL_H__ #include <ft2build.h> #include FT_FREETYPE_H #ifdef FREETYPE_H #error "freetype.h of FreeType 1 has been loaded!" #error "Please fix the directory search order for header files" #error "so that freetype.h of FreeType 2 is found first." #endif FT_BEGIN_HEADER /*************************************************************************/ /* */ /* <Section> */ /* ot_validation */ /* */ /* <Title> */ /* OpenType Validation */ /* */ /* <Abstract> */ /* An API to validate OpenType tables. */ /* */ /* <Description> */ /* This section contains the declaration of functions to validate */ /* some OpenType tables (BASE, GDEF, GPOS, GSUB, JSTF, MATH). */ /* */ /*************************************************************************/ /********************************************************************** * * @enum: * FT_VALIDATE_OTXXX * * @description: * A list of bit-field constants used with @FT_OpenType_Validate to * indicate which OpenType tables should be validated. * * @values: * FT_VALIDATE_BASE :: * Validate BASE table. * * FT_VALIDATE_GDEF :: * Validate GDEF table. * * FT_VALIDATE_GPOS :: * Validate GPOS table. * * FT_VALIDATE_GSUB :: * Validate GSUB table. * * FT_VALIDATE_JSTF :: * Validate JSTF table. * * FT_VALIDATE_MATH :: * Validate MATH table. * * FT_VALIDATE_OT :: * Validate all OpenType tables (BASE, GDEF, GPOS, GSUB, JSTF, MATH). * */ #define FT_VALIDATE_BASE 0x0100 #define FT_VALIDATE_GDEF 0x0200 #define FT_VALIDATE_GPOS 0x0400 #define FT_VALIDATE_GSUB 0x0800 #define FT_VALIDATE_JSTF 0x1000 #define FT_VALIDATE_MATH 0x2000 #define FT_VALIDATE_OT FT_VALIDATE_BASE | \ FT_VALIDATE_GDEF | \ FT_VALIDATE_GPOS | \ FT_VALIDATE_GSUB | \ FT_VALIDATE_JSTF | \ FT_VALIDATE_MATH /* */ /********************************************************************** * * @function: * FT_OpenType_Validate * * @description: * Validate various OpenType tables to assure that all offsets and * indices are valid. The idea is that a higher-level library which * actually does the text layout can access those tables without * error checking (which can be quite time consuming). * * @input: * face :: * A handle to the input face. * * validation_flags :: * A bit field which specifies the tables to be validated. See * @FT_VALIDATE_OTXXX for possible values. * * @output: * BASE_table :: * A pointer to the BASE table. * * GDEF_table :: * A pointer to the GDEF table. * * GPOS_table :: * A pointer to the GPOS table. * * GSUB_table :: * A pointer to the GSUB table. * * JSTF_table :: * A pointer to the JSTF table. * * @return: * FreeType error code. 0~means success. * * @note: * This function only works with OpenType fonts, returning an error * otherwise. * * After use, the application should deallocate the five tables with * @FT_OpenType_Free. A NULL value indicates that the table either * doesn't exist in the font, or the application hasn't asked for * validation. */ FT_EXPORT( FT_Error ) FT_OpenType_Validate( FT_Face face, FT_UInt validation_flags, FT_Bytes *BASE_table, FT_Bytes *GDEF_table, FT_Bytes *GPOS_table, FT_Bytes *GSUB_table, FT_Bytes *JSTF_table ); /* */ /********************************************************************** * * @function: * FT_OpenType_Free * * @description: * Free the buffer allocated by OpenType validator. * * @input: * face :: * A handle to the input face. * * table :: * The pointer to the buffer that is allocated by * @FT_OpenType_Validate. * * @note: * This function must be used to free the buffer allocated by * @FT_OpenType_Validate only. */ FT_EXPORT( void ) FT_OpenType_Free( FT_Face face, FT_Bytes table ); /* */ FT_END_HEADER #endif /* __FTOTVAL_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/ftoutln.h ================================================ /***************************************************************************/ /* */ /* ftoutln.h */ /* */ /* Support for the FT_Outline type used to store glyph shapes of */ /* most scalable font formats (specification). */ /* */ /* Copyright 1996-2003, 2005-2011 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __FTOUTLN_H__ #define __FTOUTLN_H__ #include <ft2build.h> #include FT_FREETYPE_H #ifdef FREETYPE_H #error "freetype.h of FreeType 1 has been loaded!" #error "Please fix the directory search order for header files" #error "so that freetype.h of FreeType 2 is found first." #endif FT_BEGIN_HEADER /*************************************************************************/ /* */ /* <Section> */ /* outline_processing */ /* */ /* <Title> */ /* Outline Processing */ /* */ /* <Abstract> */ /* Functions to create, transform, and render vectorial glyph images. */ /* */ /* <Description> */ /* This section contains routines used to create and destroy scalable */ /* glyph images known as `outlines'. These can also be measured, */ /* transformed, and converted into bitmaps and pixmaps. */ /* */ /* <Order> */ /* FT_Outline */ /* FT_OUTLINE_FLAGS */ /* FT_Outline_New */ /* FT_Outline_Done */ /* FT_Outline_Copy */ /* FT_Outline_Translate */ /* FT_Outline_Transform */ /* FT_Outline_Embolden */ /* FT_Outline_Reverse */ /* FT_Outline_Check */ /* */ /* FT_Outline_Get_CBox */ /* FT_Outline_Get_BBox */ /* */ /* FT_Outline_Get_Bitmap */ /* FT_Outline_Render */ /* */ /* FT_Outline_Decompose */ /* FT_Outline_Funcs */ /* FT_Outline_MoveTo_Func */ /* FT_Outline_LineTo_Func */ /* FT_Outline_ConicTo_Func */ /* FT_Outline_CubicTo_Func */ /* */ /*************************************************************************/ /*************************************************************************/ /* */ /* <Function> */ /* FT_Outline_Decompose */ /* */ /* <Description> */ /* Walk over an outline's structure to decompose it into individual */ /* segments and Bézier arcs. This function also emits `move to' */ /* operations to indicate the start of new contours in the outline. */ /* */ /* <Input> */ /* outline :: A pointer to the source target. */ /* */ /* func_interface :: A table of `emitters', i.e., function pointers */ /* called during decomposition to indicate path */ /* operations. */ /* */ /* <InOut> */ /* user :: A typeless pointer which is passed to each */ /* emitter during the decomposition. It can be */ /* used to store the state during the */ /* decomposition. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ FT_EXPORT( FT_Error ) FT_Outline_Decompose( FT_Outline* outline, const FT_Outline_Funcs* func_interface, void* user ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Outline_New */ /* */ /* <Description> */ /* Create a new outline of a given size. */ /* */ /* <Input> */ /* library :: A handle to the library object from where the */ /* outline is allocated. Note however that the new */ /* outline will *not* necessarily be *freed*, when */ /* destroying the library, by @FT_Done_FreeType. */ /* */ /* numPoints :: The maximal number of points within the outline. */ /* */ /* numContours :: The maximal number of contours within the outline. */ /* */ /* <Output> */ /* anoutline :: A handle to the new outline. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ /* <Note> */ /* The reason why this function takes a `library' parameter is simply */ /* to use the library's memory allocator. */ /* */ FT_EXPORT( FT_Error ) FT_Outline_New( FT_Library library, FT_UInt numPoints, FT_Int numContours, FT_Outline *anoutline ); FT_EXPORT( FT_Error ) FT_Outline_New_Internal( FT_Memory memory, FT_UInt numPoints, FT_Int numContours, FT_Outline *anoutline ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Outline_Done */ /* */ /* <Description> */ /* Destroy an outline created with @FT_Outline_New. */ /* */ /* <Input> */ /* library :: A handle of the library object used to allocate the */ /* outline. */ /* */ /* outline :: A pointer to the outline object to be discarded. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ /* <Note> */ /* If the outline's `owner' field is not set, only the outline */ /* descriptor will be released. */ /* */ /* The reason why this function takes an `library' parameter is */ /* simply to use ft_mem_free(). */ /* */ FT_EXPORT( FT_Error ) FT_Outline_Done( FT_Library library, FT_Outline* outline ); FT_EXPORT( FT_Error ) FT_Outline_Done_Internal( FT_Memory memory, FT_Outline* outline ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Outline_Check */ /* */ /* <Description> */ /* Check the contents of an outline descriptor. */ /* */ /* <Input> */ /* outline :: A handle to a source outline. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ FT_EXPORT( FT_Error ) FT_Outline_Check( FT_Outline* outline ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Outline_Get_CBox */ /* */ /* <Description> */ /* Return an outline's `control box'. The control box encloses all */ /* the outline's points, including Bézier control points. Though it */ /* coincides with the exact bounding box for most glyphs, it can be */ /* slightly larger in some situations (like when rotating an outline */ /* which contains Bézier outside arcs). */ /* */ /* Computing the control box is very fast, while getting the bounding */ /* box can take much more time as it needs to walk over all segments */ /* and arcs in the outline. To get the latter, you can use the */ /* `ftbbox' component which is dedicated to this single task. */ /* */ /* <Input> */ /* outline :: A pointer to the source outline descriptor. */ /* */ /* <Output> */ /* acbox :: The outline's control box. */ /* */ /* <Note> */ /* See @FT_Glyph_Get_CBox for a discussion of tricky fonts. */ /* */ FT_EXPORT( void ) FT_Outline_Get_CBox( const FT_Outline* outline, FT_BBox *acbox ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Outline_Translate */ /* */ /* <Description> */ /* Apply a simple translation to the points of an outline. */ /* */ /* <InOut> */ /* outline :: A pointer to the target outline descriptor. */ /* */ /* <Input> */ /* xOffset :: The horizontal offset. */ /* */ /* yOffset :: The vertical offset. */ /* */ FT_EXPORT( void ) FT_Outline_Translate( const FT_Outline* outline, FT_Pos xOffset, FT_Pos yOffset ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Outline_Copy */ /* */ /* <Description> */ /* Copy an outline into another one. Both objects must have the */ /* same sizes (number of points & number of contours) when this */ /* function is called. */ /* */ /* <Input> */ /* source :: A handle to the source outline. */ /* */ /* <Output> */ /* target :: A handle to the target outline. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ FT_EXPORT( FT_Error ) FT_Outline_Copy( const FT_Outline* source, FT_Outline *target ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Outline_Transform */ /* */ /* <Description> */ /* Apply a simple 2x2 matrix to all of an outline's points. Useful */ /* for applying rotations, slanting, flipping, etc. */ /* */ /* <InOut> */ /* outline :: A pointer to the target outline descriptor. */ /* */ /* <Input> */ /* matrix :: A pointer to the transformation matrix. */ /* */ /* <Note> */ /* You can use @FT_Outline_Translate if you need to translate the */ /* outline's points. */ /* */ FT_EXPORT( void ) FT_Outline_Transform( const FT_Outline* outline, const FT_Matrix* matrix ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Outline_Embolden */ /* */ /* <Description> */ /* Embolden an outline. The new outline will be at most 4~times */ /* `strength' pixels wider and higher. You may think of the left and */ /* bottom borders as unchanged. */ /* */ /* Negative `strength' values to reduce the outline thickness are */ /* possible also. */ /* */ /* <InOut> */ /* outline :: A handle to the target outline. */ /* */ /* <Input> */ /* strength :: How strong the glyph is emboldened. Expressed in */ /* 26.6 pixel format. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ /* <Note> */ /* The used algorithm to increase or decrease the thickness of the */ /* glyph doesn't change the number of points; this means that certain */ /* situations like acute angles or intersections are sometimes */ /* handled incorrectly. */ /* */ /* If you need `better' metrics values you should call */ /* @FT_Outline_Get_CBox or @FT_Outline_Get_BBox. */ /* */ /* Example call: */ /* */ /* { */ /* FT_Load_Glyph( face, index, FT_LOAD_DEFAULT ); */ /* if ( face->slot->format == FT_GLYPH_FORMAT_OUTLINE ) */ /* FT_Outline_Embolden( &face->slot->outline, strength ); */ /* } */ /* */ FT_EXPORT( FT_Error ) FT_Outline_Embolden( FT_Outline* outline, FT_Pos strength ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Outline_Reverse */ /* */ /* <Description> */ /* Reverse the drawing direction of an outline. This is used to */ /* ensure consistent fill conventions for mirrored glyphs. */ /* */ /* <InOut> */ /* outline :: A pointer to the target outline descriptor. */ /* */ /* <Note> */ /* This function toggles the bit flag @FT_OUTLINE_REVERSE_FILL in */ /* the outline's `flags' field. */ /* */ /* It shouldn't be used by a normal client application, unless it */ /* knows what it is doing. */ /* */ FT_EXPORT( void ) FT_Outline_Reverse( FT_Outline* outline ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Outline_Get_Bitmap */ /* */ /* <Description> */ /* Render an outline within a bitmap. The outline's image is simply */ /* OR-ed to the target bitmap. */ /* */ /* <Input> */ /* library :: A handle to a FreeType library object. */ /* */ /* outline :: A pointer to the source outline descriptor. */ /* */ /* <InOut> */ /* abitmap :: A pointer to the target bitmap descriptor. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ /* <Note> */ /* This function does NOT CREATE the bitmap, it only renders an */ /* outline image within the one you pass to it! Consequently, the */ /* various fields in `abitmap' should be set accordingly. */ /* */ /* It will use the raster corresponding to the default glyph format. */ /* */ /* The value of the `num_grays' field in `abitmap' is ignored. If */ /* you select the gray-level rasterizer, and you want less than 256 */ /* gray levels, you have to use @FT_Outline_Render directly. */ /* */ FT_EXPORT( FT_Error ) FT_Outline_Get_Bitmap( FT_Library library, FT_Outline* outline, const FT_Bitmap *abitmap ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Outline_Render */ /* */ /* <Description> */ /* Render an outline within a bitmap using the current scan-convert. */ /* This function uses an @FT_Raster_Params structure as an argument, */ /* allowing advanced features like direct composition, translucency, */ /* etc. */ /* */ /* <Input> */ /* library :: A handle to a FreeType library object. */ /* */ /* outline :: A pointer to the source outline descriptor. */ /* */ /* <InOut> */ /* params :: A pointer to an @FT_Raster_Params structure used to */ /* describe the rendering operation. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ /* <Note> */ /* You should know what you are doing and how @FT_Raster_Params works */ /* to use this function. */ /* */ /* The field `params.source' will be set to `outline' before the scan */ /* converter is called, which means that the value you give to it is */ /* actually ignored. */ /* */ /* The gray-level rasterizer always uses 256 gray levels. If you */ /* want less gray levels, you have to provide your own span callback. */ /* See the @FT_RASTER_FLAG_DIRECT value of the `flags' field in the */ /* @FT_Raster_Params structure for more details. */ /* */ FT_EXPORT( FT_Error ) FT_Outline_Render( FT_Library library, FT_Outline* outline, FT_Raster_Params* params ); /************************************************************************** * * @enum: * FT_Orientation * * @description: * A list of values used to describe an outline's contour orientation. * * The TrueType and PostScript specifications use different conventions * to determine whether outline contours should be filled or unfilled. * * @values: * FT_ORIENTATION_TRUETYPE :: * According to the TrueType specification, clockwise contours must * be filled, and counter-clockwise ones must be unfilled. * * FT_ORIENTATION_POSTSCRIPT :: * According to the PostScript specification, counter-clockwise contours * must be filled, and clockwise ones must be unfilled. * * FT_ORIENTATION_FILL_RIGHT :: * This is identical to @FT_ORIENTATION_TRUETYPE, but is used to * remember that in TrueType, everything that is to the right of * the drawing direction of a contour must be filled. * * FT_ORIENTATION_FILL_LEFT :: * This is identical to @FT_ORIENTATION_POSTSCRIPT, but is used to * remember that in PostScript, everything that is to the left of * the drawing direction of a contour must be filled. * * FT_ORIENTATION_NONE :: * The orientation cannot be determined. That is, different parts of * the glyph have different orientation. * */ typedef enum FT_Orientation_ { FT_ORIENTATION_TRUETYPE = 0, FT_ORIENTATION_POSTSCRIPT = 1, FT_ORIENTATION_FILL_RIGHT = FT_ORIENTATION_TRUETYPE, FT_ORIENTATION_FILL_LEFT = FT_ORIENTATION_POSTSCRIPT, FT_ORIENTATION_NONE } FT_Orientation; /************************************************************************** * * @function: * FT_Outline_Get_Orientation * * @description: * This function analyzes a glyph outline and tries to compute its * fill orientation (see @FT_Orientation). This is done by computing * the direction of each global horizontal and/or vertical extrema * within the outline. * * Note that this will return @FT_ORIENTATION_TRUETYPE for empty * outlines. * * @input: * outline :: * A handle to the source outline. * * @return: * The orientation. * */ FT_EXPORT( FT_Orientation ) FT_Outline_Get_Orientation( FT_Outline* outline ); /* */ FT_END_HEADER #endif /* __FTOUTLN_H__ */ /* END */ /* Local Variables: */ /* coding: utf-8 */ /* End: */ ================================================ FILE: other/freetype/include/freetype/ftpfr.h ================================================ /***************************************************************************/ /* */ /* ftpfr.h */ /* */ /* FreeType API for accessing PFR-specific data (specification only). */ /* */ /* Copyright 2002, 2003, 2004, 2006, 2008, 2009 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __FTPFR_H__ #define __FTPFR_H__ #include <ft2build.h> #include FT_FREETYPE_H #ifdef FREETYPE_H #error "freetype.h of FreeType 1 has been loaded!" #error "Please fix the directory search order for header files" #error "so that freetype.h of FreeType 2 is found first." #endif FT_BEGIN_HEADER /*************************************************************************/ /* */ /* <Section> */ /* pfr_fonts */ /* */ /* <Title> */ /* PFR Fonts */ /* */ /* <Abstract> */ /* PFR/TrueDoc specific API. */ /* */ /* <Description> */ /* This section contains the declaration of PFR-specific functions. */ /* */ /*************************************************************************/ /********************************************************************** * * @function: * FT_Get_PFR_Metrics * * @description: * Return the outline and metrics resolutions of a given PFR face. * * @input: * face :: Handle to the input face. It can be a non-PFR face. * * @output: * aoutline_resolution :: * Outline resolution. This is equivalent to `face->units_per_EM' * for non-PFR fonts. Optional (parameter can be NULL). * * ametrics_resolution :: * Metrics resolution. This is equivalent to `outline_resolution' * for non-PFR fonts. Optional (parameter can be NULL). * * ametrics_x_scale :: * A 16.16 fixed-point number used to scale distance expressed * in metrics units to device sub-pixels. This is equivalent to * `face->size->x_scale', but for metrics only. Optional (parameter * can be NULL). * * ametrics_y_scale :: * Same as `ametrics_x_scale' but for the vertical direction. * optional (parameter can be NULL). * * @return: * FreeType error code. 0~means success. * * @note: * If the input face is not a PFR, this function will return an error. * However, in all cases, it will return valid values. */ FT_EXPORT( FT_Error ) FT_Get_PFR_Metrics( FT_Face face, FT_UInt *aoutline_resolution, FT_UInt *ametrics_resolution, FT_Fixed *ametrics_x_scale, FT_Fixed *ametrics_y_scale ); /********************************************************************** * * @function: * FT_Get_PFR_Kerning * * @description: * Return the kerning pair corresponding to two glyphs in a PFR face. * The distance is expressed in metrics units, unlike the result of * @FT_Get_Kerning. * * @input: * face :: A handle to the input face. * * left :: Index of the left glyph. * * right :: Index of the right glyph. * * @output: * avector :: A kerning vector. * * @return: * FreeType error code. 0~means success. * * @note: * This function always return distances in original PFR metrics * units. This is unlike @FT_Get_Kerning with the @FT_KERNING_UNSCALED * mode, which always returns distances converted to outline units. * * You can use the value of the `x_scale' and `y_scale' parameters * returned by @FT_Get_PFR_Metrics to scale these to device sub-pixels. */ FT_EXPORT( FT_Error ) FT_Get_PFR_Kerning( FT_Face face, FT_UInt left, FT_UInt right, FT_Vector *avector ); /********************************************************************** * * @function: * FT_Get_PFR_Advance * * @description: * Return a given glyph advance, expressed in original metrics units, * from a PFR font. * * @input: * face :: A handle to the input face. * * gindex :: The glyph index. * * @output: * aadvance :: The glyph advance in metrics units. * * @return: * FreeType error code. 0~means success. * * @note: * You can use the `x_scale' or `y_scale' results of @FT_Get_PFR_Metrics * to convert the advance to device sub-pixels (i.e., 1/64th of pixels). */ FT_EXPORT( FT_Error ) FT_Get_PFR_Advance( FT_Face face, FT_UInt gindex, FT_Pos *aadvance ); /* */ FT_END_HEADER #endif /* __FTPFR_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/ftrender.h ================================================ /***************************************************************************/ /* */ /* ftrender.h */ /* */ /* FreeType renderer modules public interface (specification). */ /* */ /* Copyright 1996-2001, 2005, 2006, 2010 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __FTRENDER_H__ #define __FTRENDER_H__ #include <ft2build.h> #include FT_MODULE_H #include FT_GLYPH_H FT_BEGIN_HEADER /*************************************************************************/ /* */ /* <Section> */ /* module_management */ /* */ /*************************************************************************/ /* create a new glyph object */ typedef FT_Error (*FT_Glyph_InitFunc)( FT_Glyph glyph, FT_GlyphSlot slot ); /* destroys a given glyph object */ typedef void (*FT_Glyph_DoneFunc)( FT_Glyph glyph ); typedef void (*FT_Glyph_TransformFunc)( FT_Glyph glyph, const FT_Matrix* matrix, const FT_Vector* delta ); typedef void (*FT_Glyph_GetBBoxFunc)( FT_Glyph glyph, FT_BBox* abbox ); typedef FT_Error (*FT_Glyph_CopyFunc)( FT_Glyph source, FT_Glyph target ); typedef FT_Error (*FT_Glyph_PrepareFunc)( FT_Glyph glyph, FT_GlyphSlot slot ); /* deprecated */ #define FT_Glyph_Init_Func FT_Glyph_InitFunc #define FT_Glyph_Done_Func FT_Glyph_DoneFunc #define FT_Glyph_Transform_Func FT_Glyph_TransformFunc #define FT_Glyph_BBox_Func FT_Glyph_GetBBoxFunc #define FT_Glyph_Copy_Func FT_Glyph_CopyFunc #define FT_Glyph_Prepare_Func FT_Glyph_PrepareFunc struct FT_Glyph_Class_ { FT_Long glyph_size; FT_Glyph_Format glyph_format; FT_Glyph_InitFunc glyph_init; FT_Glyph_DoneFunc glyph_done; FT_Glyph_CopyFunc glyph_copy; FT_Glyph_TransformFunc glyph_transform; FT_Glyph_GetBBoxFunc glyph_bbox; FT_Glyph_PrepareFunc glyph_prepare; }; typedef FT_Error (*FT_Renderer_RenderFunc)( FT_Renderer renderer, FT_GlyphSlot slot, FT_UInt mode, const FT_Vector* origin ); typedef FT_Error (*FT_Renderer_TransformFunc)( FT_Renderer renderer, FT_GlyphSlot slot, const FT_Matrix* matrix, const FT_Vector* delta ); typedef void (*FT_Renderer_GetCBoxFunc)( FT_Renderer renderer, FT_GlyphSlot slot, FT_BBox* cbox ); typedef FT_Error (*FT_Renderer_SetModeFunc)( FT_Renderer renderer, FT_ULong mode_tag, FT_Pointer mode_ptr ); /* deprecated identifiers */ #define FTRenderer_render FT_Renderer_RenderFunc #define FTRenderer_transform FT_Renderer_TransformFunc #define FTRenderer_getCBox FT_Renderer_GetCBoxFunc #define FTRenderer_setMode FT_Renderer_SetModeFunc /*************************************************************************/ /* */ /* <Struct> */ /* FT_Renderer_Class */ /* */ /* <Description> */ /* The renderer module class descriptor. */ /* */ /* <Fields> */ /* root :: The root @FT_Module_Class fields. */ /* */ /* glyph_format :: The glyph image format this renderer handles. */ /* */ /* render_glyph :: A method used to render the image that is in a */ /* given glyph slot into a bitmap. */ /* */ /* transform_glyph :: A method used to transform the image that is in */ /* a given glyph slot. */ /* */ /* get_glyph_cbox :: A method used to access the glyph's cbox. */ /* */ /* set_mode :: A method used to pass additional parameters. */ /* */ /* raster_class :: For @FT_GLYPH_FORMAT_OUTLINE renderers only. */ /* This is a pointer to its raster's class. */ /* */ typedef struct FT_Renderer_Class_ { FT_Module_Class root; FT_Glyph_Format glyph_format; FT_Renderer_RenderFunc render_glyph; FT_Renderer_TransformFunc transform_glyph; FT_Renderer_GetCBoxFunc get_glyph_cbox; FT_Renderer_SetModeFunc set_mode; FT_Raster_Funcs* raster_class; } FT_Renderer_Class; /*************************************************************************/ /* */ /* <Function> */ /* FT_Get_Renderer */ /* */ /* <Description> */ /* Retrieve the current renderer for a given glyph format. */ /* */ /* <Input> */ /* library :: A handle to the library object. */ /* */ /* format :: The glyph format. */ /* */ /* <Return> */ /* A renderer handle. 0~if none found. */ /* */ /* <Note> */ /* An error will be returned if a module already exists by that name, */ /* or if the module requires a version of FreeType that is too great. */ /* */ /* To add a new renderer, simply use @FT_Add_Module. To retrieve a */ /* renderer by its name, use @FT_Get_Module. */ /* */ FT_EXPORT( FT_Renderer ) FT_Get_Renderer( FT_Library library, FT_Glyph_Format format ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Set_Renderer */ /* */ /* <Description> */ /* Set the current renderer to use, and set additional mode. */ /* */ /* <InOut> */ /* library :: A handle to the library object. */ /* */ /* <Input> */ /* renderer :: A handle to the renderer object. */ /* */ /* num_params :: The number of additional parameters. */ /* */ /* parameters :: Additional parameters. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ /* <Note> */ /* In case of success, the renderer will be used to convert glyph */ /* images in the renderer's known format into bitmaps. */ /* */ /* This doesn't change the current renderer for other formats. */ /* */ /* Currently, only the B/W renderer, if compiled with */ /* FT_RASTER_OPTION_ANTI_ALIASING (providing a 5-levels */ /* anti-aliasing mode; this option must be set directly in */ /* `ftraster.c' and is undefined by default) accepts a single tag */ /* `pal5' to set its gray palette as a character string with */ /* 5~elements. Consequently, the third and fourth argument are zero */ /* normally. */ /* */ FT_EXPORT( FT_Error ) FT_Set_Renderer( FT_Library library, FT_Renderer renderer, FT_UInt num_params, FT_Parameter* parameters ); /* */ FT_END_HEADER #endif /* __FTRENDER_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/ftsizes.h ================================================ /***************************************************************************/ /* */ /* ftsizes.h */ /* */ /* FreeType size objects management (specification). */ /* */ /* Copyright 1996-2001, 2003, 2004, 2006, 2009 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /*************************************************************************/ /* */ /* Typical application would normally not need to use these functions. */ /* However, they have been placed in a public API for the rare cases */ /* where they are needed. */ /* */ /*************************************************************************/ #ifndef __FTSIZES_H__ #define __FTSIZES_H__ #include <ft2build.h> #include FT_FREETYPE_H #ifdef FREETYPE_H #error "freetype.h of FreeType 1 has been loaded!" #error "Please fix the directory search order for header files" #error "so that freetype.h of FreeType 2 is found first." #endif FT_BEGIN_HEADER /*************************************************************************/ /* */ /* <Section> */ /* sizes_management */ /* */ /* <Title> */ /* Size Management */ /* */ /* <Abstract> */ /* Managing multiple sizes per face. */ /* */ /* <Description> */ /* When creating a new face object (e.g., with @FT_New_Face), an */ /* @FT_Size object is automatically created and used to store all */ /* pixel-size dependent information, available in the `face->size' */ /* field. */ /* */ /* It is however possible to create more sizes for a given face, */ /* mostly in order to manage several character pixel sizes of the */ /* same font family and style. See @FT_New_Size and @FT_Done_Size. */ /* */ /* Note that @FT_Set_Pixel_Sizes and @FT_Set_Char_Size only */ /* modify the contents of the current `active' size; you thus need */ /* to use @FT_Activate_Size to change it. */ /* */ /* 99% of applications won't need the functions provided here, */ /* especially if they use the caching sub-system, so be cautious */ /* when using these. */ /* */ /*************************************************************************/ /*************************************************************************/ /* */ /* <Function> */ /* FT_New_Size */ /* */ /* <Description> */ /* Create a new size object from a given face object. */ /* */ /* <Input> */ /* face :: A handle to a parent face object. */ /* */ /* <Output> */ /* asize :: A handle to a new size object. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ /* <Note> */ /* You need to call @FT_Activate_Size in order to select the new size */ /* for upcoming calls to @FT_Set_Pixel_Sizes, @FT_Set_Char_Size, */ /* @FT_Load_Glyph, @FT_Load_Char, etc. */ /* */ FT_EXPORT( FT_Error ) FT_New_Size( FT_Face face, FT_Size* size ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Done_Size */ /* */ /* <Description> */ /* Discard a given size object. Note that @FT_Done_Face */ /* automatically discards all size objects allocated with */ /* @FT_New_Size. */ /* */ /* <Input> */ /* size :: A handle to a target size object. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ FT_EXPORT( FT_Error ) FT_Done_Size( FT_Size size ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Activate_Size */ /* */ /* <Description> */ /* Even though it is possible to create several size objects for a */ /* given face (see @FT_New_Size for details), functions like */ /* @FT_Load_Glyph or @FT_Load_Char only use the one which has been */ /* activated last to determine the `current character pixel size'. */ /* */ /* This function can be used to `activate' a previously created size */ /* object. */ /* */ /* <Input> */ /* size :: A handle to a target size object. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ /* <Note> */ /* If `face' is the size's parent face object, this function changes */ /* the value of `face->size' to the input size handle. */ /* */ FT_EXPORT( FT_Error ) FT_Activate_Size( FT_Size size ); /* */ FT_END_HEADER #endif /* __FTSIZES_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/ftsnames.h ================================================ /***************************************************************************/ /* */ /* ftsnames.h */ /* */ /* Simple interface to access SFNT name tables (which are used */ /* to hold font names, copyright info, notices, etc.) (specification). */ /* */ /* This is _not_ used to retrieve glyph names! */ /* */ /* Copyright 1996-2001, 2002, 2003, 2006, 2009, 2010 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __FT_SFNT_NAMES_H__ #define __FT_SFNT_NAMES_H__ #include <ft2build.h> #include FT_FREETYPE_H #ifdef FREETYPE_H #error "freetype.h of FreeType 1 has been loaded!" #error "Please fix the directory search order for header files" #error "so that freetype.h of FreeType 2 is found first." #endif FT_BEGIN_HEADER /*************************************************************************/ /* */ /* <Section> */ /* sfnt_names */ /* */ /* <Title> */ /* SFNT Names */ /* */ /* <Abstract> */ /* Access the names embedded in TrueType and OpenType files. */ /* */ /* <Description> */ /* The TrueType and OpenType specifications allow the inclusion of */ /* a special `names table' in font files. This table contains */ /* textual (and internationalized) information regarding the font, */ /* like family name, copyright, version, etc. */ /* */ /* The definitions below are used to access them if available. */ /* */ /* Note that this has nothing to do with glyph names! */ /* */ /*************************************************************************/ /*************************************************************************/ /* */ /* <Struct> */ /* FT_SfntName */ /* */ /* <Description> */ /* A structure used to model an SFNT `name' table entry. */ /* */ /* <Fields> */ /* platform_id :: The platform ID for `string'. */ /* */ /* encoding_id :: The encoding ID for `string'. */ /* */ /* language_id :: The language ID for `string'. */ /* */ /* name_id :: An identifier for `string'. */ /* */ /* string :: The `name' string. Note that its format differs */ /* depending on the (platform,encoding) pair. It can */ /* be a Pascal String, a UTF-16 one, etc. */ /* */ /* Generally speaking, the string is not */ /* zero-terminated. Please refer to the TrueType */ /* specification for details. */ /* */ /* string_len :: The length of `string' in bytes. */ /* */ /* <Note> */ /* Possible values for `platform_id', `encoding_id', `language_id', */ /* and `name_id' are given in the file `ttnameid.h'. For details */ /* please refer to the TrueType or OpenType specification. */ /* */ /* See also @TT_PLATFORM_XXX, @TT_APPLE_ID_XXX, @TT_MAC_ID_XXX, */ /* @TT_ISO_ID_XXX, and @TT_MS_ID_XXX. */ /* */ typedef struct FT_SfntName_ { FT_UShort platform_id; FT_UShort encoding_id; FT_UShort language_id; FT_UShort name_id; FT_Byte* string; /* this string is *not* null-terminated! */ FT_UInt string_len; /* in bytes */ } FT_SfntName; /*************************************************************************/ /* */ /* <Function> */ /* FT_Get_Sfnt_Name_Count */ /* */ /* <Description> */ /* Retrieve the number of name strings in the SFNT `name' table. */ /* */ /* <Input> */ /* face :: A handle to the source face. */ /* */ /* <Return> */ /* The number of strings in the `name' table. */ /* */ FT_EXPORT( FT_UInt ) FT_Get_Sfnt_Name_Count( FT_Face face ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Get_Sfnt_Name */ /* */ /* <Description> */ /* Retrieve a string of the SFNT `name' table for a given index. */ /* */ /* <Input> */ /* face :: A handle to the source face. */ /* */ /* idx :: The index of the `name' string. */ /* */ /* <Output> */ /* aname :: The indexed @FT_SfntName structure. */ /* */ /* <Return> */ /* FreeType error code. 0~means success. */ /* */ /* <Note> */ /* The `string' array returned in the `aname' structure is not */ /* null-terminated. The application should deallocate it if it is no */ /* longer in use. */ /* */ /* Use @FT_Get_Sfnt_Name_Count to get the total number of available */ /* `name' table entries, then do a loop until you get the right */ /* platform, encoding, and name ID. */ /* */ FT_EXPORT( FT_Error ) FT_Get_Sfnt_Name( FT_Face face, FT_UInt idx, FT_SfntName *aname ); /*************************************************************************** * * @constant: * FT_PARAM_TAG_IGNORE_PREFERRED_FAMILY * * @description: * A constant used as the tag of @FT_Parameter structures to make * FT_Open_Face() ignore preferred family subfamily names in `name' * table since OpenType version 1.4. For backwards compatibility with * legacy systems which has 4-face-per-family restriction. * */ #define FT_PARAM_TAG_IGNORE_PREFERRED_FAMILY FT_MAKE_TAG( 'i', 'g', 'p', 'f' ) /*************************************************************************** * * @constant: * FT_PARAM_TAG_IGNORE_PREFERRED_SUBFAMILY * * @description: * A constant used as the tag of @FT_Parameter structures to make * FT_Open_Face() ignore preferred subfamily names in `name' table since * OpenType version 1.4. For backwards compatibility with legacy * systems which has 4-face-per-family restriction. * */ #define FT_PARAM_TAG_IGNORE_PREFERRED_SUBFAMILY FT_MAKE_TAG( 'i', 'g', 'p', 's' ) /* */ FT_END_HEADER #endif /* __FT_SFNT_NAMES_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/ftstroke.h ================================================ /***************************************************************************/ /* */ /* ftstroke.h */ /* */ /* FreeType path stroker (specification). */ /* */ /* Copyright 2002-2006, 2008, 2009, 2011 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __FT_STROKE_H__ #define __FT_STROKE_H__ #include <ft2build.h> #include FT_OUTLINE_H #include FT_GLYPH_H FT_BEGIN_HEADER /************************************************************************ * * @section: * glyph_stroker * * @title: * Glyph Stroker * * @abstract: * Generating bordered and stroked glyphs. * * @description: * This component generates stroked outlines of a given vectorial * glyph. It also allows you to retrieve the `outside' and/or the * `inside' borders of the stroke. * * This can be useful to generate `bordered' glyph, i.e., glyphs * displayed with a coloured (and anti-aliased) border around their * shape. */ /************************************************************** * * @type: * FT_Stroker * * @description: * Opaque handler to a path stroker object. */ typedef struct FT_StrokerRec_* FT_Stroker; /************************************************************** * * @enum: * FT_Stroker_LineJoin * * @description: * These values determine how two joining lines are rendered * in a stroker. * * @values: * FT_STROKER_LINEJOIN_ROUND :: * Used to render rounded line joins. Circular arcs are used * to join two lines smoothly. * * FT_STROKER_LINEJOIN_BEVEL :: * Used to render beveled line joins. The outer corner of * the joined lines is filled by enclosing the triangular * region of the corner with a straight line between the * outer corners of each stroke. * * FT_STROKER_LINEJOIN_MITER_FIXED :: * Used to render mitered line joins, with fixed bevels if the * miter limit is exceeded. The outer edges of the strokes * for the two segments are extended until they meet at an * angle. If the segments meet at too sharp an angle (such * that the miter would extend from the intersection of the * segments a distance greater than the product of the miter * limit value and the border radius), then a bevel join (see * above) is used instead. This prevents long spikes being * created. FT_STROKER_LINEJOIN_MITER_FIXED generates a miter * line join as used in PostScript and PDF. * * FT_STROKER_LINEJOIN_MITER_VARIABLE :: * FT_STROKER_LINEJOIN_MITER :: * Used to render mitered line joins, with variable bevels if * the miter limit is exceeded. The intersection of the * strokes is clipped at a line perpendicular to the bisector * of the angle between the strokes, at the distance from the * intersection of the segments equal to the product of the * miter limit value and the border radius. This prevents * long spikes being created. * FT_STROKER_LINEJOIN_MITER_VARIABLE generates a mitered line * join as used in XPS. FT_STROKER_LINEJOIN_MITER is an alias * for FT_STROKER_LINEJOIN_MITER_VARIABLE, retained for * backwards compatibility. */ typedef enum FT_Stroker_LineJoin_ { FT_STROKER_LINEJOIN_ROUND = 0, FT_STROKER_LINEJOIN_BEVEL = 1, FT_STROKER_LINEJOIN_MITER_VARIABLE = 2, FT_STROKER_LINEJOIN_MITER = FT_STROKER_LINEJOIN_MITER_VARIABLE, FT_STROKER_LINEJOIN_MITER_FIXED = 3 } FT_Stroker_LineJoin; /************************************************************** * * @enum: * FT_Stroker_LineCap * * @description: * These values determine how the end of opened sub-paths are * rendered in a stroke. * * @values: * FT_STROKER_LINECAP_BUTT :: * The end of lines is rendered as a full stop on the last * point itself. * * FT_STROKER_LINECAP_ROUND :: * The end of lines is rendered as a half-circle around the * last point. * * FT_STROKER_LINECAP_SQUARE :: * The end of lines is rendered as a square around the * last point. */ typedef enum FT_Stroker_LineCap_ { FT_STROKER_LINECAP_BUTT = 0, FT_STROKER_LINECAP_ROUND, FT_STROKER_LINECAP_SQUARE } FT_Stroker_LineCap; /************************************************************** * * @enum: * FT_StrokerBorder * * @description: * These values are used to select a given stroke border * in @FT_Stroker_GetBorderCounts and @FT_Stroker_ExportBorder. * * @values: * FT_STROKER_BORDER_LEFT :: * Select the left border, relative to the drawing direction. * * FT_STROKER_BORDER_RIGHT :: * Select the right border, relative to the drawing direction. * * @note: * Applications are generally interested in the `inside' and `outside' * borders. However, there is no direct mapping between these and the * `left' and `right' ones, since this really depends on the glyph's * drawing orientation, which varies between font formats. * * You can however use @FT_Outline_GetInsideBorder and * @FT_Outline_GetOutsideBorder to get these. */ typedef enum FT_StrokerBorder_ { FT_STROKER_BORDER_LEFT = 0, FT_STROKER_BORDER_RIGHT } FT_StrokerBorder; /************************************************************** * * @function: * FT_Outline_GetInsideBorder * * @description: * Retrieve the @FT_StrokerBorder value corresponding to the * `inside' borders of a given outline. * * @input: * outline :: * The source outline handle. * * @return: * The border index. @FT_STROKER_BORDER_RIGHT for empty or invalid * outlines. */ FT_EXPORT( FT_StrokerBorder ) FT_Outline_GetInsideBorder( FT_Outline* outline ); /************************************************************** * * @function: * FT_Outline_GetOutsideBorder * * @description: * Retrieve the @FT_StrokerBorder value corresponding to the * `outside' borders of a given outline. * * @input: * outline :: * The source outline handle. * * @return: * The border index. @FT_STROKER_BORDER_LEFT for empty or invalid * outlines. */ FT_EXPORT( FT_StrokerBorder ) FT_Outline_GetOutsideBorder( FT_Outline* outline ); /************************************************************** * * @function: * FT_Stroker_New * * @description: * Create a new stroker object. * * @input: * library :: * FreeType library handle. * * @output: * astroker :: * A new stroker object handle. NULL in case of error. * * @return: * FreeType error code. 0~means success. */ FT_EXPORT( FT_Error ) FT_Stroker_New( FT_Library library, FT_Stroker *astroker ); /************************************************************** * * @function: * FT_Stroker_Set * * @description: * Reset a stroker object's attributes. * * @input: * stroker :: * The target stroker handle. * * radius :: * The border radius. * * line_cap :: * The line cap style. * * line_join :: * The line join style. * * miter_limit :: * The miter limit for the FT_STROKER_LINEJOIN_MITER_FIXED and * FT_STROKER_LINEJOIN_MITER_VARIABLE line join styles, * expressed as 16.16 fixed point value. * * @note: * The radius is expressed in the same units as the outline * coordinates. */ FT_EXPORT( void ) FT_Stroker_Set( FT_Stroker stroker, FT_Fixed radius, FT_Stroker_LineCap line_cap, FT_Stroker_LineJoin line_join, FT_Fixed miter_limit ); /************************************************************** * * @function: * FT_Stroker_Rewind * * @description: * Reset a stroker object without changing its attributes. * You should call this function before beginning a new * series of calls to @FT_Stroker_BeginSubPath or * @FT_Stroker_EndSubPath. * * @input: * stroker :: * The target stroker handle. */ FT_EXPORT( void ) FT_Stroker_Rewind( FT_Stroker stroker ); /************************************************************** * * @function: * FT_Stroker_ParseOutline * * @description: * A convenience function used to parse a whole outline with * the stroker. The resulting outline(s) can be retrieved * later by functions like @FT_Stroker_GetCounts and @FT_Stroker_Export. * * @input: * stroker :: * The target stroker handle. * * outline :: * The source outline. * * opened :: * A boolean. If~1, the outline is treated as an open path instead * of a closed one. * * @return: * FreeType error code. 0~means success. * * @note: * If `opened' is~0 (the default), the outline is treated as a closed * path, and the stroker generates two distinct `border' outlines. * * If `opened' is~1, the outline is processed as an open path, and the * stroker generates a single `stroke' outline. * * This function calls @FT_Stroker_Rewind automatically. */ FT_EXPORT( FT_Error ) FT_Stroker_ParseOutline( FT_Stroker stroker, FT_Outline* outline, FT_Bool opened ); /************************************************************** * * @function: * FT_Stroker_BeginSubPath * * @description: * Start a new sub-path in the stroker. * * @input: * stroker :: * The target stroker handle. * * to :: * A pointer to the start vector. * * open :: * A boolean. If~1, the sub-path is treated as an open one. * * @return: * FreeType error code. 0~means success. * * @note: * This function is useful when you need to stroke a path that is * not stored as an @FT_Outline object. */ FT_EXPORT( FT_Error ) FT_Stroker_BeginSubPath( FT_Stroker stroker, FT_Vector* to, FT_Bool open ); /************************************************************** * * @function: * FT_Stroker_EndSubPath * * @description: * Close the current sub-path in the stroker. * * @input: * stroker :: * The target stroker handle. * * @return: * FreeType error code. 0~means success. * * @note: * You should call this function after @FT_Stroker_BeginSubPath. * If the subpath was not `opened', this function `draws' a * single line segment to the start position when needed. */ FT_EXPORT( FT_Error ) FT_Stroker_EndSubPath( FT_Stroker stroker ); /************************************************************** * * @function: * FT_Stroker_LineTo * * @description: * `Draw' a single line segment in the stroker's current sub-path, * from the last position. * * @input: * stroker :: * The target stroker handle. * * to :: * A pointer to the destination point. * * @return: * FreeType error code. 0~means success. * * @note: * You should call this function between @FT_Stroker_BeginSubPath and * @FT_Stroker_EndSubPath. */ FT_EXPORT( FT_Error ) FT_Stroker_LineTo( FT_Stroker stroker, FT_Vector* to ); /************************************************************** * * @function: * FT_Stroker_ConicTo * * @description: * `Draw' a single quadratic Bézier in the stroker's current sub-path, * from the last position. * * @input: * stroker :: * The target stroker handle. * * control :: * A pointer to a Bézier control point. * * to :: * A pointer to the destination point. * * @return: * FreeType error code. 0~means success. * * @note: * You should call this function between @FT_Stroker_BeginSubPath and * @FT_Stroker_EndSubPath. */ FT_EXPORT( FT_Error ) FT_Stroker_ConicTo( FT_Stroker stroker, FT_Vector* control, FT_Vector* to ); /************************************************************** * * @function: * FT_Stroker_CubicTo * * @description: * `Draw' a single cubic Bézier in the stroker's current sub-path, * from the last position. * * @input: * stroker :: * The target stroker handle. * * control1 :: * A pointer to the first Bézier control point. * * control2 :: * A pointer to second Bézier control point. * * to :: * A pointer to the destination point. * * @return: * FreeType error code. 0~means success. * * @note: * You should call this function between @FT_Stroker_BeginSubPath and * @FT_Stroker_EndSubPath. */ FT_EXPORT( FT_Error ) FT_Stroker_CubicTo( FT_Stroker stroker, FT_Vector* control1, FT_Vector* control2, FT_Vector* to ); /************************************************************** * * @function: * FT_Stroker_GetBorderCounts * * @description: * Call this function once you have finished parsing your paths * with the stroker. It returns the number of points and * contours necessary to export one of the `border' or `stroke' * outlines generated by the stroker. * * @input: * stroker :: * The target stroker handle. * * border :: * The border index. * * @output: * anum_points :: * The number of points. * * anum_contours :: * The number of contours. * * @return: * FreeType error code. 0~means success. * * @note: * When an outline, or a sub-path, is `closed', the stroker generates * two independent `border' outlines, named `left' and `right'. * * When the outline, or a sub-path, is `opened', the stroker merges * the `border' outlines with caps. The `left' border receives all * points, while the `right' border becomes empty. * * Use the function @FT_Stroker_GetCounts instead if you want to * retrieve the counts associated to both borders. */ FT_EXPORT( FT_Error ) FT_Stroker_GetBorderCounts( FT_Stroker stroker, FT_StrokerBorder border, FT_UInt *anum_points, FT_UInt *anum_contours ); /************************************************************** * * @function: * FT_Stroker_ExportBorder * * @description: * Call this function after @FT_Stroker_GetBorderCounts to * export the corresponding border to your own @FT_Outline * structure. * * Note that this function appends the border points and * contours to your outline, but does not try to resize its * arrays. * * @input: * stroker :: * The target stroker handle. * * border :: * The border index. * * outline :: * The target outline handle. * * @note: * Always call this function after @FT_Stroker_GetBorderCounts to * get sure that there is enough room in your @FT_Outline object to * receive all new data. * * When an outline, or a sub-path, is `closed', the stroker generates * two independent `border' outlines, named `left' and `right' * * When the outline, or a sub-path, is `opened', the stroker merges * the `border' outlines with caps. The `left' border receives all * points, while the `right' border becomes empty. * * Use the function @FT_Stroker_Export instead if you want to * retrieve all borders at once. */ FT_EXPORT( void ) FT_Stroker_ExportBorder( FT_Stroker stroker, FT_StrokerBorder border, FT_Outline* outline ); /************************************************************** * * @function: * FT_Stroker_GetCounts * * @description: * Call this function once you have finished parsing your paths * with the stroker. It returns the number of points and * contours necessary to export all points/borders from the stroked * outline/path. * * @input: * stroker :: * The target stroker handle. * * @output: * anum_points :: * The number of points. * * anum_contours :: * The number of contours. * * @return: * FreeType error code. 0~means success. */ FT_EXPORT( FT_Error ) FT_Stroker_GetCounts( FT_Stroker stroker, FT_UInt *anum_points, FT_UInt *anum_contours ); /************************************************************** * * @function: * FT_Stroker_Export * * @description: * Call this function after @FT_Stroker_GetBorderCounts to * export all borders to your own @FT_Outline structure. * * Note that this function appends the border points and * contours to your outline, but does not try to resize its * arrays. * * @input: * stroker :: * The target stroker handle. * * outline :: * The target outline handle. */ FT_EXPORT( void ) FT_Stroker_Export( FT_Stroker stroker, FT_Outline* outline ); /************************************************************** * * @function: * FT_Stroker_Done * * @description: * Destroy a stroker object. * * @input: * stroker :: * A stroker handle. Can be NULL. */ FT_EXPORT( void ) FT_Stroker_Done( FT_Stroker stroker ); /************************************************************** * * @function: * FT_Glyph_Stroke * * @description: * Stroke a given outline glyph object with a given stroker. * * @inout: * pglyph :: * Source glyph handle on input, new glyph handle on output. * * @input: * stroker :: * A stroker handle. * * destroy :: * A Boolean. If~1, the source glyph object is destroyed * on success. * * @return: * FreeType error code. 0~means success. * * @note: * The source glyph is untouched in case of error. */ FT_EXPORT( FT_Error ) FT_Glyph_Stroke( FT_Glyph *pglyph, FT_Stroker stroker, FT_Bool destroy ); /************************************************************** * * @function: * FT_Glyph_StrokeBorder * * @description: * Stroke a given outline glyph object with a given stroker, but * only return either its inside or outside border. * * @inout: * pglyph :: * Source glyph handle on input, new glyph handle on output. * * @input: * stroker :: * A stroker handle. * * inside :: * A Boolean. If~1, return the inside border, otherwise * the outside border. * * destroy :: * A Boolean. If~1, the source glyph object is destroyed * on success. * * @return: * FreeType error code. 0~means success. * * @note: * The source glyph is untouched in case of error. */ FT_EXPORT( FT_Error ) FT_Glyph_StrokeBorder( FT_Glyph *pglyph, FT_Stroker stroker, FT_Bool inside, FT_Bool destroy ); /* */ FT_END_HEADER #endif /* __FT_STROKE_H__ */ /* END */ /* Local Variables: */ /* coding: utf-8 */ /* End: */ ================================================ FILE: other/freetype/include/freetype/ftsynth.h ================================================ /***************************************************************************/ /* */ /* ftsynth.h */ /* */ /* FreeType synthesizing code for emboldening and slanting */ /* (specification). */ /* */ /* Copyright 2000-2001, 2003, 2006, 2008 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /********* *********/ /********* WARNING, THIS IS ALPHA CODE! THIS API *********/ /********* IS DUE TO CHANGE UNTIL STRICTLY NOTIFIED BY THE *********/ /********* FREETYPE DEVELOPMENT TEAM *********/ /********* *********/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /* Main reason for not lifting the functions in this module to a */ /* `standard' API is that the used parameters for emboldening and */ /* slanting are not configurable. Consider the functions as a */ /* code resource which should be copied into the application and */ /* adapted to the particular needs. */ #ifndef __FTSYNTH_H__ #define __FTSYNTH_H__ #include <ft2build.h> #include FT_FREETYPE_H #ifdef FREETYPE_H #error "freetype.h of FreeType 1 has been loaded!" #error "Please fix the directory search order for header files" #error "so that freetype.h of FreeType 2 is found first." #endif FT_BEGIN_HEADER /* Embolden a glyph by a `reasonable' value (which is highly a matter of */ /* taste). This function is actually a convenience function, providing */ /* a wrapper for @FT_Outline_Embolden and @FT_Bitmap_Embolden. */ /* */ /* For emboldened outlines the metrics are estimates only; if you need */ /* precise values you should call @FT_Outline_Get_CBox. */ FT_EXPORT( void ) FT_GlyphSlot_Embolden( FT_GlyphSlot slot ); /* Slant an outline glyph to the right by about 12 degrees. */ FT_EXPORT( void ) FT_GlyphSlot_Oblique( FT_GlyphSlot slot ); /* */ FT_END_HEADER #endif /* __FTSYNTH_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/ftsystem.h ================================================ /***************************************************************************/ /* */ /* ftsystem.h */ /* */ /* FreeType low-level system interface definition (specification). */ /* */ /* Copyright 1996-2001, 2002, 2005, 2010 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __FTSYSTEM_H__ #define __FTSYSTEM_H__ #include <ft2build.h> FT_BEGIN_HEADER /*************************************************************************/ /* */ /* <Section> */ /* system_interface */ /* */ /* <Title> */ /* System Interface */ /* */ /* <Abstract> */ /* How FreeType manages memory and i/o. */ /* */ /* <Description> */ /* This section contains various definitions related to memory */ /* management and i/o access. You need to understand this */ /* information if you want to use a custom memory manager or you own */ /* i/o streams. */ /* */ /*************************************************************************/ /*************************************************************************/ /* */ /* M E M O R Y M A N A G E M E N T */ /* */ /*************************************************************************/ /************************************************************************* * * @type: * FT_Memory * * @description: * A handle to a given memory manager object, defined with an * @FT_MemoryRec structure. * */ typedef struct FT_MemoryRec_* FT_Memory; /************************************************************************* * * @functype: * FT_Alloc_Func * * @description: * A function used to allocate `size' bytes from `memory'. * * @input: * memory :: * A handle to the source memory manager. * * size :: * The size in bytes to allocate. * * @return: * Address of new memory block. 0~in case of failure. * */ typedef void* (*FT_Alloc_Func)( FT_Memory memory, long size ); /************************************************************************* * * @functype: * FT_Free_Func * * @description: * A function used to release a given block of memory. * * @input: * memory :: * A handle to the source memory manager. * * block :: * The address of the target memory block. * */ typedef void (*FT_Free_Func)( FT_Memory memory, void* block ); /************************************************************************* * * @functype: * FT_Realloc_Func * * @description: * A function used to re-allocate a given block of memory. * * @input: * memory :: * A handle to the source memory manager. * * cur_size :: * The block's current size in bytes. * * new_size :: * The block's requested new size. * * block :: * The block's current address. * * @return: * New block address. 0~in case of memory shortage. * * @note: * In case of error, the old block must still be available. * */ typedef void* (*FT_Realloc_Func)( FT_Memory memory, long cur_size, long new_size, void* block ); /************************************************************************* * * @struct: * FT_MemoryRec * * @description: * A structure used to describe a given memory manager to FreeType~2. * * @fields: * user :: * A generic typeless pointer for user data. * * alloc :: * A pointer type to an allocation function. * * free :: * A pointer type to an memory freeing function. * * realloc :: * A pointer type to a reallocation function. * */ struct FT_MemoryRec_ { void* user; FT_Alloc_Func alloc; FT_Free_Func free; FT_Realloc_Func realloc; }; /*************************************************************************/ /* */ /* I / O M A N A G E M E N T */ /* */ /*************************************************************************/ /************************************************************************* * * @type: * FT_Stream * * @description: * A handle to an input stream. * */ typedef struct FT_StreamRec_* FT_Stream; /************************************************************************* * * @struct: * FT_StreamDesc * * @description: * A union type used to store either a long or a pointer. This is used * to store a file descriptor or a `FILE*' in an input stream. * */ typedef union FT_StreamDesc_ { long value; void* pointer; } FT_StreamDesc; /************************************************************************* * * @functype: * FT_Stream_IoFunc * * @description: * A function used to seek and read data from a given input stream. * * @input: * stream :: * A handle to the source stream. * * offset :: * The offset of read in stream (always from start). * * buffer :: * The address of the read buffer. * * count :: * The number of bytes to read from the stream. * * @return: * The number of bytes effectively read by the stream. * * @note: * This function might be called to perform a seek or skip operation * with a `count' of~0. A non-zero return value then indicates an * error. * */ typedef unsigned long (*FT_Stream_IoFunc)( FT_Stream stream, unsigned long offset, unsigned char* buffer, unsigned long count ); /************************************************************************* * * @functype: * FT_Stream_CloseFunc * * @description: * A function used to close a given input stream. * * @input: * stream :: * A handle to the target stream. * */ typedef void (*FT_Stream_CloseFunc)( FT_Stream stream ); /************************************************************************* * * @struct: * FT_StreamRec * * @description: * A structure used to describe an input stream. * * @input: * base :: * For memory-based streams, this is the address of the first stream * byte in memory. This field should always be set to NULL for * disk-based streams. * * size :: * The stream size in bytes. * * pos :: * The current position within the stream. * * descriptor :: * This field is a union that can hold an integer or a pointer. It is * used by stream implementations to store file descriptors or `FILE*' * pointers. * * pathname :: * This field is completely ignored by FreeType. However, it is often * useful during debugging to use it to store the stream's filename * (where available). * * read :: * The stream's input function. * * close :: * The stream's close function. * * memory :: * The memory manager to use to preload frames. This is set * internally by FreeType and shouldn't be touched by stream * implementations. * * cursor :: * This field is set and used internally by FreeType when parsing * frames. * * limit :: * This field is set and used internally by FreeType when parsing * frames. * */ typedef struct FT_StreamRec_ { unsigned char* base; unsigned long size; unsigned long pos; FT_StreamDesc descriptor; FT_StreamDesc pathname; FT_Stream_IoFunc read; FT_Stream_CloseFunc close; FT_Memory memory; unsigned char* cursor; unsigned char* limit; } FT_StreamRec; /* */ FT_END_HEADER #endif /* __FTSYSTEM_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/fttrigon.h ================================================ /***************************************************************************/ /* */ /* fttrigon.h */ /* */ /* FreeType trigonometric functions (specification). */ /* */ /* Copyright 2001, 2003, 2005, 2007 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __FTTRIGON_H__ #define __FTTRIGON_H__ #include FT_FREETYPE_H #ifdef FREETYPE_H #error "freetype.h of FreeType 1 has been loaded!" #error "Please fix the directory search order for header files" #error "so that freetype.h of FreeType 2 is found first." #endif FT_BEGIN_HEADER /*************************************************************************/ /* */ /* <Section> */ /* computations */ /* */ /*************************************************************************/ /************************************************************************* * * @type: * FT_Angle * * @description: * This type is used to model angle values in FreeType. Note that the * angle is a 16.16 fixed float value expressed in degrees. * */ typedef FT_Fixed FT_Angle; /************************************************************************* * * @macro: * FT_ANGLE_PI * * @description: * The angle pi expressed in @FT_Angle units. * */ #define FT_ANGLE_PI ( 180L << 16 ) /************************************************************************* * * @macro: * FT_ANGLE_2PI * * @description: * The angle 2*pi expressed in @FT_Angle units. * */ #define FT_ANGLE_2PI ( FT_ANGLE_PI * 2 ) /************************************************************************* * * @macro: * FT_ANGLE_PI2 * * @description: * The angle pi/2 expressed in @FT_Angle units. * */ #define FT_ANGLE_PI2 ( FT_ANGLE_PI / 2 ) /************************************************************************* * * @macro: * FT_ANGLE_PI4 * * @description: * The angle pi/4 expressed in @FT_Angle units. * */ #define FT_ANGLE_PI4 ( FT_ANGLE_PI / 4 ) /************************************************************************* * * @function: * FT_Sin * * @description: * Return the sinus of a given angle in fixed point format. * * @input: * angle :: * The input angle. * * @return: * The sinus value. * * @note: * If you need both the sinus and cosinus for a given angle, use the * function @FT_Vector_Unit. * */ FT_EXPORT( FT_Fixed ) FT_Sin( FT_Angle angle ); /************************************************************************* * * @function: * FT_Cos * * @description: * Return the cosinus of a given angle in fixed point format. * * @input: * angle :: * The input angle. * * @return: * The cosinus value. * * @note: * If you need both the sinus and cosinus for a given angle, use the * function @FT_Vector_Unit. * */ FT_EXPORT( FT_Fixed ) FT_Cos( FT_Angle angle ); /************************************************************************* * * @function: * FT_Tan * * @description: * Return the tangent of a given angle in fixed point format. * * @input: * angle :: * The input angle. * * @return: * The tangent value. * */ FT_EXPORT( FT_Fixed ) FT_Tan( FT_Angle angle ); /************************************************************************* * * @function: * FT_Atan2 * * @description: * Return the arc-tangent corresponding to a given vector (x,y) in * the 2d plane. * * @input: * x :: * The horizontal vector coordinate. * * y :: * The vertical vector coordinate. * * @return: * The arc-tangent value (i.e. angle). * */ FT_EXPORT( FT_Angle ) FT_Atan2( FT_Fixed x, FT_Fixed y ); /************************************************************************* * * @function: * FT_Angle_Diff * * @description: * Return the difference between two angles. The result is always * constrained to the ]-PI..PI] interval. * * @input: * angle1 :: * First angle. * * angle2 :: * Second angle. * * @return: * Constrained value of `value2-value1'. * */ FT_EXPORT( FT_Angle ) FT_Angle_Diff( FT_Angle angle1, FT_Angle angle2 ); /************************************************************************* * * @function: * FT_Vector_Unit * * @description: * Return the unit vector corresponding to a given angle. After the * call, the value of `vec.x' will be `sin(angle)', and the value of * `vec.y' will be `cos(angle)'. * * This function is useful to retrieve both the sinus and cosinus of a * given angle quickly. * * @output: * vec :: * The address of target vector. * * @input: * angle :: * The address of angle. * */ FT_EXPORT( void ) FT_Vector_Unit( FT_Vector* vec, FT_Angle angle ); /************************************************************************* * * @function: * FT_Vector_Rotate * * @description: * Rotate a vector by a given angle. * * @inout: * vec :: * The address of target vector. * * @input: * angle :: * The address of angle. * */ FT_EXPORT( void ) FT_Vector_Rotate( FT_Vector* vec, FT_Angle angle ); /************************************************************************* * * @function: * FT_Vector_Length * * @description: * Return the length of a given vector. * * @input: * vec :: * The address of target vector. * * @return: * The vector length, expressed in the same units that the original * vector coordinates. * */ FT_EXPORT( FT_Fixed ) FT_Vector_Length( FT_Vector* vec ); /************************************************************************* * * @function: * FT_Vector_Polarize * * @description: * Compute both the length and angle of a given vector. * * @input: * vec :: * The address of source vector. * * @output: * length :: * The vector length. * * angle :: * The vector angle. * */ FT_EXPORT( void ) FT_Vector_Polarize( FT_Vector* vec, FT_Fixed *length, FT_Angle *angle ); /************************************************************************* * * @function: * FT_Vector_From_Polar * * @description: * Compute vector coordinates from a length and angle. * * @output: * vec :: * The address of source vector. * * @input: * length :: * The vector length. * * angle :: * The vector angle. * */ FT_EXPORT( void ) FT_Vector_From_Polar( FT_Vector* vec, FT_Fixed length, FT_Angle angle ); /* */ FT_END_HEADER #endif /* __FTTRIGON_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/fttypes.h ================================================ /***************************************************************************/ /* */ /* fttypes.h */ /* */ /* FreeType simple types definitions (specification only). */ /* */ /* Copyright 1996-2001, 2002, 2004, 2006, 2007, 2008 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __FTTYPES_H__ #define __FTTYPES_H__ #include <ft2build.h> #include FT_CONFIG_CONFIG_H #include FT_SYSTEM_H #include FT_IMAGE_H #include <stddef.h> FT_BEGIN_HEADER /*************************************************************************/ /* */ /* <Section> */ /* basic_types */ /* */ /* <Title> */ /* Basic Data Types */ /* */ /* <Abstract> */ /* The basic data types defined by the library. */ /* */ /* <Description> */ /* This section contains the basic data types defined by FreeType~2, */ /* ranging from simple scalar types to bitmap descriptors. More */ /* font-specific structures are defined in a different section. */ /* */ /* <Order> */ /* FT_Byte */ /* FT_Bytes */ /* FT_Char */ /* FT_Int */ /* FT_UInt */ /* FT_Int16 */ /* FT_UInt16 */ /* FT_Int32 */ /* FT_UInt32 */ /* FT_Short */ /* FT_UShort */ /* FT_Long */ /* FT_ULong */ /* FT_Bool */ /* FT_Offset */ /* FT_PtrDist */ /* FT_String */ /* FT_Tag */ /* FT_Error */ /* FT_Fixed */ /* FT_Pointer */ /* FT_Pos */ /* FT_Vector */ /* FT_BBox */ /* FT_Matrix */ /* FT_FWord */ /* FT_UFWord */ /* FT_F2Dot14 */ /* FT_UnitVector */ /* FT_F26Dot6 */ /* */ /* */ /* FT_Generic */ /* FT_Generic_Finalizer */ /* */ /* FT_Bitmap */ /* FT_Pixel_Mode */ /* FT_Palette_Mode */ /* FT_Glyph_Format */ /* FT_IMAGE_TAG */ /* */ /*************************************************************************/ /*************************************************************************/ /* */ /* <Type> */ /* FT_Bool */ /* */ /* <Description> */ /* A typedef of unsigned char, used for simple booleans. As usual, */ /* values 1 and~0 represent true and false, respectively. */ /* */ typedef unsigned char FT_Bool; /*************************************************************************/ /* */ /* <Type> */ /* FT_FWord */ /* */ /* <Description> */ /* A signed 16-bit integer used to store a distance in original font */ /* units. */ /* */ typedef signed short FT_FWord; /* distance in FUnits */ /*************************************************************************/ /* */ /* <Type> */ /* FT_UFWord */ /* */ /* <Description> */ /* An unsigned 16-bit integer used to store a distance in original */ /* font units. */ /* */ typedef unsigned short FT_UFWord; /* unsigned distance */ /*************************************************************************/ /* */ /* <Type> */ /* FT_Char */ /* */ /* <Description> */ /* A simple typedef for the _signed_ char type. */ /* */ typedef signed char FT_Char; /*************************************************************************/ /* */ /* <Type> */ /* FT_Byte */ /* */ /* <Description> */ /* A simple typedef for the _unsigned_ char type. */ /* */ typedef unsigned char FT_Byte; /*************************************************************************/ /* */ /* <Type> */ /* FT_Bytes */ /* */ /* <Description> */ /* A typedef for constant memory areas. */ /* */ typedef const FT_Byte* FT_Bytes; /*************************************************************************/ /* */ /* <Type> */ /* FT_Tag */ /* */ /* <Description> */ /* A typedef for 32-bit tags (as used in the SFNT format). */ /* */ typedef FT_UInt32 FT_Tag; /*************************************************************************/ /* */ /* <Type> */ /* FT_String */ /* */ /* <Description> */ /* A simple typedef for the char type, usually used for strings. */ /* */ typedef char FT_String; /*************************************************************************/ /* */ /* <Type> */ /* FT_Short */ /* */ /* <Description> */ /* A typedef for signed short. */ /* */ typedef signed short FT_Short; /*************************************************************************/ /* */ /* <Type> */ /* FT_UShort */ /* */ /* <Description> */ /* A typedef for unsigned short. */ /* */ typedef unsigned short FT_UShort; /*************************************************************************/ /* */ /* <Type> */ /* FT_Int */ /* */ /* <Description> */ /* A typedef for the int type. */ /* */ typedef signed int FT_Int; /*************************************************************************/ /* */ /* <Type> */ /* FT_UInt */ /* */ /* <Description> */ /* A typedef for the unsigned int type. */ /* */ typedef unsigned int FT_UInt; /*************************************************************************/ /* */ /* <Type> */ /* FT_Long */ /* */ /* <Description> */ /* A typedef for signed long. */ /* */ typedef signed long FT_Long; /*************************************************************************/ /* */ /* <Type> */ /* FT_ULong */ /* */ /* <Description> */ /* A typedef for unsigned long. */ /* */ typedef unsigned long FT_ULong; /*************************************************************************/ /* */ /* <Type> */ /* FT_F2Dot14 */ /* */ /* <Description> */ /* A signed 2.14 fixed float type used for unit vectors. */ /* */ typedef signed short FT_F2Dot14; /*************************************************************************/ /* */ /* <Type> */ /* FT_F26Dot6 */ /* */ /* <Description> */ /* A signed 26.6 fixed float type used for vectorial pixel */ /* coordinates. */ /* */ typedef signed long FT_F26Dot6; /*************************************************************************/ /* */ /* <Type> */ /* FT_Fixed */ /* */ /* <Description> */ /* This type is used to store 16.16 fixed float values, like scaling */ /* values or matrix coefficients. */ /* */ typedef signed long FT_Fixed; /*************************************************************************/ /* */ /* <Type> */ /* FT_Error */ /* */ /* <Description> */ /* The FreeType error code type. A value of~0 is always interpreted */ /* as a successful operation. */ /* */ typedef int FT_Error; /*************************************************************************/ /* */ /* <Type> */ /* FT_Pointer */ /* */ /* <Description> */ /* A simple typedef for a typeless pointer. */ /* */ typedef void* FT_Pointer; /*************************************************************************/ /* */ /* <Type> */ /* FT_Offset */ /* */ /* <Description> */ /* This is equivalent to the ANSI~C `size_t' type, i.e., the largest */ /* _unsigned_ integer type used to express a file size or position, */ /* or a memory block size. */ /* */ typedef size_t FT_Offset; /*************************************************************************/ /* */ /* <Type> */ /* FT_PtrDist */ /* */ /* <Description> */ /* This is equivalent to the ANSI~C `ptrdiff_t' type, i.e., the */ /* largest _signed_ integer type used to express the distance */ /* between two pointers. */ /* */ typedef ft_ptrdiff_t FT_PtrDist; /*************************************************************************/ /* */ /* <Struct> */ /* FT_UnitVector */ /* */ /* <Description> */ /* A simple structure used to store a 2D vector unit vector. Uses */ /* FT_F2Dot14 types. */ /* */ /* <Fields> */ /* x :: Horizontal coordinate. */ /* */ /* y :: Vertical coordinate. */ /* */ typedef struct FT_UnitVector_ { FT_F2Dot14 x; FT_F2Dot14 y; } FT_UnitVector; /*************************************************************************/ /* */ /* <Struct> */ /* FT_Matrix */ /* */ /* <Description> */ /* A simple structure used to store a 2x2 matrix. Coefficients are */ /* in 16.16 fixed float format. The computation performed is: */ /* */ /* { */ /* x' = x*xx + y*xy */ /* y' = x*yx + y*yy */ /* } */ /* */ /* <Fields> */ /* xx :: Matrix coefficient. */ /* */ /* xy :: Matrix coefficient. */ /* */ /* yx :: Matrix coefficient. */ /* */ /* yy :: Matrix coefficient. */ /* */ typedef struct FT_Matrix_ { FT_Fixed xx, xy; FT_Fixed yx, yy; } FT_Matrix; /*************************************************************************/ /* */ /* <Struct> */ /* FT_Data */ /* */ /* <Description> */ /* Read-only binary data represented as a pointer and a length. */ /* */ /* <Fields> */ /* pointer :: The data. */ /* */ /* length :: The length of the data in bytes. */ /* */ typedef struct FT_Data_ { const FT_Byte* pointer; FT_Int length; } FT_Data; /*************************************************************************/ /* */ /* <FuncType> */ /* FT_Generic_Finalizer */ /* */ /* <Description> */ /* Describe a function used to destroy the `client' data of any */ /* FreeType object. See the description of the @FT_Generic type for */ /* details of usage. */ /* */ /* <Input> */ /* The address of the FreeType object which is under finalization. */ /* Its client data is accessed through its `generic' field. */ /* */ typedef void (*FT_Generic_Finalizer)(void* object); /*************************************************************************/ /* */ /* <Struct> */ /* FT_Generic */ /* */ /* <Description> */ /* Client applications often need to associate their own data to a */ /* variety of FreeType core objects. For example, a text layout API */ /* might want to associate a glyph cache to a given size object. */ /* */ /* Most FreeType object contains a `generic' field, of type */ /* FT_Generic, which usage is left to client applications and font */ /* servers. */ /* */ /* It can be used to store a pointer to client-specific data, as well */ /* as the address of a `finalizer' function, which will be called by */ /* FreeType when the object is destroyed (for example, the previous */ /* client example would put the address of the glyph cache destructor */ /* in the `finalizer' field). */ /* */ /* <Fields> */ /* data :: A typeless pointer to any client-specified data. This */ /* field is completely ignored by the FreeType library. */ /* */ /* finalizer :: A pointer to a `generic finalizer' function, which */ /* will be called when the object is destroyed. If this */ /* field is set to NULL, no code will be called. */ /* */ typedef struct FT_Generic_ { void* data; FT_Generic_Finalizer finalizer; } FT_Generic; /*************************************************************************/ /* */ /* <Macro> */ /* FT_MAKE_TAG */ /* */ /* <Description> */ /* This macro converts four-letter tags which are used to label */ /* TrueType tables into an unsigned long to be used within FreeType. */ /* */ /* <Note> */ /* The produced values *must* be 32-bit integers. Don't redefine */ /* this macro. */ /* */ #define FT_MAKE_TAG( _x1, _x2, _x3, _x4 ) \ (FT_Tag) \ ( ( (FT_ULong)_x1 << 24 ) | \ ( (FT_ULong)_x2 << 16 ) | \ ( (FT_ULong)_x3 << 8 ) | \ (FT_ULong)_x4 ) /*************************************************************************/ /*************************************************************************/ /* */ /* L I S T M A N A G E M E N T */ /* */ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /* */ /* <Section> */ /* list_processing */ /* */ /*************************************************************************/ /*************************************************************************/ /* */ /* <Type> */ /* FT_ListNode */ /* */ /* <Description> */ /* Many elements and objects in FreeType are listed through an */ /* @FT_List record (see @FT_ListRec). As its name suggests, an */ /* FT_ListNode is a handle to a single list element. */ /* */ typedef struct FT_ListNodeRec_* FT_ListNode; /*************************************************************************/ /* */ /* <Type> */ /* FT_List */ /* */ /* <Description> */ /* A handle to a list record (see @FT_ListRec). */ /* */ typedef struct FT_ListRec_* FT_List; /*************************************************************************/ /* */ /* <Struct> */ /* FT_ListNodeRec */ /* */ /* <Description> */ /* A structure used to hold a single list element. */ /* */ /* <Fields> */ /* prev :: The previous element in the list. NULL if first. */ /* */ /* next :: The next element in the list. NULL if last. */ /* */ /* data :: A typeless pointer to the listed object. */ /* */ typedef struct FT_ListNodeRec_ { FT_ListNode prev; FT_ListNode next; void* data; } FT_ListNodeRec; /*************************************************************************/ /* */ /* <Struct> */ /* FT_ListRec */ /* */ /* <Description> */ /* A structure used to hold a simple doubly-linked list. These are */ /* used in many parts of FreeType. */ /* */ /* <Fields> */ /* head :: The head (first element) of doubly-linked list. */ /* */ /* tail :: The tail (last element) of doubly-linked list. */ /* */ typedef struct FT_ListRec_ { FT_ListNode head; FT_ListNode tail; } FT_ListRec; /* */ #define FT_IS_EMPTY( list ) ( (list).head == 0 ) /* return base error code (without module-specific prefix) */ #define FT_ERROR_BASE( x ) ( (x) & 0xFF ) /* return module error code */ #define FT_ERROR_MODULE( x ) ( (x) & 0xFF00U ) #define FT_BOOL( x ) ( (FT_Bool)( x ) ) FT_END_HEADER #endif /* __FTTYPES_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/ftwinfnt.h ================================================ /***************************************************************************/ /* */ /* ftwinfnt.h */ /* */ /* FreeType API for accessing Windows fnt-specific data. */ /* */ /* Copyright 2003, 2004, 2008 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __FTWINFNT_H__ #define __FTWINFNT_H__ #include <ft2build.h> #include FT_FREETYPE_H #ifdef FREETYPE_H #error "freetype.h of FreeType 1 has been loaded!" #error "Please fix the directory search order for header files" #error "so that freetype.h of FreeType 2 is found first." #endif FT_BEGIN_HEADER /*************************************************************************/ /* */ /* <Section> */ /* winfnt_fonts */ /* */ /* <Title> */ /* Window FNT Files */ /* */ /* <Abstract> */ /* Windows FNT specific API. */ /* */ /* <Description> */ /* This section contains the declaration of Windows FNT specific */ /* functions. */ /* */ /*************************************************************************/ /************************************************************************* * * @enum: * FT_WinFNT_ID_XXX * * @description: * A list of valid values for the `charset' byte in * @FT_WinFNT_HeaderRec. Exact mapping tables for the various cpXXXX * encodings (except for cp1361) can be found at ftp://ftp.unicode.org * in the MAPPINGS/VENDORS/MICSFT/WINDOWS subdirectory. cp1361 is * roughly a superset of MAPPINGS/OBSOLETE/EASTASIA/KSC/JOHAB.TXT. * * @values: * FT_WinFNT_ID_DEFAULT :: * This is used for font enumeration and font creation as a * `don't care' value. Valid font files don't contain this value. * When querying for information about the character set of the font * that is currently selected into a specified device context, this * return value (of the related Windows API) simply denotes failure. * * FT_WinFNT_ID_SYMBOL :: * There is no known mapping table available. * * FT_WinFNT_ID_MAC :: * Mac Roman encoding. * * FT_WinFNT_ID_OEM :: * From Michael Pöttgen <michael@poettgen.de>: * * The `Windows Font Mapping' article says that FT_WinFNT_ID_OEM * is used for the charset of vector fonts, like `modern.fon', * `roman.fon', and `script.fon' on Windows. * * The `CreateFont' documentation says: The FT_WinFNT_ID_OEM value * specifies a character set that is operating-system dependent. * * The `IFIMETRICS' documentation from the `Windows Driver * Development Kit' says: This font supports an OEM-specific * character set. The OEM character set is system dependent. * * In general OEM, as opposed to ANSI (i.e., cp1252), denotes the * second default codepage that most international versions of * Windows have. It is one of the OEM codepages from * * http://www.microsoft.com/globaldev/reference/cphome.mspx, * * and is used for the `DOS boxes', to support legacy applications. * A German Windows version for example usually uses ANSI codepage * 1252 and OEM codepage 850. * * FT_WinFNT_ID_CP874 :: * A superset of Thai TIS 620 and ISO 8859-11. * * FT_WinFNT_ID_CP932 :: * A superset of Japanese Shift-JIS (with minor deviations). * * FT_WinFNT_ID_CP936 :: * A superset of simplified Chinese GB 2312-1980 (with different * ordering and minor deviations). * * FT_WinFNT_ID_CP949 :: * A superset of Korean Hangul KS~C 5601-1987 (with different * ordering and minor deviations). * * FT_WinFNT_ID_CP950 :: * A superset of traditional Chinese Big~5 ETen (with different * ordering and minor deviations). * * FT_WinFNT_ID_CP1250 :: * A superset of East European ISO 8859-2 (with slightly different * ordering). * * FT_WinFNT_ID_CP1251 :: * A superset of Russian ISO 8859-5 (with different ordering). * * FT_WinFNT_ID_CP1252 :: * ANSI encoding. A superset of ISO 8859-1. * * FT_WinFNT_ID_CP1253 :: * A superset of Greek ISO 8859-7 (with minor modifications). * * FT_WinFNT_ID_CP1254 :: * A superset of Turkish ISO 8859-9. * * FT_WinFNT_ID_CP1255 :: * A superset of Hebrew ISO 8859-8 (with some modifications). * * FT_WinFNT_ID_CP1256 :: * A superset of Arabic ISO 8859-6 (with different ordering). * * FT_WinFNT_ID_CP1257 :: * A superset of Baltic ISO 8859-13 (with some deviations). * * FT_WinFNT_ID_CP1258 :: * For Vietnamese. This encoding doesn't cover all necessary * characters. * * FT_WinFNT_ID_CP1361 :: * Korean (Johab). */ #define FT_WinFNT_ID_CP1252 0 #define FT_WinFNT_ID_DEFAULT 1 #define FT_WinFNT_ID_SYMBOL 2 #define FT_WinFNT_ID_MAC 77 #define FT_WinFNT_ID_CP932 128 #define FT_WinFNT_ID_CP949 129 #define FT_WinFNT_ID_CP1361 130 #define FT_WinFNT_ID_CP936 134 #define FT_WinFNT_ID_CP950 136 #define FT_WinFNT_ID_CP1253 161 #define FT_WinFNT_ID_CP1254 162 #define FT_WinFNT_ID_CP1258 163 #define FT_WinFNT_ID_CP1255 177 #define FT_WinFNT_ID_CP1256 178 #define FT_WinFNT_ID_CP1257 186 #define FT_WinFNT_ID_CP1251 204 #define FT_WinFNT_ID_CP874 222 #define FT_WinFNT_ID_CP1250 238 #define FT_WinFNT_ID_OEM 255 /*************************************************************************/ /* */ /* <Struct> */ /* FT_WinFNT_HeaderRec */ /* */ /* <Description> */ /* Windows FNT Header info. */ /* */ typedef struct FT_WinFNT_HeaderRec_ { FT_UShort version; FT_ULong file_size; FT_Byte copyright[60]; FT_UShort file_type; FT_UShort nominal_point_size; FT_UShort vertical_resolution; FT_UShort horizontal_resolution; FT_UShort ascent; FT_UShort internal_leading; FT_UShort external_leading; FT_Byte italic; FT_Byte underline; FT_Byte strike_out; FT_UShort weight; FT_Byte charset; FT_UShort pixel_width; FT_UShort pixel_height; FT_Byte pitch_and_family; FT_UShort avg_width; FT_UShort max_width; FT_Byte first_char; FT_Byte last_char; FT_Byte default_char; FT_Byte break_char; FT_UShort bytes_per_row; FT_ULong device_offset; FT_ULong face_name_offset; FT_ULong bits_pointer; FT_ULong bits_offset; FT_Byte reserved; FT_ULong flags; FT_UShort A_space; FT_UShort B_space; FT_UShort C_space; FT_UShort color_table_offset; FT_ULong reserved1[4]; } FT_WinFNT_HeaderRec; /*************************************************************************/ /* */ /* <Struct> */ /* FT_WinFNT_Header */ /* */ /* <Description> */ /* A handle to an @FT_WinFNT_HeaderRec structure. */ /* */ typedef struct FT_WinFNT_HeaderRec_* FT_WinFNT_Header; /********************************************************************** * * @function: * FT_Get_WinFNT_Header * * @description: * Retrieve a Windows FNT font info header. * * @input: * face :: A handle to the input face. * * @output: * aheader :: The WinFNT header. * * @return: * FreeType error code. 0~means success. * * @note: * This function only works with Windows FNT faces, returning an error * otherwise. */ FT_EXPORT( FT_Error ) FT_Get_WinFNT_Header( FT_Face face, FT_WinFNT_HeaderRec *aheader ); /* */ FT_END_HEADER #endif /* __FTWINFNT_H__ */ /* END */ /* Local Variables: */ /* coding: utf-8 */ /* End: */ ================================================ FILE: other/freetype/include/freetype/ftxf86.h ================================================ /***************************************************************************/ /* */ /* ftxf86.h */ /* */ /* Support functions for X11. */ /* */ /* Copyright 2002, 2003, 2004, 2006, 2007 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __FTXF86_H__ #define __FTXF86_H__ #include <ft2build.h> #include FT_FREETYPE_H #ifdef FREETYPE_H #error "freetype.h of FreeType 1 has been loaded!" #error "Please fix the directory search order for header files" #error "so that freetype.h of FreeType 2 is found first." #endif FT_BEGIN_HEADER /*************************************************************************/ /* */ /* <Section> */ /* font_formats */ /* */ /* <Title> */ /* Font Formats */ /* */ /* <Abstract> */ /* Getting the font format. */ /* */ /* <Description> */ /* The single function in this section can be used to get the font */ /* format. Note that this information is not needed normally; */ /* however, there are special cases (like in PDF devices) where it is */ /* important to differentiate, in spite of FreeType's uniform API. */ /* */ /* This function is in the X11/xf86 namespace for historical reasons */ /* and in no way depends on that windowing system. */ /* */ /*************************************************************************/ /*************************************************************************/ /* */ /* <Function> */ /* FT_Get_X11_Font_Format */ /* */ /* <Description> */ /* Return a string describing the format of a given face, using values */ /* which can be used as an X11 FONT_PROPERTY. Possible values are */ /* `TrueType', `Type~1', `BDF', `PCF', `Type~42', `CID~Type~1', `CFF', */ /* `PFR', and `Windows~FNT'. */ /* */ /* <Input> */ /* face :: */ /* Input face handle. */ /* */ /* <Return> */ /* Font format string. NULL in case of error. */ /* */ FT_EXPORT( const char* ) FT_Get_X11_Font_Format( FT_Face face ); /* */ FT_END_HEADER #endif /* __FTXF86_H__ */ ================================================ FILE: other/freetype/include/freetype/internal/autohint.h ================================================ /***************************************************************************/ /* */ /* autohint.h */ /* */ /* High-level `autohint' module-specific interface (specification). */ /* */ /* Copyright 1996-2001, 2002, 2007 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /*************************************************************************/ /* */ /* The auto-hinter is used to load and automatically hint glyphs if a */ /* format-specific hinter isn't available. */ /* */ /*************************************************************************/ #ifndef __AUTOHINT_H__ #define __AUTOHINT_H__ /*************************************************************************/ /* */ /* A small technical note regarding automatic hinting in order to */ /* clarify this module interface. */ /* */ /* An automatic hinter might compute two kinds of data for a given face: */ /* */ /* - global hints: Usually some metrics that describe global properties */ /* of the face. It is computed by scanning more or less */ /* aggressively the glyphs in the face, and thus can be */ /* very slow to compute (even if the size of global */ /* hints is really small). */ /* */ /* - glyph hints: These describe some important features of the glyph */ /* outline, as well as how to align them. They are */ /* generally much faster to compute than global hints. */ /* */ /* The current FreeType auto-hinter does a pretty good job while */ /* performing fast computations for both global and glyph hints. */ /* However, we might be interested in introducing more complex and */ /* powerful algorithms in the future, like the one described in the John */ /* D. Hobby paper, which unfortunately requires a lot more horsepower. */ /* */ /* Because a sufficiently sophisticated font management system would */ /* typically implement an LRU cache of opened face objects to reduce */ /* memory usage, it is a good idea to be able to avoid recomputing */ /* global hints every time the same face is re-opened. */ /* */ /* We thus provide the ability to cache global hints outside of the face */ /* object, in order to speed up font re-opening time. Of course, this */ /* feature is purely optional, so most client programs won't even notice */ /* it. */ /* */ /* I initially thought that it would be a good idea to cache the glyph */ /* hints too. However, my general idea now is that if you really need */ /* to cache these too, you are simply in need of a new font format, */ /* where all this information could be stored within the font file and */ /* decoded on the fly. */ /* */ /*************************************************************************/ #include <ft2build.h> #include FT_FREETYPE_H FT_BEGIN_HEADER typedef struct FT_AutoHinterRec_ *FT_AutoHinter; /*************************************************************************/ /* */ /* <FuncType> */ /* FT_AutoHinter_GlobalGetFunc */ /* */ /* <Description> */ /* Retrieves the global hints computed for a given face object the */ /* resulting data is dissociated from the face and will survive a */ /* call to FT_Done_Face(). It must be discarded through the API */ /* FT_AutoHinter_GlobalDoneFunc(). */ /* */ /* <Input> */ /* hinter :: A handle to the source auto-hinter. */ /* */ /* face :: A handle to the source face object. */ /* */ /* <Output> */ /* global_hints :: A typeless pointer to the global hints. */ /* */ /* global_len :: The size in bytes of the global hints. */ /* */ typedef void (*FT_AutoHinter_GlobalGetFunc)( FT_AutoHinter hinter, FT_Face face, void** global_hints, long* global_len ); /*************************************************************************/ /* */ /* <FuncType> */ /* FT_AutoHinter_GlobalDoneFunc */ /* */ /* <Description> */ /* Discards the global hints retrieved through */ /* FT_AutoHinter_GlobalGetFunc(). This is the only way these hints */ /* are freed from memory. */ /* */ /* <Input> */ /* hinter :: A handle to the auto-hinter module. */ /* */ /* global :: A pointer to retrieved global hints to discard. */ /* */ typedef void (*FT_AutoHinter_GlobalDoneFunc)( FT_AutoHinter hinter, void* global ); /*************************************************************************/ /* */ /* <FuncType> */ /* FT_AutoHinter_GlobalResetFunc */ /* */ /* <Description> */ /* This function is used to recompute the global metrics in a given */ /* font. This is useful when global font data changes (e.g. Multiple */ /* Masters fonts where blend coordinates change). */ /* */ /* <Input> */ /* hinter :: A handle to the source auto-hinter. */ /* */ /* face :: A handle to the face. */ /* */ typedef void (*FT_AutoHinter_GlobalResetFunc)( FT_AutoHinter hinter, FT_Face face ); /*************************************************************************/ /* */ /* <FuncType> */ /* FT_AutoHinter_GlyphLoadFunc */ /* */ /* <Description> */ /* This function is used to load, scale, and automatically hint a */ /* glyph from a given face. */ /* */ /* <Input> */ /* face :: A handle to the face. */ /* */ /* glyph_index :: The glyph index. */ /* */ /* load_flags :: The load flags. */ /* */ /* <Note> */ /* This function is capable of loading composite glyphs by hinting */ /* each sub-glyph independently (which improves quality). */ /* */ /* It will call the font driver with FT_Load_Glyph(), with */ /* FT_LOAD_NO_SCALE set. */ /* */ typedef FT_Error (*FT_AutoHinter_GlyphLoadFunc)( FT_AutoHinter hinter, FT_GlyphSlot slot, FT_Size size, FT_UInt glyph_index, FT_Int32 load_flags ); /*************************************************************************/ /* */ /* <Struct> */ /* FT_AutoHinter_ServiceRec */ /* */ /* <Description> */ /* The auto-hinter module's interface. */ /* */ typedef struct FT_AutoHinter_ServiceRec_ { FT_AutoHinter_GlobalResetFunc reset_face; FT_AutoHinter_GlobalGetFunc get_global_hints; FT_AutoHinter_GlobalDoneFunc done_global_hints; FT_AutoHinter_GlyphLoadFunc load_glyph; } FT_AutoHinter_ServiceRec, *FT_AutoHinter_Service; #ifndef FT_CONFIG_OPTION_PIC #define FT_DEFINE_AUTOHINTER_SERVICE(class_, reset_face_, get_global_hints_, \ done_global_hints_, load_glyph_) \ FT_CALLBACK_TABLE_DEF \ const FT_AutoHinter_ServiceRec class_ = \ { \ reset_face_, get_global_hints_, done_global_hints_, load_glyph_ \ }; #else /* FT_CONFIG_OPTION_PIC */ #define FT_DEFINE_AUTOHINTER_SERVICE(class_, reset_face_, get_global_hints_, \ done_global_hints_, load_glyph_) \ void \ FT_Init_Class_##class_( FT_Library library, \ FT_AutoHinter_ServiceRec* clazz) \ { \ FT_UNUSED(library); \ clazz->reset_face = reset_face_; \ clazz->get_global_hints = get_global_hints_; \ clazz->done_global_hints = done_global_hints_; \ clazz->load_glyph = load_glyph_; \ } #endif /* FT_CONFIG_OPTION_PIC */ FT_END_HEADER #endif /* __AUTOHINT_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/internal/ftcalc.h ================================================ /***************************************************************************/ /* */ /* ftcalc.h */ /* */ /* Arithmetic computations (specification). */ /* */ /* Copyright 1996-2001, 2002, 2003, 2004, 2005, 2006, 2008, 2009 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __FTCALC_H__ #define __FTCALC_H__ #include <ft2build.h> #include FT_FREETYPE_H FT_BEGIN_HEADER /*************************************************************************/ /* */ /* <Function> */ /* FT_FixedSqrt */ /* */ /* <Description> */ /* Computes the square root of a 16.16 fixed point value. */ /* */ /* <Input> */ /* x :: The value to compute the root for. */ /* */ /* <Return> */ /* The result of `sqrt(x)'. */ /* */ /* <Note> */ /* This function is not very fast. */ /* */ FT_BASE( FT_Int32 ) FT_SqrtFixed( FT_Int32 x ); #ifdef FT_CONFIG_OPTION_OLD_INTERNALS /*************************************************************************/ /* */ /* <Function> */ /* FT_Sqrt32 */ /* */ /* <Description> */ /* Computes the square root of an Int32 integer (which will be */ /* handled as an unsigned long value). */ /* */ /* <Input> */ /* x :: The value to compute the root for. */ /* */ /* <Return> */ /* The result of `sqrt(x)'. */ /* */ FT_EXPORT( FT_Int32 ) FT_Sqrt32( FT_Int32 x ); #endif /* FT_CONFIG_OPTION_OLD_INTERNALS */ /*************************************************************************/ /* */ /* FT_MulDiv() and FT_MulFix() are declared in freetype.h. */ /* */ /*************************************************************************/ #ifdef TT_USE_BYTECODE_INTERPRETER /*************************************************************************/ /* */ /* <Function> */ /* FT_MulDiv_No_Round */ /* */ /* <Description> */ /* A very simple function used to perform the computation `(a*b)/c' */ /* (without rounding) with maximal accuracy (it uses a 64-bit */ /* intermediate integer whenever necessary). */ /* */ /* This function isn't necessarily as fast as some processor specific */ /* operations, but is at least completely portable. */ /* */ /* <Input> */ /* a :: The first multiplier. */ /* b :: The second multiplier. */ /* c :: The divisor. */ /* */ /* <Return> */ /* The result of `(a*b)/c'. This function never traps when trying to */ /* divide by zero; it simply returns `MaxInt' or `MinInt' depending */ /* on the signs of `a' and `b'. */ /* */ FT_BASE( FT_Long ) FT_MulDiv_No_Round( FT_Long a, FT_Long b, FT_Long c ); #endif /* TT_USE_BYTECODE_INTERPRETER */ /* * A variant of FT_Matrix_Multiply which scales its result afterwards. * The idea is that both `a' and `b' are scaled by factors of 10 so that * the values are as precise as possible to get a correct result during * the 64bit multiplication. Let `sa' and `sb' be the scaling factors of * `a' and `b', respectively, then the scaling factor of the result is * `sa*sb'. */ FT_BASE( void ) FT_Matrix_Multiply_Scaled( const FT_Matrix* a, FT_Matrix *b, FT_Long scaling ); /* * A variant of FT_Vector_Transform. See comments for * FT_Matrix_Multiply_Scaled. */ FT_BASE( void ) FT_Vector_Transform_Scaled( FT_Vector* vector, const FT_Matrix* matrix, FT_Long scaling ); /* * Return -1, 0, or +1, depending on the orientation of a given corner. * We use the Cartesian coordinate system, with positive vertical values * going upwards. The function returns +1 if the corner turns to the * left, -1 to the right, and 0 for undecidable cases. */ FT_BASE( FT_Int ) ft_corner_orientation( FT_Pos in_x, FT_Pos in_y, FT_Pos out_x, FT_Pos out_y ); /* * Return TRUE if a corner is flat or nearly flat. This is equivalent to * saying that the angle difference between the `in' and `out' vectors is * very small. */ FT_BASE( FT_Int ) ft_corner_is_flat( FT_Pos in_x, FT_Pos in_y, FT_Pos out_x, FT_Pos out_y ); #define INT_TO_F26DOT6( x ) ( (FT_Long)(x) << 6 ) #define INT_TO_F2DOT14( x ) ( (FT_Long)(x) << 14 ) #define INT_TO_FIXED( x ) ( (FT_Long)(x) << 16 ) #define F2DOT14_TO_FIXED( x ) ( (FT_Long)(x) << 2 ) #define FLOAT_TO_FIXED( x ) ( (FT_Long)( x * 65536.0 ) ) #define FIXED_TO_INT( x ) ( FT_RoundFix( x ) >> 16 ) #define ROUND_F26DOT6( x ) ( x >= 0 ? ( ( (x) + 32 ) & -64 ) \ : ( -( ( 32 - (x) ) & -64 ) ) ) FT_END_HEADER #endif /* __FTCALC_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/internal/ftdebug.h ================================================ /***************************************************************************/ /* */ /* ftdebug.h */ /* */ /* Debugging and logging component (specification). */ /* */ /* Copyright 1996-2001, 2002, 2004, 2006, 2007, 2008, 2009 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /* */ /* IMPORTANT: A description of FreeType's debugging support can be */ /* found in `docs/DEBUG.TXT'. Read it if you need to use or */ /* understand this code. */ /* */ /***************************************************************************/ #ifndef __FTDEBUG_H__ #define __FTDEBUG_H__ #include <ft2build.h> #include FT_CONFIG_CONFIG_H #include FT_FREETYPE_H FT_BEGIN_HEADER /* force the definition of FT_DEBUG_LEVEL_ERROR if FT_DEBUG_LEVEL_TRACE */ /* is already defined; this simplifies the following #ifdefs */ /* */ #ifdef FT_DEBUG_LEVEL_TRACE #undef FT_DEBUG_LEVEL_ERROR #define FT_DEBUG_LEVEL_ERROR #endif /*************************************************************************/ /* */ /* Define the trace enums as well as the trace levels array when they */ /* are needed. */ /* */ /*************************************************************************/ #ifdef FT_DEBUG_LEVEL_TRACE #define FT_TRACE_DEF( x ) trace_ ## x , /* defining the enumeration */ typedef enum FT_Trace_ { #include FT_INTERNAL_TRACE_H trace_count } FT_Trace; /* defining the array of trace levels, provided by `src/base/ftdebug.c' */ extern int ft_trace_levels[trace_count]; #undef FT_TRACE_DEF #endif /* FT_DEBUG_LEVEL_TRACE */ /*************************************************************************/ /* */ /* Define the FT_TRACE macro */ /* */ /* IMPORTANT! */ /* */ /* Each component must define the macro FT_COMPONENT to a valid FT_Trace */ /* value before using any TRACE macro. */ /* */ /*************************************************************************/ #ifdef FT_DEBUG_LEVEL_TRACE #define FT_TRACE( level, varformat ) \ do \ { \ if ( ft_trace_levels[FT_COMPONENT] >= level ) \ FT_Message varformat; \ } while ( 0 ) #else /* !FT_DEBUG_LEVEL_TRACE */ #define FT_TRACE( level, varformat ) do { } while ( 0 ) /* nothing */ #endif /* !FT_DEBUG_LEVEL_TRACE */ /*************************************************************************/ /* */ /* <Function> */ /* FT_Trace_Get_Count */ /* */ /* <Description> */ /* Return the number of available trace components. */ /* */ /* <Return> */ /* The number of trace components. 0 if FreeType 2 is not built with */ /* FT_DEBUG_LEVEL_TRACE definition. */ /* */ /* <Note> */ /* This function may be useful if you want to access elements of */ /* the internal `ft_trace_levels' array by an index. */ /* */ FT_BASE( FT_Int ) FT_Trace_Get_Count( void ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Trace_Get_Name */ /* */ /* <Description> */ /* Return the name of a trace component. */ /* */ /* <Input> */ /* The index of the trace component. */ /* */ /* <Return> */ /* The name of the trace component. This is a statically allocated */ /* C string, so do not free it after use. NULL if FreeType 2 is not */ /* built with FT_DEBUG_LEVEL_TRACE definition. */ /* */ /* <Note> */ /* Use @FT_Trace_Get_Count to get the number of available trace */ /* components. */ /* */ /* This function may be useful if you want to control FreeType 2's */ /* debug level in your application. */ /* */ FT_BASE( const char * ) FT_Trace_Get_Name( FT_Int idx ); /*************************************************************************/ /* */ /* You need two opening and closing parentheses! */ /* */ /* Example: FT_TRACE0(( "Value is %i", foo )) */ /* */ /* Output of the FT_TRACEX macros is sent to stderr. */ /* */ /*************************************************************************/ #define FT_TRACE0( varformat ) FT_TRACE( 0, varformat ) #define FT_TRACE1( varformat ) FT_TRACE( 1, varformat ) #define FT_TRACE2( varformat ) FT_TRACE( 2, varformat ) #define FT_TRACE3( varformat ) FT_TRACE( 3, varformat ) #define FT_TRACE4( varformat ) FT_TRACE( 4, varformat ) #define FT_TRACE5( varformat ) FT_TRACE( 5, varformat ) #define FT_TRACE6( varformat ) FT_TRACE( 6, varformat ) #define FT_TRACE7( varformat ) FT_TRACE( 7, varformat ) /*************************************************************************/ /* */ /* Define the FT_ERROR macro. */ /* */ /* Output of this macro is sent to stderr. */ /* */ /*************************************************************************/ #ifdef FT_DEBUG_LEVEL_ERROR #define FT_ERROR( varformat ) FT_Message varformat #else /* !FT_DEBUG_LEVEL_ERROR */ #define FT_ERROR( varformat ) do { } while ( 0 ) /* nothing */ #endif /* !FT_DEBUG_LEVEL_ERROR */ /*************************************************************************/ /* */ /* Define the FT_ASSERT macro. */ /* */ /*************************************************************************/ #ifdef FT_DEBUG_LEVEL_ERROR #define FT_ASSERT( condition ) \ do \ { \ if ( !( condition ) ) \ FT_Panic( "assertion failed on line %d of file %s\n", \ __LINE__, __FILE__ ); \ } while ( 0 ) #else /* !FT_DEBUG_LEVEL_ERROR */ #define FT_ASSERT( condition ) do { } while ( 0 ) #endif /* !FT_DEBUG_LEVEL_ERROR */ /*************************************************************************/ /* */ /* Define `FT_Message' and `FT_Panic' when needed. */ /* */ /*************************************************************************/ #ifdef FT_DEBUG_LEVEL_ERROR #include "stdio.h" /* for vfprintf() */ /* print a message */ FT_BASE( void ) FT_Message( const char* fmt, ... ); /* print a message and exit */ FT_BASE( void ) FT_Panic( const char* fmt, ... ); #endif /* FT_DEBUG_LEVEL_ERROR */ FT_BASE( void ) ft_debug_init( void ); #if defined( _MSC_VER ) /* Visual C++ (and Intel C++) */ /* We disable the warning `conditional expression is constant' here */ /* in order to compile cleanly with the maximum level of warnings. */ #pragma warning( disable : 4127 ) #endif /* _MSC_VER */ FT_END_HEADER #endif /* __FTDEBUG_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/internal/ftdriver.h ================================================ /***************************************************************************/ /* */ /* ftdriver.h */ /* */ /* FreeType font driver interface (specification). */ /* */ /* Copyright 1996-2001, 2002, 2003, 2006, 2008 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __FTDRIVER_H__ #define __FTDRIVER_H__ #include <ft2build.h> #include FT_MODULE_H FT_BEGIN_HEADER typedef FT_Error (*FT_Face_InitFunc)( FT_Stream stream, FT_Face face, FT_Int typeface_index, FT_Int num_params, FT_Parameter* parameters ); typedef void (*FT_Face_DoneFunc)( FT_Face face ); typedef FT_Error (*FT_Size_InitFunc)( FT_Size size ); typedef void (*FT_Size_DoneFunc)( FT_Size size ); typedef FT_Error (*FT_Slot_InitFunc)( FT_GlyphSlot slot ); typedef void (*FT_Slot_DoneFunc)( FT_GlyphSlot slot ); typedef FT_Error (*FT_Size_RequestFunc)( FT_Size size, FT_Size_Request req ); typedef FT_Error (*FT_Size_SelectFunc)( FT_Size size, FT_ULong size_index ); #ifdef FT_CONFIG_OPTION_OLD_INTERNALS typedef FT_Error (*FT_Size_ResetPointsFunc)( FT_Size size, FT_F26Dot6 char_width, FT_F26Dot6 char_height, FT_UInt horz_resolution, FT_UInt vert_resolution ); typedef FT_Error (*FT_Size_ResetPixelsFunc)( FT_Size size, FT_UInt pixel_width, FT_UInt pixel_height ); #endif /* FT_CONFIG_OPTION_OLD_INTERNALS */ typedef FT_Error (*FT_Slot_LoadFunc)( FT_GlyphSlot slot, FT_Size size, FT_UInt glyph_index, FT_Int32 load_flags ); typedef FT_UInt (*FT_CharMap_CharIndexFunc)( FT_CharMap charmap, FT_Long charcode ); typedef FT_Long (*FT_CharMap_CharNextFunc)( FT_CharMap charmap, FT_Long charcode ); typedef FT_Error (*FT_Face_GetKerningFunc)( FT_Face face, FT_UInt left_glyph, FT_UInt right_glyph, FT_Vector* kerning ); typedef FT_Error (*FT_Face_AttachFunc)( FT_Face face, FT_Stream stream ); typedef FT_Error (*FT_Face_GetAdvancesFunc)( FT_Face face, FT_UInt first, FT_UInt count, FT_Int32 flags, FT_Fixed* advances ); /*************************************************************************/ /* */ /* <Struct> */ /* FT_Driver_ClassRec */ /* */ /* <Description> */ /* The font driver class. This structure mostly contains pointers to */ /* driver methods. */ /* */ /* <Fields> */ /* root :: The parent module. */ /* */ /* face_object_size :: The size of a face object in bytes. */ /* */ /* size_object_size :: The size of a size object in bytes. */ /* */ /* slot_object_size :: The size of a glyph object in bytes. */ /* */ /* init_face :: The format-specific face constructor. */ /* */ /* done_face :: The format-specific face destructor. */ /* */ /* init_size :: The format-specific size constructor. */ /* */ /* done_size :: The format-specific size destructor. */ /* */ /* init_slot :: The format-specific slot constructor. */ /* */ /* done_slot :: The format-specific slot destructor. */ /* */ /* */ /* load_glyph :: A function handle to load a glyph to a slot. */ /* This field is mandatory! */ /* */ /* get_kerning :: A function handle to return the unscaled */ /* kerning for a given pair of glyphs. Can be */ /* set to 0 if the format doesn't support */ /* kerning. */ /* */ /* attach_file :: This function handle is used to read */ /* additional data for a face from another */ /* file/stream. For example, this can be used to */ /* add data from AFM or PFM files on a Type 1 */ /* face, or a CIDMap on a CID-keyed face. */ /* */ /* get_advances :: A function handle used to return advance */ /* widths of `count' glyphs (in font units), */ /* starting at `first'. The `vertical' flag must */ /* be set to get vertical advance heights. The */ /* `advances' buffer is caller-allocated. */ /* Currently not implemented. The idea of this */ /* function is to be able to perform */ /* device-independent text layout without loading */ /* a single glyph image. */ /* */ /* request_size :: A handle to a function used to request the new */ /* character size. Can be set to 0 if the */ /* scaling done in the base layer suffices. */ /* */ /* select_size :: A handle to a function used to select a new */ /* fixed size. It is used only if */ /* @FT_FACE_FLAG_FIXED_SIZES is set. Can be set */ /* to 0 if the scaling done in the base layer */ /* suffices. */ /* <Note> */ /* Most function pointers, with the exception of `load_glyph', can be */ /* set to 0 to indicate a default behaviour. */ /* */ typedef struct FT_Driver_ClassRec_ { FT_Module_Class root; FT_Long face_object_size; FT_Long size_object_size; FT_Long slot_object_size; FT_Face_InitFunc init_face; FT_Face_DoneFunc done_face; FT_Size_InitFunc init_size; FT_Size_DoneFunc done_size; FT_Slot_InitFunc init_slot; FT_Slot_DoneFunc done_slot; #ifdef FT_CONFIG_OPTION_OLD_INTERNALS FT_Size_ResetPointsFunc set_char_sizes; FT_Size_ResetPixelsFunc set_pixel_sizes; #endif /* FT_CONFIG_OPTION_OLD_INTERNALS */ FT_Slot_LoadFunc load_glyph; FT_Face_GetKerningFunc get_kerning; FT_Face_AttachFunc attach_file; FT_Face_GetAdvancesFunc get_advances; /* since version 2.2 */ FT_Size_RequestFunc request_size; FT_Size_SelectFunc select_size; } FT_Driver_ClassRec, *FT_Driver_Class; /* * The following functions are used as stubs for `set_char_sizes' and * `set_pixel_sizes'; the code uses `request_size' and `select_size' * functions instead. * * Implementation is in `src/base/ftobjs.c'. */ #ifdef FT_CONFIG_OPTION_OLD_INTERNALS FT_BASE( FT_Error ) ft_stub_set_char_sizes( FT_Size size, FT_F26Dot6 width, FT_F26Dot6 height, FT_UInt horz_res, FT_UInt vert_res ); FT_BASE( FT_Error ) ft_stub_set_pixel_sizes( FT_Size size, FT_UInt width, FT_UInt height ); #endif /* FT_CONFIG_OPTION_OLD_INTERNALS */ /*************************************************************************/ /* */ /* <Macro> */ /* FT_DECLARE_DRIVER */ /* */ /* <Description> */ /* Used to create a forward declaration of a */ /* FT_Driver_ClassRec stract instance. */ /* */ /* <Macro> */ /* FT_DEFINE_DRIVER */ /* */ /* <Description> */ /* Used to initialize an instance of FT_Driver_ClassRec struct. */ /* */ /* When FT_CONFIG_OPTION_PIC is defined a Create funtion will need */ /* to called with a pointer where the allocated stracture is returned.*/ /* And when it is no longer needed a Destroy function needs */ /* to be called to release that allocation. */ /* fcinit.c (ft_create_default_module_classes) already contains */ /* a mechanism to call these functions for the default modules */ /* described in ftmodule.h */ /* */ /* Notice that the created Create and Destroy functions call */ /* pic_init and pic_free function to allow you to manually allocate */ /* and initialize any additional global data, like module specific */ /* interface, and put them in the global pic container defined in */ /* ftpic.h. if you don't need them just implement the functions as */ /* empty to resolve the link error. */ /* */ /* When FT_CONFIG_OPTION_PIC is not defined the struct will be */ /* allocated in the global scope (or the scope where the macro */ /* is used). */ /* */ #ifndef FT_CONFIG_OPTION_PIC #ifdef FT_CONFIG_OPTION_OLD_INTERNALS #define FT_DEFINE_DRIVERS_OLD_INTERNALS(a_,b_) \ a_, b_, #else #define FT_DEFINE_DRIVERS_OLD_INTERNALS(a_,b_) #endif #define FT_DECLARE_DRIVER(class_) \ FT_CALLBACK_TABLE \ const FT_Driver_ClassRec class_; #define FT_DEFINE_DRIVER(class_, \ flags_, size_, name_, version_, requires_, \ interface_, init_, done_, get_interface_, \ face_object_size_, size_object_size_, \ slot_object_size_, init_face_, done_face_, \ init_size_, done_size_, init_slot_, done_slot_, \ old_set_char_sizes_, old_set_pixel_sizes_, \ load_glyph_, get_kerning_, attach_file_, \ get_advances_, request_size_, select_size_ ) \ FT_CALLBACK_TABLE_DEF \ const FT_Driver_ClassRec class_ = \ { \ FT_DEFINE_ROOT_MODULE(flags_,size_,name_,version_,requires_,interface_, \ init_,done_,get_interface_) \ \ face_object_size_, \ size_object_size_, \ slot_object_size_, \ \ init_face_, \ done_face_, \ \ init_size_, \ done_size_, \ \ init_slot_, \ done_slot_, \ \ FT_DEFINE_DRIVERS_OLD_INTERNALS(old_set_char_sizes_, old_set_pixel_sizes_) \ \ load_glyph_, \ \ get_kerning_, \ attach_file_, \ get_advances_, \ \ request_size_, \ select_size_ \ }; #else /* FT_CONFIG_OPTION_PIC */ #ifdef FT_CONFIG_OPTION_OLD_INTERNALS #define FT_DEFINE_DRIVERS_OLD_INTERNALS(a_,b_) \ clazz->set_char_sizes = a_; \ clazz->set_pixel_sizes = b_; #else #define FT_DEFINE_DRIVERS_OLD_INTERNALS(a_,b_) #endif #define FT_DECLARE_DRIVER(class_) FT_DECLARE_MODULE(class_) #define FT_DEFINE_DRIVER(class_, \ flags_, size_, name_, version_, requires_, \ interface_, init_, done_, get_interface_, \ face_object_size_, size_object_size_, \ slot_object_size_, init_face_, done_face_, \ init_size_, done_size_, init_slot_, done_slot_, \ old_set_char_sizes_, old_set_pixel_sizes_, \ load_glyph_, get_kerning_, attach_file_, \ get_advances_, request_size_, select_size_ ) \ void class_##_pic_free( FT_Library library ); \ FT_Error class_##_pic_init( FT_Library library ); \ \ void \ FT_Destroy_Class_##class_( FT_Library library, \ FT_Module_Class* clazz ) \ { \ FT_Memory memory = library->memory; \ FT_Driver_Class dclazz = (FT_Driver_Class)clazz; \ class_##_pic_free( library ); \ if ( dclazz ) \ FT_FREE( dclazz ); \ } \ \ FT_Error \ FT_Create_Class_##class_( FT_Library library, \ FT_Module_Class** output_class ) \ { \ FT_Driver_Class clazz; \ FT_Error error; \ FT_Memory memory = library->memory; \ \ if ( FT_ALLOC( clazz, sizeof(*clazz) ) ) \ return error; \ \ error = class_##_pic_init( library ); \ if(error) \ { \ FT_FREE( clazz ); \ return error; \ } \ \ FT_DEFINE_ROOT_MODULE(flags_,size_,name_,version_,requires_,interface_, \ init_,done_,get_interface_) \ \ clazz->face_object_size = face_object_size_; \ clazz->size_object_size = size_object_size_; \ clazz->slot_object_size = slot_object_size_; \ \ clazz->init_face = init_face_; \ clazz->done_face = done_face_; \ \ clazz->init_size = init_size_; \ clazz->done_size = done_size_; \ \ clazz->init_slot = init_slot_; \ clazz->done_slot = done_slot_; \ \ FT_DEFINE_DRIVERS_OLD_INTERNALS(old_set_char_sizes_, old_set_pixel_sizes_) \ \ clazz->load_glyph = load_glyph_; \ \ clazz->get_kerning = get_kerning_; \ clazz->attach_file = attach_file_; \ clazz->get_advances = get_advances_; \ \ clazz->request_size = request_size_; \ clazz->select_size = select_size_; \ \ *output_class = (FT_Module_Class*)clazz; \ return FT_Err_Ok; \ } #endif /* FT_CONFIG_OPTION_PIC */ FT_END_HEADER #endif /* __FTDRIVER_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/internal/ftgloadr.h ================================================ /***************************************************************************/ /* */ /* ftgloadr.h */ /* */ /* The FreeType glyph loader (specification). */ /* */ /* Copyright 2002, 2003, 2005, 2006 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __FTGLOADR_H__ #define __FTGLOADR_H__ #include <ft2build.h> #include FT_FREETYPE_H FT_BEGIN_HEADER /*************************************************************************/ /* */ /* <Struct> */ /* FT_GlyphLoader */ /* */ /* <Description> */ /* The glyph loader is an internal object used to load several glyphs */ /* together (for example, in the case of composites). */ /* */ /* <Note> */ /* The glyph loader implementation is not part of the high-level API, */ /* hence the forward structure declaration. */ /* */ typedef struct FT_GlyphLoaderRec_* FT_GlyphLoader ; #if 0 /* moved to freetype.h in version 2.2 */ #define FT_SUBGLYPH_FLAG_ARGS_ARE_WORDS 1 #define FT_SUBGLYPH_FLAG_ARGS_ARE_XY_VALUES 2 #define FT_SUBGLYPH_FLAG_ROUND_XY_TO_GRID 4 #define FT_SUBGLYPH_FLAG_SCALE 8 #define FT_SUBGLYPH_FLAG_XY_SCALE 0x40 #define FT_SUBGLYPH_FLAG_2X2 0x80 #define FT_SUBGLYPH_FLAG_USE_MY_METRICS 0x200 #endif typedef struct FT_SubGlyphRec_ { FT_Int index; FT_UShort flags; FT_Int arg1; FT_Int arg2; FT_Matrix transform; } FT_SubGlyphRec; typedef struct FT_GlyphLoadRec_ { FT_Outline outline; /* outline */ FT_Vector* extra_points; /* extra points table */ FT_Vector* extra_points2; /* second extra points table */ FT_UInt num_subglyphs; /* number of subglyphs */ FT_SubGlyph subglyphs; /* subglyphs */ } FT_GlyphLoadRec, *FT_GlyphLoad; typedef struct FT_GlyphLoaderRec_ { FT_Memory memory; FT_UInt max_points; FT_UInt max_contours; FT_UInt max_subglyphs; FT_Bool use_extra; FT_GlyphLoadRec base; FT_GlyphLoadRec current; void* other; /* for possible future extension? */ } FT_GlyphLoaderRec; /* create new empty glyph loader */ FT_BASE( FT_Error ) FT_GlyphLoader_New( FT_Memory memory, FT_GlyphLoader *aloader ); /* add an extra points table to a glyph loader */ FT_BASE( FT_Error ) FT_GlyphLoader_CreateExtra( FT_GlyphLoader loader ); /* destroy a glyph loader */ FT_BASE( void ) FT_GlyphLoader_Done( FT_GlyphLoader loader ); /* reset a glyph loader (frees everything int it) */ FT_BASE( void ) FT_GlyphLoader_Reset( FT_GlyphLoader loader ); /* rewind a glyph loader */ FT_BASE( void ) FT_GlyphLoader_Rewind( FT_GlyphLoader loader ); /* check that there is enough space to add `n_points' and `n_contours' */ /* to the glyph loader */ FT_BASE( FT_Error ) FT_GlyphLoader_CheckPoints( FT_GlyphLoader loader, FT_UInt n_points, FT_UInt n_contours ); #define FT_GLYPHLOADER_CHECK_P( _loader, _count ) \ ( (_count) == 0 || ((_loader)->base.outline.n_points + \ (_loader)->current.outline.n_points + \ (unsigned long)(_count)) <= (_loader)->max_points ) #define FT_GLYPHLOADER_CHECK_C( _loader, _count ) \ ( (_count) == 0 || ((_loader)->base.outline.n_contours + \ (_loader)->current.outline.n_contours + \ (unsigned long)(_count)) <= (_loader)->max_contours ) #define FT_GLYPHLOADER_CHECK_POINTS( _loader, _points,_contours ) \ ( ( FT_GLYPHLOADER_CHECK_P( _loader, _points ) && \ FT_GLYPHLOADER_CHECK_C( _loader, _contours ) ) \ ? 0 \ : FT_GlyphLoader_CheckPoints( (_loader), (_points), (_contours) ) ) /* check that there is enough space to add `n_subs' sub-glyphs to */ /* a glyph loader */ FT_BASE( FT_Error ) FT_GlyphLoader_CheckSubGlyphs( FT_GlyphLoader loader, FT_UInt n_subs ); /* prepare a glyph loader, i.e. empty the current glyph */ FT_BASE( void ) FT_GlyphLoader_Prepare( FT_GlyphLoader loader ); /* add the current glyph to the base glyph */ FT_BASE( void ) FT_GlyphLoader_Add( FT_GlyphLoader loader ); /* copy points from one glyph loader to another */ FT_BASE( FT_Error ) FT_GlyphLoader_CopyPoints( FT_GlyphLoader target, FT_GlyphLoader source ); /* */ FT_END_HEADER #endif /* __FTGLOADR_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/internal/ftmemory.h ================================================ /***************************************************************************/ /* */ /* ftmemory.h */ /* */ /* The FreeType memory management macros (specification). */ /* */ /* Copyright 1996-2001, 2002, 2004, 2005, 2006, 2007, 2010 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __FTMEMORY_H__ #define __FTMEMORY_H__ #include <ft2build.h> #include FT_CONFIG_CONFIG_H #include FT_TYPES_H FT_BEGIN_HEADER /*************************************************************************/ /* */ /* <Macro> */ /* FT_SET_ERROR */ /* */ /* <Description> */ /* This macro is used to set an implicit `error' variable to a given */ /* expression's value (usually a function call), and convert it to a */ /* boolean which is set whenever the value is != 0. */ /* */ #undef FT_SET_ERROR #define FT_SET_ERROR( expression ) \ ( ( error = (expression) ) != 0 ) /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /**** ****/ /**** ****/ /**** M E M O R Y ****/ /**** ****/ /**** ****/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /* * C++ refuses to handle statements like p = (void*)anything, with `p' a * typed pointer. Since we don't have a `typeof' operator in standard * C++, we have to use a template to emulate it. */ #ifdef __cplusplus extern "C++" template <typename T> inline T* cplusplus_typeof( T*, void *v ) { return static_cast <T*> ( v ); } #define FT_ASSIGNP( p, val ) (p) = cplusplus_typeof( (p), (val) ) #else #define FT_ASSIGNP( p, val ) (p) = (val) #endif #ifdef FT_DEBUG_MEMORY FT_BASE( const char* ) _ft_debug_file; FT_BASE( long ) _ft_debug_lineno; #define FT_DEBUG_INNER( exp ) ( _ft_debug_file = __FILE__, \ _ft_debug_lineno = __LINE__, \ (exp) ) #define FT_ASSIGNP_INNER( p, exp ) ( _ft_debug_file = __FILE__, \ _ft_debug_lineno = __LINE__, \ FT_ASSIGNP( p, exp ) ) #else /* !FT_DEBUG_MEMORY */ #define FT_DEBUG_INNER( exp ) (exp) #define FT_ASSIGNP_INNER( p, exp ) FT_ASSIGNP( p, exp ) #endif /* !FT_DEBUG_MEMORY */ /* * The allocation functions return a pointer, and the error code * is written to through the `p_error' parameter. See below for * for documentation. */ FT_BASE( FT_Pointer ) ft_mem_alloc( FT_Memory memory, FT_Long size, FT_Error *p_error ); FT_BASE( FT_Pointer ) ft_mem_qalloc( FT_Memory memory, FT_Long size, FT_Error *p_error ); FT_BASE( FT_Pointer ) ft_mem_realloc( FT_Memory memory, FT_Long item_size, FT_Long cur_count, FT_Long new_count, void* block, FT_Error *p_error ); FT_BASE( FT_Pointer ) ft_mem_qrealloc( FT_Memory memory, FT_Long item_size, FT_Long cur_count, FT_Long new_count, void* block, FT_Error *p_error ); FT_BASE( void ) ft_mem_free( FT_Memory memory, const void* P ); #define FT_MEM_ALLOC( ptr, size ) \ FT_ASSIGNP_INNER( ptr, ft_mem_alloc( memory, (size), &error ) ) #define FT_MEM_FREE( ptr ) \ FT_BEGIN_STMNT \ ft_mem_free( memory, (ptr) ); \ (ptr) = NULL; \ FT_END_STMNT #define FT_MEM_NEW( ptr ) \ FT_MEM_ALLOC( ptr, sizeof ( *(ptr) ) ) #define FT_MEM_REALLOC( ptr, cursz, newsz ) \ FT_ASSIGNP_INNER( ptr, ft_mem_realloc( memory, 1, \ (cursz), (newsz), \ (ptr), &error ) ) #define FT_MEM_QALLOC( ptr, size ) \ FT_ASSIGNP_INNER( ptr, ft_mem_qalloc( memory, (size), &error ) ) #define FT_MEM_QNEW( ptr ) \ FT_MEM_QALLOC( ptr, sizeof ( *(ptr) ) ) #define FT_MEM_QREALLOC( ptr, cursz, newsz ) \ FT_ASSIGNP_INNER( ptr, ft_mem_qrealloc( memory, 1, \ (cursz), (newsz), \ (ptr), &error ) ) #define FT_MEM_QRENEW_ARRAY( ptr, cursz, newsz ) \ FT_ASSIGNP_INNER( ptr, ft_mem_qrealloc( memory, sizeof ( *(ptr) ), \ (cursz), (newsz), \ (ptr), &error ) ) #define FT_MEM_ALLOC_MULT( ptr, count, item_size ) \ FT_ASSIGNP_INNER( ptr, ft_mem_realloc( memory, (item_size), \ 0, (count), \ NULL, &error ) ) #define FT_MEM_REALLOC_MULT( ptr, oldcnt, newcnt, itmsz ) \ FT_ASSIGNP_INNER( ptr, ft_mem_realloc( memory, (itmsz), \ (oldcnt), (newcnt), \ (ptr), &error ) ) #define FT_MEM_QALLOC_MULT( ptr, count, item_size ) \ FT_ASSIGNP_INNER( ptr, ft_mem_qrealloc( memory, (item_size), \ 0, (count), \ NULL, &error ) ) #define FT_MEM_QREALLOC_MULT( ptr, oldcnt, newcnt, itmsz) \ FT_ASSIGNP_INNER( ptr, ft_mem_qrealloc( memory, (itmsz), \ (oldcnt), (newcnt), \ (ptr), &error ) ) #define FT_MEM_SET_ERROR( cond ) ( (cond), error != 0 ) #define FT_MEM_SET( dest, byte, count ) ft_memset( dest, byte, count ) #define FT_MEM_COPY( dest, source, count ) ft_memcpy( dest, source, count ) #define FT_MEM_MOVE( dest, source, count ) ft_memmove( dest, source, count ) #define FT_MEM_ZERO( dest, count ) FT_MEM_SET( dest, 0, count ) #define FT_ZERO( p ) FT_MEM_ZERO( p, sizeof ( *(p) ) ) #define FT_ARRAY_ZERO( dest, count ) \ FT_MEM_ZERO( dest, (count) * sizeof ( *(dest) ) ) #define FT_ARRAY_COPY( dest, source, count ) \ FT_MEM_COPY( dest, source, (count) * sizeof ( *(dest) ) ) #define FT_ARRAY_MOVE( dest, source, count ) \ FT_MEM_MOVE( dest, source, (count) * sizeof ( *(dest) ) ) /* * Return the maximum number of addressable elements in an array. * We limit ourselves to INT_MAX, rather than UINT_MAX, to avoid * any problems. */ #define FT_ARRAY_MAX( ptr ) ( FT_INT_MAX / sizeof ( *(ptr) ) ) #define FT_ARRAY_CHECK( ptr, count ) ( (count) <= FT_ARRAY_MAX( ptr ) ) /*************************************************************************/ /* */ /* The following functions macros expect that their pointer argument is */ /* _typed_ in order to automatically compute array element sizes. */ /* */ #define FT_MEM_NEW_ARRAY( ptr, count ) \ FT_ASSIGNP_INNER( ptr, ft_mem_realloc( memory, sizeof ( *(ptr) ), \ 0, (count), \ NULL, &error ) ) #define FT_MEM_RENEW_ARRAY( ptr, cursz, newsz ) \ FT_ASSIGNP_INNER( ptr, ft_mem_realloc( memory, sizeof ( *(ptr) ), \ (cursz), (newsz), \ (ptr), &error ) ) #define FT_MEM_QNEW_ARRAY( ptr, count ) \ FT_ASSIGNP_INNER( ptr, ft_mem_qrealloc( memory, sizeof ( *(ptr) ), \ 0, (count), \ NULL, &error ) ) #define FT_MEM_QRENEW_ARRAY( ptr, cursz, newsz ) \ FT_ASSIGNP_INNER( ptr, ft_mem_qrealloc( memory, sizeof ( *(ptr) ), \ (cursz), (newsz), \ (ptr), &error ) ) #define FT_ALLOC( ptr, size ) \ FT_MEM_SET_ERROR( FT_MEM_ALLOC( ptr, size ) ) #define FT_REALLOC( ptr, cursz, newsz ) \ FT_MEM_SET_ERROR( FT_MEM_REALLOC( ptr, cursz, newsz ) ) #define FT_ALLOC_MULT( ptr, count, item_size ) \ FT_MEM_SET_ERROR( FT_MEM_ALLOC_MULT( ptr, count, item_size ) ) #define FT_REALLOC_MULT( ptr, oldcnt, newcnt, itmsz ) \ FT_MEM_SET_ERROR( FT_MEM_REALLOC_MULT( ptr, oldcnt, \ newcnt, itmsz ) ) #define FT_QALLOC( ptr, size ) \ FT_MEM_SET_ERROR( FT_MEM_QALLOC( ptr, size ) ) #define FT_QREALLOC( ptr, cursz, newsz ) \ FT_MEM_SET_ERROR( FT_MEM_QREALLOC( ptr, cursz, newsz ) ) #define FT_QALLOC_MULT( ptr, count, item_size ) \ FT_MEM_SET_ERROR( FT_MEM_QALLOC_MULT( ptr, count, item_size ) ) #define FT_QREALLOC_MULT( ptr, oldcnt, newcnt, itmsz ) \ FT_MEM_SET_ERROR( FT_MEM_QREALLOC_MULT( ptr, oldcnt, \ newcnt, itmsz ) ) #define FT_FREE( ptr ) FT_MEM_FREE( ptr ) #define FT_NEW( ptr ) FT_MEM_SET_ERROR( FT_MEM_NEW( ptr ) ) #define FT_NEW_ARRAY( ptr, count ) \ FT_MEM_SET_ERROR( FT_MEM_NEW_ARRAY( ptr, count ) ) #define FT_RENEW_ARRAY( ptr, curcnt, newcnt ) \ FT_MEM_SET_ERROR( FT_MEM_RENEW_ARRAY( ptr, curcnt, newcnt ) ) #define FT_QNEW( ptr ) \ FT_MEM_SET_ERROR( FT_MEM_QNEW( ptr ) ) #define FT_QNEW_ARRAY( ptr, count ) \ FT_MEM_SET_ERROR( FT_MEM_NEW_ARRAY( ptr, count ) ) #define FT_QRENEW_ARRAY( ptr, curcnt, newcnt ) \ FT_MEM_SET_ERROR( FT_MEM_RENEW_ARRAY( ptr, curcnt, newcnt ) ) #ifdef FT_CONFIG_OPTION_OLD_INTERNALS FT_BASE( FT_Error ) FT_Alloc( FT_Memory memory, FT_Long size, void* *P ); FT_BASE( FT_Error ) FT_QAlloc( FT_Memory memory, FT_Long size, void* *p ); FT_BASE( FT_Error ) FT_Realloc( FT_Memory memory, FT_Long current, FT_Long size, void* *P ); FT_BASE( FT_Error ) FT_QRealloc( FT_Memory memory, FT_Long current, FT_Long size, void* *p ); FT_BASE( void ) FT_Free( FT_Memory memory, void* *P ); #endif /* FT_CONFIG_OPTION_OLD_INTERNALS */ FT_BASE( FT_Pointer ) ft_mem_strdup( FT_Memory memory, const char* str, FT_Error *p_error ); FT_BASE( FT_Pointer ) ft_mem_dup( FT_Memory memory, const void* address, FT_ULong size, FT_Error *p_error ); #define FT_MEM_STRDUP( dst, str ) \ (dst) = (char*)ft_mem_strdup( memory, (const char*)(str), &error ) #define FT_STRDUP( dst, str ) \ FT_MEM_SET_ERROR( FT_MEM_STRDUP( dst, str ) ) #define FT_MEM_DUP( dst, address, size ) \ (dst) = ft_mem_dup( memory, (address), (FT_ULong)(size), &error ) #define FT_DUP( dst, address, size ) \ FT_MEM_SET_ERROR( FT_MEM_DUP( dst, address, size ) ) /* Return >= 1 if a truncation occurs. */ /* Return 0 if the source string fits the buffer. */ /* This is *not* the same as strlcpy(). */ FT_BASE( FT_Int ) ft_mem_strcpyn( char* dst, const char* src, FT_ULong size ); #define FT_STRCPYN( dst, src, size ) \ ft_mem_strcpyn( (char*)dst, (const char*)(src), (FT_ULong)(size) ) /* */ FT_END_HEADER #endif /* __FTMEMORY_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/internal/ftobjs.h ================================================ /***************************************************************************/ /* */ /* ftobjs.h */ /* */ /* The FreeType private base classes (specification). */ /* */ /* Copyright 1996-2001, 2002, 2003, 2004, 2005, 2006, 2008, 2010 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /*************************************************************************/ /* */ /* This file contains the definition of all internal FreeType classes. */ /* */ /*************************************************************************/ #ifndef __FTOBJS_H__ #define __FTOBJS_H__ #include <ft2build.h> #include FT_RENDER_H #include FT_SIZES_H #include FT_LCD_FILTER_H #include FT_INTERNAL_MEMORY_H #include FT_INTERNAL_GLYPH_LOADER_H #include FT_INTERNAL_DRIVER_H #include FT_INTERNAL_AUTOHINT_H #include FT_INTERNAL_SERVICE_H #include FT_INTERNAL_PIC_H #ifdef FT_CONFIG_OPTION_INCREMENTAL #include FT_INCREMENTAL_H #endif FT_BEGIN_HEADER /*************************************************************************/ /* */ /* Some generic definitions. */ /* */ #ifndef TRUE #define TRUE 1 #endif #ifndef FALSE #define FALSE 0 #endif #ifndef NULL #define NULL (void*)0 #endif /*************************************************************************/ /* */ /* The min and max functions missing in C. As usual, be careful not to */ /* write things like FT_MIN( a++, b++ ) to avoid side effects. */ /* */ #define FT_MIN( a, b ) ( (a) < (b) ? (a) : (b) ) #define FT_MAX( a, b ) ( (a) > (b) ? (a) : (b) ) #define FT_ABS( a ) ( (a) < 0 ? -(a) : (a) ) #define FT_PAD_FLOOR( x, n ) ( (x) & ~((n)-1) ) #define FT_PAD_ROUND( x, n ) FT_PAD_FLOOR( (x) + ((n)/2), n ) #define FT_PAD_CEIL( x, n ) FT_PAD_FLOOR( (x) + ((n)-1), n ) #define FT_PIX_FLOOR( x ) ( (x) & ~63 ) #define FT_PIX_ROUND( x ) FT_PIX_FLOOR( (x) + 32 ) #define FT_PIX_CEIL( x ) FT_PIX_FLOOR( (x) + 63 ) /* * Return the highest power of 2 that is <= value; this correspond to * the highest bit in a given 32-bit value. */ FT_BASE( FT_UInt32 ) ft_highpow2( FT_UInt32 value ); /* * character classification functions -- since these are used to parse * font files, we must not use those in <ctypes.h> which are * locale-dependent */ #define ft_isdigit( x ) ( ( (unsigned)(x) - '0' ) < 10U ) #define ft_isxdigit( x ) ( ( (unsigned)(x) - '0' ) < 10U || \ ( (unsigned)(x) - 'a' ) < 6U || \ ( (unsigned)(x) - 'A' ) < 6U ) /* the next two macros assume ASCII representation */ #define ft_isupper( x ) ( ( (unsigned)(x) - 'A' ) < 26U ) #define ft_islower( x ) ( ( (unsigned)(x) - 'a' ) < 26U ) #define ft_isalpha( x ) ( ft_isupper( x ) || ft_islower( x ) ) #define ft_isalnum( x ) ( ft_isdigit( x ) || ft_isalpha( x ) ) /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /**** ****/ /**** ****/ /**** C H A R M A P S ****/ /**** ****/ /**** ****/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /* handle to internal charmap object */ typedef struct FT_CMapRec_* FT_CMap; /* handle to charmap class structure */ typedef const struct FT_CMap_ClassRec_* FT_CMap_Class; /* internal charmap object structure */ typedef struct FT_CMapRec_ { FT_CharMapRec charmap; FT_CMap_Class clazz; } FT_CMapRec; /* typecase any pointer to a charmap handle */ #define FT_CMAP( x ) ((FT_CMap)( x )) /* obvious macros */ #define FT_CMAP_PLATFORM_ID( x ) FT_CMAP( x )->charmap.platform_id #define FT_CMAP_ENCODING_ID( x ) FT_CMAP( x )->charmap.encoding_id #define FT_CMAP_ENCODING( x ) FT_CMAP( x )->charmap.encoding #define FT_CMAP_FACE( x ) FT_CMAP( x )->charmap.face /* class method definitions */ typedef FT_Error (*FT_CMap_InitFunc)( FT_CMap cmap, FT_Pointer init_data ); typedef void (*FT_CMap_DoneFunc)( FT_CMap cmap ); typedef FT_UInt (*FT_CMap_CharIndexFunc)( FT_CMap cmap, FT_UInt32 char_code ); typedef FT_UInt (*FT_CMap_CharNextFunc)( FT_CMap cmap, FT_UInt32 *achar_code ); typedef FT_UInt (*FT_CMap_CharVarIndexFunc)( FT_CMap cmap, FT_CMap unicode_cmap, FT_UInt32 char_code, FT_UInt32 variant_selector ); typedef FT_Bool (*FT_CMap_CharVarIsDefaultFunc)( FT_CMap cmap, FT_UInt32 char_code, FT_UInt32 variant_selector ); typedef FT_UInt32 * (*FT_CMap_VariantListFunc)( FT_CMap cmap, FT_Memory mem ); typedef FT_UInt32 * (*FT_CMap_CharVariantListFunc)( FT_CMap cmap, FT_Memory mem, FT_UInt32 char_code ); typedef FT_UInt32 * (*FT_CMap_VariantCharListFunc)( FT_CMap cmap, FT_Memory mem, FT_UInt32 variant_selector ); typedef struct FT_CMap_ClassRec_ { FT_ULong size; FT_CMap_InitFunc init; FT_CMap_DoneFunc done; FT_CMap_CharIndexFunc char_index; FT_CMap_CharNextFunc char_next; /* Subsequent entries are special ones for format 14 -- the variant */ /* selector subtable which behaves like no other */ FT_CMap_CharVarIndexFunc char_var_index; FT_CMap_CharVarIsDefaultFunc char_var_default; FT_CMap_VariantListFunc variant_list; FT_CMap_CharVariantListFunc charvariant_list; FT_CMap_VariantCharListFunc variantchar_list; } FT_CMap_ClassRec; #ifndef FT_CONFIG_OPTION_PIC #define FT_DECLARE_CMAP_CLASS(class_) \ FT_CALLBACK_TABLE const FT_CMap_ClassRec class_; #define FT_DEFINE_CMAP_CLASS(class_, size_, init_, done_, char_index_, \ char_next_, char_var_index_, char_var_default_, variant_list_, \ charvariant_list_, variantchar_list_) \ FT_CALLBACK_TABLE_DEF \ const FT_CMap_ClassRec class_ = \ { \ size_, init_, done_, char_index_, char_next_, char_var_index_, \ char_var_default_, variant_list_, charvariant_list_, variantchar_list_ \ }; #else /* FT_CONFIG_OPTION_PIC */ #define FT_DECLARE_CMAP_CLASS(class_) \ void FT_Init_Class_##class_( FT_Library library, FT_CMap_ClassRec* clazz); #define FT_DEFINE_CMAP_CLASS(class_, size_, init_, done_, char_index_, \ char_next_, char_var_index_, char_var_default_, variant_list_, \ charvariant_list_, variantchar_list_) \ void \ FT_Init_Class_##class_( FT_Library library, \ FT_CMap_ClassRec* clazz) \ { \ FT_UNUSED(library); \ clazz->size = size_; \ clazz->init = init_; \ clazz->done = done_; \ clazz->char_index = char_index_; \ clazz->char_next = char_next_; \ clazz->char_var_index = char_var_index_; \ clazz->char_var_default = char_var_default_; \ clazz->variant_list = variant_list_; \ clazz->charvariant_list = charvariant_list_; \ clazz->variantchar_list = variantchar_list_; \ } #endif /* FT_CONFIG_OPTION_PIC */ /* create a new charmap and add it to charmap->face */ FT_BASE( FT_Error ) FT_CMap_New( FT_CMap_Class clazz, FT_Pointer init_data, FT_CharMap charmap, FT_CMap *acmap ); /* destroy a charmap and remove it from face's list */ FT_BASE( void ) FT_CMap_Done( FT_CMap cmap ); /*************************************************************************/ /* */ /* <Struct> */ /* FT_Face_InternalRec */ /* */ /* <Description> */ /* This structure contains the internal fields of each FT_Face */ /* object. These fields may change between different releases of */ /* FreeType. */ /* */ /* <Fields> */ /* max_points :: */ /* The maximal number of points used to store the vectorial outline */ /* of any glyph in this face. If this value cannot be known in */ /* advance, or if the face isn't scalable, this should be set to 0. */ /* Only relevant for scalable formats. */ /* */ /* max_contours :: */ /* The maximal number of contours used to store the vectorial */ /* outline of any glyph in this face. If this value cannot be */ /* known in advance, or if the face isn't scalable, this should be */ /* set to 0. Only relevant for scalable formats. */ /* */ /* transform_matrix :: */ /* A 2x2 matrix of 16.16 coefficients used to transform glyph */ /* outlines after they are loaded from the font. Only used by the */ /* convenience functions. */ /* */ /* transform_delta :: */ /* A translation vector used to transform glyph outlines after they */ /* are loaded from the font. Only used by the convenience */ /* functions. */ /* */ /* transform_flags :: */ /* Some flags used to classify the transform. Only used by the */ /* convenience functions. */ /* */ /* services :: */ /* A cache for frequently used services. It should be only */ /* accessed with the macro `FT_FACE_LOOKUP_SERVICE'. */ /* */ /* incremental_interface :: */ /* If non-null, the interface through which glyph data and metrics */ /* are loaded incrementally for faces that do not provide all of */ /* this data when first opened. This field exists only if */ /* @FT_CONFIG_OPTION_INCREMENTAL is defined. */ /* */ /* ignore_unpatented_hinter :: */ /* This boolean flag instructs the glyph loader to ignore the */ /* native font hinter, if one is found. This is exclusively used */ /* in the case when the unpatented hinter is compiled within the */ /* library. */ /* */ /* refcount :: */ /* A counter initialized to~1 at the time an @FT_Face structure is */ /* created. @FT_Reference_Face increments this counter, and */ /* @FT_Done_Face only destroys a face if the counter is~1, */ /* otherwise it simply decrements it. */ /* */ typedef struct FT_Face_InternalRec_ { #ifdef FT_CONFIG_OPTION_OLD_INTERNALS FT_UShort reserved1; FT_Short reserved2; #endif FT_Matrix transform_matrix; FT_Vector transform_delta; FT_Int transform_flags; FT_ServiceCacheRec services; #ifdef FT_CONFIG_OPTION_INCREMENTAL FT_Incremental_InterfaceRec* incremental_interface; #endif FT_Bool ignore_unpatented_hinter; FT_UInt refcount; } FT_Face_InternalRec; /*************************************************************************/ /* */ /* <Struct> */ /* FT_Slot_InternalRec */ /* */ /* <Description> */ /* This structure contains the internal fields of each FT_GlyphSlot */ /* object. These fields may change between different releases of */ /* FreeType. */ /* */ /* <Fields> */ /* loader :: The glyph loader object used to load outlines */ /* into the glyph slot. */ /* */ /* flags :: Possible values are zero or */ /* FT_GLYPH_OWN_BITMAP. The latter indicates */ /* that the FT_GlyphSlot structure owns the */ /* bitmap buffer. */ /* */ /* glyph_transformed :: Boolean. Set to TRUE when the loaded glyph */ /* must be transformed through a specific */ /* font transformation. This is _not_ the same */ /* as the face transform set through */ /* FT_Set_Transform(). */ /* */ /* glyph_matrix :: The 2x2 matrix corresponding to the glyph */ /* transformation, if necessary. */ /* */ /* glyph_delta :: The 2d translation vector corresponding to */ /* the glyph transformation, if necessary. */ /* */ /* glyph_hints :: Format-specific glyph hints management. */ /* */ #define FT_GLYPH_OWN_BITMAP 0x1 typedef struct FT_Slot_InternalRec_ { FT_GlyphLoader loader; FT_UInt flags; FT_Bool glyph_transformed; FT_Matrix glyph_matrix; FT_Vector glyph_delta; void* glyph_hints; } FT_GlyphSlot_InternalRec; #if 0 /*************************************************************************/ /* */ /* <Struct> */ /* FT_Size_InternalRec */ /* */ /* <Description> */ /* This structure contains the internal fields of each FT_Size */ /* object. Currently, it's empty. */ /* */ /*************************************************************************/ typedef struct FT_Size_InternalRec_ { /* empty */ } FT_Size_InternalRec; #endif /*************************************************************************/ /*************************************************************************/ /**** ****/ /**** ****/ /**** M O D U L E S ****/ /**** ****/ /**** ****/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /* */ /* <Struct> */ /* FT_ModuleRec */ /* */ /* <Description> */ /* A module object instance. */ /* */ /* <Fields> */ /* clazz :: A pointer to the module's class. */ /* */ /* library :: A handle to the parent library object. */ /* */ /* memory :: A handle to the memory manager. */ /* */ /* generic :: A generic structure for user-level extensibility (?). */ /* */ typedef struct FT_ModuleRec_ { FT_Module_Class* clazz; FT_Library library; FT_Memory memory; FT_Generic generic; } FT_ModuleRec; /* typecast an object to a FT_Module */ #define FT_MODULE( x ) ((FT_Module)( x )) #define FT_MODULE_CLASS( x ) FT_MODULE( x )->clazz #define FT_MODULE_LIBRARY( x ) FT_MODULE( x )->library #define FT_MODULE_MEMORY( x ) FT_MODULE( x )->memory #define FT_MODULE_IS_DRIVER( x ) ( FT_MODULE_CLASS( x )->module_flags & \ FT_MODULE_FONT_DRIVER ) #define FT_MODULE_IS_RENDERER( x ) ( FT_MODULE_CLASS( x )->module_flags & \ FT_MODULE_RENDERER ) #define FT_MODULE_IS_HINTER( x ) ( FT_MODULE_CLASS( x )->module_flags & \ FT_MODULE_HINTER ) #define FT_MODULE_IS_STYLER( x ) ( FT_MODULE_CLASS( x )->module_flags & \ FT_MODULE_STYLER ) #define FT_DRIVER_IS_SCALABLE( x ) ( FT_MODULE_CLASS( x )->module_flags & \ FT_MODULE_DRIVER_SCALABLE ) #define FT_DRIVER_USES_OUTLINES( x ) !( FT_MODULE_CLASS( x )->module_flags & \ FT_MODULE_DRIVER_NO_OUTLINES ) #define FT_DRIVER_HAS_HINTER( x ) ( FT_MODULE_CLASS( x )->module_flags & \ FT_MODULE_DRIVER_HAS_HINTER ) /*************************************************************************/ /* */ /* <Function> */ /* FT_Get_Module_Interface */ /* */ /* <Description> */ /* Finds a module and returns its specific interface as a typeless */ /* pointer. */ /* */ /* <Input> */ /* library :: A handle to the library object. */ /* */ /* module_name :: The module's name (as an ASCII string). */ /* */ /* <Return> */ /* A module-specific interface if available, 0 otherwise. */ /* */ /* <Note> */ /* You should better be familiar with FreeType internals to know */ /* which module to look for, and what its interface is :-) */ /* */ FT_BASE( const void* ) FT_Get_Module_Interface( FT_Library library, const char* mod_name ); FT_BASE( FT_Pointer ) ft_module_get_service( FT_Module module, const char* service_id ); /* */ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /**** ****/ /**** ****/ /**** FACE, SIZE & GLYPH SLOT OBJECTS ****/ /**** ****/ /**** ****/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /* a few macros used to perform easy typecasts with minimal brain damage */ #define FT_FACE( x ) ((FT_Face)(x)) #define FT_SIZE( x ) ((FT_Size)(x)) #define FT_SLOT( x ) ((FT_GlyphSlot)(x)) #define FT_FACE_DRIVER( x ) FT_FACE( x )->driver #define FT_FACE_LIBRARY( x ) FT_FACE_DRIVER( x )->root.library #define FT_FACE_MEMORY( x ) FT_FACE( x )->memory #define FT_FACE_STREAM( x ) FT_FACE( x )->stream #define FT_SIZE_FACE( x ) FT_SIZE( x )->face #define FT_SLOT_FACE( x ) FT_SLOT( x )->face #define FT_FACE_SLOT( x ) FT_FACE( x )->glyph #define FT_FACE_SIZE( x ) FT_FACE( x )->size /*************************************************************************/ /* */ /* <Function> */ /* FT_New_GlyphSlot */ /* */ /* <Description> */ /* It is sometimes useful to have more than one glyph slot for a */ /* given face object. This function is used to create additional */ /* slots. All of them are automatically discarded when the face is */ /* destroyed. */ /* */ /* <Input> */ /* face :: A handle to a parent face object. */ /* */ /* <Output> */ /* aslot :: A handle to a new glyph slot object. */ /* */ /* <Return> */ /* FreeType error code. 0 means success. */ /* */ FT_BASE( FT_Error ) FT_New_GlyphSlot( FT_Face face, FT_GlyphSlot *aslot ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Done_GlyphSlot */ /* */ /* <Description> */ /* Destroys a given glyph slot. Remember however that all slots are */ /* automatically destroyed with its parent. Using this function is */ /* not always mandatory. */ /* */ /* <Input> */ /* slot :: A handle to a target glyph slot. */ /* */ FT_BASE( void ) FT_Done_GlyphSlot( FT_GlyphSlot slot ); /* */ #define FT_REQUEST_WIDTH( req ) \ ( (req)->horiResolution \ ? (FT_Pos)( (req)->width * (req)->horiResolution + 36 ) / 72 \ : (req)->width ) #define FT_REQUEST_HEIGHT( req ) \ ( (req)->vertResolution \ ? (FT_Pos)( (req)->height * (req)->vertResolution + 36 ) / 72 \ : (req)->height ) /* Set the metrics according to a bitmap strike. */ FT_BASE( void ) FT_Select_Metrics( FT_Face face, FT_ULong strike_index ); /* Set the metrics according to a size request. */ FT_BASE( void ) FT_Request_Metrics( FT_Face face, FT_Size_Request req ); /* Match a size request against `available_sizes'. */ FT_BASE( FT_Error ) FT_Match_Size( FT_Face face, FT_Size_Request req, FT_Bool ignore_width, FT_ULong* size_index ); /* Use the horizontal metrics to synthesize the vertical metrics. */ /* If `advance' is zero, it is also synthesized. */ FT_BASE( void ) ft_synthesize_vertical_metrics( FT_Glyph_Metrics* metrics, FT_Pos advance ); /* Free the bitmap of a given glyphslot when needed (i.e., only when it */ /* was allocated with ft_glyphslot_alloc_bitmap). */ FT_BASE( void ) ft_glyphslot_free_bitmap( FT_GlyphSlot slot ); /* Allocate a new bitmap buffer in a glyph slot. */ FT_BASE( FT_Error ) ft_glyphslot_alloc_bitmap( FT_GlyphSlot slot, FT_ULong size ); /* Set the bitmap buffer in a glyph slot to a given pointer. The buffer */ /* will not be freed by a later call to ft_glyphslot_free_bitmap. */ FT_BASE( void ) ft_glyphslot_set_bitmap( FT_GlyphSlot slot, FT_Byte* buffer ); /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /**** ****/ /**** ****/ /**** R E N D E R E R S ****/ /**** ****/ /**** ****/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ #define FT_RENDERER( x ) ((FT_Renderer)( x )) #define FT_GLYPH( x ) ((FT_Glyph)( x )) #define FT_BITMAP_GLYPH( x ) ((FT_BitmapGlyph)( x )) #define FT_OUTLINE_GLYPH( x ) ((FT_OutlineGlyph)( x )) typedef struct FT_RendererRec_ { FT_ModuleRec root; FT_Renderer_Class* clazz; FT_Glyph_Format glyph_format; FT_Glyph_Class glyph_class; FT_Raster raster; FT_Raster_Render_Func raster_render; FT_Renderer_RenderFunc render; } FT_RendererRec; /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /**** ****/ /**** ****/ /**** F O N T D R I V E R S ****/ /**** ****/ /**** ****/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /* typecast a module into a driver easily */ #define FT_DRIVER( x ) ((FT_Driver)(x)) /* typecast a module as a driver, and get its driver class */ #define FT_DRIVER_CLASS( x ) FT_DRIVER( x )->clazz /*************************************************************************/ /* */ /* <Struct> */ /* FT_DriverRec */ /* */ /* <Description> */ /* The root font driver class. A font driver is responsible for */ /* managing and loading font files of a given format. */ /* */ /* <Fields> */ /* root :: Contains the fields of the root module class. */ /* */ /* clazz :: A pointer to the font driver's class. Note that */ /* this is NOT root.clazz. `class' wasn't used */ /* as it is a reserved word in C++. */ /* */ /* faces_list :: The list of faces currently opened by this */ /* driver. */ /* */ /* extensions :: A typeless pointer to the driver's extensions */ /* registry, if they are supported through the */ /* configuration macro FT_CONFIG_OPTION_EXTENSIONS. */ /* */ /* glyph_loader :: The glyph loader for all faces managed by this */ /* driver. This object isn't defined for unscalable */ /* formats. */ /* */ typedef struct FT_DriverRec_ { FT_ModuleRec root; FT_Driver_Class clazz; FT_ListRec faces_list; void* extensions; FT_GlyphLoader glyph_loader; } FT_DriverRec; /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /**** ****/ /**** ****/ /**** L I B R A R I E S ****/ /**** ****/ /**** ****/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /* This hook is used by the TrueType debugger. It must be set to an */ /* alternate truetype bytecode interpreter function. */ #define FT_DEBUG_HOOK_TRUETYPE 0 /* Set this debug hook to a non-null pointer to force unpatented hinting */ /* for all faces when both TT_USE_BYTECODE_INTERPRETER and */ /* TT_CONFIG_OPTION_UNPATENTED_HINTING are defined. This is only used */ /* during debugging. */ #define FT_DEBUG_HOOK_UNPATENTED_HINTING 1 typedef void (*FT_Bitmap_LcdFilterFunc)( FT_Bitmap* bitmap, FT_Render_Mode render_mode, FT_Library library ); /*************************************************************************/ /* */ /* <Struct> */ /* FT_LibraryRec */ /* */ /* <Description> */ /* The FreeType library class. This is the root of all FreeType */ /* data. Use FT_New_Library() to create a library object, and */ /* FT_Done_Library() to discard it and all child objects. */ /* */ /* <Fields> */ /* memory :: The library's memory object. Manages memory */ /* allocation. */ /* */ /* generic :: Client data variable. Used to extend the */ /* Library class by higher levels and clients. */ /* */ /* version_major :: The major version number of the library. */ /* */ /* version_minor :: The minor version number of the library. */ /* */ /* version_patch :: The current patch level of the library. */ /* */ /* num_modules :: The number of modules currently registered */ /* within this library. This is set to 0 for new */ /* libraries. New modules are added through the */ /* FT_Add_Module() API function. */ /* */ /* modules :: A table used to store handles to the currently */ /* registered modules. Note that each font driver */ /* contains a list of its opened faces. */ /* */ /* renderers :: The list of renderers currently registered */ /* within the library. */ /* */ /* cur_renderer :: The current outline renderer. This is a */ /* shortcut used to avoid parsing the list on */ /* each call to FT_Outline_Render(). It is a */ /* handle to the current renderer for the */ /* FT_GLYPH_FORMAT_OUTLINE format. */ /* */ /* auto_hinter :: XXX */ /* */ /* raster_pool :: The raster object's render pool. This can */ /* ideally be changed dynamically at run-time. */ /* */ /* raster_pool_size :: The size of the render pool in bytes. */ /* */ /* debug_hooks :: XXX */ /* */ /* lcd_filter :: If subpixel rendering is activated, the */ /* selected LCD filter mode. */ /* */ /* lcd_extra :: If subpixel rendering is activated, the number */ /* of extra pixels needed for the LCD filter. */ /* */ /* lcd_weights :: If subpixel rendering is activated, the LCD */ /* filter weights, if any. */ /* */ /* lcd_filter_func :: If subpixel rendering is activated, the LCD */ /* filtering callback function. */ /* */ /* pic_container :: Contains global structs and tables, instead */ /* of defining them globallly. */ /* */ /* refcount :: A counter initialized to~1 at the time an */ /* @FT_Library structure is created. */ /* @FT_Reference_Library increments this counter, */ /* and @FT_Done_Library only destroys a library */ /* if the counter is~1, otherwise it simply */ /* decrements it. */ /* */ typedef struct FT_LibraryRec_ { FT_Memory memory; /* library's memory manager */ FT_Generic generic; FT_Int version_major; FT_Int version_minor; FT_Int version_patch; FT_UInt num_modules; FT_Module modules[FT_MAX_MODULES]; /* module objects */ FT_ListRec renderers; /* list of renderers */ FT_Renderer cur_renderer; /* current outline renderer */ FT_Module auto_hinter; FT_Byte* raster_pool; /* scan-line conversion */ /* render pool */ FT_ULong raster_pool_size; /* size of render pool in bytes */ FT_DebugHook_Func debug_hooks[4]; #ifdef FT_CONFIG_OPTION_SUBPIXEL_RENDERING FT_LcdFilter lcd_filter; FT_Int lcd_extra; /* number of extra pixels */ FT_Byte lcd_weights[7]; /* filter weights, if any */ FT_Bitmap_LcdFilterFunc lcd_filter_func; /* filtering callback */ #endif #ifdef FT_CONFIG_OPTION_PIC FT_PIC_Container pic_container; #endif FT_UInt refcount; } FT_LibraryRec; FT_BASE( FT_Renderer ) FT_Lookup_Renderer( FT_Library library, FT_Glyph_Format format, FT_ListNode* node ); FT_BASE( FT_Error ) FT_Render_Glyph_Internal( FT_Library library, FT_GlyphSlot slot, FT_Render_Mode render_mode ); typedef const char* (*FT_Face_GetPostscriptNameFunc)( FT_Face face ); typedef FT_Error (*FT_Face_GetGlyphNameFunc)( FT_Face face, FT_UInt glyph_index, FT_Pointer buffer, FT_UInt buffer_max ); typedef FT_UInt (*FT_Face_GetGlyphNameIndexFunc)( FT_Face face, FT_String* glyph_name ); #ifndef FT_CONFIG_OPTION_NO_DEFAULT_SYSTEM /*************************************************************************/ /* */ /* <Function> */ /* FT_New_Memory */ /* */ /* <Description> */ /* Creates a new memory object. */ /* */ /* <Return> */ /* A pointer to the new memory object. 0 in case of error. */ /* */ FT_BASE( FT_Memory ) FT_New_Memory( void ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Done_Memory */ /* */ /* <Description> */ /* Discards memory manager. */ /* */ /* <Input> */ /* memory :: A handle to the memory manager. */ /* */ FT_BASE( void ) FT_Done_Memory( FT_Memory memory ); #endif /* !FT_CONFIG_OPTION_NO_DEFAULT_SYSTEM */ /* Define default raster's interface. The default raster is located in */ /* `src/base/ftraster.c'. */ /* */ /* Client applications can register new rasters through the */ /* FT_Set_Raster() API. */ #ifndef FT_NO_DEFAULT_RASTER FT_EXPORT_VAR( FT_Raster_Funcs ) ft_default_raster; #endif /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /**** ****/ /**** ****/ /**** PIC-Support Macros for ftimage.h ****/ /**** ****/ /**** ****/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /* */ /* <Macro> */ /* FT_DEFINE_OUTLINE_FUNCS */ /* */ /* <Description> */ /* Used to initialize an instance of FT_Outline_Funcs struct. */ /* When FT_CONFIG_OPTION_PIC is defined an init funtion will need to */ /* called with a pre-allocated stracture to be filled. */ /* When FT_CONFIG_OPTION_PIC is not defined the struct will be */ /* allocated in the global scope (or the scope where the macro */ /* is used). */ /* */ #ifndef FT_CONFIG_OPTION_PIC #define FT_DEFINE_OUTLINE_FUNCS(class_, move_to_, line_to_, conic_to_, \ cubic_to_, shift_, delta_) \ static const FT_Outline_Funcs class_ = \ { \ move_to_, line_to_, conic_to_, cubic_to_, shift_, delta_ \ }; #else /* FT_CONFIG_OPTION_PIC */ #define FT_DEFINE_OUTLINE_FUNCS(class_, move_to_, line_to_, conic_to_, \ cubic_to_, shift_, delta_) \ static FT_Error \ Init_Class_##class_( FT_Outline_Funcs* clazz ) \ { \ clazz->move_to = move_to_; \ clazz->line_to = line_to_; \ clazz->conic_to = conic_to_; \ clazz->cubic_to = cubic_to_; \ clazz->shift = shift_; \ clazz->delta = delta_; \ return FT_Err_Ok; \ } #endif /* FT_CONFIG_OPTION_PIC */ /*************************************************************************/ /* */ /* <Macro> */ /* FT_DEFINE_RASTER_FUNCS */ /* */ /* <Description> */ /* Used to initialize an instance of FT_Raster_Funcs struct. */ /* When FT_CONFIG_OPTION_PIC is defined an init funtion will need to */ /* called with a pre-allocated stracture to be filled. */ /* When FT_CONFIG_OPTION_PIC is not defined the struct will be */ /* allocated in the global scope (or the scope where the macro */ /* is used). */ /* */ #ifndef FT_CONFIG_OPTION_PIC #define FT_DEFINE_RASTER_FUNCS(class_, glyph_format_, raster_new_, \ raster_reset_, raster_set_mode_, \ raster_render_, raster_done_) \ const FT_Raster_Funcs class_ = \ { \ glyph_format_, raster_new_, raster_reset_, \ raster_set_mode_, raster_render_, raster_done_ \ }; #else /* FT_CONFIG_OPTION_PIC */ #define FT_DEFINE_RASTER_FUNCS(class_, glyph_format_, raster_new_, \ raster_reset_, raster_set_mode_, raster_render_, raster_done_) \ void \ FT_Init_Class_##class_( FT_Raster_Funcs* clazz ) \ { \ clazz->glyph_format = glyph_format_; \ clazz->raster_new = raster_new_; \ clazz->raster_reset = raster_reset_; \ clazz->raster_set_mode = raster_set_mode_; \ clazz->raster_render = raster_render_; \ clazz->raster_done = raster_done_; \ } #endif /* FT_CONFIG_OPTION_PIC */ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /**** ****/ /**** ****/ /**** PIC-Support Macros for ftrender.h ****/ /**** ****/ /**** ****/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /* */ /* <Macro> */ /* FT_DEFINE_GLYPH */ /* */ /* <Description> */ /* Used to initialize an instance of FT_Glyph_Class struct. */ /* When FT_CONFIG_OPTION_PIC is defined an init funtion will need to */ /* called with a pre-allocated stracture to be filled. */ /* When FT_CONFIG_OPTION_PIC is not defined the struct will be */ /* allocated in the global scope (or the scope where the macro */ /* is used). */ /* */ #ifndef FT_CONFIG_OPTION_PIC #define FT_DEFINE_GLYPH(class_, size_, format_, init_, done_, copy_, \ transform_, bbox_, prepare_) \ FT_CALLBACK_TABLE_DEF \ const FT_Glyph_Class class_ = \ { \ size_, format_, init_, done_, copy_, transform_, bbox_, prepare_ \ }; #else /* FT_CONFIG_OPTION_PIC */ #define FT_DEFINE_GLYPH(class_, size_, format_, init_, done_, copy_, \ transform_, bbox_, prepare_) \ void \ FT_Init_Class_##class_( FT_Glyph_Class* clazz ) \ { \ clazz->glyph_size = size_; \ clazz->glyph_format = format_; \ clazz->glyph_init = init_; \ clazz->glyph_done = done_; \ clazz->glyph_copy = copy_; \ clazz->glyph_transform = transform_; \ clazz->glyph_bbox = bbox_; \ clazz->glyph_prepare = prepare_; \ } #endif /* FT_CONFIG_OPTION_PIC */ /*************************************************************************/ /* */ /* <Macro> */ /* FT_DECLARE_RENDERER */ /* */ /* <Description> */ /* Used to create a forward declaration of a */ /* FT_Renderer_Class stract instance. */ /* */ /* <Macro> */ /* FT_DEFINE_RENDERER */ /* */ /* <Description> */ /* Used to initialize an instance of FT_Renderer_Class struct. */ /* */ /* When FT_CONFIG_OPTION_PIC is defined a Create funtion will need */ /* to called with a pointer where the allocated stracture is returned.*/ /* And when it is no longer needed a Destroy function needs */ /* to be called to release that allocation. */ /* fcinit.c (ft_create_default_module_classes) already contains */ /* a mechanism to call these functions for the default modules */ /* described in ftmodule.h */ /* */ /* Notice that the created Create and Destroy functions call */ /* pic_init and pic_free function to allow you to manually allocate */ /* and initialize any additional global data, like module specific */ /* interface, and put them in the global pic container defined in */ /* ftpic.h. if you don't need them just implement the functions as */ /* empty to resolve the link error. */ /* */ /* When FT_CONFIG_OPTION_PIC is not defined the struct will be */ /* allocated in the global scope (or the scope where the macro */ /* is used). */ /* */ #ifndef FT_CONFIG_OPTION_PIC #define FT_DECLARE_RENDERER(class_) \ FT_EXPORT_VAR( const FT_Renderer_Class ) class_; #define FT_DEFINE_RENDERER(class_, \ flags_, size_, name_, version_, requires_, \ interface_, init_, done_, get_interface_, \ glyph_format_, render_glyph_, transform_glyph_, \ get_glyph_cbox_, set_mode_, raster_class_ ) \ FT_CALLBACK_TABLE_DEF \ const FT_Renderer_Class class_ = \ { \ FT_DEFINE_ROOT_MODULE(flags_,size_,name_,version_,requires_, \ interface_,init_,done_,get_interface_) \ glyph_format_, \ \ render_glyph_, \ transform_glyph_, \ get_glyph_cbox_, \ set_mode_, \ \ raster_class_ \ }; #else /* FT_CONFIG_OPTION_PIC */ #define FT_DECLARE_RENDERER(class_) FT_DECLARE_MODULE(class_) #define FT_DEFINE_RENDERER(class_, \ flags_, size_, name_, version_, requires_, \ interface_, init_, done_, get_interface_, \ glyph_format_, render_glyph_, transform_glyph_, \ get_glyph_cbox_, set_mode_, raster_class_ ) \ void class_##_pic_free( FT_Library library ); \ FT_Error class_##_pic_init( FT_Library library ); \ \ void \ FT_Destroy_Class_##class_( FT_Library library, \ FT_Module_Class* clazz ) \ { \ FT_Renderer_Class* rclazz = (FT_Renderer_Class*)clazz; \ FT_Memory memory = library->memory; \ class_##_pic_free( library ); \ if ( rclazz ) \ FT_FREE( rclazz ); \ } \ \ FT_Error \ FT_Create_Class_##class_( FT_Library library, \ FT_Module_Class** output_class ) \ { \ FT_Renderer_Class* clazz; \ FT_Error error; \ FT_Memory memory = library->memory; \ \ if ( FT_ALLOC( clazz, sizeof(*clazz) ) ) \ return error; \ \ error = class_##_pic_init( library ); \ if(error) \ { \ FT_FREE( clazz ); \ return error; \ } \ \ FT_DEFINE_ROOT_MODULE(flags_,size_,name_,version_,requires_, \ interface_,init_,done_,get_interface_) \ \ clazz->glyph_format = glyph_format_; \ \ clazz->render_glyph = render_glyph_; \ clazz->transform_glyph = transform_glyph_; \ clazz->get_glyph_cbox = get_glyph_cbox_; \ clazz->set_mode = set_mode_; \ \ clazz->raster_class = raster_class_; \ \ *output_class = (FT_Module_Class*)clazz; \ return FT_Err_Ok; \ } #endif /* FT_CONFIG_OPTION_PIC */ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /**** ****/ /**** ****/ /**** PIC-Support Macros for ftmodapi.h ****/ /**** ****/ /**** ****/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ #ifdef FT_CONFIG_OPTION_PIC /*************************************************************************/ /* */ /* <FuncType> */ /* FT_Module_Creator */ /* */ /* <Description> */ /* A function used to create (allocate) a new module class object. */ /* The object's members are initialized, but the module itself is */ /* not. */ /* */ /* <Input> */ /* memory :: A handle to the memory manager. */ /* output_class :: Initialized with the newly allocated class. */ /* */ typedef FT_Error (*FT_Module_Creator)( FT_Memory memory, FT_Module_Class** output_class ); /*************************************************************************/ /* */ /* <FuncType> */ /* FT_Module_Destroyer */ /* */ /* <Description> */ /* A function used to destroy (deallocate) a module class object. */ /* */ /* <Input> */ /* memory :: A handle to the memory manager. */ /* clazz :: Module class to destroy. */ /* */ typedef void (*FT_Module_Destroyer)( FT_Memory memory, FT_Module_Class* clazz ); #endif /*************************************************************************/ /* */ /* <Macro> */ /* FT_DECLARE_MODULE */ /* */ /* <Description> */ /* Used to create a forward declaration of a */ /* FT_Module_Class stract instance. */ /* */ /* <Macro> */ /* FT_DEFINE_MODULE */ /* */ /* <Description> */ /* Used to initialize an instance of FT_Module_Class struct. */ /* */ /* When FT_CONFIG_OPTION_PIC is defined a Create funtion will need */ /* to called with a pointer where the allocated stracture is returned.*/ /* And when it is no longer needed a Destroy function needs */ /* to be called to release that allocation. */ /* fcinit.c (ft_create_default_module_classes) already contains */ /* a mechanism to call these functions for the default modules */ /* described in ftmodule.h */ /* */ /* Notice that the created Create and Destroy functions call */ /* pic_init and pic_free function to allow you to manually allocate */ /* and initialize any additional global data, like module specific */ /* interface, and put them in the global pic container defined in */ /* ftpic.h. if you don't need them just implement the functions as */ /* empty to resolve the link error. */ /* */ /* When FT_CONFIG_OPTION_PIC is not defined the struct will be */ /* allocated in the global scope (or the scope where the macro */ /* is used). */ /* */ /* <Macro> */ /* FT_DEFINE_ROOT_MODULE */ /* */ /* <Description> */ /* Used to initialize an instance of FT_Module_Class struct inside */ /* another stract that contains it or in a function that initializes */ /* that containing stract */ /* */ #ifndef FT_CONFIG_OPTION_PIC #define FT_DECLARE_MODULE(class_) \ FT_CALLBACK_TABLE \ const FT_Module_Class class_; \ #define FT_DEFINE_ROOT_MODULE(flags_, size_, name_, version_, requires_, \ interface_, init_, done_, get_interface_) \ { \ flags_, \ size_, \ \ name_, \ version_, \ requires_, \ \ interface_, \ \ init_, \ done_, \ get_interface_, \ }, #define FT_DEFINE_MODULE(class_, flags_, size_, name_, version_, requires_, \ interface_, init_, done_, get_interface_) \ FT_CALLBACK_TABLE_DEF \ const FT_Module_Class class_ = \ { \ flags_, \ size_, \ \ name_, \ version_, \ requires_, \ \ interface_, \ \ init_, \ done_, \ get_interface_, \ }; #else /* FT_CONFIG_OPTION_PIC */ #define FT_DECLARE_MODULE(class_) \ FT_Error FT_Create_Class_##class_( FT_Library library, \ FT_Module_Class** output_class ); \ void FT_Destroy_Class_##class_( FT_Library library, \ FT_Module_Class* clazz ); #define FT_DEFINE_ROOT_MODULE(flags_, size_, name_, version_, requires_, \ interface_, init_, done_, get_interface_) \ clazz->root.module_flags = flags_; \ clazz->root.module_size = size_; \ clazz->root.module_name = name_; \ clazz->root.module_version = version_; \ clazz->root.module_requires = requires_; \ \ clazz->root.module_interface = interface_; \ \ clazz->root.module_init = init_; \ clazz->root.module_done = done_; \ clazz->root.get_interface = get_interface_; #define FT_DEFINE_MODULE(class_, flags_, size_, name_, version_, requires_, \ interface_, init_, done_, get_interface_) \ void class_##_pic_free( FT_Library library ); \ FT_Error class_##_pic_init( FT_Library library ); \ \ void \ FT_Destroy_Class_##class_( FT_Library library, \ FT_Module_Class* clazz ) \ { \ FT_Memory memory = library->memory; \ class_##_pic_free( library ); \ if ( clazz ) \ FT_FREE( clazz ); \ } \ \ FT_Error \ FT_Create_Class_##class_( FT_Library library, \ FT_Module_Class** output_class ) \ { \ FT_Memory memory = library->memory; \ FT_Module_Class* clazz; \ FT_Error error; \ \ if ( FT_ALLOC( clazz, sizeof(*clazz) ) ) \ return error; \ error = class_##_pic_init( library ); \ if(error) \ { \ FT_FREE( clazz ); \ return error; \ } \ \ clazz->module_flags = flags_; \ clazz->module_size = size_; \ clazz->module_name = name_; \ clazz->module_version = version_; \ clazz->module_requires = requires_; \ \ clazz->module_interface = interface_; \ \ clazz->module_init = init_; \ clazz->module_done = done_; \ clazz->get_interface = get_interface_; \ \ *output_class = clazz; \ return FT_Err_Ok; \ } #endif /* FT_CONFIG_OPTION_PIC */ FT_END_HEADER #endif /* __FTOBJS_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/internal/ftpic.h ================================================ /***************************************************************************/ /* */ /* ftpic.h */ /* */ /* The FreeType position independent code services (declaration). */ /* */ /* Copyright 2009 by */ /* Oran Agra and Mickey Gabel. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /*************************************************************************/ /* */ /* Modules that ordinarily have const global data that need address */ /* can instead define pointers here. */ /* */ /*************************************************************************/ #ifndef __FTPIC_H__ #define __FTPIC_H__ FT_BEGIN_HEADER #ifdef FT_CONFIG_OPTION_PIC typedef struct FT_PIC_Container_ { /* pic containers for base */ void* base; /* pic containers for modules */ void* autofit; void* cff; void* pshinter; void* psnames; void* raster; void* sfnt; void* smooth; void* truetype; } FT_PIC_Container; /* Initialize the various function tables, structs, etc. stored in the container. */ FT_BASE( FT_Error ) ft_pic_container_init( FT_Library library ); /* Destroy the contents of the container. */ FT_BASE( void ) ft_pic_container_destroy( FT_Library library ); #endif /* FT_CONFIG_OPTION_PIC */ /* */ FT_END_HEADER #endif /* __FTPIC_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/internal/ftrfork.h ================================================ /***************************************************************************/ /* */ /* ftrfork.h */ /* */ /* Embedded resource forks accessor (specification). */ /* */ /* Copyright 2004, 2006, 2007 by */ /* Masatake YAMATO and Redhat K.K. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /***************************************************************************/ /* Development of the code in this file is support of */ /* Information-technology Promotion Agency, Japan. */ /***************************************************************************/ #ifndef __FTRFORK_H__ #define __FTRFORK_H__ #include <ft2build.h> #include FT_INTERNAL_OBJECTS_H FT_BEGIN_HEADER /* Number of guessing rules supported in `FT_Raccess_Guess'. */ /* Don't forget to increment the number if you add a new guessing rule. */ #define FT_RACCESS_N_RULES 9 /* A structure to describe a reference in a resource by its resource ID */ /* and internal offset. The `POST' resource expects to be concatenated */ /* by the order of resource IDs instead of its appearance in the file. */ typedef struct FT_RFork_Ref_ { FT_UShort res_id; FT_ULong offset; } FT_RFork_Ref; /*************************************************************************/ /* */ /* <Function> */ /* FT_Raccess_Guess */ /* */ /* <Description> */ /* Guess a file name and offset where the actual resource fork is */ /* stored. The macro FT_RACCESS_N_RULES holds the number of */ /* guessing rules; the guessed result for the Nth rule is */ /* represented as a triplet: a new file name (new_names[N]), a file */ /* offset (offsets[N]), and an error code (errors[N]). */ /* */ /* <Input> */ /* library :: */ /* A FreeType library instance. */ /* */ /* stream :: */ /* A file stream containing the resource fork. */ /* */ /* base_name :: */ /* The (base) file name of the resource fork used for some */ /* guessing rules. */ /* */ /* <Output> */ /* new_names :: */ /* An array of guessed file names in which the resource forks may */ /* exist. If `new_names[N]' is NULL, the guessed file name is */ /* equal to `base_name'. */ /* */ /* offsets :: */ /* An array of guessed file offsets. `offsets[N]' holds the file */ /* offset of the possible start of the resource fork in file */ /* `new_names[N]'. */ /* */ /* errors :: */ /* An array of FreeType error codes. `errors[N]' is the error */ /* code of Nth guessing rule function. If `errors[N]' is not */ /* FT_Err_Ok, `new_names[N]' and `offsets[N]' are meaningless. */ /* */ FT_BASE( void ) FT_Raccess_Guess( FT_Library library, FT_Stream stream, char* base_name, char** new_names, FT_Long* offsets, FT_Error* errors ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Raccess_Get_HeaderInfo */ /* */ /* <Description> */ /* Get the information from the header of resource fork. The */ /* information includes the file offset where the resource map */ /* starts, and the file offset where the resource data starts. */ /* `FT_Raccess_Get_DataOffsets' requires these two data. */ /* */ /* <Input> */ /* library :: */ /* A FreeType library instance. */ /* */ /* stream :: */ /* A file stream containing the resource fork. */ /* */ /* rfork_offset :: */ /* The file offset where the resource fork starts. */ /* */ /* <Output> */ /* map_offset :: */ /* The file offset where the resource map starts. */ /* */ /* rdata_pos :: */ /* The file offset where the resource data starts. */ /* */ /* <Return> */ /* FreeType error code. FT_Err_Ok means success. */ /* */ FT_BASE( FT_Error ) FT_Raccess_Get_HeaderInfo( FT_Library library, FT_Stream stream, FT_Long rfork_offset, FT_Long *map_offset, FT_Long *rdata_pos ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Raccess_Get_DataOffsets */ /* */ /* <Description> */ /* Get the data offsets for a tag in a resource fork. Offsets are */ /* stored in an array because, in some cases, resources in a resource */ /* fork have the same tag. */ /* */ /* <Input> */ /* library :: */ /* A FreeType library instance. */ /* */ /* stream :: */ /* A file stream containing the resource fork. */ /* */ /* map_offset :: */ /* The file offset where the resource map starts. */ /* */ /* rdata_pos :: */ /* The file offset where the resource data starts. */ /* */ /* tag :: */ /* The resource tag. */ /* */ /* <Output> */ /* offsets :: */ /* The stream offsets for the resource data specified by `tag'. */ /* This array is allocated by the function, so you have to call */ /* @ft_mem_free after use. */ /* */ /* count :: */ /* The length of offsets array. */ /* */ /* <Return> */ /* FreeType error code. FT_Err_Ok means success. */ /* */ /* <Note> */ /* Normally you should use `FT_Raccess_Get_HeaderInfo' to get the */ /* value for `map_offset' and `rdata_pos'. */ /* */ FT_BASE( FT_Error ) FT_Raccess_Get_DataOffsets( FT_Library library, FT_Stream stream, FT_Long map_offset, FT_Long rdata_pos, FT_Long tag, FT_Long **offsets, FT_Long *count ); FT_END_HEADER #endif /* __FTRFORK_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/internal/ftserv.h ================================================ /***************************************************************************/ /* */ /* ftserv.h */ /* */ /* The FreeType services (specification only). */ /* */ /* Copyright 2003, 2004, 2005, 2006, 2007 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /*************************************************************************/ /* */ /* Each module can export one or more `services'. Each service is */ /* identified by a constant string and modeled by a pointer; the latter */ /* generally corresponds to a structure containing function pointers. */ /* */ /* Note that a service's data cannot be a mere function pointer because */ /* in C it is possible that function pointers might be implemented */ /* differently than data pointers (e.g. 48 bits instead of 32). */ /* */ /*************************************************************************/ #ifndef __FTSERV_H__ #define __FTSERV_H__ FT_BEGIN_HEADER #if defined( _MSC_VER ) /* Visual C++ (and Intel C++) */ /* we disable the warning `conditional expression is constant' here */ /* in order to compile cleanly with the maximum level of warnings */ #pragma warning( disable : 4127 ) #endif /* _MSC_VER */ /* * @macro: * FT_FACE_FIND_SERVICE * * @description: * This macro is used to look up a service from a face's driver module. * * @input: * face :: * The source face handle. * * id :: * A string describing the service as defined in the service's * header files (e.g. FT_SERVICE_ID_MULTI_MASTERS which expands to * `multi-masters'). It is automatically prefixed with * `FT_SERVICE_ID_'. * * @output: * ptr :: * A variable that receives the service pointer. Will be NULL * if not found. */ #ifdef __cplusplus #define FT_FACE_FIND_SERVICE( face, ptr, id ) \ FT_BEGIN_STMNT \ FT_Module module = FT_MODULE( FT_FACE( face )->driver ); \ FT_Pointer _tmp_ = NULL; \ FT_Pointer* _pptr_ = (FT_Pointer*)&(ptr); \ \ \ if ( module->clazz->get_interface ) \ _tmp_ = module->clazz->get_interface( module, FT_SERVICE_ID_ ## id ); \ *_pptr_ = _tmp_; \ FT_END_STMNT #else /* !C++ */ #define FT_FACE_FIND_SERVICE( face, ptr, id ) \ FT_BEGIN_STMNT \ FT_Module module = FT_MODULE( FT_FACE( face )->driver ); \ FT_Pointer _tmp_ = NULL; \ \ if ( module->clazz->get_interface ) \ _tmp_ = module->clazz->get_interface( module, FT_SERVICE_ID_ ## id ); \ ptr = _tmp_; \ FT_END_STMNT #endif /* !C++ */ /* * @macro: * FT_FACE_FIND_GLOBAL_SERVICE * * @description: * This macro is used to look up a service from all modules. * * @input: * face :: * The source face handle. * * id :: * A string describing the service as defined in the service's * header files (e.g. FT_SERVICE_ID_MULTI_MASTERS which expands to * `multi-masters'). It is automatically prefixed with * `FT_SERVICE_ID_'. * * @output: * ptr :: * A variable that receives the service pointer. Will be NULL * if not found. */ #ifdef __cplusplus #define FT_FACE_FIND_GLOBAL_SERVICE( face, ptr, id ) \ FT_BEGIN_STMNT \ FT_Module module = FT_MODULE( FT_FACE( face )->driver ); \ FT_Pointer _tmp_; \ FT_Pointer* _pptr_ = (FT_Pointer*)&(ptr); \ \ \ _tmp_ = ft_module_get_service( module, FT_SERVICE_ID_ ## id ); \ *_pptr_ = _tmp_; \ FT_END_STMNT #else /* !C++ */ #define FT_FACE_FIND_GLOBAL_SERVICE( face, ptr, id ) \ FT_BEGIN_STMNT \ FT_Module module = FT_MODULE( FT_FACE( face )->driver ); \ FT_Pointer _tmp_; \ \ \ _tmp_ = ft_module_get_service( module, FT_SERVICE_ID_ ## id ); \ ptr = _tmp_; \ FT_END_STMNT #endif /* !C++ */ /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** S E R V I C E D E S C R I P T O R S *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ /* * The following structure is used to _describe_ a given service * to the library. This is useful to build simple static service lists. */ typedef struct FT_ServiceDescRec_ { const char* serv_id; /* service name */ const void* serv_data; /* service pointer/data */ } FT_ServiceDescRec; typedef const FT_ServiceDescRec* FT_ServiceDesc; /*************************************************************************/ /* */ /* <Macro> */ /* FT_DEFINE_SERVICEDESCREC1 .. FT_DEFINE_SERVICEDESCREC6 */ /* */ /* <Description> */ /* Used to initialize an array of FT_ServiceDescRec structs. */ /* */ /* When FT_CONFIG_OPTION_PIC is defined a Create funtion will need */ /* to called with a pointer where the allocated array is returned. */ /* And when it is no longer needed a Destroy function needs */ /* to be called to release that allocation. */ /* */ /* These functions should be manyally called from the pic_init and */ /* pic_free functions of your module (see FT_DEFINE_MODULE) */ /* */ /* When FT_CONFIG_OPTION_PIC is not defined the array will be */ /* allocated in the global scope (or the scope where the macro */ /* is used). */ /* */ #ifndef FT_CONFIG_OPTION_PIC #define FT_DEFINE_SERVICEDESCREC1(class_, serv_id_1, serv_data_1) \ static const FT_ServiceDescRec class_[] = \ { \ {serv_id_1, serv_data_1}, \ {NULL, NULL} \ }; #define FT_DEFINE_SERVICEDESCREC2(class_, serv_id_1, serv_data_1, \ serv_id_2, serv_data_2) \ static const FT_ServiceDescRec class_[] = \ { \ {serv_id_1, serv_data_1}, \ {serv_id_2, serv_data_2}, \ {NULL, NULL} \ }; #define FT_DEFINE_SERVICEDESCREC3(class_, serv_id_1, serv_data_1, \ serv_id_2, serv_data_2, serv_id_3, serv_data_3) \ static const FT_ServiceDescRec class_[] = \ { \ {serv_id_1, serv_data_1}, \ {serv_id_2, serv_data_2}, \ {serv_id_3, serv_data_3}, \ {NULL, NULL} \ }; #define FT_DEFINE_SERVICEDESCREC4(class_, serv_id_1, serv_data_1, \ serv_id_2, serv_data_2, serv_id_3, serv_data_3, \ serv_id_4, serv_data_4) \ static const FT_ServiceDescRec class_[] = \ { \ {serv_id_1, serv_data_1}, \ {serv_id_2, serv_data_2}, \ {serv_id_3, serv_data_3}, \ {serv_id_4, serv_data_4}, \ {NULL, NULL} \ }; #define FT_DEFINE_SERVICEDESCREC5(class_, serv_id_1, serv_data_1, \ serv_id_2, serv_data_2, serv_id_3, serv_data_3, \ serv_id_4, serv_data_4, serv_id_5, serv_data_5) \ static const FT_ServiceDescRec class_[] = \ { \ {serv_id_1, serv_data_1}, \ {serv_id_2, serv_data_2}, \ {serv_id_3, serv_data_3}, \ {serv_id_4, serv_data_4}, \ {serv_id_5, serv_data_5}, \ {NULL, NULL} \ }; #define FT_DEFINE_SERVICEDESCREC6(class_, serv_id_1, serv_data_1, \ serv_id_2, serv_data_2, serv_id_3, serv_data_3, \ serv_id_4, serv_data_4, serv_id_5, serv_data_5, \ serv_id_6, serv_data_6) \ static const FT_ServiceDescRec class_[] = \ { \ {serv_id_1, serv_data_1}, \ {serv_id_2, serv_data_2}, \ {serv_id_3, serv_data_3}, \ {serv_id_4, serv_data_4}, \ {serv_id_5, serv_data_5}, \ {serv_id_6, serv_data_6}, \ {NULL, NULL} \ }; #else /* FT_CONFIG_OPTION_PIC */ #define FT_DEFINE_SERVICEDESCREC1(class_, serv_id_1, serv_data_1) \ void \ FT_Destroy_Class_##class_( FT_Library library, \ FT_ServiceDescRec* clazz ) \ { \ FT_Memory memory = library->memory; \ if ( clazz ) \ FT_FREE( clazz ); \ } \ \ FT_Error \ FT_Create_Class_##class_( FT_Library library, \ FT_ServiceDescRec** output_class) \ { \ FT_ServiceDescRec* clazz; \ FT_Error error; \ FT_Memory memory = library->memory; \ \ if ( FT_ALLOC( clazz, sizeof(*clazz)*2 ) ) \ return error; \ clazz[0].serv_id = serv_id_1; \ clazz[0].serv_data = serv_data_1; \ clazz[1].serv_id = NULL; \ clazz[1].serv_data = NULL; \ *output_class = clazz; \ return FT_Err_Ok; \ } #define FT_DEFINE_SERVICEDESCREC2(class_, serv_id_1, serv_data_1, \ serv_id_2, serv_data_2) \ void \ FT_Destroy_Class_##class_( FT_Library library, \ FT_ServiceDescRec* clazz ) \ { \ FT_Memory memory = library->memory; \ if ( clazz ) \ FT_FREE( clazz ); \ } \ \ FT_Error \ FT_Create_Class_##class_( FT_Library library, \ FT_ServiceDescRec** output_class) \ { \ FT_ServiceDescRec* clazz; \ FT_Error error; \ FT_Memory memory = library->memory; \ \ if ( FT_ALLOC( clazz, sizeof(*clazz)*3 ) ) \ return error; \ clazz[0].serv_id = serv_id_1; \ clazz[0].serv_data = serv_data_1; \ clazz[1].serv_id = serv_id_2; \ clazz[1].serv_data = serv_data_2; \ clazz[2].serv_id = NULL; \ clazz[2].serv_data = NULL; \ *output_class = clazz; \ return FT_Err_Ok; \ } #define FT_DEFINE_SERVICEDESCREC3(class_, serv_id_1, serv_data_1, \ serv_id_2, serv_data_2, serv_id_3, serv_data_3) \ void \ FT_Destroy_Class_##class_( FT_Library library, \ FT_ServiceDescRec* clazz ) \ { \ FT_Memory memory = library->memory; \ if ( clazz ) \ FT_FREE( clazz ); \ } \ \ FT_Error \ FT_Create_Class_##class_( FT_Library library, \ FT_ServiceDescRec** output_class) \ { \ FT_ServiceDescRec* clazz; \ FT_Error error; \ FT_Memory memory = library->memory; \ \ if ( FT_ALLOC( clazz, sizeof(*clazz)*4 ) ) \ return error; \ clazz[0].serv_id = serv_id_1; \ clazz[0].serv_data = serv_data_1; \ clazz[1].serv_id = serv_id_2; \ clazz[1].serv_data = serv_data_2; \ clazz[2].serv_id = serv_id_3; \ clazz[2].serv_data = serv_data_3; \ clazz[3].serv_id = NULL; \ clazz[3].serv_data = NULL; \ *output_class = clazz; \ return FT_Err_Ok; \ } #define FT_DEFINE_SERVICEDESCREC4(class_, serv_id_1, serv_data_1, \ serv_id_2, serv_data_2, serv_id_3, serv_data_3, \ serv_id_4, serv_data_4) \ void \ FT_Destroy_Class_##class_( FT_Library library, \ FT_ServiceDescRec* clazz ) \ { \ FT_Memory memory = library->memory; \ if ( clazz ) \ FT_FREE( clazz ); \ } \ \ FT_Error \ FT_Create_Class_##class_( FT_Library library, \ FT_ServiceDescRec** output_class) \ { \ FT_ServiceDescRec* clazz; \ FT_Error error; \ FT_Memory memory = library->memory; \ \ if ( FT_ALLOC( clazz, sizeof(*clazz)*5 ) ) \ return error; \ clazz[0].serv_id = serv_id_1; \ clazz[0].serv_data = serv_data_1; \ clazz[1].serv_id = serv_id_2; \ clazz[1].serv_data = serv_data_2; \ clazz[2].serv_id = serv_id_3; \ clazz[2].serv_data = serv_data_3; \ clazz[3].serv_id = serv_id_4; \ clazz[3].serv_data = serv_data_4; \ clazz[4].serv_id = NULL; \ clazz[4].serv_data = NULL; \ *output_class = clazz; \ return FT_Err_Ok; \ } #define FT_DEFINE_SERVICEDESCREC5(class_, serv_id_1, serv_data_1, \ serv_id_2, serv_data_2, serv_id_3, serv_data_3, serv_id_4, \ serv_data_4, serv_id_5, serv_data_5) \ void \ FT_Destroy_Class_##class_( FT_Library library, \ FT_ServiceDescRec* clazz ) \ { \ FT_Memory memory = library->memory; \ if ( clazz ) \ FT_FREE( clazz ); \ } \ \ FT_Error \ FT_Create_Class_##class_( FT_Library library, \ FT_ServiceDescRec** output_class) \ { \ FT_ServiceDescRec* clazz; \ FT_Error error; \ FT_Memory memory = library->memory; \ \ if ( FT_ALLOC( clazz, sizeof(*clazz)*6 ) ) \ return error; \ clazz[0].serv_id = serv_id_1; \ clazz[0].serv_data = serv_data_1; \ clazz[1].serv_id = serv_id_2; \ clazz[1].serv_data = serv_data_2; \ clazz[2].serv_id = serv_id_3; \ clazz[2].serv_data = serv_data_3; \ clazz[3].serv_id = serv_id_4; \ clazz[3].serv_data = serv_data_4; \ clazz[4].serv_id = serv_id_5; \ clazz[4].serv_data = serv_data_5; \ clazz[5].serv_id = NULL; \ clazz[5].serv_data = NULL; \ *output_class = clazz; \ return FT_Err_Ok; \ } #define FT_DEFINE_SERVICEDESCREC6(class_, serv_id_1, serv_data_1, \ serv_id_2, serv_data_2, serv_id_3, serv_data_3, \ serv_id_4, serv_data_4, serv_id_5, serv_data_5, \ serv_id_6, serv_data_6) \ void \ FT_Destroy_Class_##class_( FT_Library library, \ FT_ServiceDescRec* clazz ) \ { \ FT_Memory memory = library->memory; \ if ( clazz ) \ FT_FREE( clazz ); \ } \ \ FT_Error \ FT_Create_Class_##class_( FT_Library library, \ FT_ServiceDescRec** output_class) \ { \ FT_ServiceDescRec* clazz; \ FT_Error error; \ FT_Memory memory = library->memory; \ \ if ( FT_ALLOC( clazz, sizeof(*clazz)*7 ) ) \ return error; \ clazz[0].serv_id = serv_id_1; \ clazz[0].serv_data = serv_data_1; \ clazz[1].serv_id = serv_id_2; \ clazz[1].serv_data = serv_data_2; \ clazz[2].serv_id = serv_id_3; \ clazz[2].serv_data = serv_data_3; \ clazz[3].serv_id = serv_id_4; \ clazz[3].serv_data = serv_data_4; \ clazz[4].serv_id = serv_id_5; \ clazz[4].serv_data = serv_data_5; \ clazz[5].serv_id = serv_id_6; \ clazz[5].serv_data = serv_data_6; \ clazz[6].serv_id = NULL; \ clazz[6].serv_data = NULL; \ *output_class = clazz; \ return FT_Err_Ok; \ } #endif /* FT_CONFIG_OPTION_PIC */ /* * Parse a list of FT_ServiceDescRec descriptors and look for * a specific service by ID. Note that the last element in the * array must be { NULL, NULL }, and that the function should * return NULL if the service isn't available. * * This function can be used by modules to implement their * `get_service' method. */ FT_BASE( FT_Pointer ) ft_service_list_lookup( FT_ServiceDesc service_descriptors, const char* service_id ); /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** S E R V I C E S C A C H E *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ /* * This structure is used to store a cache for several frequently used * services. It is the type of `face->internal->services'. You * should only use FT_FACE_LOOKUP_SERVICE to access it. * * All fields should have the type FT_Pointer to relax compilation * dependencies. We assume the developer isn't completely stupid. * * Each field must be named `service_XXXX' where `XXX' corresponds to * the correct FT_SERVICE_ID_XXXX macro. See the definition of * FT_FACE_LOOKUP_SERVICE below how this is implemented. * */ typedef struct FT_ServiceCacheRec_ { FT_Pointer service_POSTSCRIPT_FONT_NAME; FT_Pointer service_MULTI_MASTERS; FT_Pointer service_GLYPH_DICT; FT_Pointer service_PFR_METRICS; FT_Pointer service_WINFNT; } FT_ServiceCacheRec, *FT_ServiceCache; /* * A magic number used within the services cache. */ #define FT_SERVICE_UNAVAILABLE ((FT_Pointer)-2) /* magic number */ /* * @macro: * FT_FACE_LOOKUP_SERVICE * * @description: * This macro is used to lookup a service from a face's driver module * using its cache. * * @input: * face:: * The source face handle containing the cache. * * field :: * The field name in the cache. * * id :: * The service ID. * * @output: * ptr :: * A variable receiving the service data. NULL if not available. */ #ifdef __cplusplus #define FT_FACE_LOOKUP_SERVICE( face, ptr, id ) \ FT_BEGIN_STMNT \ FT_Pointer svc; \ FT_Pointer* Pptr = (FT_Pointer*)&(ptr); \ \ \ svc = FT_FACE( face )->internal->services. service_ ## id; \ if ( svc == FT_SERVICE_UNAVAILABLE ) \ svc = NULL; \ else if ( svc == NULL ) \ { \ FT_FACE_FIND_SERVICE( face, svc, id ); \ \ FT_FACE( face )->internal->services. service_ ## id = \ (FT_Pointer)( svc != NULL ? svc \ : FT_SERVICE_UNAVAILABLE ); \ } \ *Pptr = svc; \ FT_END_STMNT #else /* !C++ */ #define FT_FACE_LOOKUP_SERVICE( face, ptr, id ) \ FT_BEGIN_STMNT \ FT_Pointer svc; \ \ \ svc = FT_FACE( face )->internal->services. service_ ## id; \ if ( svc == FT_SERVICE_UNAVAILABLE ) \ svc = NULL; \ else if ( svc == NULL ) \ { \ FT_FACE_FIND_SERVICE( face, svc, id ); \ \ FT_FACE( face )->internal->services. service_ ## id = \ (FT_Pointer)( svc != NULL ? svc \ : FT_SERVICE_UNAVAILABLE ); \ } \ ptr = svc; \ FT_END_STMNT #endif /* !C++ */ /* * A macro used to define new service structure types. */ #define FT_DEFINE_SERVICE( name ) \ typedef struct FT_Service_ ## name ## Rec_ \ FT_Service_ ## name ## Rec ; \ typedef struct FT_Service_ ## name ## Rec_ \ const * FT_Service_ ## name ; \ struct FT_Service_ ## name ## Rec_ /* */ /* * The header files containing the services. */ #define FT_SERVICE_BDF_H <freetype/internal/services/svbdf.h> #define FT_SERVICE_CID_H <freetype/internal/services/svcid.h> #define FT_SERVICE_GLYPH_DICT_H <freetype/internal/services/svgldict.h> #define FT_SERVICE_GX_VALIDATE_H <freetype/internal/services/svgxval.h> #define FT_SERVICE_KERNING_H <freetype/internal/services/svkern.h> #define FT_SERVICE_MULTIPLE_MASTERS_H <freetype/internal/services/svmm.h> #define FT_SERVICE_OPENTYPE_VALIDATE_H <freetype/internal/services/svotval.h> #define FT_SERVICE_PFR_H <freetype/internal/services/svpfr.h> #define FT_SERVICE_POSTSCRIPT_CMAPS_H <freetype/internal/services/svpscmap.h> #define FT_SERVICE_POSTSCRIPT_INFO_H <freetype/internal/services/svpsinfo.h> #define FT_SERVICE_POSTSCRIPT_NAME_H <freetype/internal/services/svpostnm.h> #define FT_SERVICE_SFNT_H <freetype/internal/services/svsfnt.h> #define FT_SERVICE_TRUETYPE_ENGINE_H <freetype/internal/services/svtteng.h> #define FT_SERVICE_TT_CMAP_H <freetype/internal/services/svttcmap.h> #define FT_SERVICE_WINFNT_H <freetype/internal/services/svwinfnt.h> #define FT_SERVICE_XFREE86_NAME_H <freetype/internal/services/svxf86nm.h> #define FT_SERVICE_TRUETYPE_GLYF_H <freetype/internal/services/svttglyf.h> /* */ FT_END_HEADER #endif /* __FTSERV_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/internal/ftstream.h ================================================ /***************************************************************************/ /* */ /* ftstream.h */ /* */ /* Stream handling (specification). */ /* */ /* Copyright 1996-2002, 2004-2006, 2011 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __FTSTREAM_H__ #define __FTSTREAM_H__ #include <ft2build.h> #include FT_SYSTEM_H #include FT_INTERNAL_OBJECTS_H FT_BEGIN_HEADER /* format of an 8-bit frame_op value: */ /* */ /* bit 76543210 */ /* xxxxxxes */ /* */ /* s is set to 1 if the value is signed. */ /* e is set to 1 if the value is little-endian. */ /* xxx is a command. */ #define FT_FRAME_OP_SHIFT 2 #define FT_FRAME_OP_SIGNED 1 #define FT_FRAME_OP_LITTLE 2 #define FT_FRAME_OP_COMMAND( x ) ( x >> FT_FRAME_OP_SHIFT ) #define FT_MAKE_FRAME_OP( command, little, sign ) \ ( ( command << FT_FRAME_OP_SHIFT ) | ( little << 1 ) | sign ) #define FT_FRAME_OP_END 0 #define FT_FRAME_OP_START 1 /* start a new frame */ #define FT_FRAME_OP_BYTE 2 /* read 1-byte value */ #define FT_FRAME_OP_SHORT 3 /* read 2-byte value */ #define FT_FRAME_OP_LONG 4 /* read 4-byte value */ #define FT_FRAME_OP_OFF3 5 /* read 3-byte value */ #define FT_FRAME_OP_BYTES 6 /* read a bytes sequence */ typedef enum FT_Frame_Op_ { ft_frame_end = 0, ft_frame_start = FT_MAKE_FRAME_OP( FT_FRAME_OP_START, 0, 0 ), ft_frame_byte = FT_MAKE_FRAME_OP( FT_FRAME_OP_BYTE, 0, 0 ), ft_frame_schar = FT_MAKE_FRAME_OP( FT_FRAME_OP_BYTE, 0, 1 ), ft_frame_ushort_be = FT_MAKE_FRAME_OP( FT_FRAME_OP_SHORT, 0, 0 ), ft_frame_short_be = FT_MAKE_FRAME_OP( FT_FRAME_OP_SHORT, 0, 1 ), ft_frame_ushort_le = FT_MAKE_FRAME_OP( FT_FRAME_OP_SHORT, 1, 0 ), ft_frame_short_le = FT_MAKE_FRAME_OP( FT_FRAME_OP_SHORT, 1, 1 ), ft_frame_ulong_be = FT_MAKE_FRAME_OP( FT_FRAME_OP_LONG, 0, 0 ), ft_frame_long_be = FT_MAKE_FRAME_OP( FT_FRAME_OP_LONG, 0, 1 ), ft_frame_ulong_le = FT_MAKE_FRAME_OP( FT_FRAME_OP_LONG, 1, 0 ), ft_frame_long_le = FT_MAKE_FRAME_OP( FT_FRAME_OP_LONG, 1, 1 ), ft_frame_uoff3_be = FT_MAKE_FRAME_OP( FT_FRAME_OP_OFF3, 0, 0 ), ft_frame_off3_be = FT_MAKE_FRAME_OP( FT_FRAME_OP_OFF3, 0, 1 ), ft_frame_uoff3_le = FT_MAKE_FRAME_OP( FT_FRAME_OP_OFF3, 1, 0 ), ft_frame_off3_le = FT_MAKE_FRAME_OP( FT_FRAME_OP_OFF3, 1, 1 ), ft_frame_bytes = FT_MAKE_FRAME_OP( FT_FRAME_OP_BYTES, 0, 0 ), ft_frame_skip = FT_MAKE_FRAME_OP( FT_FRAME_OP_BYTES, 0, 1 ) } FT_Frame_Op; typedef struct FT_Frame_Field_ { FT_Byte value; FT_Byte size; FT_UShort offset; } FT_Frame_Field; /* Construct an FT_Frame_Field out of a structure type and a field name. */ /* The structure type must be set in the FT_STRUCTURE macro before */ /* calling the FT_FRAME_START() macro. */ /* */ #define FT_FIELD_SIZE( f ) \ (FT_Byte)sizeof ( ((FT_STRUCTURE*)0)->f ) #define FT_FIELD_SIZE_DELTA( f ) \ (FT_Byte)sizeof ( ((FT_STRUCTURE*)0)->f[0] ) #define FT_FIELD_OFFSET( f ) \ (FT_UShort)( offsetof( FT_STRUCTURE, f ) ) #define FT_FRAME_FIELD( frame_op, field ) \ { \ frame_op, \ FT_FIELD_SIZE( field ), \ FT_FIELD_OFFSET( field ) \ } #define FT_MAKE_EMPTY_FIELD( frame_op ) { frame_op, 0, 0 } #define FT_FRAME_START( size ) { ft_frame_start, 0, size } #define FT_FRAME_END { ft_frame_end, 0, 0 } #define FT_FRAME_LONG( f ) FT_FRAME_FIELD( ft_frame_long_be, f ) #define FT_FRAME_ULONG( f ) FT_FRAME_FIELD( ft_frame_ulong_be, f ) #define FT_FRAME_SHORT( f ) FT_FRAME_FIELD( ft_frame_short_be, f ) #define FT_FRAME_USHORT( f ) FT_FRAME_FIELD( ft_frame_ushort_be, f ) #define FT_FRAME_OFF3( f ) FT_FRAME_FIELD( ft_frame_off3_be, f ) #define FT_FRAME_UOFF3( f ) FT_FRAME_FIELD( ft_frame_uoff3_be, f ) #define FT_FRAME_BYTE( f ) FT_FRAME_FIELD( ft_frame_byte, f ) #define FT_FRAME_CHAR( f ) FT_FRAME_FIELD( ft_frame_schar, f ) #define FT_FRAME_LONG_LE( f ) FT_FRAME_FIELD( ft_frame_long_le, f ) #define FT_FRAME_ULONG_LE( f ) FT_FRAME_FIELD( ft_frame_ulong_le, f ) #define FT_FRAME_SHORT_LE( f ) FT_FRAME_FIELD( ft_frame_short_le, f ) #define FT_FRAME_USHORT_LE( f ) FT_FRAME_FIELD( ft_frame_ushort_le, f ) #define FT_FRAME_OFF3_LE( f ) FT_FRAME_FIELD( ft_frame_off3_le, f ) #define FT_FRAME_UOFF3_LE( f ) FT_FRAME_FIELD( ft_frame_uoff3_le, f ) #define FT_FRAME_SKIP_LONG { ft_frame_long_be, 0, 0 } #define FT_FRAME_SKIP_SHORT { ft_frame_short_be, 0, 0 } #define FT_FRAME_SKIP_BYTE { ft_frame_byte, 0, 0 } #define FT_FRAME_BYTES( field, count ) \ { \ ft_frame_bytes, \ count, \ FT_FIELD_OFFSET( field ) \ } #define FT_FRAME_SKIP_BYTES( count ) { ft_frame_skip, count, 0 } /*************************************************************************/ /* */ /* Integer extraction macros -- the `buffer' parameter must ALWAYS be of */ /* type `char*' or equivalent (1-byte elements). */ /* */ #define FT_BYTE_( p, i ) ( ((const FT_Byte*)(p))[(i)] ) #define FT_INT8_( p, i ) ( ((const FT_Char*)(p))[(i)] ) #define FT_INT16( x ) ( (FT_Int16)(x) ) #define FT_UINT16( x ) ( (FT_UInt16)(x) ) #define FT_INT32( x ) ( (FT_Int32)(x) ) #define FT_UINT32( x ) ( (FT_UInt32)(x) ) #define FT_BYTE_I16( p, i, s ) ( FT_INT16( FT_BYTE_( p, i ) ) << (s) ) #define FT_BYTE_U16( p, i, s ) ( FT_UINT16( FT_BYTE_( p, i ) ) << (s) ) #define FT_BYTE_I32( p, i, s ) ( FT_INT32( FT_BYTE_( p, i ) ) << (s) ) #define FT_BYTE_U32( p, i, s ) ( FT_UINT32( FT_BYTE_( p, i ) ) << (s) ) #define FT_INT8_I16( p, i, s ) ( FT_INT16( FT_INT8_( p, i ) ) << (s) ) #define FT_INT8_U16( p, i, s ) ( FT_UINT16( FT_INT8_( p, i ) ) << (s) ) #define FT_INT8_I32( p, i, s ) ( FT_INT32( FT_INT8_( p, i ) ) << (s) ) #define FT_INT8_U32( p, i, s ) ( FT_UINT32( FT_INT8_( p, i ) ) << (s) ) #define FT_PEEK_SHORT( p ) FT_INT16( FT_INT8_I16( p, 0, 8) | \ FT_BYTE_I16( p, 1, 0) ) #define FT_PEEK_USHORT( p ) FT_UINT16( FT_BYTE_U16( p, 0, 8 ) | \ FT_BYTE_U16( p, 1, 0 ) ) #define FT_PEEK_LONG( p ) FT_INT32( FT_INT8_I32( p, 0, 24 ) | \ FT_BYTE_I32( p, 1, 16 ) | \ FT_BYTE_I32( p, 2, 8 ) | \ FT_BYTE_I32( p, 3, 0 ) ) #define FT_PEEK_ULONG( p ) FT_UINT32( FT_BYTE_U32( p, 0, 24 ) | \ FT_BYTE_U32( p, 1, 16 ) | \ FT_BYTE_U32( p, 2, 8 ) | \ FT_BYTE_U32( p, 3, 0 ) ) #define FT_PEEK_OFF3( p ) FT_INT32( FT_INT8_I32( p, 0, 16 ) | \ FT_BYTE_I32( p, 1, 8 ) | \ FT_BYTE_I32( p, 2, 0 ) ) #define FT_PEEK_UOFF3( p ) FT_UINT32( FT_BYTE_U32( p, 0, 16 ) | \ FT_BYTE_U32( p, 1, 8 ) | \ FT_BYTE_U32( p, 2, 0 ) ) #define FT_PEEK_SHORT_LE( p ) FT_INT16( FT_INT8_I16( p, 1, 8 ) | \ FT_BYTE_I16( p, 0, 0 ) ) #define FT_PEEK_USHORT_LE( p ) FT_UINT16( FT_BYTE_U16( p, 1, 8 ) | \ FT_BYTE_U16( p, 0, 0 ) ) #define FT_PEEK_LONG_LE( p ) FT_INT32( FT_INT8_I32( p, 3, 24 ) | \ FT_BYTE_I32( p, 2, 16 ) | \ FT_BYTE_I32( p, 1, 8 ) | \ FT_BYTE_I32( p, 0, 0 ) ) #define FT_PEEK_ULONG_LE( p ) FT_UINT32( FT_BYTE_U32( p, 3, 24 ) | \ FT_BYTE_U32( p, 2, 16 ) | \ FT_BYTE_U32( p, 1, 8 ) | \ FT_BYTE_U32( p, 0, 0 ) ) #define FT_PEEK_OFF3_LE( p ) FT_INT32( FT_INT8_I32( p, 2, 16 ) | \ FT_BYTE_I32( p, 1, 8 ) | \ FT_BYTE_I32( p, 0, 0 ) ) #define FT_PEEK_UOFF3_LE( p ) FT_UINT32( FT_BYTE_U32( p, 2, 16 ) | \ FT_BYTE_U32( p, 1, 8 ) | \ FT_BYTE_U32( p, 0, 0 ) ) #define FT_NEXT_CHAR( buffer ) \ ( (signed char)*buffer++ ) #define FT_NEXT_BYTE( buffer ) \ ( (unsigned char)*buffer++ ) #define FT_NEXT_SHORT( buffer ) \ ( (short)( buffer += 2, FT_PEEK_SHORT( buffer - 2 ) ) ) #define FT_NEXT_USHORT( buffer ) \ ( (unsigned short)( buffer += 2, FT_PEEK_USHORT( buffer - 2 ) ) ) #define FT_NEXT_OFF3( buffer ) \ ( (long)( buffer += 3, FT_PEEK_OFF3( buffer - 3 ) ) ) #define FT_NEXT_UOFF3( buffer ) \ ( (unsigned long)( buffer += 3, FT_PEEK_UOFF3( buffer - 3 ) ) ) #define FT_NEXT_LONG( buffer ) \ ( (long)( buffer += 4, FT_PEEK_LONG( buffer - 4 ) ) ) #define FT_NEXT_ULONG( buffer ) \ ( (unsigned long)( buffer += 4, FT_PEEK_ULONG( buffer - 4 ) ) ) #define FT_NEXT_SHORT_LE( buffer ) \ ( (short)( buffer += 2, FT_PEEK_SHORT_LE( buffer - 2 ) ) ) #define FT_NEXT_USHORT_LE( buffer ) \ ( (unsigned short)( buffer += 2, FT_PEEK_USHORT_LE( buffer - 2 ) ) ) #define FT_NEXT_OFF3_LE( buffer ) \ ( (long)( buffer += 3, FT_PEEK_OFF3_LE( buffer - 3 ) ) ) #define FT_NEXT_UOFF3_LE( buffer ) \ ( (unsigned long)( buffer += 3, FT_PEEK_UOFF3_LE( buffer - 3 ) ) ) #define FT_NEXT_LONG_LE( buffer ) \ ( (long)( buffer += 4, FT_PEEK_LONG_LE( buffer - 4 ) ) ) #define FT_NEXT_ULONG_LE( buffer ) \ ( (unsigned long)( buffer += 4, FT_PEEK_ULONG_LE( buffer - 4 ) ) ) /*************************************************************************/ /* */ /* Each GET_xxxx() macro uses an implicit `stream' variable. */ /* */ #if 0 #define FT_GET_MACRO( type ) FT_NEXT_ ## type ( stream->cursor ) #define FT_GET_CHAR() FT_GET_MACRO( CHAR ) #define FT_GET_BYTE() FT_GET_MACRO( BYTE ) #define FT_GET_SHORT() FT_GET_MACRO( SHORT ) #define FT_GET_USHORT() FT_GET_MACRO( USHORT ) #define FT_GET_OFF3() FT_GET_MACRO( OFF3 ) #define FT_GET_UOFF3() FT_GET_MACRO( UOFF3 ) #define FT_GET_LONG() FT_GET_MACRO( LONG ) #define FT_GET_ULONG() FT_GET_MACRO( ULONG ) #define FT_GET_TAG4() FT_GET_MACRO( ULONG ) #define FT_GET_SHORT_LE() FT_GET_MACRO( SHORT_LE ) #define FT_GET_USHORT_LE() FT_GET_MACRO( USHORT_LE ) #define FT_GET_LONG_LE() FT_GET_MACRO( LONG_LE ) #define FT_GET_ULONG_LE() FT_GET_MACRO( ULONG_LE ) #else #define FT_GET_MACRO( func, type ) ( (type)func( stream ) ) #define FT_GET_CHAR() FT_GET_MACRO( FT_Stream_GetChar, FT_Char ) #define FT_GET_BYTE() FT_GET_MACRO( FT_Stream_GetChar, FT_Byte ) #define FT_GET_SHORT() FT_GET_MACRO( FT_Stream_GetUShort, FT_Short ) #define FT_GET_USHORT() FT_GET_MACRO( FT_Stream_GetUShort, FT_UShort ) #define FT_GET_OFF3() FT_GET_MACRO( FT_Stream_GetUOffset, FT_Long ) #define FT_GET_UOFF3() FT_GET_MACRO( FT_Stream_GetUOffset, FT_ULong ) #define FT_GET_LONG() FT_GET_MACRO( FT_Stream_GetULong, FT_Long ) #define FT_GET_ULONG() FT_GET_MACRO( FT_Stream_GetULong, FT_ULong ) #define FT_GET_TAG4() FT_GET_MACRO( FT_Stream_GetULong, FT_ULong ) #define FT_GET_SHORT_LE() FT_GET_MACRO( FT_Stream_GetUShortLE, FT_Short ) #define FT_GET_USHORT_LE() FT_GET_MACRO( FT_Stream_GetUShortLE, FT_UShort ) #define FT_GET_LONG_LE() FT_GET_MACRO( FT_Stream_GetULongLE, FT_Long ) #define FT_GET_ULONG_LE() FT_GET_MACRO( FT_Stream_GetULongLE, FT_ULong ) #endif #define FT_READ_MACRO( func, type, var ) \ ( var = (type)func( stream, &error ), \ error != FT_Err_Ok ) #define FT_READ_BYTE( var ) FT_READ_MACRO( FT_Stream_ReadChar, FT_Byte, var ) #define FT_READ_CHAR( var ) FT_READ_MACRO( FT_Stream_ReadChar, FT_Char, var ) #define FT_READ_SHORT( var ) FT_READ_MACRO( FT_Stream_ReadUShort, FT_Short, var ) #define FT_READ_USHORT( var ) FT_READ_MACRO( FT_Stream_ReadUShort, FT_UShort, var ) #define FT_READ_OFF3( var ) FT_READ_MACRO( FT_Stream_ReadUOffset, FT_Long, var ) #define FT_READ_UOFF3( var ) FT_READ_MACRO( FT_Stream_ReadUOffset, FT_ULong, var ) #define FT_READ_LONG( var ) FT_READ_MACRO( FT_Stream_ReadULong, FT_Long, var ) #define FT_READ_ULONG( var ) FT_READ_MACRO( FT_Stream_ReadULong, FT_ULong, var ) #define FT_READ_SHORT_LE( var ) FT_READ_MACRO( FT_Stream_ReadUShortLE, FT_Short, var ) #define FT_READ_USHORT_LE( var ) FT_READ_MACRO( FT_Stream_ReadUShortLE, FT_UShort, var ) #define FT_READ_LONG_LE( var ) FT_READ_MACRO( FT_Stream_ReadULongLE, FT_Long, var ) #define FT_READ_ULONG_LE( var ) FT_READ_MACRO( FT_Stream_ReadULongLE, FT_ULong, var ) #ifndef FT_CONFIG_OPTION_NO_DEFAULT_SYSTEM /* initialize a stream for reading a regular system stream */ FT_BASE( FT_Error ) FT_Stream_Open( FT_Stream stream, const char* filepathname ); #endif /* FT_CONFIG_OPTION_NO_DEFAULT_SYSTEM */ /* create a new (input) stream from an FT_Open_Args structure */ FT_BASE( FT_Error ) FT_Stream_New( FT_Library library, const FT_Open_Args* args, FT_Stream *astream ); /* free a stream */ FT_BASE( void ) FT_Stream_Free( FT_Stream stream, FT_Int external ); /* initialize a stream for reading in-memory data */ FT_BASE( void ) FT_Stream_OpenMemory( FT_Stream stream, const FT_Byte* base, FT_ULong size ); /* close a stream (does not destroy the stream structure) */ FT_BASE( void ) FT_Stream_Close( FT_Stream stream ); /* seek within a stream. position is relative to start of stream */ FT_BASE( FT_Error ) FT_Stream_Seek( FT_Stream stream, FT_ULong pos ); /* skip bytes in a stream */ FT_BASE( FT_Error ) FT_Stream_Skip( FT_Stream stream, FT_Long distance ); /* return current stream position */ FT_BASE( FT_Long ) FT_Stream_Pos( FT_Stream stream ); /* read bytes from a stream into a user-allocated buffer, returns an */ /* error if not all bytes could be read. */ FT_BASE( FT_Error ) FT_Stream_Read( FT_Stream stream, FT_Byte* buffer, FT_ULong count ); /* read bytes from a stream at a given position */ FT_BASE( FT_Error ) FT_Stream_ReadAt( FT_Stream stream, FT_ULong pos, FT_Byte* buffer, FT_ULong count ); /* try to read bytes at the end of a stream; return number of bytes */ /* really available */ FT_BASE( FT_ULong ) FT_Stream_TryRead( FT_Stream stream, FT_Byte* buffer, FT_ULong count ); /* Enter a frame of `count' consecutive bytes in a stream. Returns an */ /* error if the frame could not be read/accessed. The caller can use */ /* the FT_Stream_Get_XXX functions to retrieve frame data without */ /* error checks. */ /* */ /* You must _always_ call FT_Stream_ExitFrame() once you have entered */ /* a stream frame! */ /* */ FT_BASE( FT_Error ) FT_Stream_EnterFrame( FT_Stream stream, FT_ULong count ); /* exit a stream frame */ FT_BASE( void ) FT_Stream_ExitFrame( FT_Stream stream ); /* Extract a stream frame. If the stream is disk-based, a heap block */ /* is allocated and the frame bytes are read into it. If the stream */ /* is memory-based, this function simply set a pointer to the data. */ /* */ /* Useful to optimize access to memory-based streams transparently. */ /* */ /* All extracted frames must be `freed' with a call to the function */ /* FT_Stream_ReleaseFrame(). */ /* */ FT_BASE( FT_Error ) FT_Stream_ExtractFrame( FT_Stream stream, FT_ULong count, FT_Byte** pbytes ); /* release an extract frame (see FT_Stream_ExtractFrame) */ FT_BASE( void ) FT_Stream_ReleaseFrame( FT_Stream stream, FT_Byte** pbytes ); /* read a byte from an entered frame */ FT_BASE( FT_Char ) FT_Stream_GetChar( FT_Stream stream ); /* read a 16-bit big-endian unsigned integer from an entered frame */ FT_BASE( FT_UShort ) FT_Stream_GetUShort( FT_Stream stream ); /* read a 24-bit big-endian unsigned integer from an entered frame */ FT_BASE( FT_ULong ) FT_Stream_GetUOffset( FT_Stream stream ); /* read a 32-bit big-endian unsigned integer from an entered frame */ FT_BASE( FT_ULong ) FT_Stream_GetULong( FT_Stream stream ); /* read a 16-bit little-endian unsigned integer from an entered frame */ FT_BASE( FT_UShort ) FT_Stream_GetUShortLE( FT_Stream stream ); /* read a 32-bit little-endian unsigned integer from an entered frame */ FT_BASE( FT_ULong ) FT_Stream_GetULongLE( FT_Stream stream ); /* read a byte from a stream */ FT_BASE( FT_Char ) FT_Stream_ReadChar( FT_Stream stream, FT_Error* error ); /* read a 16-bit big-endian unsigned integer from a stream */ FT_BASE( FT_UShort ) FT_Stream_ReadUShort( FT_Stream stream, FT_Error* error ); /* read a 24-bit big-endian unsigned integer from a stream */ FT_BASE( FT_ULong ) FT_Stream_ReadUOffset( FT_Stream stream, FT_Error* error ); /* read a 32-bit big-endian integer from a stream */ FT_BASE( FT_ULong ) FT_Stream_ReadULong( FT_Stream stream, FT_Error* error ); /* read a 16-bit little-endian unsigned integer from a stream */ FT_BASE( FT_UShort ) FT_Stream_ReadUShortLE( FT_Stream stream, FT_Error* error ); /* read a 32-bit little-endian unsigned integer from a stream */ FT_BASE( FT_ULong ) FT_Stream_ReadULongLE( FT_Stream stream, FT_Error* error ); /* Read a structure from a stream. The structure must be described */ /* by an array of FT_Frame_Field records. */ FT_BASE( FT_Error ) FT_Stream_ReadFields( FT_Stream stream, const FT_Frame_Field* fields, void* structure ); #define FT_STREAM_POS() \ FT_Stream_Pos( stream ) #define FT_STREAM_SEEK( position ) \ FT_SET_ERROR( FT_Stream_Seek( stream, position ) ) #define FT_STREAM_SKIP( distance ) \ FT_SET_ERROR( FT_Stream_Skip( stream, distance ) ) #define FT_STREAM_READ( buffer, count ) \ FT_SET_ERROR( FT_Stream_Read( stream, \ (FT_Byte*)buffer, \ count ) ) #define FT_STREAM_READ_AT( position, buffer, count ) \ FT_SET_ERROR( FT_Stream_ReadAt( stream, \ position, \ (FT_Byte*)buffer, \ count ) ) #define FT_STREAM_READ_FIELDS( fields, object ) \ FT_SET_ERROR( FT_Stream_ReadFields( stream, fields, object ) ) #define FT_FRAME_ENTER( size ) \ FT_SET_ERROR( \ FT_DEBUG_INNER( FT_Stream_EnterFrame( stream, size ) ) ) #define FT_FRAME_EXIT() \ FT_DEBUG_INNER( FT_Stream_ExitFrame( stream ) ) #define FT_FRAME_EXTRACT( size, bytes ) \ FT_SET_ERROR( \ FT_DEBUG_INNER( FT_Stream_ExtractFrame( stream, size, \ (FT_Byte**)&(bytes) ) ) ) #define FT_FRAME_RELEASE( bytes ) \ FT_DEBUG_INNER( FT_Stream_ReleaseFrame( stream, \ (FT_Byte**)&(bytes) ) ) FT_END_HEADER #endif /* __FTSTREAM_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/internal/fttrace.h ================================================ /***************************************************************************/ /* */ /* fttrace.h */ /* */ /* Tracing handling (specification only). */ /* */ /* Copyright 2002, 2004-2007, 2009, 2011 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /* definitions of trace levels for FreeType 2 */ /* the first level must always be `trace_any' */ FT_TRACE_DEF( any ) /* base components */ FT_TRACE_DEF( calc ) /* calculations (ftcalc.c) */ FT_TRACE_DEF( memory ) /* memory manager (ftobjs.c) */ FT_TRACE_DEF( stream ) /* stream manager (ftstream.c) */ FT_TRACE_DEF( io ) /* i/o interface (ftsystem.c) */ FT_TRACE_DEF( list ) /* list management (ftlist.c) */ FT_TRACE_DEF( init ) /* initialization (ftinit.c) */ FT_TRACE_DEF( objs ) /* base objects (ftobjs.c) */ FT_TRACE_DEF( outline ) /* outline management (ftoutln.c) */ FT_TRACE_DEF( glyph ) /* glyph management (ftglyph.c) */ FT_TRACE_DEF( gloader ) /* glyph loader (ftgloadr.c) */ FT_TRACE_DEF( raster ) /* monochrome rasterizer (ftraster.c) */ FT_TRACE_DEF( smooth ) /* anti-aliasing raster (ftgrays.c) */ FT_TRACE_DEF( mm ) /* MM interface (ftmm.c) */ FT_TRACE_DEF( raccess ) /* resource fork accessor (ftrfork.c) */ FT_TRACE_DEF( synth ) /* bold/slant synthesizer (ftsynth.c) */ /* Cache sub-system */ FT_TRACE_DEF( cache ) /* cache sub-system (ftcache.c, etc.) */ /* SFNT driver components */ FT_TRACE_DEF( sfdriver ) /* SFNT font driver (sfdriver.c) */ FT_TRACE_DEF( sfobjs ) /* SFNT object handler (sfobjs.c) */ FT_TRACE_DEF( ttcmap ) /* charmap handler (ttcmap.c) */ FT_TRACE_DEF( ttkern ) /* kerning handler (ttkern.c) */ FT_TRACE_DEF( ttload ) /* basic TrueType tables (ttload.c) */ FT_TRACE_DEF( ttmtx ) /* metrics-related tables (ttmtx.c) */ FT_TRACE_DEF( ttpost ) /* PS table processing (ttpost.c) */ FT_TRACE_DEF( ttsbit ) /* TrueType sbit handling (ttsbit.c) */ FT_TRACE_DEF( ttbdf ) /* TrueType embedded BDF (ttbdf.c) */ /* TrueType driver components */ FT_TRACE_DEF( ttdriver ) /* TT font driver (ttdriver.c) */ FT_TRACE_DEF( ttgload ) /* TT glyph loader (ttgload.c) */ FT_TRACE_DEF( ttinterp ) /* bytecode interpreter (ttinterp.c) */ FT_TRACE_DEF( ttobjs ) /* TT objects manager (ttobjs.c) */ FT_TRACE_DEF( ttpload ) /* TT data/program loader (ttpload.c) */ FT_TRACE_DEF( ttgxvar ) /* TrueType GX var handler (ttgxvar.c) */ /* Type 1 driver components */ FT_TRACE_DEF( t1afm ) FT_TRACE_DEF( t1driver ) FT_TRACE_DEF( t1gload ) FT_TRACE_DEF( t1hint ) FT_TRACE_DEF( t1load ) FT_TRACE_DEF( t1objs ) FT_TRACE_DEF( t1parse ) /* PostScript helper module `psaux' */ FT_TRACE_DEF( t1decode ) FT_TRACE_DEF( psobjs ) /* PostScript hinting module `pshinter' */ FT_TRACE_DEF( pshrec ) FT_TRACE_DEF( pshalgo1 ) FT_TRACE_DEF( pshalgo2 ) /* Type 2 driver components */ FT_TRACE_DEF( cffdriver ) FT_TRACE_DEF( cffgload ) FT_TRACE_DEF( cffload ) FT_TRACE_DEF( cffobjs ) FT_TRACE_DEF( cffparse ) /* Type 42 driver component */ FT_TRACE_DEF( t42 ) /* CID driver components */ FT_TRACE_DEF( cidafm ) FT_TRACE_DEF( ciddriver ) FT_TRACE_DEF( cidgload ) FT_TRACE_DEF( cidload ) FT_TRACE_DEF( cidobjs ) FT_TRACE_DEF( cidparse ) /* Windows font component */ FT_TRACE_DEF( winfnt ) /* PCF font components */ FT_TRACE_DEF( pcfdriver ) FT_TRACE_DEF( pcfread ) /* BDF font components */ FT_TRACE_DEF( bdfdriver ) FT_TRACE_DEF( bdflib ) /* PFR font component */ FT_TRACE_DEF( pfr ) /* OpenType validation components */ FT_TRACE_DEF( otvmodule ) FT_TRACE_DEF( otvcommon ) FT_TRACE_DEF( otvbase ) FT_TRACE_DEF( otvgdef ) FT_TRACE_DEF( otvgpos ) FT_TRACE_DEF( otvgsub ) FT_TRACE_DEF( otvjstf ) FT_TRACE_DEF( otvmath ) /* TrueTypeGX/AAT validation components */ FT_TRACE_DEF( gxvmodule ) FT_TRACE_DEF( gxvcommon ) FT_TRACE_DEF( gxvfeat ) FT_TRACE_DEF( gxvmort ) FT_TRACE_DEF( gxvmorx ) FT_TRACE_DEF( gxvbsln ) FT_TRACE_DEF( gxvjust ) FT_TRACE_DEF( gxvkern ) FT_TRACE_DEF( gxvopbd ) FT_TRACE_DEF( gxvtrak ) FT_TRACE_DEF( gxvprop ) FT_TRACE_DEF( gxvlcar ) /* autofit components */ FT_TRACE_DEF( afcjk ) FT_TRACE_DEF( aflatin ) FT_TRACE_DEF( aflatin2 ) FT_TRACE_DEF( afwarp ) /* END */ ================================================ FILE: other/freetype/include/freetype/internal/ftvalid.h ================================================ /***************************************************************************/ /* */ /* ftvalid.h */ /* */ /* FreeType validation support (specification). */ /* */ /* Copyright 2004 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __FTVALID_H__ #define __FTVALID_H__ #include <ft2build.h> #include FT_CONFIG_STANDARD_LIBRARY_H /* for ft_setjmp and ft_longjmp */ FT_BEGIN_HEADER /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /**** ****/ /**** ****/ /**** V A L I D A T I O N ****/ /**** ****/ /**** ****/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /* handle to a validation object */ typedef struct FT_ValidatorRec_ volatile* FT_Validator; /*************************************************************************/ /* */ /* There are three distinct validation levels defined here: */ /* */ /* FT_VALIDATE_DEFAULT :: */ /* A table that passes this validation level can be used reliably by */ /* FreeType. It generally means that all offsets have been checked to */ /* prevent out-of-bound reads, that array counts are correct, etc. */ /* */ /* FT_VALIDATE_TIGHT :: */ /* A table that passes this validation level can be used reliably and */ /* doesn't contain invalid data. For example, a charmap table that */ /* returns invalid glyph indices will not pass, even though it can */ /* be used with FreeType in default mode (the library will simply */ /* return an error later when trying to load the glyph). */ /* */ /* It also checks that fields which must be a multiple of 2, 4, or 8, */ /* don't have incorrect values, etc. */ /* */ /* FT_VALIDATE_PARANOID :: */ /* Only for font debugging. Checks that a table follows the */ /* specification by 100%. Very few fonts will be able to pass this */ /* level anyway but it can be useful for certain tools like font */ /* editors/converters. */ /* */ typedef enum FT_ValidationLevel_ { FT_VALIDATE_DEFAULT = 0, FT_VALIDATE_TIGHT, FT_VALIDATE_PARANOID } FT_ValidationLevel; /* validator structure */ typedef struct FT_ValidatorRec_ { const FT_Byte* base; /* address of table in memory */ const FT_Byte* limit; /* `base' + sizeof(table) in memory */ FT_ValidationLevel level; /* validation level */ FT_Error error; /* error returned. 0 means success */ ft_jmp_buf jump_buffer; /* used for exception handling */ } FT_ValidatorRec; #define FT_VALIDATOR( x ) ((FT_Validator)( x )) FT_BASE( void ) ft_validator_init( FT_Validator valid, const FT_Byte* base, const FT_Byte* limit, FT_ValidationLevel level ); /* Do not use this. It's broken and will cause your validator to crash */ /* if you run it on an invalid font. */ FT_BASE( FT_Int ) ft_validator_run( FT_Validator valid ); /* Sets the error field in a validator, then calls `longjmp' to return */ /* to high-level caller. Using `setjmp/longjmp' avoids many stupid */ /* error checks within the validation routines. */ /* */ FT_BASE( void ) ft_validator_error( FT_Validator valid, FT_Error error ); /* Calls ft_validate_error. Assumes that the `valid' local variable */ /* holds a pointer to the current validator object. */ /* */ /* Use preprocessor prescan to pass FT_ERR_PREFIX. */ /* */ #define FT_INVALID( _prefix, _error ) FT_INVALID_( _prefix, _error ) #define FT_INVALID_( _prefix, _error ) \ ft_validator_error( valid, _prefix ## _error ) /* called when a broken table is detected */ #define FT_INVALID_TOO_SHORT \ FT_INVALID( FT_ERR_PREFIX, Invalid_Table ) /* called when an invalid offset is detected */ #define FT_INVALID_OFFSET \ FT_INVALID( FT_ERR_PREFIX, Invalid_Offset ) /* called when an invalid format/value is detected */ #define FT_INVALID_FORMAT \ FT_INVALID( FT_ERR_PREFIX, Invalid_Table ) /* called when an invalid glyph index is detected */ #define FT_INVALID_GLYPH_ID \ FT_INVALID( FT_ERR_PREFIX, Invalid_Glyph_Index ) /* called when an invalid field value is detected */ #define FT_INVALID_DATA \ FT_INVALID( FT_ERR_PREFIX, Invalid_Table ) FT_END_HEADER #endif /* __FTVALID_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/internal/internal.h ================================================ /***************************************************************************/ /* */ /* internal.h */ /* */ /* Internal header files (specification only). */ /* */ /* Copyright 1996-2001, 2002, 2003, 2004 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /*************************************************************************/ /* */ /* This file is automatically included by `ft2build.h'. */ /* Do not include it manually! */ /* */ /*************************************************************************/ #define FT_INTERNAL_OBJECTS_H <freetype/internal/ftobjs.h> #define FT_INTERNAL_PIC_H <freetype/internal/ftpic.h> #define FT_INTERNAL_STREAM_H <freetype/internal/ftstream.h> #define FT_INTERNAL_MEMORY_H <freetype/internal/ftmemory.h> #define FT_INTERNAL_DEBUG_H <freetype/internal/ftdebug.h> #define FT_INTERNAL_CALC_H <freetype/internal/ftcalc.h> #define FT_INTERNAL_DRIVER_H <freetype/internal/ftdriver.h> #define FT_INTERNAL_TRACE_H <freetype/internal/fttrace.h> #define FT_INTERNAL_GLYPH_LOADER_H <freetype/internal/ftgloadr.h> #define FT_INTERNAL_SFNT_H <freetype/internal/sfnt.h> #define FT_INTERNAL_SERVICE_H <freetype/internal/ftserv.h> #define FT_INTERNAL_RFORK_H <freetype/internal/ftrfork.h> #define FT_INTERNAL_VALIDATE_H <freetype/internal/ftvalid.h> #define FT_INTERNAL_TRUETYPE_TYPES_H <freetype/internal/tttypes.h> #define FT_INTERNAL_TYPE1_TYPES_H <freetype/internal/t1types.h> #define FT_INTERNAL_POSTSCRIPT_AUX_H <freetype/internal/psaux.h> #define FT_INTERNAL_POSTSCRIPT_HINTS_H <freetype/internal/pshints.h> #define FT_INTERNAL_POSTSCRIPT_GLOBALS_H <freetype/internal/psglobal.h> #define FT_INTERNAL_AUTOHINT_H <freetype/internal/autohint.h> /* END */ ================================================ FILE: other/freetype/include/freetype/internal/psaux.h ================================================ /***************************************************************************/ /* */ /* psaux.h */ /* */ /* Auxiliary functions and data structures related to PostScript fonts */ /* (specification). */ /* */ /* Copyright 1996-2001, 2002, 2003, 2004, 2006, 2008, 2009 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __PSAUX_H__ #define __PSAUX_H__ #include <ft2build.h> #include FT_INTERNAL_OBJECTS_H #include FT_INTERNAL_TYPE1_TYPES_H #include FT_SERVICE_POSTSCRIPT_CMAPS_H FT_BEGIN_HEADER /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** T1_TABLE *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ typedef struct PS_TableRec_* PS_Table; typedef const struct PS_Table_FuncsRec_* PS_Table_Funcs; /*************************************************************************/ /* */ /* <Struct> */ /* PS_Table_FuncsRec */ /* */ /* <Description> */ /* A set of function pointers to manage PS_Table objects. */ /* */ /* <Fields> */ /* table_init :: Used to initialize a table. */ /* */ /* table_done :: Finalizes resp. destroy a given table. */ /* */ /* table_add :: Adds a new object to a table. */ /* */ /* table_release :: Releases table data, then finalizes it. */ /* */ typedef struct PS_Table_FuncsRec_ { FT_Error (*init)( PS_Table table, FT_Int count, FT_Memory memory ); void (*done)( PS_Table table ); FT_Error (*add)( PS_Table table, FT_Int idx, void* object, FT_PtrDist length ); void (*release)( PS_Table table ); } PS_Table_FuncsRec; /*************************************************************************/ /* */ /* <Struct> */ /* PS_TableRec */ /* */ /* <Description> */ /* A PS_Table is a simple object used to store an array of objects in */ /* a single memory block. */ /* */ /* <Fields> */ /* block :: The address in memory of the growheap's block. This */ /* can change between two object adds, due to */ /* reallocation. */ /* */ /* cursor :: The current top of the grow heap within its block. */ /* */ /* capacity :: The current size of the heap block. Increments by */ /* 1kByte chunks. */ /* */ /* max_elems :: The maximum number of elements in table. */ /* */ /* num_elems :: The current number of elements in table. */ /* */ /* elements :: A table of element addresses within the block. */ /* */ /* lengths :: A table of element sizes within the block. */ /* */ /* memory :: The object used for memory operations */ /* (alloc/realloc). */ /* */ /* funcs :: A table of method pointers for this object. */ /* */ typedef struct PS_TableRec_ { FT_Byte* block; /* current memory block */ FT_Offset cursor; /* current cursor in memory block */ FT_Offset capacity; /* current size of memory block */ FT_Long init; FT_Int max_elems; FT_Int num_elems; FT_Byte** elements; /* addresses of table elements */ FT_PtrDist* lengths; /* lengths of table elements */ FT_Memory memory; PS_Table_FuncsRec funcs; } PS_TableRec; /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** T1 FIELDS & TOKENS *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ typedef struct PS_ParserRec_* PS_Parser; typedef struct T1_TokenRec_* T1_Token; typedef struct T1_FieldRec_* T1_Field; /* simple enumeration type used to identify token types */ typedef enum T1_TokenType_ { T1_TOKEN_TYPE_NONE = 0, T1_TOKEN_TYPE_ANY, T1_TOKEN_TYPE_STRING, T1_TOKEN_TYPE_ARRAY, T1_TOKEN_TYPE_KEY, /* aka `name' */ /* do not remove */ T1_TOKEN_TYPE_MAX } T1_TokenType; /* a simple structure used to identify tokens */ typedef struct T1_TokenRec_ { FT_Byte* start; /* first character of token in input stream */ FT_Byte* limit; /* first character after the token */ T1_TokenType type; /* type of token */ } T1_TokenRec; /* enumeration type used to identify object fields */ typedef enum T1_FieldType_ { T1_FIELD_TYPE_NONE = 0, T1_FIELD_TYPE_BOOL, T1_FIELD_TYPE_INTEGER, T1_FIELD_TYPE_FIXED, T1_FIELD_TYPE_FIXED_1000, T1_FIELD_TYPE_STRING, T1_FIELD_TYPE_KEY, T1_FIELD_TYPE_BBOX, T1_FIELD_TYPE_INTEGER_ARRAY, T1_FIELD_TYPE_FIXED_ARRAY, T1_FIELD_TYPE_CALLBACK, /* do not remove */ T1_FIELD_TYPE_MAX } T1_FieldType; typedef enum T1_FieldLocation_ { T1_FIELD_LOCATION_CID_INFO, T1_FIELD_LOCATION_FONT_DICT, T1_FIELD_LOCATION_FONT_EXTRA, T1_FIELD_LOCATION_FONT_INFO, T1_FIELD_LOCATION_PRIVATE, T1_FIELD_LOCATION_BBOX, T1_FIELD_LOCATION_LOADER, T1_FIELD_LOCATION_FACE, T1_FIELD_LOCATION_BLEND, /* do not remove */ T1_FIELD_LOCATION_MAX } T1_FieldLocation; typedef void (*T1_Field_ParseFunc)( FT_Face face, FT_Pointer parser ); /* structure type used to model object fields */ typedef struct T1_FieldRec_ { const char* ident; /* field identifier */ T1_FieldLocation location; T1_FieldType type; /* type of field */ T1_Field_ParseFunc reader; FT_UInt offset; /* offset of field in object */ FT_Byte size; /* size of field in bytes */ FT_UInt array_max; /* maximal number of elements for */ /* array */ FT_UInt count_offset; /* offset of element count for */ /* arrays; must not be zero if in */ /* use -- in other words, a */ /* `num_FOO' element must not */ /* start the used structure if we */ /* parse a `FOO' array */ FT_UInt dict; /* where we expect it */ } T1_FieldRec; #define T1_FIELD_DICT_FONTDICT ( 1 << 0 ) /* also FontInfo and FDArray */ #define T1_FIELD_DICT_PRIVATE ( 1 << 1 ) #define T1_NEW_SIMPLE_FIELD( _ident, _type, _fname, _dict ) \ { \ _ident, T1CODE, _type, \ 0, \ FT_FIELD_OFFSET( _fname ), \ FT_FIELD_SIZE( _fname ), \ 0, 0, \ _dict \ }, #define T1_NEW_CALLBACK_FIELD( _ident, _reader, _dict ) \ { \ _ident, T1CODE, T1_FIELD_TYPE_CALLBACK, \ (T1_Field_ParseFunc)_reader, \ 0, 0, \ 0, 0, \ _dict \ }, #define T1_NEW_TABLE_FIELD( _ident, _type, _fname, _max, _dict ) \ { \ _ident, T1CODE, _type, \ 0, \ FT_FIELD_OFFSET( _fname ), \ FT_FIELD_SIZE_DELTA( _fname ), \ _max, \ FT_FIELD_OFFSET( num_ ## _fname ), \ _dict \ }, #define T1_NEW_TABLE_FIELD2( _ident, _type, _fname, _max, _dict ) \ { \ _ident, T1CODE, _type, \ 0, \ FT_FIELD_OFFSET( _fname ), \ FT_FIELD_SIZE_DELTA( _fname ), \ _max, 0, \ _dict \ }, #define T1_FIELD_BOOL( _ident, _fname, _dict ) \ T1_NEW_SIMPLE_FIELD( _ident, T1_FIELD_TYPE_BOOL, _fname, _dict ) #define T1_FIELD_NUM( _ident, _fname, _dict ) \ T1_NEW_SIMPLE_FIELD( _ident, T1_FIELD_TYPE_INTEGER, _fname, _dict ) #define T1_FIELD_FIXED( _ident, _fname, _dict ) \ T1_NEW_SIMPLE_FIELD( _ident, T1_FIELD_TYPE_FIXED, _fname, _dict ) #define T1_FIELD_FIXED_1000( _ident, _fname, _dict ) \ T1_NEW_SIMPLE_FIELD( _ident, T1_FIELD_TYPE_FIXED_1000, _fname, \ _dict ) #define T1_FIELD_STRING( _ident, _fname, _dict ) \ T1_NEW_SIMPLE_FIELD( _ident, T1_FIELD_TYPE_STRING, _fname, _dict ) #define T1_FIELD_KEY( _ident, _fname, _dict ) \ T1_NEW_SIMPLE_FIELD( _ident, T1_FIELD_TYPE_KEY, _fname, _dict ) #define T1_FIELD_BBOX( _ident, _fname, _dict ) \ T1_NEW_SIMPLE_FIELD( _ident, T1_FIELD_TYPE_BBOX, _fname, _dict ) #define T1_FIELD_NUM_TABLE( _ident, _fname, _fmax, _dict ) \ T1_NEW_TABLE_FIELD( _ident, T1_FIELD_TYPE_INTEGER_ARRAY, \ _fname, _fmax, _dict ) #define T1_FIELD_FIXED_TABLE( _ident, _fname, _fmax, _dict ) \ T1_NEW_TABLE_FIELD( _ident, T1_FIELD_TYPE_FIXED_ARRAY, \ _fname, _fmax, _dict ) #define T1_FIELD_NUM_TABLE2( _ident, _fname, _fmax, _dict ) \ T1_NEW_TABLE_FIELD2( _ident, T1_FIELD_TYPE_INTEGER_ARRAY, \ _fname, _fmax, _dict ) #define T1_FIELD_FIXED_TABLE2( _ident, _fname, _fmax, _dict ) \ T1_NEW_TABLE_FIELD2( _ident, T1_FIELD_TYPE_FIXED_ARRAY, \ _fname, _fmax, _dict ) #define T1_FIELD_CALLBACK( _ident, _name, _dict ) \ T1_NEW_CALLBACK_FIELD( _ident, _name, _dict ) /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** T1 PARSER *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ typedef const struct PS_Parser_FuncsRec_* PS_Parser_Funcs; typedef struct PS_Parser_FuncsRec_ { void (*init)( PS_Parser parser, FT_Byte* base, FT_Byte* limit, FT_Memory memory ); void (*done)( PS_Parser parser ); void (*skip_spaces)( PS_Parser parser ); void (*skip_PS_token)( PS_Parser parser ); FT_Long (*to_int)( PS_Parser parser ); FT_Fixed (*to_fixed)( PS_Parser parser, FT_Int power_ten ); FT_Error (*to_bytes)( PS_Parser parser, FT_Byte* bytes, FT_Offset max_bytes, FT_Long* pnum_bytes, FT_Bool delimiters ); FT_Int (*to_coord_array)( PS_Parser parser, FT_Int max_coords, FT_Short* coords ); FT_Int (*to_fixed_array)( PS_Parser parser, FT_Int max_values, FT_Fixed* values, FT_Int power_ten ); void (*to_token)( PS_Parser parser, T1_Token token ); void (*to_token_array)( PS_Parser parser, T1_Token tokens, FT_UInt max_tokens, FT_Int* pnum_tokens ); FT_Error (*load_field)( PS_Parser parser, const T1_Field field, void** objects, FT_UInt max_objects, FT_ULong* pflags ); FT_Error (*load_field_table)( PS_Parser parser, const T1_Field field, void** objects, FT_UInt max_objects, FT_ULong* pflags ); } PS_Parser_FuncsRec; /*************************************************************************/ /* */ /* <Struct> */ /* PS_ParserRec */ /* */ /* <Description> */ /* A PS_Parser is an object used to parse a Type 1 font very quickly. */ /* */ /* <Fields> */ /* cursor :: The current position in the text. */ /* */ /* base :: Start of the processed text. */ /* */ /* limit :: End of the processed text. */ /* */ /* error :: The last error returned. */ /* */ /* memory :: The object used for memory operations (alloc/realloc). */ /* */ /* funcs :: A table of functions for the parser. */ /* */ typedef struct PS_ParserRec_ { FT_Byte* cursor; FT_Byte* base; FT_Byte* limit; FT_Error error; FT_Memory memory; PS_Parser_FuncsRec funcs; } PS_ParserRec; /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** T1 BUILDER *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ typedef struct T1_BuilderRec_* T1_Builder; typedef FT_Error (*T1_Builder_Check_Points_Func)( T1_Builder builder, FT_Int count ); typedef void (*T1_Builder_Add_Point_Func)( T1_Builder builder, FT_Pos x, FT_Pos y, FT_Byte flag ); typedef FT_Error (*T1_Builder_Add_Point1_Func)( T1_Builder builder, FT_Pos x, FT_Pos y ); typedef FT_Error (*T1_Builder_Add_Contour_Func)( T1_Builder builder ); typedef FT_Error (*T1_Builder_Start_Point_Func)( T1_Builder builder, FT_Pos x, FT_Pos y ); typedef void (*T1_Builder_Close_Contour_Func)( T1_Builder builder ); typedef const struct T1_Builder_FuncsRec_* T1_Builder_Funcs; typedef struct T1_Builder_FuncsRec_ { void (*init)( T1_Builder builder, FT_Face face, FT_Size size, FT_GlyphSlot slot, FT_Bool hinting ); void (*done)( T1_Builder builder ); T1_Builder_Check_Points_Func check_points; T1_Builder_Add_Point_Func add_point; T1_Builder_Add_Point1_Func add_point1; T1_Builder_Add_Contour_Func add_contour; T1_Builder_Start_Point_Func start_point; T1_Builder_Close_Contour_Func close_contour; } T1_Builder_FuncsRec; /* an enumeration type to handle charstring parsing states */ typedef enum T1_ParseState_ { T1_Parse_Start, T1_Parse_Have_Width, T1_Parse_Have_Moveto, T1_Parse_Have_Path } T1_ParseState; /*************************************************************************/ /* */ /* <Structure> */ /* T1_BuilderRec */ /* */ /* <Description> */ /* A structure used during glyph loading to store its outline. */ /* */ /* <Fields> */ /* memory :: The current memory object. */ /* */ /* face :: The current face object. */ /* */ /* glyph :: The current glyph slot. */ /* */ /* loader :: XXX */ /* */ /* base :: The base glyph outline. */ /* */ /* current :: The current glyph outline. */ /* */ /* max_points :: maximum points in builder outline */ /* */ /* max_contours :: Maximal number of contours in builder outline. */ /* */ /* pos_x :: The horizontal translation (if composite glyph). */ /* */ /* pos_y :: The vertical translation (if composite glyph). */ /* */ /* left_bearing :: The left side bearing point. */ /* */ /* advance :: The horizontal advance vector. */ /* */ /* bbox :: Unused. */ /* */ /* parse_state :: An enumeration which controls the charstring */ /* parsing state. */ /* */ /* load_points :: If this flag is not set, no points are loaded. */ /* */ /* no_recurse :: Set but not used. */ /* */ /* metrics_only :: A boolean indicating that we only want to compute */ /* the metrics of a given glyph, not load all of its */ /* points. */ /* */ /* funcs :: An array of function pointers for the builder. */ /* */ typedef struct T1_BuilderRec_ { FT_Memory memory; FT_Face face; FT_GlyphSlot glyph; FT_GlyphLoader loader; FT_Outline* base; FT_Outline* current; FT_Pos pos_x; FT_Pos pos_y; FT_Vector left_bearing; FT_Vector advance; FT_BBox bbox; /* bounding box */ T1_ParseState parse_state; FT_Bool load_points; FT_Bool no_recurse; FT_Bool metrics_only; void* hints_funcs; /* hinter-specific */ void* hints_globals; /* hinter-specific */ T1_Builder_FuncsRec funcs; } T1_BuilderRec; /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** T1 DECODER *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ #if 0 /*************************************************************************/ /* */ /* T1_MAX_SUBRS_CALLS details the maximum number of nested sub-routine */ /* calls during glyph loading. */ /* */ #define T1_MAX_SUBRS_CALLS 8 /*************************************************************************/ /* */ /* T1_MAX_CHARSTRING_OPERANDS is the charstring stack's capacity. A */ /* minimum of 16 is required. */ /* */ #define T1_MAX_CHARSTRINGS_OPERANDS 32 #endif /* 0 */ typedef struct T1_Decoder_ZoneRec_ { FT_Byte* cursor; FT_Byte* base; FT_Byte* limit; } T1_Decoder_ZoneRec, *T1_Decoder_Zone; typedef struct T1_DecoderRec_* T1_Decoder; typedef const struct T1_Decoder_FuncsRec_* T1_Decoder_Funcs; typedef FT_Error (*T1_Decoder_Callback)( T1_Decoder decoder, FT_UInt glyph_index ); typedef struct T1_Decoder_FuncsRec_ { FT_Error (*init)( T1_Decoder decoder, FT_Face face, FT_Size size, FT_GlyphSlot slot, FT_Byte** glyph_names, PS_Blend blend, FT_Bool hinting, FT_Render_Mode hint_mode, T1_Decoder_Callback callback ); void (*done)( T1_Decoder decoder ); FT_Error (*parse_charstrings)( T1_Decoder decoder, FT_Byte* base, FT_UInt len ); } T1_Decoder_FuncsRec; typedef struct T1_DecoderRec_ { T1_BuilderRec builder; FT_Long stack[T1_MAX_CHARSTRINGS_OPERANDS]; FT_Long* top; T1_Decoder_ZoneRec zones[T1_MAX_SUBRS_CALLS + 1]; T1_Decoder_Zone zone; FT_Service_PsCMaps psnames; /* for seac */ FT_UInt num_glyphs; FT_Byte** glyph_names; FT_Int lenIV; /* internal for sub routine calls */ FT_UInt num_subrs; FT_Byte** subrs; FT_PtrDist* subrs_len; /* array of subrs length (optional) */ FT_Matrix font_matrix; FT_Vector font_offset; FT_Int flex_state; FT_Int num_flex_vectors; FT_Vector flex_vectors[7]; PS_Blend blend; /* for multiple master support */ FT_Render_Mode hint_mode; T1_Decoder_Callback parse_callback; T1_Decoder_FuncsRec funcs; FT_Long* buildchar; FT_UInt len_buildchar; FT_Bool seac; } T1_DecoderRec; /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** AFM PARSER *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ typedef struct AFM_ParserRec_* AFM_Parser; typedef struct AFM_Parser_FuncsRec_ { FT_Error (*init)( AFM_Parser parser, FT_Memory memory, FT_Byte* base, FT_Byte* limit ); void (*done)( AFM_Parser parser ); FT_Error (*parse)( AFM_Parser parser ); } AFM_Parser_FuncsRec; typedef struct AFM_StreamRec_* AFM_Stream; /*************************************************************************/ /* */ /* <Struct> */ /* AFM_ParserRec */ /* */ /* <Description> */ /* An AFM_Parser is a parser for the AFM files. */ /* */ /* <Fields> */ /* memory :: The object used for memory operations (alloc and */ /* realloc). */ /* */ /* stream :: This is an opaque object. */ /* */ /* FontInfo :: The result will be stored here. */ /* */ /* get_index :: A user provided function to get a glyph index by its */ /* name. */ /* */ typedef struct AFM_ParserRec_ { FT_Memory memory; AFM_Stream stream; AFM_FontInfo FontInfo; FT_Int (*get_index)( const char* name, FT_Offset len, void* user_data ); void* user_data; } AFM_ParserRec; /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** TYPE1 CHARMAPS *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ typedef const struct T1_CMap_ClassesRec_* T1_CMap_Classes; typedef struct T1_CMap_ClassesRec_ { FT_CMap_Class standard; FT_CMap_Class expert; FT_CMap_Class custom; FT_CMap_Class unicode; } T1_CMap_ClassesRec; /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** PSAux Module Interface *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ typedef struct PSAux_ServiceRec_ { /* don't use `PS_Table_Funcs' and friends to avoid compiler warnings */ const PS_Table_FuncsRec* ps_table_funcs; const PS_Parser_FuncsRec* ps_parser_funcs; const T1_Builder_FuncsRec* t1_builder_funcs; const T1_Decoder_FuncsRec* t1_decoder_funcs; void (*t1_decrypt)( FT_Byte* buffer, FT_Offset length, FT_UShort seed ); T1_CMap_Classes t1_cmap_classes; /* fields after this comment line were added after version 2.1.10 */ const AFM_Parser_FuncsRec* afm_parser_funcs; } PSAux_ServiceRec, *PSAux_Service; /* backwards-compatible type definition */ typedef PSAux_ServiceRec PSAux_Interface; /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** Some convenience functions *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ #define IS_PS_NEWLINE( ch ) \ ( (ch) == '\r' || \ (ch) == '\n' ) #define IS_PS_SPACE( ch ) \ ( (ch) == ' ' || \ IS_PS_NEWLINE( ch ) || \ (ch) == '\t' || \ (ch) == '\f' || \ (ch) == '\0' ) #define IS_PS_SPECIAL( ch ) \ ( (ch) == '/' || \ (ch) == '(' || (ch) == ')' || \ (ch) == '<' || (ch) == '>' || \ (ch) == '[' || (ch) == ']' || \ (ch) == '{' || (ch) == '}' || \ (ch) == '%' ) #define IS_PS_DELIM( ch ) \ ( IS_PS_SPACE( ch ) || \ IS_PS_SPECIAL( ch ) ) #define IS_PS_DIGIT( ch ) \ ( (ch) >= '0' && (ch) <= '9' ) #define IS_PS_XDIGIT( ch ) \ ( IS_PS_DIGIT( ch ) || \ ( (ch) >= 'A' && (ch) <= 'F' ) || \ ( (ch) >= 'a' && (ch) <= 'f' ) ) #define IS_PS_BASE85( ch ) \ ( (ch) >= '!' && (ch) <= 'u' ) #define IS_PS_TOKEN( cur, limit, token ) \ ( (char)(cur)[0] == (token)[0] && \ ( (cur) + sizeof ( (token) ) == (limit) || \ ( (cur) + sizeof( (token) ) < (limit) && \ IS_PS_DELIM( (cur)[sizeof ( (token) ) - 1] ) ) ) && \ ft_strncmp( (char*)(cur), (token), sizeof ( (token) ) - 1 ) == 0 ) FT_END_HEADER #endif /* __PSAUX_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/internal/pshints.h ================================================ /***************************************************************************/ /* */ /* pshints.h */ /* */ /* Interface to Postscript-specific (Type 1 and Type 2) hints */ /* recorders (specification only). These are used to support native */ /* T1/T2 hints in the `type1', `cid', and `cff' font drivers. */ /* */ /* Copyright 2001, 2002, 2003, 2005, 2006, 2007, 2009 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __PSHINTS_H__ #define __PSHINTS_H__ #include <ft2build.h> #include FT_FREETYPE_H #include FT_TYPE1_TABLES_H FT_BEGIN_HEADER /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** INTERNAL REPRESENTATION OF GLOBALS *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ typedef struct PSH_GlobalsRec_* PSH_Globals; typedef FT_Error (*PSH_Globals_NewFunc)( FT_Memory memory, T1_Private* private_dict, PSH_Globals* aglobals ); typedef FT_Error (*PSH_Globals_SetScaleFunc)( PSH_Globals globals, FT_Fixed x_scale, FT_Fixed y_scale, FT_Fixed x_delta, FT_Fixed y_delta ); typedef void (*PSH_Globals_DestroyFunc)( PSH_Globals globals ); typedef struct PSH_Globals_FuncsRec_ { PSH_Globals_NewFunc create; PSH_Globals_SetScaleFunc set_scale; PSH_Globals_DestroyFunc destroy; } PSH_Globals_FuncsRec, *PSH_Globals_Funcs; /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** PUBLIC TYPE 1 HINTS RECORDER *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ /************************************************************************* * * @type: * T1_Hints * * @description: * This is a handle to an opaque structure used to record glyph hints * from a Type 1 character glyph character string. * * The methods used to operate on this object are defined by the * @T1_Hints_FuncsRec structure. Recording glyph hints is normally * achieved through the following scheme: * * - Open a new hint recording session by calling the `open' method. * This rewinds the recorder and prepare it for new input. * * - For each hint found in the glyph charstring, call the corresponding * method (`stem', `stem3', or `reset'). Note that these functions do * not return an error code. * * - Close the recording session by calling the `close' method. It * returns an error code if the hints were invalid or something * strange happened (e.g., memory shortage). * * The hints accumulated in the object can later be used by the * PostScript hinter. * */ typedef struct T1_HintsRec_* T1_Hints; /************************************************************************* * * @type: * T1_Hints_Funcs * * @description: * A pointer to the @T1_Hints_FuncsRec structure that defines the API of * a given @T1_Hints object. * */ typedef const struct T1_Hints_FuncsRec_* T1_Hints_Funcs; /************************************************************************* * * @functype: * T1_Hints_OpenFunc * * @description: * A method of the @T1_Hints class used to prepare it for a new Type 1 * hints recording session. * * @input: * hints :: * A handle to the Type 1 hints recorder. * * @note: * You should always call the @T1_Hints_CloseFunc method in order to * close an opened recording session. * */ typedef void (*T1_Hints_OpenFunc)( T1_Hints hints ); /************************************************************************* * * @functype: * T1_Hints_SetStemFunc * * @description: * A method of the @T1_Hints class used to record a new horizontal or * vertical stem. This corresponds to the Type 1 `hstem' and `vstem' * operators. * * @input: * hints :: * A handle to the Type 1 hints recorder. * * dimension :: * 0 for horizontal stems (hstem), 1 for vertical ones (vstem). * * coords :: * Array of 2 coordinates in 16.16 format, used as (position,length) * stem descriptor. * * @note: * Use vertical coordinates (y) for horizontal stems (dim=0). Use * horizontal coordinates (x) for vertical stems (dim=1). * * `coords[0]' is the absolute stem position (lowest coordinate); * `coords[1]' is the length. * * The length can be negative, in which case it must be either -20 or * -21. It is interpreted as a `ghost' stem, according to the Type 1 * specification. * * If the length is -21 (corresponding to a bottom ghost stem), then * the real stem position is `coords[0]+coords[1]'. * */ typedef void (*T1_Hints_SetStemFunc)( T1_Hints hints, FT_UInt dimension, FT_Fixed* coords ); /************************************************************************* * * @functype: * T1_Hints_SetStem3Func * * @description: * A method of the @T1_Hints class used to record three * counter-controlled horizontal or vertical stems at once. * * @input: * hints :: * A handle to the Type 1 hints recorder. * * dimension :: * 0 for horizontal stems, 1 for vertical ones. * * coords :: * An array of 6 values in 16.16 format, holding 3 (position,length) * pairs for the counter-controlled stems. * * @note: * Use vertical coordinates (y) for horizontal stems (dim=0). Use * horizontal coordinates (x) for vertical stems (dim=1). * * The lengths cannot be negative (ghost stems are never * counter-controlled). * */ typedef void (*T1_Hints_SetStem3Func)( T1_Hints hints, FT_UInt dimension, FT_Fixed* coords ); /************************************************************************* * * @functype: * T1_Hints_ResetFunc * * @description: * A method of the @T1_Hints class used to reset the stems hints in a * recording session. * * @input: * hints :: * A handle to the Type 1 hints recorder. * * end_point :: * The index of the last point in the input glyph in which the * previously defined hints apply. * */ typedef void (*T1_Hints_ResetFunc)( T1_Hints hints, FT_UInt end_point ); /************************************************************************* * * @functype: * T1_Hints_CloseFunc * * @description: * A method of the @T1_Hints class used to close a hint recording * session. * * @input: * hints :: * A handle to the Type 1 hints recorder. * * end_point :: * The index of the last point in the input glyph. * * @return: * FreeType error code. 0 means success. * * @note: * The error code is set to indicate that an error occurred during the * recording session. * */ typedef FT_Error (*T1_Hints_CloseFunc)( T1_Hints hints, FT_UInt end_point ); /************************************************************************* * * @functype: * T1_Hints_ApplyFunc * * @description: * A method of the @T1_Hints class used to apply hints to the * corresponding glyph outline. Must be called once all hints have been * recorded. * * @input: * hints :: * A handle to the Type 1 hints recorder. * * outline :: * A pointer to the target outline descriptor. * * globals :: * The hinter globals for this font. * * hint_mode :: * Hinting information. * * @return: * FreeType error code. 0 means success. * * @note: * On input, all points within the outline are in font coordinates. On * output, they are in 1/64th of pixels. * * The scaling transformation is taken from the `globals' object which * must correspond to the same font as the glyph. * */ typedef FT_Error (*T1_Hints_ApplyFunc)( T1_Hints hints, FT_Outline* outline, PSH_Globals globals, FT_Render_Mode hint_mode ); /************************************************************************* * * @struct: * T1_Hints_FuncsRec * * @description: * The structure used to provide the API to @T1_Hints objects. * * @fields: * hints :: * A handle to the T1 Hints recorder. * * open :: * The function to open a recording session. * * close :: * The function to close a recording session. * * stem :: * The function to set a simple stem. * * stem3 :: * The function to set counter-controlled stems. * * reset :: * The function to reset stem hints. * * apply :: * The function to apply the hints to the corresponding glyph outline. * */ typedef struct T1_Hints_FuncsRec_ { T1_Hints hints; T1_Hints_OpenFunc open; T1_Hints_CloseFunc close; T1_Hints_SetStemFunc stem; T1_Hints_SetStem3Func stem3; T1_Hints_ResetFunc reset; T1_Hints_ApplyFunc apply; } T1_Hints_FuncsRec; /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** PUBLIC TYPE 2 HINTS RECORDER *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ /************************************************************************* * * @type: * T2_Hints * * @description: * This is a handle to an opaque structure used to record glyph hints * from a Type 2 character glyph character string. * * The methods used to operate on this object are defined by the * @T2_Hints_FuncsRec structure. Recording glyph hints is normally * achieved through the following scheme: * * - Open a new hint recording session by calling the `open' method. * This rewinds the recorder and prepare it for new input. * * - For each hint found in the glyph charstring, call the corresponding * method (`stems', `hintmask', `counters'). Note that these * functions do not return an error code. * * - Close the recording session by calling the `close' method. It * returns an error code if the hints were invalid or something * strange happened (e.g., memory shortage). * * The hints accumulated in the object can later be used by the * Postscript hinter. * */ typedef struct T2_HintsRec_* T2_Hints; /************************************************************************* * * @type: * T2_Hints_Funcs * * @description: * A pointer to the @T2_Hints_FuncsRec structure that defines the API of * a given @T2_Hints object. * */ typedef const struct T2_Hints_FuncsRec_* T2_Hints_Funcs; /************************************************************************* * * @functype: * T2_Hints_OpenFunc * * @description: * A method of the @T2_Hints class used to prepare it for a new Type 2 * hints recording session. * * @input: * hints :: * A handle to the Type 2 hints recorder. * * @note: * You should always call the @T2_Hints_CloseFunc method in order to * close an opened recording session. * */ typedef void (*T2_Hints_OpenFunc)( T2_Hints hints ); /************************************************************************* * * @functype: * T2_Hints_StemsFunc * * @description: * A method of the @T2_Hints class used to set the table of stems in * either the vertical or horizontal dimension. Equivalent to the * `hstem', `vstem', `hstemhm', and `vstemhm' Type 2 operators. * * @input: * hints :: * A handle to the Type 2 hints recorder. * * dimension :: * 0 for horizontal stems (hstem), 1 for vertical ones (vstem). * * count :: * The number of stems. * * coords :: * An array of `count' (position,length) pairs in 16.16 format. * * @note: * Use vertical coordinates (y) for horizontal stems (dim=0). Use * horizontal coordinates (x) for vertical stems (dim=1). * * There are `2*count' elements in the `coords' array. Each even * element is an absolute position in font units, each odd element is a * length in font units. * * A length can be negative, in which case it must be either -20 or * -21. It is interpreted as a `ghost' stem, according to the Type 1 * specification. * */ typedef void (*T2_Hints_StemsFunc)( T2_Hints hints, FT_UInt dimension, FT_UInt count, FT_Fixed* coordinates ); /************************************************************************* * * @functype: * T2_Hints_MaskFunc * * @description: * A method of the @T2_Hints class used to set a given hintmask (this * corresponds to the `hintmask' Type 2 operator). * * @input: * hints :: * A handle to the Type 2 hints recorder. * * end_point :: * The glyph index of the last point to which the previously defined * or activated hints apply. * * bit_count :: * The number of bits in the hint mask. * * bytes :: * An array of bytes modelling the hint mask. * * @note: * If the hintmask starts the charstring (before any glyph point * definition), the value of `end_point' should be 0. * * `bit_count' is the number of meaningful bits in the `bytes' array; it * must be equal to the total number of hints defined so far (i.e., * horizontal+verticals). * * The `bytes' array can come directly from the Type 2 charstring and * respects the same format. * */ typedef void (*T2_Hints_MaskFunc)( T2_Hints hints, FT_UInt end_point, FT_UInt bit_count, const FT_Byte* bytes ); /************************************************************************* * * @functype: * T2_Hints_CounterFunc * * @description: * A method of the @T2_Hints class used to set a given counter mask * (this corresponds to the `hintmask' Type 2 operator). * * @input: * hints :: * A handle to the Type 2 hints recorder. * * end_point :: * A glyph index of the last point to which the previously defined or * active hints apply. * * bit_count :: * The number of bits in the hint mask. * * bytes :: * An array of bytes modelling the hint mask. * * @note: * If the hintmask starts the charstring (before any glyph point * definition), the value of `end_point' should be 0. * * `bit_count' is the number of meaningful bits in the `bytes' array; it * must be equal to the total number of hints defined so far (i.e., * horizontal+verticals). * * The `bytes' array can come directly from the Type 2 charstring and * respects the same format. * */ typedef void (*T2_Hints_CounterFunc)( T2_Hints hints, FT_UInt bit_count, const FT_Byte* bytes ); /************************************************************************* * * @functype: * T2_Hints_CloseFunc * * @description: * A method of the @T2_Hints class used to close a hint recording * session. * * @input: * hints :: * A handle to the Type 2 hints recorder. * * end_point :: * The index of the last point in the input glyph. * * @return: * FreeType error code. 0 means success. * * @note: * The error code is set to indicate that an error occurred during the * recording session. * */ typedef FT_Error (*T2_Hints_CloseFunc)( T2_Hints hints, FT_UInt end_point ); /************************************************************************* * * @functype: * T2_Hints_ApplyFunc * * @description: * A method of the @T2_Hints class used to apply hints to the * corresponding glyph outline. Must be called after the `close' * method. * * @input: * hints :: * A handle to the Type 2 hints recorder. * * outline :: * A pointer to the target outline descriptor. * * globals :: * The hinter globals for this font. * * hint_mode :: * Hinting information. * * @return: * FreeType error code. 0 means success. * * @note: * On input, all points within the outline are in font coordinates. On * output, they are in 1/64th of pixels. * * The scaling transformation is taken from the `globals' object which * must correspond to the same font than the glyph. * */ typedef FT_Error (*T2_Hints_ApplyFunc)( T2_Hints hints, FT_Outline* outline, PSH_Globals globals, FT_Render_Mode hint_mode ); /************************************************************************* * * @struct: * T2_Hints_FuncsRec * * @description: * The structure used to provide the API to @T2_Hints objects. * * @fields: * hints :: * A handle to the T2 hints recorder object. * * open :: * The function to open a recording session. * * close :: * The function to close a recording session. * * stems :: * The function to set the dimension's stems table. * * hintmask :: * The function to set hint masks. * * counter :: * The function to set counter masks. * * apply :: * The function to apply the hints on the corresponding glyph outline. * */ typedef struct T2_Hints_FuncsRec_ { T2_Hints hints; T2_Hints_OpenFunc open; T2_Hints_CloseFunc close; T2_Hints_StemsFunc stems; T2_Hints_MaskFunc hintmask; T2_Hints_CounterFunc counter; T2_Hints_ApplyFunc apply; } T2_Hints_FuncsRec; /* */ typedef struct PSHinter_Interface_ { PSH_Globals_Funcs (*get_globals_funcs)( FT_Module module ); T1_Hints_Funcs (*get_t1_funcs) ( FT_Module module ); T2_Hints_Funcs (*get_t2_funcs) ( FT_Module module ); } PSHinter_Interface; typedef PSHinter_Interface* PSHinter_Service; #ifndef FT_CONFIG_OPTION_PIC #define FT_DEFINE_PSHINTER_INTERFACE(class_, get_globals_funcs_, \ get_t1_funcs_, get_t2_funcs_) \ static const PSHinter_Interface class_ = \ { \ get_globals_funcs_, get_t1_funcs_, get_t2_funcs_ \ }; #else /* FT_CONFIG_OPTION_PIC */ #define FT_DEFINE_PSHINTER_INTERFACE(class_, get_globals_funcs_, \ get_t1_funcs_, get_t2_funcs_) \ void \ FT_Init_Class_##class_( FT_Library library, \ PSHinter_Interface* clazz) \ { \ FT_UNUSED(library); \ clazz->get_globals_funcs = get_globals_funcs_; \ clazz->get_t1_funcs = get_t1_funcs_; \ clazz->get_t2_funcs = get_t2_funcs_; \ } #endif /* FT_CONFIG_OPTION_PIC */ FT_END_HEADER #endif /* __PSHINTS_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/internal/services/svbdf.h ================================================ /***************************************************************************/ /* */ /* svbdf.h */ /* */ /* The FreeType BDF services (specification). */ /* */ /* Copyright 2003 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __SVBDF_H__ #define __SVBDF_H__ #include FT_BDF_H #include FT_INTERNAL_SERVICE_H FT_BEGIN_HEADER #define FT_SERVICE_ID_BDF "bdf" typedef FT_Error (*FT_BDF_GetCharsetIdFunc)( FT_Face face, const char* *acharset_encoding, const char* *acharset_registry ); typedef FT_Error (*FT_BDF_GetPropertyFunc)( FT_Face face, const char* prop_name, BDF_PropertyRec *aproperty ); FT_DEFINE_SERVICE( BDF ) { FT_BDF_GetCharsetIdFunc get_charset_id; FT_BDF_GetPropertyFunc get_property; }; #ifndef FT_CONFIG_OPTION_PIC #define FT_DEFINE_SERVICE_BDFRec(class_, get_charset_id_, get_property_) \ static const FT_Service_BDFRec class_ = \ { \ get_charset_id_, get_property_ \ }; #else /* FT_CONFIG_OPTION_PIC */ #define FT_DEFINE_SERVICE_BDFRec(class_, get_charset_id_, get_property_) \ void \ FT_Init_Class_##class_( FT_Service_BDFRec* clazz ) \ { \ clazz->get_charset_id = get_charset_id_; \ clazz->get_property = get_property_; \ } #endif /* FT_CONFIG_OPTION_PIC */ /* */ FT_END_HEADER #endif /* __SVBDF_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/internal/services/svcid.h ================================================ /***************************************************************************/ /* */ /* svcid.h */ /* */ /* The FreeType CID font services (specification). */ /* */ /* Copyright 2007, 2009 by Derek Clegg, Michael Toftdal. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __SVCID_H__ #define __SVCID_H__ #include FT_INTERNAL_SERVICE_H FT_BEGIN_HEADER #define FT_SERVICE_ID_CID "CID" typedef FT_Error (*FT_CID_GetRegistryOrderingSupplementFunc)( FT_Face face, const char* *registry, const char* *ordering, FT_Int *supplement ); typedef FT_Error (*FT_CID_GetIsInternallyCIDKeyedFunc)( FT_Face face, FT_Bool *is_cid ); typedef FT_Error (*FT_CID_GetCIDFromGlyphIndexFunc)( FT_Face face, FT_UInt glyph_index, FT_UInt *cid ); FT_DEFINE_SERVICE( CID ) { FT_CID_GetRegistryOrderingSupplementFunc get_ros; FT_CID_GetIsInternallyCIDKeyedFunc get_is_cid; FT_CID_GetCIDFromGlyphIndexFunc get_cid_from_glyph_index; }; #ifndef FT_CONFIG_OPTION_PIC #define FT_DEFINE_SERVICE_CIDREC(class_, get_ros_, \ get_is_cid_, get_cid_from_glyph_index_ ) \ static const FT_Service_CIDRec class_ = \ { \ get_ros_, get_is_cid_, get_cid_from_glyph_index_ \ }; #else /* FT_CONFIG_OPTION_PIC */ #define FT_DEFINE_SERVICE_CIDREC(class_, get_ros_, \ get_is_cid_, get_cid_from_glyph_index_ ) \ void \ FT_Init_Class_##class_( FT_Library library, \ FT_Service_CIDRec* clazz) \ { \ FT_UNUSED(library); \ clazz->get_ros = get_ros_; \ clazz->get_is_cid = get_is_cid_; \ clazz->get_cid_from_glyph_index = get_cid_from_glyph_index_; \ } #endif /* FT_CONFIG_OPTION_PIC */ /* */ FT_END_HEADER #endif /* __SVCID_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/internal/services/svgldict.h ================================================ /***************************************************************************/ /* */ /* svgldict.h */ /* */ /* The FreeType glyph dictionary services (specification). */ /* */ /* Copyright 2003 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __SVGLDICT_H__ #define __SVGLDICT_H__ #include FT_INTERNAL_SERVICE_H FT_BEGIN_HEADER /* * A service used to retrieve glyph names, as well as to find the * index of a given glyph name in a font. * */ #define FT_SERVICE_ID_GLYPH_DICT "glyph-dict" typedef FT_Error (*FT_GlyphDict_GetNameFunc)( FT_Face face, FT_UInt glyph_index, FT_Pointer buffer, FT_UInt buffer_max ); typedef FT_UInt (*FT_GlyphDict_NameIndexFunc)( FT_Face face, FT_String* glyph_name ); FT_DEFINE_SERVICE( GlyphDict ) { FT_GlyphDict_GetNameFunc get_name; FT_GlyphDict_NameIndexFunc name_index; /* optional */ }; #ifndef FT_CONFIG_OPTION_PIC #define FT_DEFINE_SERVICE_GLYPHDICTREC(class_, get_name_, name_index_) \ static const FT_Service_GlyphDictRec class_ = \ { \ get_name_, name_index_ \ }; #else /* FT_CONFIG_OPTION_PIC */ #define FT_DEFINE_SERVICE_GLYPHDICTREC(class_, get_name_, name_index_) \ void \ FT_Init_Class_##class_( FT_Library library, \ FT_Service_GlyphDictRec* clazz) \ { \ FT_UNUSED(library); \ clazz->get_name = get_name_; \ clazz->name_index = name_index_; \ } #endif /* FT_CONFIG_OPTION_PIC */ /* */ FT_END_HEADER #endif /* __SVGLDICT_H__ */ ================================================ FILE: other/freetype/include/freetype/internal/services/svgxval.h ================================================ /***************************************************************************/ /* */ /* svgxval.h */ /* */ /* FreeType API for validating TrueTypeGX/AAT tables (specification). */ /* */ /* Copyright 2004, 2005 by */ /* Masatake YAMATO, Red Hat K.K., */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /***************************************************************************/ /* */ /* gxvalid is derived from both gxlayout module and otvalid module. */ /* Development of gxlayout is supported by the Information-technology */ /* Promotion Agency(IPA), Japan. */ /* */ /***************************************************************************/ #ifndef __SVGXVAL_H__ #define __SVGXVAL_H__ #include FT_GX_VALIDATE_H #include FT_INTERNAL_VALIDATE_H FT_BEGIN_HEADER #define FT_SERVICE_ID_GX_VALIDATE "truetypegx-validate" #define FT_SERVICE_ID_CLASSICKERN_VALIDATE "classickern-validate" typedef FT_Error (*gxv_validate_func)( FT_Face face, FT_UInt gx_flags, FT_Bytes tables[FT_VALIDATE_GX_LENGTH], FT_UInt table_length ); typedef FT_Error (*ckern_validate_func)( FT_Face face, FT_UInt ckern_flags, FT_Bytes *ckern_table ); FT_DEFINE_SERVICE( GXvalidate ) { gxv_validate_func validate; }; FT_DEFINE_SERVICE( CKERNvalidate ) { ckern_validate_func validate; }; /* */ FT_END_HEADER #endif /* __SVGXVAL_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/internal/services/svkern.h ================================================ /***************************************************************************/ /* */ /* svkern.h */ /* */ /* The FreeType Kerning service (specification). */ /* */ /* Copyright 2006 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __SVKERN_H__ #define __SVKERN_H__ #include FT_INTERNAL_SERVICE_H #include FT_TRUETYPE_TABLES_H FT_BEGIN_HEADER #define FT_SERVICE_ID_KERNING "kerning" typedef FT_Error (*FT_Kerning_TrackGetFunc)( FT_Face face, FT_Fixed point_size, FT_Int degree, FT_Fixed* akerning ); FT_DEFINE_SERVICE( Kerning ) { FT_Kerning_TrackGetFunc get_track; }; /* */ FT_END_HEADER #endif /* __SVKERN_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/internal/services/svmm.h ================================================ /***************************************************************************/ /* */ /* svmm.h */ /* */ /* The FreeType Multiple Masters and GX var services (specification). */ /* */ /* Copyright 2003, 2004 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __SVMM_H__ #define __SVMM_H__ #include FT_INTERNAL_SERVICE_H FT_BEGIN_HEADER /* * A service used to manage multiple-masters data in a given face. * * See the related APIs in `ftmm.h' (FT_MULTIPLE_MASTERS_H). * */ #define FT_SERVICE_ID_MULTI_MASTERS "multi-masters" typedef FT_Error (*FT_Get_MM_Func)( FT_Face face, FT_Multi_Master* master ); typedef FT_Error (*FT_Get_MM_Var_Func)( FT_Face face, FT_MM_Var* *master ); typedef FT_Error (*FT_Set_MM_Design_Func)( FT_Face face, FT_UInt num_coords, FT_Long* coords ); typedef FT_Error (*FT_Set_Var_Design_Func)( FT_Face face, FT_UInt num_coords, FT_Fixed* coords ); typedef FT_Error (*FT_Set_MM_Blend_Func)( FT_Face face, FT_UInt num_coords, FT_Long* coords ); FT_DEFINE_SERVICE( MultiMasters ) { FT_Get_MM_Func get_mm; FT_Set_MM_Design_Func set_mm_design; FT_Set_MM_Blend_Func set_mm_blend; FT_Get_MM_Var_Func get_mm_var; FT_Set_Var_Design_Func set_var_design; }; #ifndef FT_CONFIG_OPTION_PIC #define FT_DEFINE_SERVICE_MULTIMASTERSREC(class_, get_mm_, set_mm_design_, \ set_mm_blend_, get_mm_var_, set_var_design_) \ static const FT_Service_MultiMastersRec class_ = \ { \ get_mm_, set_mm_design_, set_mm_blend_, get_mm_var_, set_var_design_ \ }; #else /* FT_CONFIG_OPTION_PIC */ #define FT_DEFINE_SERVICE_MULTIMASTERSREC(class_, get_mm_, set_mm_design_, \ set_mm_blend_, get_mm_var_, set_var_design_) \ void \ FT_Init_Class_##class_( FT_Service_MultiMastersRec* clazz ) \ { \ clazz->get_mm = get_mm_; \ clazz->set_mm_design = set_mm_design_; \ clazz->set_mm_blend = set_mm_blend_; \ clazz->get_mm_var = get_mm_var_; \ clazz->set_var_design = set_var_design_; \ } #endif /* FT_CONFIG_OPTION_PIC */ /* */ FT_END_HEADER #endif /* __SVMM_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/internal/services/svotval.h ================================================ /***************************************************************************/ /* */ /* svotval.h */ /* */ /* The FreeType OpenType validation service (specification). */ /* */ /* Copyright 2004, 2006 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __SVOTVAL_H__ #define __SVOTVAL_H__ #include FT_OPENTYPE_VALIDATE_H #include FT_INTERNAL_VALIDATE_H FT_BEGIN_HEADER #define FT_SERVICE_ID_OPENTYPE_VALIDATE "opentype-validate" typedef FT_Error (*otv_validate_func)( FT_Face volatile face, FT_UInt ot_flags, FT_Bytes *base, FT_Bytes *gdef, FT_Bytes *gpos, FT_Bytes *gsub, FT_Bytes *jstf ); FT_DEFINE_SERVICE( OTvalidate ) { otv_validate_func validate; }; /* */ FT_END_HEADER #endif /* __SVOTVAL_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/internal/services/svpfr.h ================================================ /***************************************************************************/ /* */ /* svpfr.h */ /* */ /* Internal PFR service functions (specification). */ /* */ /* Copyright 2003, 2006 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __SVPFR_H__ #define __SVPFR_H__ #include FT_PFR_H #include FT_INTERNAL_SERVICE_H FT_BEGIN_HEADER #define FT_SERVICE_ID_PFR_METRICS "pfr-metrics" typedef FT_Error (*FT_PFR_GetMetricsFunc)( FT_Face face, FT_UInt *aoutline, FT_UInt *ametrics, FT_Fixed *ax_scale, FT_Fixed *ay_scale ); typedef FT_Error (*FT_PFR_GetKerningFunc)( FT_Face face, FT_UInt left, FT_UInt right, FT_Vector *avector ); typedef FT_Error (*FT_PFR_GetAdvanceFunc)( FT_Face face, FT_UInt gindex, FT_Pos *aadvance ); FT_DEFINE_SERVICE( PfrMetrics ) { FT_PFR_GetMetricsFunc get_metrics; FT_PFR_GetKerningFunc get_kerning; FT_PFR_GetAdvanceFunc get_advance; }; /* */ FT_END_HEADER #endif /* __SVPFR_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/internal/services/svpostnm.h ================================================ /***************************************************************************/ /* */ /* svpostnm.h */ /* */ /* The FreeType PostScript name services (specification). */ /* */ /* Copyright 2003, 2007 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __SVPOSTNM_H__ #define __SVPOSTNM_H__ #include FT_INTERNAL_SERVICE_H FT_BEGIN_HEADER /* * A trivial service used to retrieve the PostScript name of a given * font when available. The `get_name' field should never be NULL. * * The corresponding function can return NULL to indicate that the * PostScript name is not available. * * The name is owned by the face and will be destroyed with it. */ #define FT_SERVICE_ID_POSTSCRIPT_FONT_NAME "postscript-font-name" typedef const char* (*FT_PsName_GetFunc)( FT_Face face ); FT_DEFINE_SERVICE( PsFontName ) { FT_PsName_GetFunc get_ps_font_name; }; #ifndef FT_CONFIG_OPTION_PIC #define FT_DEFINE_SERVICE_PSFONTNAMEREC(class_, get_ps_font_name_) \ static const FT_Service_PsFontNameRec class_ = \ { \ get_ps_font_name_ \ }; #else /* FT_CONFIG_OPTION_PIC */ #define FT_DEFINE_SERVICE_PSFONTNAMEREC(class_, get_ps_font_name_) \ void \ FT_Init_Class_##class_( FT_Library library, \ FT_Service_PsFontNameRec* clazz) \ { \ FT_UNUSED(library); \ clazz->get_ps_font_name = get_ps_font_name_; \ } #endif /* FT_CONFIG_OPTION_PIC */ /* */ FT_END_HEADER #endif /* __SVPOSTNM_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/internal/services/svpscmap.h ================================================ /***************************************************************************/ /* */ /* svpscmap.h */ /* */ /* The FreeType PostScript charmap service (specification). */ /* */ /* Copyright 2003, 2006 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __SVPSCMAP_H__ #define __SVPSCMAP_H__ #include FT_INTERNAL_OBJECTS_H FT_BEGIN_HEADER #define FT_SERVICE_ID_POSTSCRIPT_CMAPS "postscript-cmaps" /* * Adobe glyph name to unicode value. */ typedef FT_UInt32 (*PS_Unicode_ValueFunc)( const char* glyph_name ); /* * Macintosh name id to glyph name. NULL if invalid index. */ typedef const char* (*PS_Macintosh_NameFunc)( FT_UInt name_index ); /* * Adobe standard string ID to glyph name. NULL if invalid index. */ typedef const char* (*PS_Adobe_Std_StringsFunc)( FT_UInt string_index ); /* * Simple unicode -> glyph index charmap built from font glyph names * table. */ typedef struct PS_UniMap_ { FT_UInt32 unicode; /* bit 31 set: is glyph variant */ FT_UInt glyph_index; } PS_UniMap; typedef struct PS_UnicodesRec_* PS_Unicodes; typedef struct PS_UnicodesRec_ { FT_CMapRec cmap; FT_UInt num_maps; PS_UniMap* maps; } PS_UnicodesRec; /* * A function which returns a glyph name for a given index. Returns * NULL if invalid index. */ typedef const char* (*PS_GetGlyphNameFunc)( FT_Pointer data, FT_UInt string_index ); /* * A function used to release the glyph name returned by * PS_GetGlyphNameFunc, when needed */ typedef void (*PS_FreeGlyphNameFunc)( FT_Pointer data, const char* name ); typedef FT_Error (*PS_Unicodes_InitFunc)( FT_Memory memory, PS_Unicodes unicodes, FT_UInt num_glyphs, PS_GetGlyphNameFunc get_glyph_name, PS_FreeGlyphNameFunc free_glyph_name, FT_Pointer glyph_data ); typedef FT_UInt (*PS_Unicodes_CharIndexFunc)( PS_Unicodes unicodes, FT_UInt32 unicode ); typedef FT_UInt32 (*PS_Unicodes_CharNextFunc)( PS_Unicodes unicodes, FT_UInt32 *unicode ); FT_DEFINE_SERVICE( PsCMaps ) { PS_Unicode_ValueFunc unicode_value; PS_Unicodes_InitFunc unicodes_init; PS_Unicodes_CharIndexFunc unicodes_char_index; PS_Unicodes_CharNextFunc unicodes_char_next; PS_Macintosh_NameFunc macintosh_name; PS_Adobe_Std_StringsFunc adobe_std_strings; const unsigned short* adobe_std_encoding; const unsigned short* adobe_expert_encoding; }; #ifndef FT_CONFIG_OPTION_PIC #define FT_DEFINE_SERVICE_PSCMAPSREC(class_, unicode_value_, unicodes_init_, \ unicodes_char_index_, unicodes_char_next_, macintosh_name_, \ adobe_std_strings_, adobe_std_encoding_, adobe_expert_encoding_) \ static const FT_Service_PsCMapsRec class_ = \ { \ unicode_value_, unicodes_init_, \ unicodes_char_index_, unicodes_char_next_, macintosh_name_, \ adobe_std_strings_, adobe_std_encoding_, adobe_expert_encoding_ \ }; #else /* FT_CONFIG_OPTION_PIC */ #define FT_DEFINE_SERVICE_PSCMAPSREC(class_, unicode_value_, unicodes_init_, \ unicodes_char_index_, unicodes_char_next_, macintosh_name_, \ adobe_std_strings_, adobe_std_encoding_, adobe_expert_encoding_) \ void \ FT_Init_Class_##class_( FT_Library library, \ FT_Service_PsCMapsRec* clazz) \ { \ FT_UNUSED(library); \ clazz->unicode_value = unicode_value_; \ clazz->unicodes_init = unicodes_init_; \ clazz->unicodes_char_index = unicodes_char_index_; \ clazz->unicodes_char_next = unicodes_char_next_; \ clazz->macintosh_name = macintosh_name_; \ clazz->adobe_std_strings = adobe_std_strings_; \ clazz->adobe_std_encoding = adobe_std_encoding_; \ clazz->adobe_expert_encoding = adobe_expert_encoding_; \ } #endif /* FT_CONFIG_OPTION_PIC */ /* */ FT_END_HEADER #endif /* __SVPSCMAP_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/internal/services/svpsinfo.h ================================================ /***************************************************************************/ /* */ /* svpsinfo.h */ /* */ /* The FreeType PostScript info service (specification). */ /* */ /* Copyright 2003, 2004, 2009, 2011 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __SVPSINFO_H__ #define __SVPSINFO_H__ #include FT_INTERNAL_SERVICE_H #include FT_INTERNAL_TYPE1_TYPES_H FT_BEGIN_HEADER #define FT_SERVICE_ID_POSTSCRIPT_INFO "postscript-info" typedef FT_Error (*PS_GetFontInfoFunc)( FT_Face face, PS_FontInfoRec* afont_info ); typedef FT_Error (*PS_GetFontExtraFunc)( FT_Face face, PS_FontExtraRec* afont_extra ); typedef FT_Int (*PS_HasGlyphNamesFunc)( FT_Face face ); typedef FT_Error (*PS_GetFontPrivateFunc)( FT_Face face, PS_PrivateRec* afont_private ); typedef FT_Long (*PS_GetFontValueFunc)( FT_Face face, PS_Dict_Keys key, FT_UInt idx, void *value, FT_Long value_len ); FT_DEFINE_SERVICE( PsInfo ) { PS_GetFontInfoFunc ps_get_font_info; PS_GetFontExtraFunc ps_get_font_extra; PS_HasGlyphNamesFunc ps_has_glyph_names; PS_GetFontPrivateFunc ps_get_font_private; PS_GetFontValueFunc ps_get_font_value; }; #ifndef FT_CONFIG_OPTION_PIC #define FT_DEFINE_SERVICE_PSINFOREC(class_, get_font_info_, \ ps_get_font_extra_, has_glyph_names_, get_font_private_, \ get_font_value_) \ static const FT_Service_PsInfoRec class_ = \ { \ get_font_info_, ps_get_font_extra_, has_glyph_names_, \ get_font_private_, get_font_value_ \ }; #else /* FT_CONFIG_OPTION_PIC */ #define FT_DEFINE_SERVICE_PSINFOREC(class_, get_font_info_, \ ps_get_font_extra_, has_glyph_names_, get_font_private_, \ get_font_value_) \ void \ FT_Init_Class_##class_( FT_Library library, \ FT_Service_PsInfoRec* clazz) \ { \ FT_UNUSED(library); \ clazz->ps_get_font_info = get_font_info_; \ clazz->ps_get_font_extra = ps_get_font_extra_; \ clazz->ps_has_glyph_names = has_glyph_names_; \ clazz->ps_get_font_private = get_font_private_; \ clazz->ps_get_font_value = get_font_value_; \ } #endif /* FT_CONFIG_OPTION_PIC */ /* */ FT_END_HEADER #endif /* __SVPSINFO_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/internal/services/svsfnt.h ================================================ /***************************************************************************/ /* */ /* svsfnt.h */ /* */ /* The FreeType SFNT table loading service (specification). */ /* */ /* Copyright 2003, 2004 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __SVSFNT_H__ #define __SVSFNT_H__ #include FT_INTERNAL_SERVICE_H #include FT_TRUETYPE_TABLES_H FT_BEGIN_HEADER /* * SFNT table loading service. */ #define FT_SERVICE_ID_SFNT_TABLE "sfnt-table" /* * Used to implement FT_Load_Sfnt_Table(). */ typedef FT_Error (*FT_SFNT_TableLoadFunc)( FT_Face face, FT_ULong tag, FT_Long offset, FT_Byte* buffer, FT_ULong* length ); /* * Used to implement FT_Get_Sfnt_Table(). */ typedef void* (*FT_SFNT_TableGetFunc)( FT_Face face, FT_Sfnt_Tag tag ); /* * Used to implement FT_Sfnt_Table_Info(). */ typedef FT_Error (*FT_SFNT_TableInfoFunc)( FT_Face face, FT_UInt idx, FT_ULong *tag, FT_ULong *offset, FT_ULong *length ); FT_DEFINE_SERVICE( SFNT_Table ) { FT_SFNT_TableLoadFunc load_table; FT_SFNT_TableGetFunc get_table; FT_SFNT_TableInfoFunc table_info; }; #ifndef FT_CONFIG_OPTION_PIC #define FT_DEFINE_SERVICE_SFNT_TABLEREC(class_, load_, get_, info_) \ static const FT_Service_SFNT_TableRec class_ = \ { \ load_, get_, info_ \ }; #else /* FT_CONFIG_OPTION_PIC */ #define FT_DEFINE_SERVICE_SFNT_TABLEREC(class_, load_, get_, info_) \ void \ FT_Init_Class_##class_( FT_Service_SFNT_TableRec* clazz ) \ { \ clazz->load_table = load_; \ clazz->get_table = get_; \ clazz->table_info = info_; \ } #endif /* FT_CONFIG_OPTION_PIC */ /* */ FT_END_HEADER #endif /* __SVSFNT_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/internal/services/svttcmap.h ================================================ /***************************************************************************/ /* */ /* svttcmap.h */ /* */ /* The FreeType TrueType/sfnt cmap extra information service. */ /* */ /* Copyright 2003 by */ /* Masatake YAMATO, Redhat K.K. */ /* */ /* Copyright 2003, 2008 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /* Development of this service is support of Information-technology Promotion Agency, Japan. */ #ifndef __SVTTCMAP_H__ #define __SVTTCMAP_H__ #include FT_INTERNAL_SERVICE_H #include FT_TRUETYPE_TABLES_H FT_BEGIN_HEADER #define FT_SERVICE_ID_TT_CMAP "tt-cmaps" /*************************************************************************/ /* */ /* <Struct> */ /* TT_CMapInfo */ /* */ /* <Description> */ /* A structure used to store TrueType/sfnt specific cmap information */ /* which is not covered by the generic @FT_CharMap structure. This */ /* structure can be accessed with the @FT_Get_TT_CMap_Info function. */ /* */ /* <Fields> */ /* language :: */ /* The language ID used in Mac fonts. Definitions of values are in */ /* freetype/ttnameid.h. */ /* */ /* format :: */ /* The cmap format. OpenType 1.5 defines the formats 0 (byte */ /* encoding table), 2~(high-byte mapping through table), 4~(segment */ /* mapping to delta values), 6~(trimmed table mapping), 8~(mixed */ /* 16-bit and 32-bit coverage), 10~(trimmed array), 12~(segmented */ /* coverage), and 14 (Unicode Variation Sequences). */ /* */ typedef struct TT_CMapInfo_ { FT_ULong language; FT_Long format; } TT_CMapInfo; typedef FT_Error (*TT_CMap_Info_GetFunc)( FT_CharMap charmap, TT_CMapInfo *cmap_info ); FT_DEFINE_SERVICE( TTCMaps ) { TT_CMap_Info_GetFunc get_cmap_info; }; #ifndef FT_CONFIG_OPTION_PIC #define FT_DEFINE_SERVICE_TTCMAPSREC(class_, get_cmap_info_) \ static const FT_Service_TTCMapsRec class_ = \ { \ get_cmap_info_ \ }; #else /* FT_CONFIG_OPTION_PIC */ #define FT_DEFINE_SERVICE_TTCMAPSREC(class_, get_cmap_info_) \ void \ FT_Init_Class_##class_( FT_Library library, \ FT_Service_TTCMapsRec* clazz) \ { \ FT_UNUSED(library); \ clazz->get_cmap_info = get_cmap_info_; \ } #endif /* FT_CONFIG_OPTION_PIC */ /* */ FT_END_HEADER #endif /* __SVTTCMAP_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/internal/services/svtteng.h ================================================ /***************************************************************************/ /* */ /* svtteng.h */ /* */ /* The FreeType TrueType engine query service (specification). */ /* */ /* Copyright 2006 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __SVTTENG_H__ #define __SVTTENG_H__ #include FT_INTERNAL_SERVICE_H #include FT_MODULE_H FT_BEGIN_HEADER /* * SFNT table loading service. */ #define FT_SERVICE_ID_TRUETYPE_ENGINE "truetype-engine" /* * Used to implement FT_Get_TrueType_Engine_Type */ FT_DEFINE_SERVICE( TrueTypeEngine ) { FT_TrueTypeEngineType engine_type; }; /* */ FT_END_HEADER #endif /* __SVTTENG_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/internal/services/svttglyf.h ================================================ /***************************************************************************/ /* */ /* svttglyf.h */ /* */ /* The FreeType TrueType glyph service. */ /* */ /* Copyright 2007 by David Turner. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __SVTTGLYF_H__ #define __SVTTGLYF_H__ #include FT_INTERNAL_SERVICE_H #include FT_TRUETYPE_TABLES_H FT_BEGIN_HEADER #define FT_SERVICE_ID_TT_GLYF "tt-glyf" typedef FT_ULong (*TT_Glyf_GetLocationFunc)( FT_Face face, FT_UInt gindex, FT_ULong *psize ); FT_DEFINE_SERVICE( TTGlyf ) { TT_Glyf_GetLocationFunc get_location; }; #ifndef FT_CONFIG_OPTION_PIC #define FT_DEFINE_SERVICE_TTGLYFREC(class_, get_location_ ) \ static const FT_Service_TTGlyfRec class_ = \ { \ get_location_ \ }; #else /* FT_CONFIG_OPTION_PIC */ #define FT_DEFINE_SERVICE_TTGLYFREC(class_, get_location_ ) \ void \ FT_Init_Class_##class_( FT_Service_TTGlyfRec* clazz ) \ { \ clazz->get_location = get_location_; \ } #endif /* FT_CONFIG_OPTION_PIC */ /* */ FT_END_HEADER #endif /* __SVTTGLYF_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/internal/services/svwinfnt.h ================================================ /***************************************************************************/ /* */ /* svwinfnt.h */ /* */ /* The FreeType Windows FNT/FONT service (specification). */ /* */ /* Copyright 2003 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __SVWINFNT_H__ #define __SVWINFNT_H__ #include FT_INTERNAL_SERVICE_H #include FT_WINFONTS_H FT_BEGIN_HEADER #define FT_SERVICE_ID_WINFNT "winfonts" typedef FT_Error (*FT_WinFnt_GetHeaderFunc)( FT_Face face, FT_WinFNT_HeaderRec *aheader ); FT_DEFINE_SERVICE( WinFnt ) { FT_WinFnt_GetHeaderFunc get_header; }; /* */ FT_END_HEADER #endif /* __SVWINFNT_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/internal/services/svxf86nm.h ================================================ /***************************************************************************/ /* */ /* svxf86nm.h */ /* */ /* The FreeType XFree86 services (specification only). */ /* */ /* Copyright 2003 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __SVXF86NM_H__ #define __SVXF86NM_H__ #include FT_INTERNAL_SERVICE_H FT_BEGIN_HEADER /* * A trivial service used to return the name of a face's font driver, * according to the XFree86 nomenclature. Note that the service data * is a simple constant string pointer. */ #define FT_SERVICE_ID_XF86_NAME "xf86-driver-name" #define FT_XF86_FORMAT_TRUETYPE "TrueType" #define FT_XF86_FORMAT_TYPE_1 "Type 1" #define FT_XF86_FORMAT_BDF "BDF" #define FT_XF86_FORMAT_PCF "PCF" #define FT_XF86_FORMAT_TYPE_42 "Type 42" #define FT_XF86_FORMAT_CID "CID Type 1" #define FT_XF86_FORMAT_CFF "CFF" #define FT_XF86_FORMAT_PFR "PFR" #define FT_XF86_FORMAT_WINFNT "Windows FNT" /* */ FT_END_HEADER #endif /* __SVXF86NM_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/internal/sfnt.h ================================================ /***************************************************************************/ /* */ /* sfnt.h */ /* */ /* High-level `sfnt' driver interface (specification). */ /* */ /* Copyright 1996-2001, 2002, 2003, 2004, 2005, 2006 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __SFNT_H__ #define __SFNT_H__ #include <ft2build.h> #include FT_INTERNAL_DRIVER_H #include FT_INTERNAL_TRUETYPE_TYPES_H FT_BEGIN_HEADER /*************************************************************************/ /* */ /* <FuncType> */ /* TT_Init_Face_Func */ /* */ /* <Description> */ /* First part of the SFNT face object initialization. This finds */ /* the face in a SFNT file or collection, and load its format tag in */ /* face->format_tag. */ /* */ /* <Input> */ /* stream :: The input stream. */ /* */ /* face :: A handle to the target face object. */ /* */ /* face_index :: The index of the TrueType font, if we are opening a */ /* collection. */ /* */ /* num_params :: The number of additional parameters. */ /* */ /* params :: Optional additional parameters. */ /* */ /* <Return> */ /* FreeType error code. 0 means success. */ /* */ /* <Note> */ /* The stream cursor must be at the font file's origin. */ /* */ /* This function recognizes fonts embedded in a `TrueType */ /* collection'. */ /* */ /* Once the format tag has been validated by the font driver, it */ /* should then call the TT_Load_Face_Func() callback to read the rest */ /* of the SFNT tables in the object. */ /* */ typedef FT_Error (*TT_Init_Face_Func)( FT_Stream stream, TT_Face face, FT_Int face_index, FT_Int num_params, FT_Parameter* params ); /*************************************************************************/ /* */ /* <FuncType> */ /* TT_Load_Face_Func */ /* */ /* <Description> */ /* Second part of the SFNT face object initialization. This loads */ /* the common SFNT tables (head, OS/2, maxp, metrics, etc.) in the */ /* face object. */ /* */ /* <Input> */ /* stream :: The input stream. */ /* */ /* face :: A handle to the target face object. */ /* */ /* face_index :: The index of the TrueType font, if we are opening a */ /* collection. */ /* */ /* num_params :: The number of additional parameters. */ /* */ /* params :: Optional additional parameters. */ /* */ /* <Return> */ /* FreeType error code. 0 means success. */ /* */ /* <Note> */ /* This function must be called after TT_Init_Face_Func(). */ /* */ typedef FT_Error (*TT_Load_Face_Func)( FT_Stream stream, TT_Face face, FT_Int face_index, FT_Int num_params, FT_Parameter* params ); /*************************************************************************/ /* */ /* <FuncType> */ /* TT_Done_Face_Func */ /* */ /* <Description> */ /* A callback used to delete the common SFNT data from a face. */ /* */ /* <Input> */ /* face :: A handle to the target face object. */ /* */ /* <Note> */ /* This function does NOT destroy the face object. */ /* */ typedef void (*TT_Done_Face_Func)( TT_Face face ); #ifdef FT_CONFIG_OPTION_OLD_INTERNALS /*************************************************************************/ /* */ /* <FuncType> */ /* TT_Load_SFNT_HeaderRec_Func */ /* */ /* <Description> */ /* Loads the header of a SFNT font file. Supports collections. */ /* */ /* <Input> */ /* face :: A handle to the target face object. */ /* */ /* stream :: The input stream. */ /* */ /* face_index :: The index of the TrueType font, if we are opening a */ /* collection. */ /* */ /* <Output> */ /* sfnt :: The SFNT header. */ /* */ /* <Return> */ /* FreeType error code. 0 means success. */ /* */ /* <Note> */ /* The stream cursor must be at the font file's origin. */ /* */ /* This function recognizes fonts embedded in a `TrueType */ /* collection'. */ /* */ /* This function checks that the header is valid by looking at the */ /* values of `search_range', `entry_selector', and `range_shift'. */ /* */ typedef FT_Error (*TT_Load_SFNT_HeaderRec_Func)( TT_Face face, FT_Stream stream, FT_Long face_index, SFNT_Header sfnt ); /*************************************************************************/ /* */ /* <FuncType> */ /* TT_Load_Directory_Func */ /* */ /* <Description> */ /* Loads the table directory into a face object. */ /* */ /* <Input> */ /* face :: A handle to the target face object. */ /* */ /* stream :: The input stream. */ /* */ /* sfnt :: The SFNT header. */ /* */ /* <Return> */ /* FreeType error code. 0 means success. */ /* */ /* <Note> */ /* The stream cursor must be on the first byte after the 4-byte font */ /* format tag. This is the case just after a call to */ /* TT_Load_Format_Tag(). */ /* */ typedef FT_Error (*TT_Load_Directory_Func)( TT_Face face, FT_Stream stream, SFNT_Header sfnt ); #endif /* FT_CONFIG_OPTION_OLD_INTERNALS */ /*************************************************************************/ /* */ /* <FuncType> */ /* TT_Load_Any_Func */ /* */ /* <Description> */ /* Load any font table into client memory. */ /* */ /* <Input> */ /* face :: The face object to look for. */ /* */ /* tag :: The tag of table to load. Use the value 0 if you want */ /* to access the whole font file, else set this parameter */ /* to a valid TrueType table tag that you can forge with */ /* the MAKE_TT_TAG macro. */ /* */ /* offset :: The starting offset in the table (or the file if */ /* tag == 0). */ /* */ /* length :: The address of the decision variable: */ /* */ /* If length == NULL: */ /* Loads the whole table. Returns an error if */ /* `offset' == 0! */ /* */ /* If *length == 0: */ /* Exits immediately; returning the length of the given */ /* table or of the font file, depending on the value of */ /* `tag'. */ /* */ /* If *length != 0: */ /* Loads the next `length' bytes of table or font, */ /* starting at offset `offset' (in table or font too). */ /* */ /* <Output> */ /* buffer :: The address of target buffer. */ /* */ /* <Return> */ /* TrueType error code. 0 means success. */ /* */ typedef FT_Error (*TT_Load_Any_Func)( TT_Face face, FT_ULong tag, FT_Long offset, FT_Byte *buffer, FT_ULong* length ); /*************************************************************************/ /* */ /* <FuncType> */ /* TT_Find_SBit_Image_Func */ /* */ /* <Description> */ /* Check whether an embedded bitmap (an `sbit') exists for a given */ /* glyph, at a given strike. */ /* */ /* <Input> */ /* face :: The target face object. */ /* */ /* glyph_index :: The glyph index. */ /* */ /* strike_index :: The current strike index. */ /* */ /* <Output> */ /* arange :: The SBit range containing the glyph index. */ /* */ /* astrike :: The SBit strike containing the glyph index. */ /* */ /* aglyph_offset :: The offset of the glyph data in `EBDT' table. */ /* */ /* <Return> */ /* FreeType error code. 0 means success. Returns */ /* SFNT_Err_Invalid_Argument if no sbit exists for the requested */ /* glyph. */ /* */ typedef FT_Error (*TT_Find_SBit_Image_Func)( TT_Face face, FT_UInt glyph_index, FT_ULong strike_index, TT_SBit_Range *arange, TT_SBit_Strike *astrike, FT_ULong *aglyph_offset ); /*************************************************************************/ /* */ /* <FuncType> */ /* TT_Load_SBit_Metrics_Func */ /* */ /* <Description> */ /* Get the big metrics for a given embedded bitmap. */ /* */ /* <Input> */ /* stream :: The input stream. */ /* */ /* range :: The SBit range containing the glyph. */ /* */ /* <Output> */ /* big_metrics :: A big SBit metrics structure for the glyph. */ /* */ /* <Return> */ /* FreeType error code. 0 means success. */ /* */ /* <Note> */ /* The stream cursor must be positioned at the glyph's offset within */ /* the `EBDT' table before the call. */ /* */ /* If the image format uses variable metrics, the stream cursor is */ /* positioned just after the metrics header in the `EBDT' table on */ /* function exit. */ /* */ typedef FT_Error (*TT_Load_SBit_Metrics_Func)( FT_Stream stream, TT_SBit_Range range, TT_SBit_Metrics metrics ); /*************************************************************************/ /* */ /* <FuncType> */ /* TT_Load_SBit_Image_Func */ /* */ /* <Description> */ /* Load a given glyph sbit image from the font resource. This also */ /* returns its metrics. */ /* */ /* <Input> */ /* face :: */ /* The target face object. */ /* */ /* strike_index :: */ /* The strike index. */ /* */ /* glyph_index :: */ /* The current glyph index. */ /* */ /* load_flags :: */ /* The current load flags. */ /* */ /* stream :: */ /* The input stream. */ /* */ /* <Output> */ /* amap :: */ /* The target pixmap. */ /* */ /* ametrics :: */ /* A big sbit metrics structure for the glyph image. */ /* */ /* <Return> */ /* FreeType error code. 0 means success. Returns an error if no */ /* glyph sbit exists for the index. */ /* */ /* <Note> */ /* The `map.buffer' field is always freed before the glyph is loaded. */ /* */ typedef FT_Error (*TT_Load_SBit_Image_Func)( TT_Face face, FT_ULong strike_index, FT_UInt glyph_index, FT_UInt load_flags, FT_Stream stream, FT_Bitmap *amap, TT_SBit_MetricsRec *ametrics ); #ifdef FT_CONFIG_OPTION_OLD_INTERNALS /*************************************************************************/ /* */ /* <FuncType> */ /* TT_Set_SBit_Strike_OldFunc */ /* */ /* <Description> */ /* Select an sbit strike for a given size request. */ /* */ /* <Input> */ /* face :: The target face object. */ /* */ /* req :: The size request. */ /* */ /* <Output> */ /* astrike_index :: The index of the sbit strike. */ /* */ /* <Return> */ /* FreeType error code. 0 means success. Returns an error if no */ /* sbit strike exists for the selected ppem values. */ /* */ typedef FT_Error (*TT_Set_SBit_Strike_OldFunc)( TT_Face face, FT_UInt x_ppem, FT_UInt y_ppem, FT_ULong* astrike_index ); /*************************************************************************/ /* */ /* <FuncType> */ /* TT_CharMap_Load_Func */ /* */ /* <Description> */ /* Loads a given TrueType character map into memory. */ /* */ /* <Input> */ /* face :: A handle to the parent face object. */ /* */ /* stream :: A handle to the current stream object. */ /* */ /* <InOut> */ /* cmap :: A pointer to a cmap object. */ /* */ /* <Return> */ /* FreeType error code. 0 means success. */ /* */ /* <Note> */ /* The function assumes that the stream is already in use (i.e., */ /* opened). In case of error, all partially allocated tables are */ /* released. */ /* */ typedef FT_Error (*TT_CharMap_Load_Func)( TT_Face face, void* cmap, FT_Stream input ); /*************************************************************************/ /* */ /* <FuncType> */ /* TT_CharMap_Free_Func */ /* */ /* <Description> */ /* Destroys a character mapping table. */ /* */ /* <Input> */ /* face :: A handle to the parent face object. */ /* */ /* cmap :: A handle to a cmap object. */ /* */ /* <Return> */ /* FreeType error code. 0 means success. */ /* */ typedef FT_Error (*TT_CharMap_Free_Func)( TT_Face face, void* cmap ); #endif /* FT_CONFIG_OPTION_OLD_INTERNALS */ /*************************************************************************/ /* */ /* <FuncType> */ /* TT_Set_SBit_Strike_Func */ /* */ /* <Description> */ /* Select an sbit strike for a given size request. */ /* */ /* <Input> */ /* face :: The target face object. */ /* */ /* req :: The size request. */ /* */ /* <Output> */ /* astrike_index :: The index of the sbit strike. */ /* */ /* <Return> */ /* FreeType error code. 0 means success. Returns an error if no */ /* sbit strike exists for the selected ppem values. */ /* */ typedef FT_Error (*TT_Set_SBit_Strike_Func)( TT_Face face, FT_Size_Request req, FT_ULong* astrike_index ); /*************************************************************************/ /* */ /* <FuncType> */ /* TT_Load_Strike_Metrics_Func */ /* */ /* <Description> */ /* Load the metrics of a given strike. */ /* */ /* <Input> */ /* face :: The target face object. */ /* */ /* strike_index :: The strike index. */ /* */ /* <Output> */ /* metrics :: the metrics of the strike. */ /* */ /* <Return> */ /* FreeType error code. 0 means success. Returns an error if no */ /* such sbit strike exists. */ /* */ typedef FT_Error (*TT_Load_Strike_Metrics_Func)( TT_Face face, FT_ULong strike_index, FT_Size_Metrics* metrics ); /*************************************************************************/ /* */ /* <FuncType> */ /* TT_Get_PS_Name_Func */ /* */ /* <Description> */ /* Get the PostScript glyph name of a glyph. */ /* */ /* <Input> */ /* idx :: The glyph index. */ /* */ /* PSname :: The address of a string pointer. Will be NULL in case */ /* of error, otherwise it is a pointer to the glyph name. */ /* */ /* You must not modify the returned string! */ /* */ /* <Output> */ /* FreeType error code. 0 means success. */ /* */ typedef FT_Error (*TT_Get_PS_Name_Func)( TT_Face face, FT_UInt idx, FT_String** PSname ); /*************************************************************************/ /* */ /* <FuncType> */ /* TT_Load_Metrics_Func */ /* */ /* <Description> */ /* Load a metrics table, which is a table with a horizontal and a */ /* vertical version. */ /* */ /* <Input> */ /* face :: A handle to the target face object. */ /* */ /* stream :: The input stream. */ /* */ /* vertical :: A boolean flag. If set, load the vertical one. */ /* */ /* <Return> */ /* FreeType error code. 0 means success. */ /* */ typedef FT_Error (*TT_Load_Metrics_Func)( TT_Face face, FT_Stream stream, FT_Bool vertical ); /*************************************************************************/ /* */ /* <FuncType> */ /* TT_Get_Metrics_Func */ /* */ /* <Description> */ /* Load the horizontal or vertical header in a face object. */ /* */ /* <Input> */ /* face :: A handle to the target face object. */ /* */ /* stream :: The input stream. */ /* */ /* vertical :: A boolean flag. If set, load vertical metrics. */ /* */ /* <Return> */ /* FreeType error code. 0 means success. */ /* */ typedef FT_Error (*TT_Get_Metrics_Func)( TT_Face face, FT_Bool vertical, FT_UInt gindex, FT_Short* abearing, FT_UShort* aadvance ); /*************************************************************************/ /* */ /* <FuncType> */ /* TT_Load_Table_Func */ /* */ /* <Description> */ /* Load a given TrueType table. */ /* */ /* <Input> */ /* face :: A handle to the target face object. */ /* */ /* stream :: The input stream. */ /* */ /* <Return> */ /* FreeType error code. 0 means success. */ /* */ /* <Note> */ /* The function uses `face->goto_table' to seek the stream to the */ /* start of the table, except while loading the font directory. */ /* */ typedef FT_Error (*TT_Load_Table_Func)( TT_Face face, FT_Stream stream ); /*************************************************************************/ /* */ /* <FuncType> */ /* TT_Free_Table_Func */ /* */ /* <Description> */ /* Free a given TrueType table. */ /* */ /* <Input> */ /* face :: A handle to the target face object. */ /* */ typedef void (*TT_Free_Table_Func)( TT_Face face ); /* * @functype: * TT_Face_GetKerningFunc * * @description: * Return the horizontal kerning value between two glyphs. * * @input: * face :: A handle to the source face object. * left_glyph :: The left glyph index. * right_glyph :: The right glyph index. * * @return: * The kerning value in font units. */ typedef FT_Int (*TT_Face_GetKerningFunc)( TT_Face face, FT_UInt left_glyph, FT_UInt right_glyph ); /*************************************************************************/ /* */ /* <Struct> */ /* SFNT_Interface */ /* */ /* <Description> */ /* This structure holds pointers to the functions used to load and */ /* free the basic tables that are required in a `sfnt' font file. */ /* */ /* <Fields> */ /* Check the various xxx_Func() descriptions for details. */ /* */ typedef struct SFNT_Interface_ { TT_Loader_GotoTableFunc goto_table; TT_Init_Face_Func init_face; TT_Load_Face_Func load_face; TT_Done_Face_Func done_face; FT_Module_Requester get_interface; TT_Load_Any_Func load_any; #ifdef FT_CONFIG_OPTION_OLD_INTERNALS TT_Load_SFNT_HeaderRec_Func load_sfnt_header; TT_Load_Directory_Func load_directory; #endif /* these functions are called by `load_face' but they can also */ /* be called from external modules, if there is a need to do so */ TT_Load_Table_Func load_head; TT_Load_Metrics_Func load_hhea; TT_Load_Table_Func load_cmap; TT_Load_Table_Func load_maxp; TT_Load_Table_Func load_os2; TT_Load_Table_Func load_post; TT_Load_Table_Func load_name; TT_Free_Table_Func free_name; /* optional tables */ #ifdef FT_CONFIG_OPTION_OLD_INTERNALS TT_Load_Table_Func load_hdmx_stub; TT_Free_Table_Func free_hdmx_stub; #endif /* this field was called `load_kerning' up to version 2.1.10 */ TT_Load_Table_Func load_kern; TT_Load_Table_Func load_gasp; TT_Load_Table_Func load_pclt; /* see `ttload.h'; this field was called `load_bitmap_header' up to */ /* version 2.1.10 */ TT_Load_Table_Func load_bhed; #ifdef FT_CONFIG_OPTION_OLD_INTERNALS /* see `ttsbit.h' */ TT_Set_SBit_Strike_OldFunc set_sbit_strike_stub; TT_Load_Table_Func load_sbits_stub; /* * The following two fields appeared in version 2.1.8, and were placed * between `load_sbits' and `load_sbit_image'. We support them as a * special exception since they are used by Xfont library within the * X.Org xserver, and because the probability that other rogue clients * use the other version 2.1.7 fields below is _extremely_ low. * * Note that this forces us to disable an interesting memory-saving * optimization though... */ TT_Find_SBit_Image_Func find_sbit_image; TT_Load_SBit_Metrics_Func load_sbit_metrics; #endif TT_Load_SBit_Image_Func load_sbit_image; #ifdef FT_CONFIG_OPTION_OLD_INTERNALS TT_Free_Table_Func free_sbits_stub; #endif /* see `ttpost.h' */ TT_Get_PS_Name_Func get_psname; TT_Free_Table_Func free_psnames; #ifdef FT_CONFIG_OPTION_OLD_INTERNALS TT_CharMap_Load_Func load_charmap_stub; TT_CharMap_Free_Func free_charmap_stub; #endif /* starting here, the structure differs from version 2.1.7 */ /* this field was introduced in version 2.1.8, named `get_psname' */ TT_Face_GetKerningFunc get_kerning; /* new elements introduced after version 2.1.10 */ /* load the font directory, i.e., the offset table and */ /* the table directory */ TT_Load_Table_Func load_font_dir; TT_Load_Metrics_Func load_hmtx; TT_Load_Table_Func load_eblc; TT_Free_Table_Func free_eblc; TT_Set_SBit_Strike_Func set_sbit_strike; TT_Load_Strike_Metrics_Func load_strike_metrics; TT_Get_Metrics_Func get_metrics; } SFNT_Interface; /* transitional */ typedef SFNT_Interface* SFNT_Service; #ifndef FT_CONFIG_OPTION_PIC #ifdef FT_CONFIG_OPTION_OLD_INTERNALS #define FT_DEFINE_DRIVERS_OLD_INTERNAL(a) \ a, #else #define FT_DEFINE_DRIVERS_OLD_INTERNAL(a) #endif #define FT_INTERNAL(a) \ a, #define FT_DEFINE_SFNT_INTERFACE(class_, \ goto_table_, init_face_, load_face_, done_face_, get_interface_, \ load_any_, load_sfnt_header_, load_directory_, load_head_, \ load_hhea_, load_cmap_, load_maxp_, load_os2_, load_post_, \ load_name_, free_name_, load_hdmx_stub_, free_hdmx_stub_, \ load_kern_, load_gasp_, load_pclt_, load_bhed_, \ set_sbit_strike_stub_, load_sbits_stub_, find_sbit_image_, \ load_sbit_metrics_, load_sbit_image_, free_sbits_stub_, \ get_psname_, free_psnames_, load_charmap_stub_, free_charmap_stub_, \ get_kerning_, load_font_dir_, load_hmtx_, load_eblc_, free_eblc_, \ set_sbit_strike_, load_strike_metrics_, get_metrics_ ) \ static const SFNT_Interface class_ = \ { \ FT_INTERNAL(goto_table_) \ FT_INTERNAL(init_face_) \ FT_INTERNAL(load_face_) \ FT_INTERNAL(done_face_) \ FT_INTERNAL(get_interface_) \ FT_INTERNAL(load_any_) \ FT_DEFINE_DRIVERS_OLD_INTERNAL(load_sfnt_header_) \ FT_DEFINE_DRIVERS_OLD_INTERNAL(load_directory_) \ FT_INTERNAL(load_head_) \ FT_INTERNAL(load_hhea_) \ FT_INTERNAL(load_cmap_) \ FT_INTERNAL(load_maxp_) \ FT_INTERNAL(load_os2_) \ FT_INTERNAL(load_post_) \ FT_INTERNAL(load_name_) \ FT_INTERNAL(free_name_) \ FT_DEFINE_DRIVERS_OLD_INTERNAL(load_hdmx_stub_) \ FT_DEFINE_DRIVERS_OLD_INTERNAL(free_hdmx_stub_) \ FT_INTERNAL(load_kern_) \ FT_INTERNAL(load_gasp_) \ FT_INTERNAL(load_pclt_) \ FT_INTERNAL(load_bhed_) \ FT_DEFINE_DRIVERS_OLD_INTERNAL(set_sbit_strike_stub_) \ FT_DEFINE_DRIVERS_OLD_INTERNAL(load_sbits_stub_) \ FT_DEFINE_DRIVERS_OLD_INTERNAL(find_sbit_image_) \ FT_DEFINE_DRIVERS_OLD_INTERNAL(load_sbit_metrics_) \ FT_INTERNAL(load_sbit_image_) \ FT_DEFINE_DRIVERS_OLD_INTERNAL(free_sbits_stub_) \ FT_INTERNAL(get_psname_) \ FT_INTERNAL(free_psnames_) \ FT_DEFINE_DRIVERS_OLD_INTERNAL(load_charmap_stub_) \ FT_DEFINE_DRIVERS_OLD_INTERNAL(free_charmap_stub_) \ FT_INTERNAL(get_kerning_) \ FT_INTERNAL(load_font_dir_) \ FT_INTERNAL(load_hmtx_) \ FT_INTERNAL(load_eblc_) \ FT_INTERNAL(free_eblc_) \ FT_INTERNAL(set_sbit_strike_) \ FT_INTERNAL(load_strike_metrics_) \ FT_INTERNAL(get_metrics_) \ }; #else /* FT_CONFIG_OPTION_PIC */ #ifdef FT_CONFIG_OPTION_OLD_INTERNALS #define FT_DEFINE_DRIVERS_OLD_INTERNAL(a, a_) \ clazz->a = a_; #else #define FT_DEFINE_DRIVERS_OLD_INTERNAL(a, a_) #endif #define FT_INTERNAL(a, a_) \ clazz->a = a_; #define FT_DEFINE_SFNT_INTERFACE(class_, \ goto_table_, init_face_, load_face_, done_face_, get_interface_, \ load_any_, load_sfnt_header_, load_directory_, load_head_, \ load_hhea_, load_cmap_, load_maxp_, load_os2_, load_post_, \ load_name_, free_name_, load_hdmx_stub_, free_hdmx_stub_, \ load_kern_, load_gasp_, load_pclt_, load_bhed_, \ set_sbit_strike_stub_, load_sbits_stub_, find_sbit_image_, \ load_sbit_metrics_, load_sbit_image_, free_sbits_stub_, \ get_psname_, free_psnames_, load_charmap_stub_, free_charmap_stub_, \ get_kerning_, load_font_dir_, load_hmtx_, load_eblc_, free_eblc_, \ set_sbit_strike_, load_strike_metrics_, get_metrics_ ) \ void \ FT_Init_Class_##class_( FT_Library library, SFNT_Interface* clazz ) \ { \ FT_UNUSED(library); \ FT_INTERNAL(goto_table,goto_table_) \ FT_INTERNAL(init_face,init_face_) \ FT_INTERNAL(load_face,load_face_) \ FT_INTERNAL(done_face,done_face_) \ FT_INTERNAL(get_interface,get_interface_) \ FT_INTERNAL(load_any,load_any_) \ FT_DEFINE_DRIVERS_OLD_INTERNAL(load_sfnt_header,load_sfnt_header_) \ FT_DEFINE_DRIVERS_OLD_INTERNAL(load_directory,load_directory_) \ FT_INTERNAL(load_head,load_head_) \ FT_INTERNAL(load_hhea,load_hhea_) \ FT_INTERNAL(load_cmap,load_cmap_) \ FT_INTERNAL(load_maxp,load_maxp_) \ FT_INTERNAL(load_os2,load_os2_) \ FT_INTERNAL(load_post,load_post_) \ FT_INTERNAL(load_name,load_name_) \ FT_INTERNAL(free_name,free_name_) \ FT_DEFINE_DRIVERS_OLD_INTERNAL(load_hdmx_stub,load_hdmx_stub_) \ FT_DEFINE_DRIVERS_OLD_INTERNAL(free_hdmx_stub,free_hdmx_stub_) \ FT_INTERNAL(load_kern,load_kern_) \ FT_INTERNAL(load_gasp,load_gasp_) \ FT_INTERNAL(load_pclt,load_pclt_) \ FT_INTERNAL(load_bhed,load_bhed_) \ FT_DEFINE_DRIVERS_OLD_INTERNAL(set_sbit_strike_stub,set_sbit_strike_stub_) \ FT_DEFINE_DRIVERS_OLD_INTERNAL(load_sbits_stub,load_sbits_stub_) \ FT_DEFINE_DRIVERS_OLD_INTERNAL(find_sbit_image,find_sbit_image_) \ FT_DEFINE_DRIVERS_OLD_INTERNAL(load_sbit_metrics,load_sbit_metrics_) \ FT_INTERNAL(load_sbit_image,load_sbit_image_) \ FT_DEFINE_DRIVERS_OLD_INTERNAL(free_sbits_stub,free_sbits_stub_) \ FT_INTERNAL(get_psname,get_psname_) \ FT_INTERNAL(free_psnames,free_psnames_) \ FT_DEFINE_DRIVERS_OLD_INTERNAL(load_charmap_stub,load_charmap_stub_) \ FT_DEFINE_DRIVERS_OLD_INTERNAL(free_charmap_stub,free_charmap_stub_) \ FT_INTERNAL(get_kerning,get_kerning_) \ FT_INTERNAL(load_font_dir,load_font_dir_) \ FT_INTERNAL(load_hmtx,load_hmtx_) \ FT_INTERNAL(load_eblc,load_eblc_) \ FT_INTERNAL(free_eblc,free_eblc_) \ FT_INTERNAL(set_sbit_strike,set_sbit_strike_) \ FT_INTERNAL(load_strike_metrics,load_strike_metrics_) \ FT_INTERNAL(get_metrics,get_metrics_) \ } #endif /* FT_CONFIG_OPTION_PIC */ FT_END_HEADER #endif /* __SFNT_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/internal/t1types.h ================================================ /***************************************************************************/ /* */ /* t1types.h */ /* */ /* Basic Type1/Type2 type definitions and interface (specification */ /* only). */ /* */ /* Copyright 1996-2004, 2006, 2008, 2009, 2011 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __T1TYPES_H__ #define __T1TYPES_H__ #include <ft2build.h> #include FT_TYPE1_TABLES_H #include FT_INTERNAL_POSTSCRIPT_HINTS_H #include FT_INTERNAL_SERVICE_H #include FT_SERVICE_POSTSCRIPT_CMAPS_H FT_BEGIN_HEADER /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /*** ***/ /*** ***/ /*** REQUIRED TYPE1/TYPE2 TABLES DEFINITIONS ***/ /*** ***/ /*** ***/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /* */ /* <Struct> */ /* T1_EncodingRec */ /* */ /* <Description> */ /* A structure modeling a custom encoding. */ /* */ /* <Fields> */ /* num_chars :: The number of character codes in the encoding. */ /* Usually 256. */ /* */ /* code_first :: The lowest valid character code in the encoding. */ /* */ /* code_last :: The highest valid character code in the encoding */ /* + 1. When equal to code_first there are no valid */ /* character codes. */ /* */ /* char_index :: An array of corresponding glyph indices. */ /* */ /* char_name :: An array of corresponding glyph names. */ /* */ typedef struct T1_EncodingRecRec_ { FT_Int num_chars; FT_Int code_first; FT_Int code_last; FT_UShort* char_index; FT_String** char_name; } T1_EncodingRec, *T1_Encoding; /* used to hold extra data of PS_FontInfoRec that * cannot be stored in the publicly defined structure. * * Note these can't be blended with multiple-masters. */ typedef struct PS_FontExtraRec_ { FT_UShort fs_type; } PS_FontExtraRec; typedef struct T1_FontRec_ { PS_FontInfoRec font_info; /* font info dictionary */ PS_FontExtraRec font_extra; /* font info extra fields */ PS_PrivateRec private_dict; /* private dictionary */ FT_String* font_name; /* top-level dictionary */ T1_EncodingType encoding_type; T1_EncodingRec encoding; FT_Byte* subrs_block; FT_Byte* charstrings_block; FT_Byte* glyph_names_block; FT_Int num_subrs; FT_Byte** subrs; FT_PtrDist* subrs_len; FT_Int num_glyphs; FT_String** glyph_names; /* array of glyph names */ FT_Byte** charstrings; /* array of glyph charstrings */ FT_PtrDist* charstrings_len; FT_Byte paint_type; FT_Byte font_type; FT_Matrix font_matrix; FT_Vector font_offset; FT_BBox font_bbox; FT_Long font_id; FT_Fixed stroke_width; } T1_FontRec, *T1_Font; typedef struct CID_SubrsRec_ { FT_UInt num_subrs; FT_Byte** code; } CID_SubrsRec, *CID_Subrs; /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /*** ***/ /*** ***/ /*** AFM FONT INFORMATION STRUCTURES ***/ /*** ***/ /*** ***/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ typedef struct AFM_TrackKernRec_ { FT_Int degree; FT_Fixed min_ptsize; FT_Fixed min_kern; FT_Fixed max_ptsize; FT_Fixed max_kern; } AFM_TrackKernRec, *AFM_TrackKern; typedef struct AFM_KernPairRec_ { FT_Int index1; FT_Int index2; FT_Int x; FT_Int y; } AFM_KernPairRec, *AFM_KernPair; typedef struct AFM_FontInfoRec_ { FT_Bool IsCIDFont; FT_BBox FontBBox; FT_Fixed Ascender; FT_Fixed Descender; AFM_TrackKern TrackKerns; /* free if non-NULL */ FT_Int NumTrackKern; AFM_KernPair KernPairs; /* free if non-NULL */ FT_Int NumKernPair; } AFM_FontInfoRec, *AFM_FontInfo; /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /*** ***/ /*** ***/ /*** ORIGINAL T1_FACE CLASS DEFINITION ***/ /*** ***/ /*** ***/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ typedef struct T1_FaceRec_* T1_Face; typedef struct CID_FaceRec_* CID_Face; typedef struct T1_FaceRec_ { FT_FaceRec root; T1_FontRec type1; const void* psnames; const void* psaux; const void* afm_data; FT_CharMapRec charmaprecs[2]; FT_CharMap charmaps[2]; #ifdef FT_CONFIG_OPTION_OLD_INTERNALS PS_Unicodes unicode_map; #endif /* support for Multiple Masters fonts */ PS_Blend blend; /* undocumented, optional: indices of subroutines that express */ /* the NormalizeDesignVector and the ConvertDesignVector procedure, */ /* respectively, as Type 2 charstrings; -1 if keywords not present */ FT_Int ndv_idx; FT_Int cdv_idx; /* undocumented, optional: has the same meaning as len_buildchar */ /* for Type 2 fonts; manipulated by othersubrs 19, 24, and 25 */ FT_UInt len_buildchar; FT_Long* buildchar; /* since version 2.1 - interface to PostScript hinter */ const void* pshinter; } T1_FaceRec; typedef struct CID_FaceRec_ { FT_FaceRec root; void* psnames; void* psaux; CID_FaceInfoRec cid; PS_FontExtraRec font_extra; #if 0 void* afm_data; #endif CID_Subrs subrs; /* since version 2.1 - interface to PostScript hinter */ void* pshinter; /* since version 2.1.8, but was originally positioned after `afm_data' */ FT_Byte* binary_data; /* used if hex data has been converted */ FT_Stream cid_stream; } CID_FaceRec; FT_END_HEADER #endif /* __T1TYPES_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/internal/tttypes.h ================================================ /***************************************************************************/ /* */ /* tttypes.h */ /* */ /* Basic SFNT/TrueType type definitions and interface (specification */ /* only). */ /* */ /* Copyright 1996-2001, 2002, 2004, 2005, 2006, 2007, 2008 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __TTTYPES_H__ #define __TTTYPES_H__ #include <ft2build.h> #include FT_TRUETYPE_TABLES_H #include FT_INTERNAL_OBJECTS_H #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT #include FT_MULTIPLE_MASTERS_H #endif FT_BEGIN_HEADER /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /*** ***/ /*** ***/ /*** REQUIRED TRUETYPE/OPENTYPE TABLES DEFINITIONS ***/ /*** ***/ /*** ***/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /* */ /* <Struct> */ /* TTC_HeaderRec */ /* */ /* <Description> */ /* TrueType collection header. This table contains the offsets of */ /* the font headers of each distinct TrueType face in the file. */ /* */ /* <Fields> */ /* tag :: Must be `ttc ' to indicate a TrueType collection. */ /* */ /* version :: The version number. */ /* */ /* count :: The number of faces in the collection. The */ /* specification says this should be an unsigned long, but */ /* we use a signed long since we need the value -1 for */ /* specific purposes. */ /* */ /* offsets :: The offsets of the font headers, one per face. */ /* */ typedef struct TTC_HeaderRec_ { FT_ULong tag; FT_Fixed version; FT_Long count; FT_ULong* offsets; } TTC_HeaderRec; /*************************************************************************/ /* */ /* <Struct> */ /* SFNT_HeaderRec */ /* */ /* <Description> */ /* SFNT file format header. */ /* */ /* <Fields> */ /* format_tag :: The font format tag. */ /* */ /* num_tables :: The number of tables in file. */ /* */ /* search_range :: Must be `16 * (max power of 2 <= num_tables)'. */ /* */ /* entry_selector :: Must be log2 of `search_range / 16'. */ /* */ /* range_shift :: Must be `num_tables * 16 - search_range'. */ /* */ typedef struct SFNT_HeaderRec_ { FT_ULong format_tag; FT_UShort num_tables; FT_UShort search_range; FT_UShort entry_selector; FT_UShort range_shift; FT_ULong offset; /* not in file */ } SFNT_HeaderRec, *SFNT_Header; /*************************************************************************/ /* */ /* <Struct> */ /* TT_TableRec */ /* */ /* <Description> */ /* This structure describes a given table of a TrueType font. */ /* */ /* <Fields> */ /* Tag :: A four-bytes tag describing the table. */ /* */ /* CheckSum :: The table checksum. This value can be ignored. */ /* */ /* Offset :: The offset of the table from the start of the TrueType */ /* font in its resource. */ /* */ /* Length :: The table length (in bytes). */ /* */ typedef struct TT_TableRec_ { FT_ULong Tag; /* table type */ FT_ULong CheckSum; /* table checksum */ FT_ULong Offset; /* table file offset */ FT_ULong Length; /* table length */ } TT_TableRec, *TT_Table; /*************************************************************************/ /* */ /* <Struct> */ /* TT_LongMetricsRec */ /* */ /* <Description> */ /* A structure modeling the long metrics of the `hmtx' and `vmtx' */ /* TrueType tables. The values are expressed in font units. */ /* */ /* <Fields> */ /* advance :: The advance width or height for the glyph. */ /* */ /* bearing :: The left-side or top-side bearing for the glyph. */ /* */ typedef struct TT_LongMetricsRec_ { FT_UShort advance; FT_Short bearing; } TT_LongMetricsRec, *TT_LongMetrics; /*************************************************************************/ /* */ /* <Type> */ /* TT_ShortMetrics */ /* */ /* <Description> */ /* A simple type to model the short metrics of the `hmtx' and `vmtx' */ /* tables. */ /* */ typedef FT_Short TT_ShortMetrics; /*************************************************************************/ /* */ /* <Struct> */ /* TT_NameEntryRec */ /* */ /* <Description> */ /* A structure modeling TrueType name records. Name records are used */ /* to store important strings like family name, style name, */ /* copyright, etc. in _localized_ versions (i.e., language, encoding, */ /* etc). */ /* */ /* <Fields> */ /* platformID :: The ID of the name's encoding platform. */ /* */ /* encodingID :: The platform-specific ID for the name's encoding. */ /* */ /* languageID :: The platform-specific ID for the name's language. */ /* */ /* nameID :: The ID specifying what kind of name this is. */ /* */ /* stringLength :: The length of the string in bytes. */ /* */ /* stringOffset :: The offset to the string in the `name' table. */ /* */ /* string :: A pointer to the string's bytes. Note that these */ /* are usually UTF-16 encoded characters. */ /* */ typedef struct TT_NameEntryRec_ { FT_UShort platformID; FT_UShort encodingID; FT_UShort languageID; FT_UShort nameID; FT_UShort stringLength; FT_ULong stringOffset; /* this last field is not defined in the spec */ /* but used by the FreeType engine */ FT_Byte* string; } TT_NameEntryRec, *TT_NameEntry; /*************************************************************************/ /* */ /* <Struct> */ /* TT_NameTableRec */ /* */ /* <Description> */ /* A structure modeling the TrueType name table. */ /* */ /* <Fields> */ /* format :: The format of the name table. */ /* */ /* numNameRecords :: The number of names in table. */ /* */ /* storageOffset :: The offset of the name table in the `name' */ /* TrueType table. */ /* */ /* names :: An array of name records. */ /* */ /* stream :: the file's input stream. */ /* */ typedef struct TT_NameTableRec_ { FT_UShort format; FT_UInt numNameRecords; FT_UInt storageOffset; TT_NameEntryRec* names; FT_Stream stream; } TT_NameTableRec, *TT_NameTable; /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /*** ***/ /*** ***/ /*** OPTIONAL TRUETYPE/OPENTYPE TABLES DEFINITIONS ***/ /*** ***/ /*** ***/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /* */ /* <Struct> */ /* TT_GaspRangeRec */ /* */ /* <Description> */ /* A tiny structure used to model a gasp range according to the */ /* TrueType specification. */ /* */ /* <Fields> */ /* maxPPEM :: The maximum ppem value to which `gaspFlag' applies. */ /* */ /* gaspFlag :: A flag describing the grid-fitting and anti-aliasing */ /* modes to be used. */ /* */ typedef struct TT_GaspRangeRec_ { FT_UShort maxPPEM; FT_UShort gaspFlag; } TT_GaspRangeRec, *TT_GaspRange; #define TT_GASP_GRIDFIT 0x01 #define TT_GASP_DOGRAY 0x02 /*************************************************************************/ /* */ /* <Struct> */ /* TT_GaspRec */ /* */ /* <Description> */ /* A structure modeling the TrueType `gasp' table used to specify */ /* grid-fitting and anti-aliasing behaviour. */ /* */ /* <Fields> */ /* version :: The version number. */ /* */ /* numRanges :: The number of gasp ranges in table. */ /* */ /* gaspRanges :: An array of gasp ranges. */ /* */ typedef struct TT_Gasp_ { FT_UShort version; FT_UShort numRanges; TT_GaspRange gaspRanges; } TT_GaspRec; #ifdef FT_CONFIG_OPTION_OLD_INTERNALS /*************************************************************************/ /* */ /* <Struct> */ /* TT_HdmxEntryRec */ /* */ /* <Description> */ /* A small structure used to model the pre-computed widths of a given */ /* size. They are found in the `hdmx' table. */ /* */ /* <Fields> */ /* ppem :: The pixels per EM value at which these metrics apply. */ /* */ /* max_width :: The maximum advance width for this metric. */ /* */ /* widths :: An array of widths. Note: These are 8-bit bytes. */ /* */ typedef struct TT_HdmxEntryRec_ { FT_Byte ppem; FT_Byte max_width; FT_Byte* widths; } TT_HdmxEntryRec, *TT_HdmxEntry; /*************************************************************************/ /* */ /* <Struct> */ /* TT_HdmxRec */ /* */ /* <Description> */ /* A structure used to model the `hdmx' table, which contains */ /* pre-computed widths for a set of given sizes/dimensions. */ /* */ /* <Fields> */ /* version :: The version number. */ /* */ /* num_records :: The number of hdmx records. */ /* */ /* records :: An array of hdmx records. */ /* */ typedef struct TT_HdmxRec_ { FT_UShort version; FT_Short num_records; TT_HdmxEntry records; } TT_HdmxRec, *TT_Hdmx; /*************************************************************************/ /* */ /* <Struct> */ /* TT_Kern0_PairRec */ /* */ /* <Description> */ /* A structure used to model a kerning pair for the kerning table */ /* format 0. The engine now loads this table if it finds one in the */ /* font file. */ /* */ /* <Fields> */ /* left :: The index of the left glyph in pair. */ /* */ /* right :: The index of the right glyph in pair. */ /* */ /* value :: The kerning distance. A positive value spaces the */ /* glyphs, a negative one makes them closer. */ /* */ typedef struct TT_Kern0_PairRec_ { FT_UShort left; /* index of left glyph in pair */ FT_UShort right; /* index of right glyph in pair */ FT_FWord value; /* kerning value */ } TT_Kern0_PairRec, *TT_Kern0_Pair; #endif /* FT_CONFIG_OPTION_OLD_INTERNALS */ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /*** ***/ /*** ***/ /*** EMBEDDED BITMAPS SUPPORT ***/ /*** ***/ /*** ***/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /* */ /* <Struct> */ /* TT_SBit_MetricsRec */ /* */ /* <Description> */ /* A structure used to hold the big metrics of a given glyph bitmap */ /* in a TrueType or OpenType font. These are usually found in the */ /* `EBDT' (Microsoft) or `bloc' (Apple) table. */ /* */ /* <Fields> */ /* height :: The glyph height in pixels. */ /* */ /* width :: The glyph width in pixels. */ /* */ /* horiBearingX :: The horizontal left bearing. */ /* */ /* horiBearingY :: The horizontal top bearing. */ /* */ /* horiAdvance :: The horizontal advance. */ /* */ /* vertBearingX :: The vertical left bearing. */ /* */ /* vertBearingY :: The vertical top bearing. */ /* */ /* vertAdvance :: The vertical advance. */ /* */ typedef struct TT_SBit_MetricsRec_ { FT_Byte height; FT_Byte width; FT_Char horiBearingX; FT_Char horiBearingY; FT_Byte horiAdvance; FT_Char vertBearingX; FT_Char vertBearingY; FT_Byte vertAdvance; } TT_SBit_MetricsRec, *TT_SBit_Metrics; /*************************************************************************/ /* */ /* <Struct> */ /* TT_SBit_SmallMetricsRec */ /* */ /* <Description> */ /* A structure used to hold the small metrics of a given glyph bitmap */ /* in a TrueType or OpenType font. These are usually found in the */ /* `EBDT' (Microsoft) or the `bdat' (Apple) table. */ /* */ /* <Fields> */ /* height :: The glyph height in pixels. */ /* */ /* width :: The glyph width in pixels. */ /* */ /* bearingX :: The left-side bearing. */ /* */ /* bearingY :: The top-side bearing. */ /* */ /* advance :: The advance width or height. */ /* */ typedef struct TT_SBit_Small_Metrics_ { FT_Byte height; FT_Byte width; FT_Char bearingX; FT_Char bearingY; FT_Byte advance; } TT_SBit_SmallMetricsRec, *TT_SBit_SmallMetrics; /*************************************************************************/ /* */ /* <Struct> */ /* TT_SBit_LineMetricsRec */ /* */ /* <Description> */ /* A structure used to describe the text line metrics of a given */ /* bitmap strike, for either a horizontal or vertical layout. */ /* */ /* <Fields> */ /* ascender :: The ascender in pixels. */ /* */ /* descender :: The descender in pixels. */ /* */ /* max_width :: The maximum glyph width in pixels. */ /* */ /* caret_slope_enumerator :: Rise of the caret slope, typically set */ /* to 1 for non-italic fonts. */ /* */ /* caret_slope_denominator :: Rise of the caret slope, typically set */ /* to 0 for non-italic fonts. */ /* */ /* caret_offset :: Offset in pixels to move the caret for */ /* proper positioning. */ /* */ /* min_origin_SB :: Minimum of horiBearingX (resp. */ /* vertBearingY). */ /* min_advance_SB :: Minimum of */ /* */ /* horizontal advance - */ /* ( horiBearingX + width ) */ /* */ /* resp. */ /* */ /* vertical advance - */ /* ( vertBearingY + height ) */ /* */ /* max_before_BL :: Maximum of horiBearingY (resp. */ /* vertBearingY). */ /* */ /* min_after_BL :: Minimum of */ /* */ /* horiBearingY - height */ /* */ /* resp. */ /* */ /* vertBearingX - width */ /* */ /* pads :: Unused (to make the size of the record */ /* a multiple of 32 bits. */ /* */ typedef struct TT_SBit_LineMetricsRec_ { FT_Char ascender; FT_Char descender; FT_Byte max_width; FT_Char caret_slope_numerator; FT_Char caret_slope_denominator; FT_Char caret_offset; FT_Char min_origin_SB; FT_Char min_advance_SB; FT_Char max_before_BL; FT_Char min_after_BL; FT_Char pads[2]; } TT_SBit_LineMetricsRec, *TT_SBit_LineMetrics; /*************************************************************************/ /* */ /* <Struct> */ /* TT_SBit_RangeRec */ /* */ /* <Description> */ /* A TrueType/OpenType subIndexTable as defined in the `EBLC' */ /* (Microsoft) or `bloc' (Apple) tables. */ /* */ /* <Fields> */ /* first_glyph :: The first glyph index in the range. */ /* */ /* last_glyph :: The last glyph index in the range. */ /* */ /* index_format :: The format of index table. Valid values are 1 */ /* to 5. */ /* */ /* image_format :: The format of `EBDT' image data. */ /* */ /* image_offset :: The offset to image data in `EBDT'. */ /* */ /* image_size :: For index formats 2 and 5. This is the size in */ /* bytes of each glyph bitmap. */ /* */ /* big_metrics :: For index formats 2 and 5. This is the big */ /* metrics for each glyph bitmap. */ /* */ /* num_glyphs :: For index formats 4 and 5. This is the number of */ /* glyphs in the code array. */ /* */ /* glyph_offsets :: For index formats 1 and 3. */ /* */ /* glyph_codes :: For index formats 4 and 5. */ /* */ /* table_offset :: The offset of the index table in the `EBLC' */ /* table. Only used during strike loading. */ /* */ typedef struct TT_SBit_RangeRec_ { FT_UShort first_glyph; FT_UShort last_glyph; FT_UShort index_format; FT_UShort image_format; FT_ULong image_offset; FT_ULong image_size; TT_SBit_MetricsRec metrics; FT_ULong num_glyphs; FT_ULong* glyph_offsets; FT_UShort* glyph_codes; FT_ULong table_offset; } TT_SBit_RangeRec, *TT_SBit_Range; /*************************************************************************/ /* */ /* <Struct> */ /* TT_SBit_StrikeRec */ /* */ /* <Description> */ /* A structure used describe a given bitmap strike in the `EBLC' */ /* (Microsoft) or `bloc' (Apple) tables. */ /* */ /* <Fields> */ /* num_index_ranges :: The number of index ranges. */ /* */ /* index_ranges :: An array of glyph index ranges. */ /* */ /* color_ref :: Unused. `color_ref' is put in for future */ /* enhancements, but these fields are already */ /* in use by other platforms (e.g. Newton). */ /* For details, please see */ /* */ /* http://fonts.apple.com/ */ /* TTRefMan/RM06/Chap6bloc.html */ /* */ /* hori :: The line metrics for horizontal layouts. */ /* */ /* vert :: The line metrics for vertical layouts. */ /* */ /* start_glyph :: The lowest glyph index for this strike. */ /* */ /* end_glyph :: The highest glyph index for this strike. */ /* */ /* x_ppem :: The number of horizontal pixels per EM. */ /* */ /* y_ppem :: The number of vertical pixels per EM. */ /* */ /* bit_depth :: The bit depth. Valid values are 1, 2, 4, */ /* and 8. */ /* */ /* flags :: Is this a vertical or horizontal strike? For */ /* details, please see */ /* */ /* http://fonts.apple.com/ */ /* TTRefMan/RM06/Chap6bloc.html */ /* */ typedef struct TT_SBit_StrikeRec_ { FT_Int num_ranges; TT_SBit_Range sbit_ranges; FT_ULong ranges_offset; FT_ULong color_ref; TT_SBit_LineMetricsRec hori; TT_SBit_LineMetricsRec vert; FT_UShort start_glyph; FT_UShort end_glyph; FT_Byte x_ppem; FT_Byte y_ppem; FT_Byte bit_depth; FT_Char flags; } TT_SBit_StrikeRec, *TT_SBit_Strike; /*************************************************************************/ /* */ /* <Struct> */ /* TT_SBit_ComponentRec */ /* */ /* <Description> */ /* A simple structure to describe a compound sbit element. */ /* */ /* <Fields> */ /* glyph_code :: The element's glyph index. */ /* */ /* x_offset :: The element's left bearing. */ /* */ /* y_offset :: The element's top bearing. */ /* */ typedef struct TT_SBit_ComponentRec_ { FT_UShort glyph_code; FT_Char x_offset; FT_Char y_offset; } TT_SBit_ComponentRec, *TT_SBit_Component; /*************************************************************************/ /* */ /* <Struct> */ /* TT_SBit_ScaleRec */ /* */ /* <Description> */ /* A structure used describe a given bitmap scaling table, as defined */ /* in the `EBSC' table. */ /* */ /* <Fields> */ /* hori :: The horizontal line metrics. */ /* */ /* vert :: The vertical line metrics. */ /* */ /* x_ppem :: The number of horizontal pixels per EM. */ /* */ /* y_ppem :: The number of vertical pixels per EM. */ /* */ /* x_ppem_substitute :: Substitution x_ppem value. */ /* */ /* y_ppem_substitute :: Substitution y_ppem value. */ /* */ typedef struct TT_SBit_ScaleRec_ { TT_SBit_LineMetricsRec hori; TT_SBit_LineMetricsRec vert; FT_Byte x_ppem; FT_Byte y_ppem; FT_Byte x_ppem_substitute; FT_Byte y_ppem_substitute; } TT_SBit_ScaleRec, *TT_SBit_Scale; /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /*** ***/ /*** ***/ /*** POSTSCRIPT GLYPH NAMES SUPPORT ***/ /*** ***/ /*** ***/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /* */ /* <Struct> */ /* TT_Post_20Rec */ /* */ /* <Description> */ /* Postscript names sub-table, format 2.0. Stores the PS name of */ /* each glyph in the font face. */ /* */ /* <Fields> */ /* num_glyphs :: The number of named glyphs in the table. */ /* */ /* num_names :: The number of PS names stored in the table. */ /* */ /* glyph_indices :: The indices of the glyphs in the names arrays. */ /* */ /* glyph_names :: The PS names not in Mac Encoding. */ /* */ typedef struct TT_Post_20Rec_ { FT_UShort num_glyphs; FT_UShort num_names; FT_UShort* glyph_indices; FT_Char** glyph_names; } TT_Post_20Rec, *TT_Post_20; /*************************************************************************/ /* */ /* <Struct> */ /* TT_Post_25Rec */ /* */ /* <Description> */ /* Postscript names sub-table, format 2.5. Stores the PS name of */ /* each glyph in the font face. */ /* */ /* <Fields> */ /* num_glyphs :: The number of glyphs in the table. */ /* */ /* offsets :: An array of signed offsets in a normal Mac */ /* Postscript name encoding. */ /* */ typedef struct TT_Post_25_ { FT_UShort num_glyphs; FT_Char* offsets; } TT_Post_25Rec, *TT_Post_25; /*************************************************************************/ /* */ /* <Struct> */ /* TT_Post_NamesRec */ /* */ /* <Description> */ /* Postscript names table, either format 2.0 or 2.5. */ /* */ /* <Fields> */ /* loaded :: A flag to indicate whether the PS names are loaded. */ /* */ /* format_20 :: The sub-table used for format 2.0. */ /* */ /* format_25 :: The sub-table used for format 2.5. */ /* */ typedef struct TT_Post_NamesRec_ { FT_Bool loaded; union { TT_Post_20Rec format_20; TT_Post_25Rec format_25; } names; } TT_Post_NamesRec, *TT_Post_Names; /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /*** ***/ /*** ***/ /*** GX VARIATION TABLE SUPPORT ***/ /*** ***/ /*** ***/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT typedef struct GX_BlendRec_ *GX_Blend; #endif /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /*** ***/ /*** ***/ /*** EMBEDDED BDF PROPERTIES TABLE SUPPORT ***/ /*** ***/ /*** ***/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /* * These types are used to support a `BDF ' table that isn't part of the * official TrueType specification. It is mainly used in SFNT-based * bitmap fonts that were generated from a set of BDF fonts. * * The format of the table is as follows. * * USHORT version `BDF ' table version number, should be 0x0001. * USHORT strikeCount Number of strikes (bitmap sizes) in this table. * ULONG stringTable Offset (from start of BDF table) to string * table. * * This is followed by an array of `strikeCount' descriptors, having the * following format. * * USHORT ppem Vertical pixels per EM for this strike. * USHORT numItems Number of items for this strike (properties and * atoms). Maximum is 255. * * This array in turn is followed by `strikeCount' value sets. Each * `value set' is an array of `numItems' items with the following format. * * ULONG item_name Offset in string table to item name. * USHORT item_type The item type. Possible values are * 0 => string (e.g., COMMENT) * 1 => atom (e.g., FONT or even SIZE) * 2 => int32 * 3 => uint32 * 0x10 => A flag to indicate a properties. This * is ORed with the above values. * ULONG item_value For strings => Offset into string table without * the corresponding double quotes. * For atoms => Offset into string table. * For integers => Direct value. * * All strings in the string table consist of bytes and are * zero-terminated. * */ #ifdef TT_CONFIG_OPTION_BDF typedef struct TT_BDFRec_ { FT_Byte* table; FT_Byte* table_end; FT_Byte* strings; FT_ULong strings_size; FT_UInt num_strikes; FT_Bool loaded; } TT_BDFRec, *TT_BDF; #endif /* TT_CONFIG_OPTION_BDF */ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /*** ***/ /*** ***/ /*** ORIGINAL TT_FACE CLASS DEFINITION ***/ /*** ***/ /*** ***/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /* */ /* This structure/class is defined here because it is common to the */ /* following formats: TTF, OpenType-TT, and OpenType-CFF. */ /* */ /* Note, however, that the classes TT_Size and TT_GlyphSlot are not */ /* shared between font drivers, and are thus defined in `ttobjs.h'. */ /* */ /*************************************************************************/ /*************************************************************************/ /* */ /* <Type> */ /* TT_Face */ /* */ /* <Description> */ /* A handle to a TrueType face/font object. A TT_Face encapsulates */ /* the resolution and scaling independent parts of a TrueType font */ /* resource. */ /* */ /* <Note> */ /* The TT_Face structure is also used as a `parent class' for the */ /* OpenType-CFF class (T2_Face). */ /* */ typedef struct TT_FaceRec_* TT_Face; /* a function type used for the truetype bytecode interpreter hooks */ typedef FT_Error (*TT_Interpreter)( void* exec_context ); /* forward declaration */ typedef struct TT_LoaderRec_* TT_Loader; /*************************************************************************/ /* */ /* <FuncType> */ /* TT_Loader_GotoTableFunc */ /* */ /* <Description> */ /* Seeks a stream to the start of a given TrueType table. */ /* */ /* <Input> */ /* face :: A handle to the target face object. */ /* */ /* tag :: A 4-byte tag used to name the table. */ /* */ /* stream :: The input stream. */ /* */ /* <Output> */ /* length :: The length of the table in bytes. Set to 0 if not */ /* needed. */ /* */ /* <Return> */ /* FreeType error code. 0 means success. */ /* */ /* <Note> */ /* The stream cursor must be at the font file's origin. */ /* */ typedef FT_Error (*TT_Loader_GotoTableFunc)( TT_Face face, FT_ULong tag, FT_Stream stream, FT_ULong* length ); /*************************************************************************/ /* */ /* <FuncType> */ /* TT_Loader_StartGlyphFunc */ /* */ /* <Description> */ /* Seeks a stream to the start of a given glyph element, and opens a */ /* frame for it. */ /* */ /* <Input> */ /* loader :: The current TrueType glyph loader object. */ /* */ /* glyph index :: The index of the glyph to access. */ /* */ /* offset :: The offset of the glyph according to the */ /* `locations' table. */ /* */ /* byte_count :: The size of the frame in bytes. */ /* */ /* <Return> */ /* FreeType error code. 0 means success. */ /* */ /* <Note> */ /* This function is normally equivalent to FT_STREAM_SEEK(offset) */ /* followed by FT_FRAME_ENTER(byte_count) with the loader's stream, */ /* but alternative formats (e.g. compressed ones) might use something */ /* different. */ /* */ typedef FT_Error (*TT_Loader_StartGlyphFunc)( TT_Loader loader, FT_UInt glyph_index, FT_ULong offset, FT_UInt byte_count ); /*************************************************************************/ /* */ /* <FuncType> */ /* TT_Loader_ReadGlyphFunc */ /* */ /* <Description> */ /* Reads one glyph element (its header, a simple glyph, or a */ /* composite) from the loader's current stream frame. */ /* */ /* <Input> */ /* loader :: The current TrueType glyph loader object. */ /* */ /* <Return> */ /* FreeType error code. 0 means success. */ /* */ typedef FT_Error (*TT_Loader_ReadGlyphFunc)( TT_Loader loader ); /*************************************************************************/ /* */ /* <FuncType> */ /* TT_Loader_EndGlyphFunc */ /* */ /* <Description> */ /* Closes the current loader stream frame for the glyph. */ /* */ /* <Input> */ /* loader :: The current TrueType glyph loader object. */ /* */ typedef void (*TT_Loader_EndGlyphFunc)( TT_Loader loader ); /*************************************************************************/ /* */ /* TrueType Face Type */ /* */ /* <Struct> */ /* TT_Face */ /* */ /* <Description> */ /* The TrueType face class. These objects model the resolution and */ /* point-size independent data found in a TrueType font file. */ /* */ /* <Fields> */ /* root :: The base FT_Face structure, managed by the */ /* base layer. */ /* */ /* ttc_header :: The TrueType collection header, used when */ /* the file is a `ttc' rather than a `ttf'. */ /* For ordinary font files, the field */ /* `ttc_header.count' is set to 0. */ /* */ /* format_tag :: The font format tag. */ /* */ /* num_tables :: The number of TrueType tables in this font */ /* file. */ /* */ /* dir_tables :: The directory of TrueType tables for this */ /* font file. */ /* */ /* header :: The font's font header (`head' table). */ /* Read on font opening. */ /* */ /* horizontal :: The font's horizontal header (`hhea' */ /* table). This field also contains the */ /* associated horizontal metrics table */ /* (`hmtx'). */ /* */ /* max_profile :: The font's maximum profile table. Read on */ /* font opening. Note that some maximum */ /* values cannot be taken directly from this */ /* table. We thus define additional fields */ /* below to hold the computed maxima. */ /* */ /* vertical_info :: A boolean which is set when the font file */ /* contains vertical metrics. If not, the */ /* value of the `vertical' field is */ /* undefined. */ /* */ /* vertical :: The font's vertical header (`vhea' table). */ /* This field also contains the associated */ /* vertical metrics table (`vmtx'), if found. */ /* IMPORTANT: The contents of this field is */ /* undefined if the `verticalInfo' field is */ /* unset. */ /* */ /* num_names :: The number of name records within this */ /* TrueType font. */ /* */ /* name_table :: The table of name records (`name'). */ /* */ /* os2 :: The font's OS/2 table (`OS/2'). */ /* */ /* postscript :: The font's PostScript table (`post' */ /* table). The PostScript glyph names are */ /* not loaded by the driver on face opening. */ /* See the `ttpost' module for more details. */ /* */ /* cmap_table :: Address of the face's `cmap' SFNT table */ /* in memory (it's an extracted frame). */ /* */ /* cmap_size :: The size in bytes of the `cmap_table' */ /* described above. */ /* */ /* goto_table :: A function called by each TrueType table */ /* loader to position a stream's cursor to */ /* the start of a given table according to */ /* its tag. It defaults to TT_Goto_Face but */ /* can be different for strange formats (e.g. */ /* Type 42). */ /* */ /* access_glyph_frame :: A function used to access the frame of a */ /* given glyph within the face's font file. */ /* */ /* forget_glyph_frame :: A function used to forget the frame of a */ /* given glyph when all data has been loaded. */ /* */ /* read_glyph_header :: A function used to read a glyph header. */ /* It must be called between an `access' and */ /* `forget'. */ /* */ /* read_simple_glyph :: A function used to read a simple glyph. */ /* It must be called after the header was */ /* read, and before the `forget'. */ /* */ /* read_composite_glyph :: A function used to read a composite glyph. */ /* It must be called after the header was */ /* read, and before the `forget'. */ /* */ /* sfnt :: A pointer to the SFNT service. */ /* */ /* psnames :: A pointer to the PostScript names service. */ /* */ /* hdmx :: The face's horizontal device metrics */ /* (`hdmx' table). This table is optional in */ /* TrueType/OpenType fonts. */ /* */ /* gasp :: The grid-fitting and scaling properties */ /* table (`gasp'). This table is optional in */ /* TrueType/OpenType fonts. */ /* */ /* pclt :: The `pclt' SFNT table. */ /* */ /* num_sbit_strikes :: The number of sbit strikes, i.e., bitmap */ /* sizes, embedded in this font. */ /* */ /* sbit_strikes :: An array of sbit strikes embedded in this */ /* font. This table is optional in a */ /* TrueType/OpenType font. */ /* */ /* num_sbit_scales :: The number of sbit scales for this font. */ /* */ /* sbit_scales :: Array of sbit scales embedded in this */ /* font. This table is optional in a */ /* TrueType/OpenType font. */ /* */ /* postscript_names :: A table used to store the Postscript names */ /* of the glyphs for this font. See the */ /* file `ttconfig.h' for comments on the */ /* TT_CONFIG_OPTION_POSTSCRIPT_NAMES option. */ /* */ /* num_locations :: The number of glyph locations in this */ /* TrueType file. This should be */ /* identical to the number of glyphs. */ /* Ignored for Type 2 fonts. */ /* */ /* glyph_locations :: An array of longs. These are offsets to */ /* glyph data within the `glyf' table. */ /* Ignored for Type 2 font faces. */ /* */ /* glyf_len :: The length of the `glyf' table. Needed */ /* for malformed `loca' tables. */ /* */ /* font_program_size :: Size in bytecodes of the face's font */ /* program. 0 if none defined. Ignored for */ /* Type 2 fonts. */ /* */ /* font_program :: The face's font program (bytecode stream) */ /* executed at load time, also used during */ /* glyph rendering. Comes from the `fpgm' */ /* table. Ignored for Type 2 font fonts. */ /* */ /* cvt_program_size :: The size in bytecodes of the face's cvt */ /* program. Ignored for Type 2 fonts. */ /* */ /* cvt_program :: The face's cvt program (bytecode stream) */ /* executed each time an instance/size is */ /* changed/reset. Comes from the `prep' */ /* table. Ignored for Type 2 fonts. */ /* */ /* cvt_size :: Size of the control value table (in */ /* entries). Ignored for Type 2 fonts. */ /* */ /* cvt :: The face's original control value table. */ /* Coordinates are expressed in unscaled font */ /* units. Comes from the `cvt ' table. */ /* Ignored for Type 2 fonts. */ /* */ /* num_kern_pairs :: The number of kerning pairs present in the */ /* font file. The engine only loads the */ /* first horizontal format 0 kern table it */ /* finds in the font file. Ignored for */ /* Type 2 fonts. */ /* */ /* kern_table_index :: The index of the kerning table in the font */ /* kerning directory. Ignored for Type 2 */ /* fonts. */ /* */ /* interpreter :: A pointer to the TrueType bytecode */ /* interpreters field is also used to hook */ /* the debugger in `ttdebug'. */ /* */ /* unpatented_hinting :: If true, use only unpatented methods in */ /* the bytecode interpreter. */ /* */ /* doblend :: A boolean which is set if the font should */ /* be blended (this is for GX var). */ /* */ /* blend :: Contains the data needed to control GX */ /* variation tables (rather like Multiple */ /* Master data). */ /* */ /* extra :: Reserved for third-party font drivers. */ /* */ /* postscript_name :: The PS name of the font. Used by the */ /* postscript name service. */ /* */ typedef struct TT_FaceRec_ { FT_FaceRec root; TTC_HeaderRec ttc_header; FT_ULong format_tag; FT_UShort num_tables; TT_Table dir_tables; TT_Header header; /* TrueType header table */ TT_HoriHeader horizontal; /* TrueType horizontal header */ TT_MaxProfile max_profile; #ifdef FT_CONFIG_OPTION_OLD_INTERNALS FT_ULong max_components; /* stubbed to 0 */ #endif FT_Bool vertical_info; TT_VertHeader vertical; /* TT Vertical header, if present */ FT_UShort num_names; /* number of name records */ TT_NameTableRec name_table; /* name table */ TT_OS2 os2; /* TrueType OS/2 table */ TT_Postscript postscript; /* TrueType Postscript table */ FT_Byte* cmap_table; /* extracted `cmap' table */ FT_ULong cmap_size; TT_Loader_GotoTableFunc goto_table; TT_Loader_StartGlyphFunc access_glyph_frame; TT_Loader_EndGlyphFunc forget_glyph_frame; TT_Loader_ReadGlyphFunc read_glyph_header; TT_Loader_ReadGlyphFunc read_simple_glyph; TT_Loader_ReadGlyphFunc read_composite_glyph; /* a typeless pointer to the SFNT_Interface table used to load */ /* the basic TrueType tables in the face object */ void* sfnt; /* a typeless pointer to the FT_Service_PsCMapsRec table used to */ /* handle glyph names <-> unicode & Mac values */ void* psnames; /***********************************************************************/ /* */ /* Optional TrueType/OpenType tables */ /* */ /***********************************************************************/ /* horizontal device metrics */ #ifdef FT_CONFIG_OPTION_OLD_INTERNALS TT_HdmxRec hdmx; #endif /* grid-fitting and scaling table */ TT_GaspRec gasp; /* the `gasp' table */ /* PCL 5 table */ TT_PCLT pclt; /* embedded bitmaps support */ #ifdef FT_CONFIG_OPTION_OLD_INTERNALS FT_ULong num_sbit_strikes; TT_SBit_Strike sbit_strikes; #endif FT_ULong num_sbit_scales; TT_SBit_Scale sbit_scales; /* postscript names table */ TT_Post_NamesRec postscript_names; /***********************************************************************/ /* */ /* TrueType-specific fields (ignored by the OTF-Type2 driver) */ /* */ /***********************************************************************/ /* the glyph locations */ #ifdef FT_CONFIG_OPTION_OLD_INTERNALS FT_UShort num_locations_stub; FT_Long* glyph_locations_stub; #endif /* the font program, if any */ FT_ULong font_program_size; FT_Byte* font_program; /* the cvt program, if any */ FT_ULong cvt_program_size; FT_Byte* cvt_program; /* the original, unscaled, control value table */ FT_ULong cvt_size; FT_Short* cvt; #ifdef FT_CONFIG_OPTION_OLD_INTERNALS /* the format 0 kerning table, if any */ FT_Int num_kern_pairs; FT_Int kern_table_index; TT_Kern0_Pair kern_pairs; #endif /* A pointer to the bytecode interpreter to use. This is also */ /* used to hook the debugger for the `ttdebug' utility. */ TT_Interpreter interpreter; #ifdef TT_CONFIG_OPTION_UNPATENTED_HINTING /* Use unpatented hinting only. */ FT_Bool unpatented_hinting; #endif /***********************************************************************/ /* */ /* Other tables or fields. This is used by derivative formats like */ /* OpenType. */ /* */ /***********************************************************************/ FT_Generic extra; const char* postscript_name; /* since version 2.1.8, but was originally placed after */ /* `glyph_locations_stub' */ FT_ULong glyf_len; /* since version 2.1.8, but was originally placed before `extra' */ #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT FT_Bool doblend; GX_Blend blend; #endif /* since version 2.2 */ FT_Byte* horz_metrics; FT_ULong horz_metrics_size; FT_Byte* vert_metrics; FT_ULong vert_metrics_size; FT_ULong num_locations; /* in broken TTF, gid > 0xFFFF */ FT_Byte* glyph_locations; FT_Byte* hdmx_table; FT_ULong hdmx_table_size; FT_UInt hdmx_record_count; FT_ULong hdmx_record_size; FT_Byte* hdmx_record_sizes; FT_Byte* sbit_table; FT_ULong sbit_table_size; FT_UInt sbit_num_strikes; FT_Byte* kern_table; FT_ULong kern_table_size; FT_UInt num_kern_tables; FT_UInt32 kern_avail_bits; FT_UInt32 kern_order_bits; #ifdef TT_CONFIG_OPTION_BDF TT_BDFRec bdf; #endif /* TT_CONFIG_OPTION_BDF */ /* since 2.3.0 */ FT_ULong horz_metrics_offset; FT_ULong vert_metrics_offset; } TT_FaceRec; /*************************************************************************/ /* */ /* <Struct> */ /* TT_GlyphZoneRec */ /* */ /* <Description> */ /* A glyph zone is used to load, scale and hint glyph outline */ /* coordinates. */ /* */ /* <Fields> */ /* memory :: A handle to the memory manager. */ /* */ /* max_points :: The maximal size in points of the zone. */ /* */ /* max_contours :: Max size in links contours of the zone. */ /* */ /* n_points :: The current number of points in the zone. */ /* */ /* n_contours :: The current number of contours in the zone. */ /* */ /* org :: The original glyph coordinates (font */ /* units/scaled). */ /* */ /* cur :: The current glyph coordinates (scaled/hinted). */ /* */ /* tags :: The point control tags. */ /* */ /* contours :: The contours end points. */ /* */ /* first_point :: Offset of the current subglyph's first point. */ /* */ typedef struct TT_GlyphZoneRec_ { FT_Memory memory; FT_UShort max_points; FT_UShort max_contours; FT_UShort n_points; /* number of points in zone */ FT_Short n_contours; /* number of contours */ FT_Vector* org; /* original point coordinates */ FT_Vector* cur; /* current point coordinates */ FT_Vector* orus; /* original (unscaled) point coordinates */ FT_Byte* tags; /* current touch flags */ FT_UShort* contours; /* contour end points */ FT_UShort first_point; /* offset of first (#0) point */ } TT_GlyphZoneRec, *TT_GlyphZone; /* handle to execution context */ typedef struct TT_ExecContextRec_* TT_ExecContext; /* glyph loader structure */ typedef struct TT_LoaderRec_ { FT_Face face; FT_Size size; FT_GlyphSlot glyph; FT_GlyphLoader gloader; FT_ULong load_flags; FT_UInt glyph_index; FT_Stream stream; FT_Int byte_len; FT_Short n_contours; FT_BBox bbox; FT_Int left_bearing; FT_Int advance; FT_Int linear; FT_Bool linear_def; FT_Bool preserve_pps; FT_Vector pp1; FT_Vector pp2; FT_ULong glyf_offset; /* the zone where we load our glyphs */ TT_GlyphZoneRec base; TT_GlyphZoneRec zone; TT_ExecContext exec; FT_Byte* instructions; FT_ULong ins_pos; /* for possible extensibility in other formats */ void* other; /* since version 2.1.8 */ FT_Int top_bearing; FT_Int vadvance; FT_Vector pp3; FT_Vector pp4; /* since version 2.2.1 */ FT_Byte* cursor; FT_Byte* limit; } TT_LoaderRec; FT_END_HEADER #endif /* __TTTYPES_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/t1tables.h ================================================ /***************************************************************************/ /* */ /* t1tables.h */ /* */ /* Basic Type 1/Type 2 tables definitions and interface (specification */ /* only). */ /* */ /* Copyright 1996-2004, 2006, 2008, 2009, 2011 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __T1TABLES_H__ #define __T1TABLES_H__ #include <ft2build.h> #include FT_FREETYPE_H #ifdef FREETYPE_H #error "freetype.h of FreeType 1 has been loaded!" #error "Please fix the directory search order for header files" #error "so that freetype.h of FreeType 2 is found first." #endif FT_BEGIN_HEADER /*************************************************************************/ /* */ /* <Section> */ /* type1_tables */ /* */ /* <Title> */ /* Type 1 Tables */ /* */ /* <Abstract> */ /* Type~1 (PostScript) specific font tables. */ /* */ /* <Description> */ /* This section contains the definition of Type 1-specific tables, */ /* including structures related to other PostScript font formats. */ /* */ /*************************************************************************/ /* Note that we separate font data in PS_FontInfoRec and PS_PrivateRec */ /* structures in order to support Multiple Master fonts. */ /*************************************************************************/ /* */ /* <Struct> */ /* PS_FontInfoRec */ /* */ /* <Description> */ /* A structure used to model a Type~1 or Type~2 FontInfo dictionary. */ /* Note that for Multiple Master fonts, each instance has its own */ /* FontInfo dictionary. */ /* */ typedef struct PS_FontInfoRec_ { FT_String* version; FT_String* notice; FT_String* full_name; FT_String* family_name; FT_String* weight; FT_Long italic_angle; FT_Bool is_fixed_pitch; FT_Short underline_position; FT_UShort underline_thickness; } PS_FontInfoRec; /*************************************************************************/ /* */ /* <Struct> */ /* PS_FontInfo */ /* */ /* <Description> */ /* A handle to a @PS_FontInfoRec structure. */ /* */ typedef struct PS_FontInfoRec_* PS_FontInfo; /*************************************************************************/ /* */ /* <Struct> */ /* T1_FontInfo */ /* */ /* <Description> */ /* This type is equivalent to @PS_FontInfoRec. It is deprecated but */ /* kept to maintain source compatibility between various versions of */ /* FreeType. */ /* */ typedef PS_FontInfoRec T1_FontInfo; /*************************************************************************/ /* */ /* <Struct> */ /* PS_PrivateRec */ /* */ /* <Description> */ /* A structure used to model a Type~1 or Type~2 private dictionary. */ /* Note that for Multiple Master fonts, each instance has its own */ /* Private dictionary. */ /* */ typedef struct PS_PrivateRec_ { FT_Int unique_id; FT_Int lenIV; FT_Byte num_blue_values; FT_Byte num_other_blues; FT_Byte num_family_blues; FT_Byte num_family_other_blues; FT_Short blue_values[14]; FT_Short other_blues[10]; FT_Short family_blues [14]; FT_Short family_other_blues[10]; FT_Fixed blue_scale; FT_Int blue_shift; FT_Int blue_fuzz; FT_UShort standard_width[1]; FT_UShort standard_height[1]; FT_Byte num_snap_widths; FT_Byte num_snap_heights; FT_Bool force_bold; FT_Bool round_stem_up; FT_Short snap_widths [13]; /* including std width */ FT_Short snap_heights[13]; /* including std height */ FT_Fixed expansion_factor; FT_Long language_group; FT_Long password; FT_Short min_feature[2]; } PS_PrivateRec; /*************************************************************************/ /* */ /* <Struct> */ /* PS_Private */ /* */ /* <Description> */ /* A handle to a @PS_PrivateRec structure. */ /* */ typedef struct PS_PrivateRec_* PS_Private; /*************************************************************************/ /* */ /* <Struct> */ /* T1_Private */ /* */ /* <Description> */ /* This type is equivalent to @PS_PrivateRec. It is deprecated but */ /* kept to maintain source compatibility between various versions of */ /* FreeType. */ /* */ typedef PS_PrivateRec T1_Private; /*************************************************************************/ /* */ /* <Enum> */ /* T1_Blend_Flags */ /* */ /* <Description> */ /* A set of flags used to indicate which fields are present in a */ /* given blend dictionary (font info or private). Used to support */ /* Multiple Masters fonts. */ /* */ typedef enum T1_Blend_Flags_ { /*# required fields in a FontInfo blend dictionary */ T1_BLEND_UNDERLINE_POSITION = 0, T1_BLEND_UNDERLINE_THICKNESS, T1_BLEND_ITALIC_ANGLE, /*# required fields in a Private blend dictionary */ T1_BLEND_BLUE_VALUES, T1_BLEND_OTHER_BLUES, T1_BLEND_STANDARD_WIDTH, T1_BLEND_STANDARD_HEIGHT, T1_BLEND_STEM_SNAP_WIDTHS, T1_BLEND_STEM_SNAP_HEIGHTS, T1_BLEND_BLUE_SCALE, T1_BLEND_BLUE_SHIFT, T1_BLEND_FAMILY_BLUES, T1_BLEND_FAMILY_OTHER_BLUES, T1_BLEND_FORCE_BOLD, /*# never remove */ T1_BLEND_MAX } T1_Blend_Flags; /* */ /*# backwards compatible definitions */ #define t1_blend_underline_position T1_BLEND_UNDERLINE_POSITION #define t1_blend_underline_thickness T1_BLEND_UNDERLINE_THICKNESS #define t1_blend_italic_angle T1_BLEND_ITALIC_ANGLE #define t1_blend_blue_values T1_BLEND_BLUE_VALUES #define t1_blend_other_blues T1_BLEND_OTHER_BLUES #define t1_blend_standard_widths T1_BLEND_STANDARD_WIDTH #define t1_blend_standard_height T1_BLEND_STANDARD_HEIGHT #define t1_blend_stem_snap_widths T1_BLEND_STEM_SNAP_WIDTHS #define t1_blend_stem_snap_heights T1_BLEND_STEM_SNAP_HEIGHTS #define t1_blend_blue_scale T1_BLEND_BLUE_SCALE #define t1_blend_blue_shift T1_BLEND_BLUE_SHIFT #define t1_blend_family_blues T1_BLEND_FAMILY_BLUES #define t1_blend_family_other_blues T1_BLEND_FAMILY_OTHER_BLUES #define t1_blend_force_bold T1_BLEND_FORCE_BOLD #define t1_blend_max T1_BLEND_MAX /* maximum number of Multiple Masters designs, as defined in the spec */ #define T1_MAX_MM_DESIGNS 16 /* maximum number of Multiple Masters axes, as defined in the spec */ #define T1_MAX_MM_AXIS 4 /* maximum number of elements in a design map */ #define T1_MAX_MM_MAP_POINTS 20 /* this structure is used to store the BlendDesignMap entry for an axis */ typedef struct PS_DesignMap_ { FT_Byte num_points; FT_Long* design_points; FT_Fixed* blend_points; } PS_DesignMapRec, *PS_DesignMap; /* backwards-compatible definition */ typedef PS_DesignMapRec T1_DesignMap; typedef struct PS_BlendRec_ { FT_UInt num_designs; FT_UInt num_axis; FT_String* axis_names[T1_MAX_MM_AXIS]; FT_Fixed* design_pos[T1_MAX_MM_DESIGNS]; PS_DesignMapRec design_map[T1_MAX_MM_AXIS]; FT_Fixed* weight_vector; FT_Fixed* default_weight_vector; PS_FontInfo font_infos[T1_MAX_MM_DESIGNS + 1]; PS_Private privates [T1_MAX_MM_DESIGNS + 1]; FT_ULong blend_bitflags; FT_BBox* bboxes [T1_MAX_MM_DESIGNS + 1]; /* since 2.3.0 */ /* undocumented, optional: the default design instance; */ /* corresponds to default_weight_vector -- */ /* num_default_design_vector == 0 means it is not present */ /* in the font and associated metrics files */ FT_UInt default_design_vector[T1_MAX_MM_DESIGNS]; FT_UInt num_default_design_vector; } PS_BlendRec, *PS_Blend; /* backwards-compatible definition */ typedef PS_BlendRec T1_Blend; /*************************************************************************/ /* */ /* <Struct> */ /* CID_FaceDictRec */ /* */ /* <Description> */ /* A structure used to represent data in a CID top-level dictionary. */ /* */ typedef struct CID_FaceDictRec_ { PS_PrivateRec private_dict; FT_UInt len_buildchar; FT_Fixed forcebold_threshold; FT_Pos stroke_width; FT_Fixed expansion_factor; FT_Byte paint_type; FT_Byte font_type; FT_Matrix font_matrix; FT_Vector font_offset; FT_UInt num_subrs; FT_ULong subrmap_offset; FT_Int sd_bytes; } CID_FaceDictRec; /*************************************************************************/ /* */ /* <Struct> */ /* CID_FaceDict */ /* */ /* <Description> */ /* A handle to a @CID_FaceDictRec structure. */ /* */ typedef struct CID_FaceDictRec_* CID_FaceDict; /* */ /* backwards-compatible definition */ typedef CID_FaceDictRec CID_FontDict; /*************************************************************************/ /* */ /* <Struct> */ /* CID_FaceInfoRec */ /* */ /* <Description> */ /* A structure used to represent CID Face information. */ /* */ typedef struct CID_FaceInfoRec_ { FT_String* cid_font_name; FT_Fixed cid_version; FT_Int cid_font_type; FT_String* registry; FT_String* ordering; FT_Int supplement; PS_FontInfoRec font_info; FT_BBox font_bbox; FT_ULong uid_base; FT_Int num_xuid; FT_ULong xuid[16]; FT_ULong cidmap_offset; FT_Int fd_bytes; FT_Int gd_bytes; FT_ULong cid_count; FT_Int num_dicts; CID_FaceDict font_dicts; FT_ULong data_offset; } CID_FaceInfoRec; /*************************************************************************/ /* */ /* <Struct> */ /* CID_FaceInfo */ /* */ /* <Description> */ /* A handle to a @CID_FaceInfoRec structure. */ /* */ typedef struct CID_FaceInfoRec_* CID_FaceInfo; /*************************************************************************/ /* */ /* <Struct> */ /* CID_Info */ /* */ /* <Description> */ /* This type is equivalent to @CID_FaceInfoRec. It is deprecated but */ /* kept to maintain source compatibility between various versions of */ /* FreeType. */ /* */ typedef CID_FaceInfoRec CID_Info; /************************************************************************ * * @function: * FT_Has_PS_Glyph_Names * * @description: * Return true if a given face provides reliable PostScript glyph * names. This is similar to using the @FT_HAS_GLYPH_NAMES macro, * except that certain fonts (mostly TrueType) contain incorrect * glyph name tables. * * When this function returns true, the caller is sure that the glyph * names returned by @FT_Get_Glyph_Name are reliable. * * @input: * face :: * face handle * * @return: * Boolean. True if glyph names are reliable. * */ FT_EXPORT( FT_Int ) FT_Has_PS_Glyph_Names( FT_Face face ); /************************************************************************ * * @function: * FT_Get_PS_Font_Info * * @description: * Retrieve the @PS_FontInfoRec structure corresponding to a given * PostScript font. * * @input: * face :: * PostScript face handle. * * @output: * afont_info :: * Output font info structure pointer. * * @return: * FreeType error code. 0~means success. * * @note: * The string pointers within the font info structure are owned by * the face and don't need to be freed by the caller. * * If the font's format is not PostScript-based, this function will * return the `FT_Err_Invalid_Argument' error code. * */ FT_EXPORT( FT_Error ) FT_Get_PS_Font_Info( FT_Face face, PS_FontInfo afont_info ); /************************************************************************ * * @function: * FT_Get_PS_Font_Private * * @description: * Retrieve the @PS_PrivateRec structure corresponding to a given * PostScript font. * * @input: * face :: * PostScript face handle. * * @output: * afont_private :: * Output private dictionary structure pointer. * * @return: * FreeType error code. 0~means success. * * @note: * The string pointers within the @PS_PrivateRec structure are owned by * the face and don't need to be freed by the caller. * * If the font's format is not PostScript-based, this function returns * the `FT_Err_Invalid_Argument' error code. * */ FT_EXPORT( FT_Error ) FT_Get_PS_Font_Private( FT_Face face, PS_Private afont_private ); /*************************************************************************/ /* */ /* <Enum> */ /* T1_EncodingType */ /* */ /* <Description> */ /* An enumeration describing the `Encoding' entry in a Type 1 */ /* dictionary. */ /* */ typedef enum T1_EncodingType_ { T1_ENCODING_TYPE_NONE = 0, T1_ENCODING_TYPE_ARRAY, T1_ENCODING_TYPE_STANDARD, T1_ENCODING_TYPE_ISOLATIN1, T1_ENCODING_TYPE_EXPERT } T1_EncodingType; /*************************************************************************/ /* */ /* <Enum> */ /* PS_Dict_Keys */ /* */ /* <Description> */ /* An enumeration used in calls to @FT_Get_PS_Font_Value to identify */ /* the Type~1 dictionary entry to retrieve. */ /* */ typedef enum PS_Dict_Keys_ { /* conventionally in the font dictionary */ PS_DICT_FONT_TYPE, /* FT_Byte */ PS_DICT_FONT_MATRIX, /* FT_Fixed */ PS_DICT_FONT_BBOX, /* FT_Fixed */ PS_DICT_PAINT_TYPE, /* FT_Byte */ PS_DICT_FONT_NAME, /* FT_String* */ PS_DICT_UNIQUE_ID, /* FT_Int */ PS_DICT_NUM_CHAR_STRINGS, /* FT_Int */ PS_DICT_CHAR_STRING_KEY, /* FT_String* */ PS_DICT_CHAR_STRING, /* FT_String* */ PS_DICT_ENCODING_TYPE, /* T1_EncodingType */ PS_DICT_ENCODING_ENTRY, /* FT_String* */ /* conventionally in the font Private dictionary */ PS_DICT_NUM_SUBRS, /* FT_Int */ PS_DICT_SUBR, /* FT_String* */ PS_DICT_STD_HW, /* FT_UShort */ PS_DICT_STD_VW, /* FT_UShort */ PS_DICT_NUM_BLUE_VALUES, /* FT_Byte */ PS_DICT_BLUE_VALUE, /* FT_Short */ PS_DICT_BLUE_FUZZ, /* FT_Int */ PS_DICT_NUM_OTHER_BLUES, /* FT_Byte */ PS_DICT_OTHER_BLUE, /* FT_Short */ PS_DICT_NUM_FAMILY_BLUES, /* FT_Byte */ PS_DICT_FAMILY_BLUE, /* FT_Short */ PS_DICT_NUM_FAMILY_OTHER_BLUES, /* FT_Byte */ PS_DICT_FAMILY_OTHER_BLUE, /* FT_Short */ PS_DICT_BLUE_SCALE, /* FT_Fixed */ PS_DICT_BLUE_SHIFT, /* FT_Int */ PS_DICT_NUM_STEM_SNAP_H, /* FT_Byte */ PS_DICT_STEM_SNAP_H, /* FT_Short */ PS_DICT_NUM_STEM_SNAP_V, /* FT_Byte */ PS_DICT_STEM_SNAP_V, /* FT_Short */ PS_DICT_FORCE_BOLD, /* FT_Bool */ PS_DICT_RND_STEM_UP, /* FT_Bool */ PS_DICT_MIN_FEATURE, /* FT_Short */ PS_DICT_LEN_IV, /* FT_Int */ PS_DICT_PASSWORD, /* FT_Long */ PS_DICT_LANGUAGE_GROUP, /* FT_Long */ /* conventionally in the font FontInfo dictionary */ PS_DICT_VERSION, /* FT_String* */ PS_DICT_NOTICE, /* FT_String* */ PS_DICT_FULL_NAME, /* FT_String* */ PS_DICT_FAMILY_NAME, /* FT_String* */ PS_DICT_WEIGHT, /* FT_String */ PS_DICT_IS_FIXED_PITCH, /* FT_Bool */ PS_DICT_UNDERLINE_POSITION, /* FT_Short */ PS_DICT_UNDERLINE_THICKNESS, /* FT_UShort */ PS_DICT_FS_TYPE, /* FT_UShort */ PS_DICT_ITALIC_ANGLE, /* FT_Long */ PS_DICT_MAX = PS_DICT_ITALIC_ANGLE } PS_Dict_Keys; /************************************************************************ * * @function: * FT_Get_PS_Font_Value * * @description: * Retrieve the value for the supplied key from a PostScript font. * * @input: * face :: * PostScript face handle. * * key :: * An enumeration value representing the dictionary key to retrieve. * * idx :: * For array values, this specifies the index to be returned. * * value :: * A pointer to memory into which to write the value. * * valen_len :: * The size, in bytes, of the memory supplied for the value. * * @output: * value :: * The value matching the above key, if it exists. * * @return: * The amount of memory (in bytes) required to hold the requested * value (if it exists, -1 otherwise). * * @note: * The values returned are not pointers into the internal structures of * the face, but are `fresh' copies, so that the memory containing them * belongs to the calling application. This also enforces the * `read-only' nature of these values, i.e., this function cannot be * used to manipulate the face. * * `value' is a void pointer because the values returned can be of * various types. * * If either `value' is NULL or `value_len' is too small, just the * required memory size for the requested entry is returned. * * The `idx' parameter is used, not only to retrieve elements of, for * example, the FontMatrix or FontBBox, but also to retrieve name keys * from the CharStrings dictionary, and the charstrings themselves. It * is ignored for atomic values. * * PS_DICT_BLUE_SCALE returns a value that is scaled up by 1000. To * get the value as in the font stream, you need to divide by * 65536000.0 (to remove the FT_Fixed scale, and the x1000 scale). * * IMPORTANT: Only key/value pairs read by the FreeType interpreter can * be retrieved. So, for example, PostScript procedures such as NP, * ND, and RD are not available. Arbitrary keys are, obviously, not be * available either. * * If the font's format is not PostScript-based, this function returns * the `FT_Err_Invalid_Argument' error code. * */ FT_EXPORT( FT_Long ) FT_Get_PS_Font_Value( FT_Face face, PS_Dict_Keys key, FT_UInt idx, void *value, FT_Long value_len ); /* */ FT_END_HEADER #endif /* __T1TABLES_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/ttnameid.h ================================================ /***************************************************************************/ /* */ /* ttnameid.h */ /* */ /* TrueType name ID definitions (specification only). */ /* */ /* Copyright 1996-2002, 2003, 2004, 2006, 2007, 2008 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __TTNAMEID_H__ #define __TTNAMEID_H__ #include <ft2build.h> FT_BEGIN_HEADER /*************************************************************************/ /* */ /* <Section> */ /* truetype_tables */ /* */ /*************************************************************************/ /* */ /* Possible values for the `platform' identifier code in the name */ /* records of the TTF `name' table. */ /* */ /*************************************************************************/ /*********************************************************************** * * @enum: * TT_PLATFORM_XXX * * @description: * A list of valid values for the `platform_id' identifier code in * @FT_CharMapRec and @FT_SfntName structures. * * @values: * TT_PLATFORM_APPLE_UNICODE :: * Used by Apple to indicate a Unicode character map and/or name entry. * See @TT_APPLE_ID_XXX for corresponding `encoding_id' values. Note * that name entries in this format are coded as big-endian UCS-2 * character codes _only_. * * TT_PLATFORM_MACINTOSH :: * Used by Apple to indicate a MacOS-specific charmap and/or name entry. * See @TT_MAC_ID_XXX for corresponding `encoding_id' values. Note that * most TrueType fonts contain an Apple roman charmap to be usable on * MacOS systems (even if they contain a Microsoft charmap as well). * * TT_PLATFORM_ISO :: * This value was used to specify ISO/IEC 10646 charmaps. It is however * now deprecated. See @TT_ISO_ID_XXX for a list of corresponding * `encoding_id' values. * * TT_PLATFORM_MICROSOFT :: * Used by Microsoft to indicate Windows-specific charmaps. See * @TT_MS_ID_XXX for a list of corresponding `encoding_id' values. * Note that most fonts contain a Unicode charmap using * (TT_PLATFORM_MICROSOFT, @TT_MS_ID_UNICODE_CS). * * TT_PLATFORM_CUSTOM :: * Used to indicate application-specific charmaps. * * TT_PLATFORM_ADOBE :: * This value isn't part of any font format specification, but is used * by FreeType to report Adobe-specific charmaps in an @FT_CharMapRec * structure. See @TT_ADOBE_ID_XXX. */ #define TT_PLATFORM_APPLE_UNICODE 0 #define TT_PLATFORM_MACINTOSH 1 #define TT_PLATFORM_ISO 2 /* deprecated */ #define TT_PLATFORM_MICROSOFT 3 #define TT_PLATFORM_CUSTOM 4 #define TT_PLATFORM_ADOBE 7 /* artificial */ /*********************************************************************** * * @enum: * TT_APPLE_ID_XXX * * @description: * A list of valid values for the `encoding_id' for * @TT_PLATFORM_APPLE_UNICODE charmaps and name entries. * * @values: * TT_APPLE_ID_DEFAULT :: * Unicode version 1.0. * * TT_APPLE_ID_UNICODE_1_1 :: * Unicode 1.1; specifies Hangul characters starting at U+34xx. * * TT_APPLE_ID_ISO_10646 :: * Deprecated (identical to preceding). * * TT_APPLE_ID_UNICODE_2_0 :: * Unicode 2.0 and beyond (UTF-16 BMP only). * * TT_APPLE_ID_UNICODE_32 :: * Unicode 3.1 and beyond, using UTF-32. * * TT_APPLE_ID_VARIANT_SELECTOR :: * From Adobe, not Apple. Not a normal cmap. Specifies variations * on a real cmap. */ #define TT_APPLE_ID_DEFAULT 0 /* Unicode 1.0 */ #define TT_APPLE_ID_UNICODE_1_1 1 /* specify Hangul at U+34xx */ #define TT_APPLE_ID_ISO_10646 2 /* deprecated */ #define TT_APPLE_ID_UNICODE_2_0 3 /* or later */ #define TT_APPLE_ID_UNICODE_32 4 /* 2.0 or later, full repertoire */ #define TT_APPLE_ID_VARIANT_SELECTOR 5 /* variation selector data */ /*********************************************************************** * * @enum: * TT_MAC_ID_XXX * * @description: * A list of valid values for the `encoding_id' for * @TT_PLATFORM_MACINTOSH charmaps and name entries. * * @values: * TT_MAC_ID_ROMAN :: * TT_MAC_ID_JAPANESE :: * TT_MAC_ID_TRADITIONAL_CHINESE :: * TT_MAC_ID_KOREAN :: * TT_MAC_ID_ARABIC :: * TT_MAC_ID_HEBREW :: * TT_MAC_ID_GREEK :: * TT_MAC_ID_RUSSIAN :: * TT_MAC_ID_RSYMBOL :: * TT_MAC_ID_DEVANAGARI :: * TT_MAC_ID_GURMUKHI :: * TT_MAC_ID_GUJARATI :: * TT_MAC_ID_ORIYA :: * TT_MAC_ID_BENGALI :: * TT_MAC_ID_TAMIL :: * TT_MAC_ID_TELUGU :: * TT_MAC_ID_KANNADA :: * TT_MAC_ID_MALAYALAM :: * TT_MAC_ID_SINHALESE :: * TT_MAC_ID_BURMESE :: * TT_MAC_ID_KHMER :: * TT_MAC_ID_THAI :: * TT_MAC_ID_LAOTIAN :: * TT_MAC_ID_GEORGIAN :: * TT_MAC_ID_ARMENIAN :: * TT_MAC_ID_MALDIVIAN :: * TT_MAC_ID_SIMPLIFIED_CHINESE :: * TT_MAC_ID_TIBETAN :: * TT_MAC_ID_MONGOLIAN :: * TT_MAC_ID_GEEZ :: * TT_MAC_ID_SLAVIC :: * TT_MAC_ID_VIETNAMESE :: * TT_MAC_ID_SINDHI :: * TT_MAC_ID_UNINTERP :: */ #define TT_MAC_ID_ROMAN 0 #define TT_MAC_ID_JAPANESE 1 #define TT_MAC_ID_TRADITIONAL_CHINESE 2 #define TT_MAC_ID_KOREAN 3 #define TT_MAC_ID_ARABIC 4 #define TT_MAC_ID_HEBREW 5 #define TT_MAC_ID_GREEK 6 #define TT_MAC_ID_RUSSIAN 7 #define TT_MAC_ID_RSYMBOL 8 #define TT_MAC_ID_DEVANAGARI 9 #define TT_MAC_ID_GURMUKHI 10 #define TT_MAC_ID_GUJARATI 11 #define TT_MAC_ID_ORIYA 12 #define TT_MAC_ID_BENGALI 13 #define TT_MAC_ID_TAMIL 14 #define TT_MAC_ID_TELUGU 15 #define TT_MAC_ID_KANNADA 16 #define TT_MAC_ID_MALAYALAM 17 #define TT_MAC_ID_SINHALESE 18 #define TT_MAC_ID_BURMESE 19 #define TT_MAC_ID_KHMER 20 #define TT_MAC_ID_THAI 21 #define TT_MAC_ID_LAOTIAN 22 #define TT_MAC_ID_GEORGIAN 23 #define TT_MAC_ID_ARMENIAN 24 #define TT_MAC_ID_MALDIVIAN 25 #define TT_MAC_ID_SIMPLIFIED_CHINESE 25 #define TT_MAC_ID_TIBETAN 26 #define TT_MAC_ID_MONGOLIAN 27 #define TT_MAC_ID_GEEZ 28 #define TT_MAC_ID_SLAVIC 29 #define TT_MAC_ID_VIETNAMESE 30 #define TT_MAC_ID_SINDHI 31 #define TT_MAC_ID_UNINTERP 32 /*********************************************************************** * * @enum: * TT_ISO_ID_XXX * * @description: * A list of valid values for the `encoding_id' for * @TT_PLATFORM_ISO charmaps and name entries. * * Their use is now deprecated. * * @values: * TT_ISO_ID_7BIT_ASCII :: * ASCII. * TT_ISO_ID_10646 :: * ISO/10646. * TT_ISO_ID_8859_1 :: * Also known as Latin-1. */ #define TT_ISO_ID_7BIT_ASCII 0 #define TT_ISO_ID_10646 1 #define TT_ISO_ID_8859_1 2 /*********************************************************************** * * @enum: * TT_MS_ID_XXX * * @description: * A list of valid values for the `encoding_id' for * @TT_PLATFORM_MICROSOFT charmaps and name entries. * * @values: * TT_MS_ID_SYMBOL_CS :: * Corresponds to Microsoft symbol encoding. See * @FT_ENCODING_MS_SYMBOL. * * TT_MS_ID_UNICODE_CS :: * Corresponds to a Microsoft WGL4 charmap, matching Unicode. See * @FT_ENCODING_UNICODE. * * TT_MS_ID_SJIS :: * Corresponds to SJIS Japanese encoding. See @FT_ENCODING_SJIS. * * TT_MS_ID_GB2312 :: * Corresponds to Simplified Chinese as used in Mainland China. See * @FT_ENCODING_GB2312. * * TT_MS_ID_BIG_5 :: * Corresponds to Traditional Chinese as used in Taiwan and Hong Kong. * See @FT_ENCODING_BIG5. * * TT_MS_ID_WANSUNG :: * Corresponds to Korean Wansung encoding. See @FT_ENCODING_WANSUNG. * * TT_MS_ID_JOHAB :: * Corresponds to Johab encoding. See @FT_ENCODING_JOHAB. * * TT_MS_ID_UCS_4 :: * Corresponds to UCS-4 or UTF-32 charmaps. This has been added to * the OpenType specification version 1.4 (mid-2001.) */ #define TT_MS_ID_SYMBOL_CS 0 #define TT_MS_ID_UNICODE_CS 1 #define TT_MS_ID_SJIS 2 #define TT_MS_ID_GB2312 3 #define TT_MS_ID_BIG_5 4 #define TT_MS_ID_WANSUNG 5 #define TT_MS_ID_JOHAB 6 #define TT_MS_ID_UCS_4 10 /*********************************************************************** * * @enum: * TT_ADOBE_ID_XXX * * @description: * A list of valid values for the `encoding_id' for * @TT_PLATFORM_ADOBE charmaps. This is a FreeType-specific extension! * * @values: * TT_ADOBE_ID_STANDARD :: * Adobe standard encoding. * TT_ADOBE_ID_EXPERT :: * Adobe expert encoding. * TT_ADOBE_ID_CUSTOM :: * Adobe custom encoding. * TT_ADOBE_ID_LATIN_1 :: * Adobe Latin~1 encoding. */ #define TT_ADOBE_ID_STANDARD 0 #define TT_ADOBE_ID_EXPERT 1 #define TT_ADOBE_ID_CUSTOM 2 #define TT_ADOBE_ID_LATIN_1 3 /*************************************************************************/ /* */ /* Possible values of the language identifier field in the name records */ /* of the TTF `name' table if the `platform' identifier code is */ /* TT_PLATFORM_MACINTOSH. */ /* */ /* The canonical source for the Apple assigned Language ID's is at */ /* */ /* http://fonts.apple.com/TTRefMan/RM06/Chap6name.html */ /* */ #define TT_MAC_LANGID_ENGLISH 0 #define TT_MAC_LANGID_FRENCH 1 #define TT_MAC_LANGID_GERMAN 2 #define TT_MAC_LANGID_ITALIAN 3 #define TT_MAC_LANGID_DUTCH 4 #define TT_MAC_LANGID_SWEDISH 5 #define TT_MAC_LANGID_SPANISH 6 #define TT_MAC_LANGID_DANISH 7 #define TT_MAC_LANGID_PORTUGUESE 8 #define TT_MAC_LANGID_NORWEGIAN 9 #define TT_MAC_LANGID_HEBREW 10 #define TT_MAC_LANGID_JAPANESE 11 #define TT_MAC_LANGID_ARABIC 12 #define TT_MAC_LANGID_FINNISH 13 #define TT_MAC_LANGID_GREEK 14 #define TT_MAC_LANGID_ICELANDIC 15 #define TT_MAC_LANGID_MALTESE 16 #define TT_MAC_LANGID_TURKISH 17 #define TT_MAC_LANGID_CROATIAN 18 #define TT_MAC_LANGID_CHINESE_TRADITIONAL 19 #define TT_MAC_LANGID_URDU 20 #define TT_MAC_LANGID_HINDI 21 #define TT_MAC_LANGID_THAI 22 #define TT_MAC_LANGID_KOREAN 23 #define TT_MAC_LANGID_LITHUANIAN 24 #define TT_MAC_LANGID_POLISH 25 #define TT_MAC_LANGID_HUNGARIAN 26 #define TT_MAC_LANGID_ESTONIAN 27 #define TT_MAC_LANGID_LETTISH 28 #define TT_MAC_LANGID_SAAMISK 29 #define TT_MAC_LANGID_FAEROESE 30 #define TT_MAC_LANGID_FARSI 31 #define TT_MAC_LANGID_RUSSIAN 32 #define TT_MAC_LANGID_CHINESE_SIMPLIFIED 33 #define TT_MAC_LANGID_FLEMISH 34 #define TT_MAC_LANGID_IRISH 35 #define TT_MAC_LANGID_ALBANIAN 36 #define TT_MAC_LANGID_ROMANIAN 37 #define TT_MAC_LANGID_CZECH 38 #define TT_MAC_LANGID_SLOVAK 39 #define TT_MAC_LANGID_SLOVENIAN 40 #define TT_MAC_LANGID_YIDDISH 41 #define TT_MAC_LANGID_SERBIAN 42 #define TT_MAC_LANGID_MACEDONIAN 43 #define TT_MAC_LANGID_BULGARIAN 44 #define TT_MAC_LANGID_UKRAINIAN 45 #define TT_MAC_LANGID_BYELORUSSIAN 46 #define TT_MAC_LANGID_UZBEK 47 #define TT_MAC_LANGID_KAZAKH 48 #define TT_MAC_LANGID_AZERBAIJANI 49 #define TT_MAC_LANGID_AZERBAIJANI_CYRILLIC_SCRIPT 49 #define TT_MAC_LANGID_AZERBAIJANI_ARABIC_SCRIPT 50 #define TT_MAC_LANGID_ARMENIAN 51 #define TT_MAC_LANGID_GEORGIAN 52 #define TT_MAC_LANGID_MOLDAVIAN 53 #define TT_MAC_LANGID_KIRGHIZ 54 #define TT_MAC_LANGID_TAJIKI 55 #define TT_MAC_LANGID_TURKMEN 56 #define TT_MAC_LANGID_MONGOLIAN 57 #define TT_MAC_LANGID_MONGOLIAN_MONGOLIAN_SCRIPT 57 #define TT_MAC_LANGID_MONGOLIAN_CYRILLIC_SCRIPT 58 #define TT_MAC_LANGID_PASHTO 59 #define TT_MAC_LANGID_KURDISH 60 #define TT_MAC_LANGID_KASHMIRI 61 #define TT_MAC_LANGID_SINDHI 62 #define TT_MAC_LANGID_TIBETAN 63 #define TT_MAC_LANGID_NEPALI 64 #define TT_MAC_LANGID_SANSKRIT 65 #define TT_MAC_LANGID_MARATHI 66 #define TT_MAC_LANGID_BENGALI 67 #define TT_MAC_LANGID_ASSAMESE 68 #define TT_MAC_LANGID_GUJARATI 69 #define TT_MAC_LANGID_PUNJABI 70 #define TT_MAC_LANGID_ORIYA 71 #define TT_MAC_LANGID_MALAYALAM 72 #define TT_MAC_LANGID_KANNADA 73 #define TT_MAC_LANGID_TAMIL 74 #define TT_MAC_LANGID_TELUGU 75 #define TT_MAC_LANGID_SINHALESE 76 #define TT_MAC_LANGID_BURMESE 77 #define TT_MAC_LANGID_KHMER 78 #define TT_MAC_LANGID_LAO 79 #define TT_MAC_LANGID_VIETNAMESE 80 #define TT_MAC_LANGID_INDONESIAN 81 #define TT_MAC_LANGID_TAGALOG 82 #define TT_MAC_LANGID_MALAY_ROMAN_SCRIPT 83 #define TT_MAC_LANGID_MALAY_ARABIC_SCRIPT 84 #define TT_MAC_LANGID_AMHARIC 85 #define TT_MAC_LANGID_TIGRINYA 86 #define TT_MAC_LANGID_GALLA 87 #define TT_MAC_LANGID_SOMALI 88 #define TT_MAC_LANGID_SWAHILI 89 #define TT_MAC_LANGID_RUANDA 90 #define TT_MAC_LANGID_RUNDI 91 #define TT_MAC_LANGID_CHEWA 92 #define TT_MAC_LANGID_MALAGASY 93 #define TT_MAC_LANGID_ESPERANTO 94 #define TT_MAC_LANGID_WELSH 128 #define TT_MAC_LANGID_BASQUE 129 #define TT_MAC_LANGID_CATALAN 130 #define TT_MAC_LANGID_LATIN 131 #define TT_MAC_LANGID_QUECHUA 132 #define TT_MAC_LANGID_GUARANI 133 #define TT_MAC_LANGID_AYMARA 134 #define TT_MAC_LANGID_TATAR 135 #define TT_MAC_LANGID_UIGHUR 136 #define TT_MAC_LANGID_DZONGKHA 137 #define TT_MAC_LANGID_JAVANESE 138 #define TT_MAC_LANGID_SUNDANESE 139 #if 0 /* these seem to be errors that have been dropped */ #define TT_MAC_LANGID_SCOTTISH_GAELIC 140 #define TT_MAC_LANGID_IRISH_GAELIC 141 #endif /* The following codes are new as of 2000-03-10 */ #define TT_MAC_LANGID_GALICIAN 140 #define TT_MAC_LANGID_AFRIKAANS 141 #define TT_MAC_LANGID_BRETON 142 #define TT_MAC_LANGID_INUKTITUT 143 #define TT_MAC_LANGID_SCOTTISH_GAELIC 144 #define TT_MAC_LANGID_MANX_GAELIC 145 #define TT_MAC_LANGID_IRISH_GAELIC 146 #define TT_MAC_LANGID_TONGAN 147 #define TT_MAC_LANGID_GREEK_POLYTONIC 148 #define TT_MAC_LANGID_GREELANDIC 149 #define TT_MAC_LANGID_AZERBAIJANI_ROMAN_SCRIPT 150 /*************************************************************************/ /* */ /* Possible values of the language identifier field in the name records */ /* of the TTF `name' table if the `platform' identifier code is */ /* TT_PLATFORM_MICROSOFT. */ /* */ /* The canonical source for the MS assigned LCID's (seems to) be at */ /* */ /* http://www.microsoft.com/globaldev/reference/lcid-all.mspx */ /* */ /* It used to be at various places, among them */ /* */ /* http://www.microsoft.com/typography/OTSPEC/lcid-cp.txt */ /* http://www.microsoft.com/globaldev/reference/loclanghome.asp */ /* http://support.microsoft.com/support/kb/articles/Q224/8/04.ASP */ /* http://msdn.microsoft.com/library/en-us/passport25/ */ /* NET_Passport_VBScript_Documentation/Single_Sign_In/ */ /* Advanced_Single_Sign_In/Localization_and_LCIDs.asp */ /* */ /* Hopefully, it seems now that the Globaldev site prevails... */ /* (updated by Antoine, 2004-02-17) */ #define TT_MS_LANGID_ARABIC_GENERAL 0x0001 #define TT_MS_LANGID_ARABIC_SAUDI_ARABIA 0x0401 #define TT_MS_LANGID_ARABIC_IRAQ 0x0801 #define TT_MS_LANGID_ARABIC_EGYPT 0x0c01 #define TT_MS_LANGID_ARABIC_LIBYA 0x1001 #define TT_MS_LANGID_ARABIC_ALGERIA 0x1401 #define TT_MS_LANGID_ARABIC_MOROCCO 0x1801 #define TT_MS_LANGID_ARABIC_TUNISIA 0x1c01 #define TT_MS_LANGID_ARABIC_OMAN 0x2001 #define TT_MS_LANGID_ARABIC_YEMEN 0x2401 #define TT_MS_LANGID_ARABIC_SYRIA 0x2801 #define TT_MS_LANGID_ARABIC_JORDAN 0x2c01 #define TT_MS_LANGID_ARABIC_LEBANON 0x3001 #define TT_MS_LANGID_ARABIC_KUWAIT 0x3401 #define TT_MS_LANGID_ARABIC_UAE 0x3801 #define TT_MS_LANGID_ARABIC_BAHRAIN 0x3c01 #define TT_MS_LANGID_ARABIC_QATAR 0x4001 #define TT_MS_LANGID_BULGARIAN_BULGARIA 0x0402 #define TT_MS_LANGID_CATALAN_SPAIN 0x0403 #define TT_MS_LANGID_CHINESE_GENERAL 0x0004 #define TT_MS_LANGID_CHINESE_TAIWAN 0x0404 #define TT_MS_LANGID_CHINESE_PRC 0x0804 #define TT_MS_LANGID_CHINESE_HONG_KONG 0x0c04 #define TT_MS_LANGID_CHINESE_SINGAPORE 0x1004 #if 1 /* this looks like the correct value */ #define TT_MS_LANGID_CHINESE_MACAU 0x1404 #else /* but beware, Microsoft may change its mind... the most recent Word reference has the following: */ #define TT_MS_LANGID_CHINESE_MACAU TT_MS_LANGID_CHINESE_HONG_KONG #endif #if 0 /* used only with .NET `cultures'; commented out */ #define TT_MS_LANGID_CHINESE_TRADITIONAL 0x7C04 #endif #define TT_MS_LANGID_CZECH_CZECH_REPUBLIC 0x0405 #define TT_MS_LANGID_DANISH_DENMARK 0x0406 #define TT_MS_LANGID_GERMAN_GERMANY 0x0407 #define TT_MS_LANGID_GERMAN_SWITZERLAND 0x0807 #define TT_MS_LANGID_GERMAN_AUSTRIA 0x0c07 #define TT_MS_LANGID_GERMAN_LUXEMBOURG 0x1007 #define TT_MS_LANGID_GERMAN_LIECHTENSTEI 0x1407 #define TT_MS_LANGID_GREEK_GREECE 0x0408 /* don't ask what this one means... It is commented out currently. */ #if 0 #define TT_MS_LANGID_GREEK_GREECE2 0x2008 #endif #define TT_MS_LANGID_ENGLISH_GENERAL 0x0009 #define TT_MS_LANGID_ENGLISH_UNITED_STATES 0x0409 #define TT_MS_LANGID_ENGLISH_UNITED_KINGDOM 0x0809 #define TT_MS_LANGID_ENGLISH_AUSTRALIA 0x0c09 #define TT_MS_LANGID_ENGLISH_CANADA 0x1009 #define TT_MS_LANGID_ENGLISH_NEW_ZEALAND 0x1409 #define TT_MS_LANGID_ENGLISH_IRELAND 0x1809 #define TT_MS_LANGID_ENGLISH_SOUTH_AFRICA 0x1c09 #define TT_MS_LANGID_ENGLISH_JAMAICA 0x2009 #define TT_MS_LANGID_ENGLISH_CARIBBEAN 0x2409 #define TT_MS_LANGID_ENGLISH_BELIZE 0x2809 #define TT_MS_LANGID_ENGLISH_TRINIDAD 0x2c09 #define TT_MS_LANGID_ENGLISH_ZIMBABWE 0x3009 #define TT_MS_LANGID_ENGLISH_PHILIPPINES 0x3409 #define TT_MS_LANGID_ENGLISH_INDONESIA 0x3809 #define TT_MS_LANGID_ENGLISH_HONG_KONG 0x3c09 #define TT_MS_LANGID_ENGLISH_INDIA 0x4009 #define TT_MS_LANGID_ENGLISH_MALAYSIA 0x4409 #define TT_MS_LANGID_ENGLISH_SINGAPORE 0x4809 #define TT_MS_LANGID_SPANISH_SPAIN_TRADITIONAL_SORT 0x040a #define TT_MS_LANGID_SPANISH_MEXICO 0x080a #define TT_MS_LANGID_SPANISH_SPAIN_INTERNATIONAL_SORT 0x0c0a #define TT_MS_LANGID_SPANISH_GUATEMALA 0x100a #define TT_MS_LANGID_SPANISH_COSTA_RICA 0x140a #define TT_MS_LANGID_SPANISH_PANAMA 0x180a #define TT_MS_LANGID_SPANISH_DOMINICAN_REPUBLIC 0x1c0a #define TT_MS_LANGID_SPANISH_VENEZUELA 0x200a #define TT_MS_LANGID_SPANISH_COLOMBIA 0x240a #define TT_MS_LANGID_SPANISH_PERU 0x280a #define TT_MS_LANGID_SPANISH_ARGENTINA 0x2c0a #define TT_MS_LANGID_SPANISH_ECUADOR 0x300a #define TT_MS_LANGID_SPANISH_CHILE 0x340a #define TT_MS_LANGID_SPANISH_URUGUAY 0x380a #define TT_MS_LANGID_SPANISH_PARAGUAY 0x3c0a #define TT_MS_LANGID_SPANISH_BOLIVIA 0x400a #define TT_MS_LANGID_SPANISH_EL_SALVADOR 0x440a #define TT_MS_LANGID_SPANISH_HONDURAS 0x480a #define TT_MS_LANGID_SPANISH_NICARAGUA 0x4c0a #define TT_MS_LANGID_SPANISH_PUERTO_RICO 0x500a #define TT_MS_LANGID_SPANISH_UNITED_STATES 0x540a /* The following ID blatantly violate MS specs by using a */ /* sublanguage > 0x1F. */ #define TT_MS_LANGID_SPANISH_LATIN_AMERICA 0xE40aU #define TT_MS_LANGID_FINNISH_FINLAND 0x040b #define TT_MS_LANGID_FRENCH_FRANCE 0x040c #define TT_MS_LANGID_FRENCH_BELGIUM 0x080c #define TT_MS_LANGID_FRENCH_CANADA 0x0c0c #define TT_MS_LANGID_FRENCH_SWITZERLAND 0x100c #define TT_MS_LANGID_FRENCH_LUXEMBOURG 0x140c #define TT_MS_LANGID_FRENCH_MONACO 0x180c #define TT_MS_LANGID_FRENCH_WEST_INDIES 0x1c0c #define TT_MS_LANGID_FRENCH_REUNION 0x200c #define TT_MS_LANGID_FRENCH_CONGO 0x240c /* which was formerly: */ #define TT_MS_LANGID_FRENCH_ZAIRE TT_MS_LANGID_FRENCH_CONGO #define TT_MS_LANGID_FRENCH_SENEGAL 0x280c #define TT_MS_LANGID_FRENCH_CAMEROON 0x2c0c #define TT_MS_LANGID_FRENCH_COTE_D_IVOIRE 0x300c #define TT_MS_LANGID_FRENCH_MALI 0x340c #define TT_MS_LANGID_FRENCH_MOROCCO 0x380c #define TT_MS_LANGID_FRENCH_HAITI 0x3c0c /* and another violation of the spec (see 0xE40aU) */ #define TT_MS_LANGID_FRENCH_NORTH_AFRICA 0xE40cU #define TT_MS_LANGID_HEBREW_ISRAEL 0x040d #define TT_MS_LANGID_HUNGARIAN_HUNGARY 0x040e #define TT_MS_LANGID_ICELANDIC_ICELAND 0x040f #define TT_MS_LANGID_ITALIAN_ITALY 0x0410 #define TT_MS_LANGID_ITALIAN_SWITZERLAND 0x0810 #define TT_MS_LANGID_JAPANESE_JAPAN 0x0411 #define TT_MS_LANGID_KOREAN_EXTENDED_WANSUNG_KOREA 0x0412 #define TT_MS_LANGID_KOREAN_JOHAB_KOREA 0x0812 #define TT_MS_LANGID_DUTCH_NETHERLANDS 0x0413 #define TT_MS_LANGID_DUTCH_BELGIUM 0x0813 #define TT_MS_LANGID_NORWEGIAN_NORWAY_BOKMAL 0x0414 #define TT_MS_LANGID_NORWEGIAN_NORWAY_NYNORSK 0x0814 #define TT_MS_LANGID_POLISH_POLAND 0x0415 #define TT_MS_LANGID_PORTUGUESE_BRAZIL 0x0416 #define TT_MS_LANGID_PORTUGUESE_PORTUGAL 0x0816 #define TT_MS_LANGID_RHAETO_ROMANIC_SWITZERLAND 0x0417 #define TT_MS_LANGID_ROMANIAN_ROMANIA 0x0418 #define TT_MS_LANGID_MOLDAVIAN_MOLDAVIA 0x0818 #define TT_MS_LANGID_RUSSIAN_RUSSIA 0x0419 #define TT_MS_LANGID_RUSSIAN_MOLDAVIA 0x0819 #define TT_MS_LANGID_CROATIAN_CROATIA 0x041a #define TT_MS_LANGID_SERBIAN_SERBIA_LATIN 0x081a #define TT_MS_LANGID_SERBIAN_SERBIA_CYRILLIC 0x0c1a #if 0 /* this used to be this value, but it looks like we were wrong */ #define TT_MS_LANGID_BOSNIAN_BOSNIA_HERZEGOVINA 0x101a #else /* current sources say */ #define TT_MS_LANGID_CROATIAN_BOSNIA_HERZEGOVINA 0x101a #define TT_MS_LANGID_BOSNIAN_BOSNIA_HERZEGOVINA 0x141a /* and XPsp2 Platform SDK added (2004-07-26) */ /* Names are shortened to be significant within 40 chars. */ #define TT_MS_LANGID_SERBIAN_BOSNIA_HERZ_LATIN 0x181a #define TT_MS_LANGID_SERBIAN_BOSNIA_HERZ_CYRILLIC 0x181a #endif #define TT_MS_LANGID_SLOVAK_SLOVAKIA 0x041b #define TT_MS_LANGID_ALBANIAN_ALBANIA 0x041c #define TT_MS_LANGID_SWEDISH_SWEDEN 0x041d #define TT_MS_LANGID_SWEDISH_FINLAND 0x081d #define TT_MS_LANGID_THAI_THAILAND 0x041e #define TT_MS_LANGID_TURKISH_TURKEY 0x041f #define TT_MS_LANGID_URDU_PAKISTAN 0x0420 #define TT_MS_LANGID_URDU_INDIA 0x0820 #define TT_MS_LANGID_INDONESIAN_INDONESIA 0x0421 #define TT_MS_LANGID_UKRAINIAN_UKRAINE 0x0422 #define TT_MS_LANGID_BELARUSIAN_BELARUS 0x0423 #define TT_MS_LANGID_SLOVENE_SLOVENIA 0x0424 #define TT_MS_LANGID_ESTONIAN_ESTONIA 0x0425 #define TT_MS_LANGID_LATVIAN_LATVIA 0x0426 #define TT_MS_LANGID_LITHUANIAN_LITHUANIA 0x0427 #define TT_MS_LANGID_CLASSIC_LITHUANIAN_LITHUANIA 0x0827 #define TT_MS_LANGID_TAJIK_TAJIKISTAN 0x0428 #define TT_MS_LANGID_FARSI_IRAN 0x0429 #define TT_MS_LANGID_VIETNAMESE_VIET_NAM 0x042a #define TT_MS_LANGID_ARMENIAN_ARMENIA 0x042b #define TT_MS_LANGID_AZERI_AZERBAIJAN_LATIN 0x042c #define TT_MS_LANGID_AZERI_AZERBAIJAN_CYRILLIC 0x082c #define TT_MS_LANGID_BASQUE_SPAIN 0x042d #define TT_MS_LANGID_SORBIAN_GERMANY 0x042e #define TT_MS_LANGID_MACEDONIAN_MACEDONIA 0x042f #define TT_MS_LANGID_SUTU_SOUTH_AFRICA 0x0430 #define TT_MS_LANGID_TSONGA_SOUTH_AFRICA 0x0431 #define TT_MS_LANGID_TSWANA_SOUTH_AFRICA 0x0432 #define TT_MS_LANGID_VENDA_SOUTH_AFRICA 0x0433 #define TT_MS_LANGID_XHOSA_SOUTH_AFRICA 0x0434 #define TT_MS_LANGID_ZULU_SOUTH_AFRICA 0x0435 #define TT_MS_LANGID_AFRIKAANS_SOUTH_AFRICA 0x0436 #define TT_MS_LANGID_GEORGIAN_GEORGIA 0x0437 #define TT_MS_LANGID_FAEROESE_FAEROE_ISLANDS 0x0438 #define TT_MS_LANGID_HINDI_INDIA 0x0439 #define TT_MS_LANGID_MALTESE_MALTA 0x043a /* Added by XPsp2 Platform SDK (2004-07-26) */ #define TT_MS_LANGID_SAMI_NORTHERN_NORWAY 0x043b #define TT_MS_LANGID_SAMI_NORTHERN_SWEDEN 0x083b #define TT_MS_LANGID_SAMI_NORTHERN_FINLAND 0x0C3b #define TT_MS_LANGID_SAMI_LULE_NORWAY 0x103b #define TT_MS_LANGID_SAMI_LULE_SWEDEN 0x143b #define TT_MS_LANGID_SAMI_SOUTHERN_NORWAY 0x183b #define TT_MS_LANGID_SAMI_SOUTHERN_SWEDEN 0x1C3b #define TT_MS_LANGID_SAMI_SKOLT_FINLAND 0x203b #define TT_MS_LANGID_SAMI_INARI_FINLAND 0x243b /* ... and we also keep our old identifier... */ #define TT_MS_LANGID_SAAMI_LAPONIA 0x043b #if 0 /* this seems to be a previous inversion */ #define TT_MS_LANGID_IRISH_GAELIC_IRELAND 0x043c #define TT_MS_LANGID_SCOTTISH_GAELIC_UNITED_KINGDOM 0x083c #else #define TT_MS_LANGID_SCOTTISH_GAELIC_UNITED_KINGDOM 0x083c #define TT_MS_LANGID_IRISH_GAELIC_IRELAND 0x043c #endif #define TT_MS_LANGID_YIDDISH_GERMANY 0x043d #define TT_MS_LANGID_MALAY_MALAYSIA 0x043e #define TT_MS_LANGID_MALAY_BRUNEI_DARUSSALAM 0x083e #define TT_MS_LANGID_KAZAK_KAZAKSTAN 0x043f #define TT_MS_LANGID_KIRGHIZ_KIRGHIZSTAN /* Cyrillic*/ 0x0440 /* alias declared in Windows 2000 */ #define TT_MS_LANGID_KIRGHIZ_KIRGHIZ_REPUBLIC \ TT_MS_LANGID_KIRGHIZ_KIRGHIZSTAN #define TT_MS_LANGID_SWAHILI_KENYA 0x0441 #define TT_MS_LANGID_TURKMEN_TURKMENISTAN 0x0442 #define TT_MS_LANGID_UZBEK_UZBEKISTAN_LATIN 0x0443 #define TT_MS_LANGID_UZBEK_UZBEKISTAN_CYRILLIC 0x0843 #define TT_MS_LANGID_TATAR_TATARSTAN 0x0444 #define TT_MS_LANGID_BENGALI_INDIA 0x0445 #define TT_MS_LANGID_BENGALI_BANGLADESH 0x0845 #define TT_MS_LANGID_PUNJABI_INDIA 0x0446 #define TT_MS_LANGID_PUNJABI_ARABIC_PAKISTAN 0x0846 #define TT_MS_LANGID_GUJARATI_INDIA 0x0447 #define TT_MS_LANGID_ORIYA_INDIA 0x0448 #define TT_MS_LANGID_TAMIL_INDIA 0x0449 #define TT_MS_LANGID_TELUGU_INDIA 0x044a #define TT_MS_LANGID_KANNADA_INDIA 0x044b #define TT_MS_LANGID_MALAYALAM_INDIA 0x044c #define TT_MS_LANGID_ASSAMESE_INDIA 0x044d #define TT_MS_LANGID_MARATHI_INDIA 0x044e #define TT_MS_LANGID_SANSKRIT_INDIA 0x044f #define TT_MS_LANGID_MONGOLIAN_MONGOLIA /* Cyrillic */ 0x0450 #define TT_MS_LANGID_MONGOLIAN_MONGOLIA_MONGOLIAN 0x0850 #define TT_MS_LANGID_TIBETAN_CHINA 0x0451 /* Don't use the next constant! It has */ /* (1) the wrong spelling (Dzonghka) */ /* (2) Microsoft doesn't officially define it -- */ /* at least it is not in the List of Local */ /* ID Values. */ /* (3) Dzongkha is not the same language as */ /* Tibetan, so merging it is wrong anyway. */ /* */ /* TT_MS_LANGID_TIBETAN_BHUTAN is correct, BTW. */ #define TT_MS_LANGID_DZONGHKA_BHUTAN 0x0851 #if 0 /* the following used to be defined */ #define TT_MS_LANGID_TIBETAN_BHUTAN 0x0451 /* ... but it was changed; */ #else /* So we will continue to #define it, but with the correct value */ #define TT_MS_LANGID_TIBETAN_BHUTAN TT_MS_LANGID_DZONGHKA_BHUTAN #endif #define TT_MS_LANGID_WELSH_WALES 0x0452 #define TT_MS_LANGID_KHMER_CAMBODIA 0x0453 #define TT_MS_LANGID_LAO_LAOS 0x0454 #define TT_MS_LANGID_BURMESE_MYANMAR 0x0455 #define TT_MS_LANGID_GALICIAN_SPAIN 0x0456 #define TT_MS_LANGID_KONKANI_INDIA 0x0457 #define TT_MS_LANGID_MANIPURI_INDIA /* Bengali */ 0x0458 #define TT_MS_LANGID_SINDHI_INDIA /* Arabic */ 0x0459 #define TT_MS_LANGID_SINDHI_PAKISTAN 0x0859 /* Missing a LCID for Sindhi in Devanagari script */ #define TT_MS_LANGID_SYRIAC_SYRIA 0x045a #define TT_MS_LANGID_SINHALESE_SRI_LANKA 0x045b #define TT_MS_LANGID_CHEROKEE_UNITED_STATES 0x045c #define TT_MS_LANGID_INUKTITUT_CANADA 0x045d #define TT_MS_LANGID_AMHARIC_ETHIOPIA 0x045e #define TT_MS_LANGID_TAMAZIGHT_MOROCCO /* Arabic */ 0x045f #define TT_MS_LANGID_TAMAZIGHT_MOROCCO_LATIN 0x085f /* Missing a LCID for Tifinagh script */ #define TT_MS_LANGID_KASHMIRI_PAKISTAN /* Arabic */ 0x0460 /* Spelled this way by XPsp2 Platform SDK (2004-07-26) */ /* script is yet unclear... might be Arabic, Nagari or Sharada */ #define TT_MS_LANGID_KASHMIRI_SASIA 0x0860 /* ... and aliased (by MS) for compatibility reasons. */ #define TT_MS_LANGID_KASHMIRI_INDIA TT_MS_LANGID_KASHMIRI_SASIA #define TT_MS_LANGID_NEPALI_NEPAL 0x0461 #define TT_MS_LANGID_NEPALI_INDIA 0x0861 #define TT_MS_LANGID_FRISIAN_NETHERLANDS 0x0462 #define TT_MS_LANGID_PASHTO_AFGHANISTAN 0x0463 #define TT_MS_LANGID_FILIPINO_PHILIPPINES 0x0464 #define TT_MS_LANGID_DHIVEHI_MALDIVES 0x0465 /* alias declared in Windows 2000 */ #define TT_MS_LANGID_DIVEHI_MALDIVES TT_MS_LANGID_DHIVEHI_MALDIVES #define TT_MS_LANGID_EDO_NIGERIA 0x0466 #define TT_MS_LANGID_FULFULDE_NIGERIA 0x0467 #define TT_MS_LANGID_HAUSA_NIGERIA 0x0468 #define TT_MS_LANGID_IBIBIO_NIGERIA 0x0469 #define TT_MS_LANGID_YORUBA_NIGERIA 0x046a #define TT_MS_LANGID_QUECHUA_BOLIVIA 0x046b #define TT_MS_LANGID_QUECHUA_ECUADOR 0x086b #define TT_MS_LANGID_QUECHUA_PERU 0x0c6b #define TT_MS_LANGID_SEPEDI_SOUTH_AFRICA 0x046c /* Also spelled by XPsp2 Platform SDK (2004-07-26) */ #define TT_MS_LANGID_SOTHO_SOUTHERN_SOUTH_AFRICA \ TT_MS_LANGID_SEPEDI_SOUTH_AFRICA /* language codes 0x046d, 0x046e and 0x046f are (still) unknown. */ #define TT_MS_LANGID_IGBO_NIGERIA 0x0470 #define TT_MS_LANGID_KANURI_NIGERIA 0x0471 #define TT_MS_LANGID_OROMO_ETHIOPIA 0x0472 #define TT_MS_LANGID_TIGRIGNA_ETHIOPIA 0x0473 #define TT_MS_LANGID_TIGRIGNA_ERYTHREA 0x0873 /* also spelled in the `Passport SDK' list as: */ #define TT_MS_LANGID_TIGRIGNA_ERYTREA TT_MS_LANGID_TIGRIGNA_ERYTHREA #define TT_MS_LANGID_GUARANI_PARAGUAY 0x0474 #define TT_MS_LANGID_HAWAIIAN_UNITED_STATES 0x0475 #define TT_MS_LANGID_LATIN 0x0476 #define TT_MS_LANGID_SOMALI_SOMALIA 0x0477 /* Note: Yi does not have a (proper) ISO 639-2 code, since it is mostly */ /* not written (but OTOH the peculiar writing system is worth */ /* studying). */ #define TT_MS_LANGID_YI_CHINA 0x0478 #define TT_MS_LANGID_PAPIAMENTU_NETHERLANDS_ANTILLES 0x0479 /* language codes from 0x047a to 0x047f are (still) unknown. */ #define TT_MS_LANGID_UIGHUR_CHINA 0x0480 #define TT_MS_LANGID_MAORI_NEW_ZEALAND 0x0481 #if 0 /* not deemed useful for fonts */ #define TT_MS_LANGID_HUMAN_INTERFACE_DEVICE 0x04ff #endif /*************************************************************************/ /* */ /* Possible values of the `name' identifier field in the name records of */ /* the TTF `name' table. These values are platform independent. */ /* */ #define TT_NAME_ID_COPYRIGHT 0 #define TT_NAME_ID_FONT_FAMILY 1 #define TT_NAME_ID_FONT_SUBFAMILY 2 #define TT_NAME_ID_UNIQUE_ID 3 #define TT_NAME_ID_FULL_NAME 4 #define TT_NAME_ID_VERSION_STRING 5 #define TT_NAME_ID_PS_NAME 6 #define TT_NAME_ID_TRADEMARK 7 /* the following values are from the OpenType spec */ #define TT_NAME_ID_MANUFACTURER 8 #define TT_NAME_ID_DESIGNER 9 #define TT_NAME_ID_DESCRIPTION 10 #define TT_NAME_ID_VENDOR_URL 11 #define TT_NAME_ID_DESIGNER_URL 12 #define TT_NAME_ID_LICENSE 13 #define TT_NAME_ID_LICENSE_URL 14 /* number 15 is reserved */ #define TT_NAME_ID_PREFERRED_FAMILY 16 #define TT_NAME_ID_PREFERRED_SUBFAMILY 17 #define TT_NAME_ID_MAC_FULL_NAME 18 /* The following code is new as of 2000-01-21 */ #define TT_NAME_ID_SAMPLE_TEXT 19 /* This is new in OpenType 1.3 */ #define TT_NAME_ID_CID_FINDFONT_NAME 20 /* This is new in OpenType 1.5 */ #define TT_NAME_ID_WWS_FAMILY 21 #define TT_NAME_ID_WWS_SUBFAMILY 22 /*************************************************************************/ /* */ /* Bit mask values for the Unicode Ranges from the TTF `OS2 ' table. */ /* */ /* Updated 08-Nov-2008. */ /* */ /* Bit 0 Basic Latin */ #define TT_UCR_BASIC_LATIN (1L << 0) /* U+0020-U+007E */ /* Bit 1 C1 Controls and Latin-1 Supplement */ #define TT_UCR_LATIN1_SUPPLEMENT (1L << 1) /* U+0080-U+00FF */ /* Bit 2 Latin Extended-A */ #define TT_UCR_LATIN_EXTENDED_A (1L << 2) /* U+0100-U+017F */ /* Bit 3 Latin Extended-B */ #define TT_UCR_LATIN_EXTENDED_B (1L << 3) /* U+0180-U+024F */ /* Bit 4 IPA Extensions */ /* Phonetic Extensions */ /* Phonetic Extensions Supplement */ #define TT_UCR_IPA_EXTENSIONS (1L << 4) /* U+0250-U+02AF */ /* U+1D00-U+1D7F */ /* U+1D80-U+1DBF */ /* Bit 5 Spacing Modifier Letters */ /* Modifier Tone Letters */ #define TT_UCR_SPACING_MODIFIER (1L << 5) /* U+02B0-U+02FF */ /* U+A700-U+A71F */ /* Bit 6 Combining Diacritical Marks */ /* Combining Diacritical Marks Supplement */ #define TT_UCR_COMBINING_DIACRITICS (1L << 6) /* U+0300-U+036F */ /* U+1DC0-U+1DFF */ /* Bit 7 Greek and Coptic */ #define TT_UCR_GREEK (1L << 7) /* U+0370-U+03FF */ /* Bit 8 Coptic */ #define TT_UCR_COPTIC (1L << 8) /* U+2C80-U+2CFF */ /* Bit 9 Cyrillic */ /* Cyrillic Supplement */ /* Cyrillic Extended-A */ /* Cyrillic Extended-B */ #define TT_UCR_CYRILLIC (1L << 9) /* U+0400-U+04FF */ /* U+0500-U+052F */ /* U+2DE0-U+2DFF */ /* U+A640-U+A69F */ /* Bit 10 Armenian */ #define TT_UCR_ARMENIAN (1L << 10) /* U+0530-U+058F */ /* Bit 11 Hebrew */ #define TT_UCR_HEBREW (1L << 11) /* U+0590-U+05FF */ /* Bit 12 Vai */ #define TT_UCR_VAI (1L << 12) /* U+A500-U+A63F */ /* Bit 13 Arabic */ /* Arabic Supplement */ #define TT_UCR_ARABIC (1L << 13) /* U+0600-U+06FF */ /* U+0750-U+077F */ /* Bit 14 NKo */ #define TT_UCR_NKO (1L << 14) /* U+07C0-U+07FF */ /* Bit 15 Devanagari */ #define TT_UCR_DEVANAGARI (1L << 15) /* U+0900-U+097F */ /* Bit 16 Bengali */ #define TT_UCR_BENGALI (1L << 16) /* U+0980-U+09FF */ /* Bit 17 Gurmukhi */ #define TT_UCR_GURMUKHI (1L << 17) /* U+0A00-U+0A7F */ /* Bit 18 Gujarati */ #define TT_UCR_GUJARATI (1L << 18) /* U+0A80-U+0AFF */ /* Bit 19 Oriya */ #define TT_UCR_ORIYA (1L << 19) /* U+0B00-U+0B7F */ /* Bit 20 Tamil */ #define TT_UCR_TAMIL (1L << 20) /* U+0B80-U+0BFF */ /* Bit 21 Telugu */ #define TT_UCR_TELUGU (1L << 21) /* U+0C00-U+0C7F */ /* Bit 22 Kannada */ #define TT_UCR_KANNADA (1L << 22) /* U+0C80-U+0CFF */ /* Bit 23 Malayalam */ #define TT_UCR_MALAYALAM (1L << 23) /* U+0D00-U+0D7F */ /* Bit 24 Thai */ #define TT_UCR_THAI (1L << 24) /* U+0E00-U+0E7F */ /* Bit 25 Lao */ #define TT_UCR_LAO (1L << 25) /* U+0E80-U+0EFF */ /* Bit 26 Georgian */ /* Georgian Supplement */ #define TT_UCR_GEORGIAN (1L << 26) /* U+10A0-U+10FF */ /* U+2D00-U+2D2F */ /* Bit 27 Balinese */ #define TT_UCR_BALINESE (1L << 27) /* U+1B00-U+1B7F */ /* Bit 28 Hangul Jamo */ #define TT_UCR_HANGUL_JAMO (1L << 28) /* U+1100-U+11FF */ /* Bit 29 Latin Extended Additional */ /* Latin Extended-C */ /* Latin Extended-D */ #define TT_UCR_LATIN_EXTENDED_ADDITIONAL (1L << 29) /* U+1E00-U+1EFF */ /* U+2C60-U+2C7F */ /* U+A720-U+A7FF */ /* Bit 30 Greek Extended */ #define TT_UCR_GREEK_EXTENDED (1L << 30) /* U+1F00-U+1FFF */ /* Bit 31 General Punctuation */ /* Supplemental Punctuation */ #define TT_UCR_GENERAL_PUNCTUATION (1L << 31) /* U+2000-U+206F */ /* U+2E00-U+2E7F */ /* Bit 32 Superscripts And Subscripts */ #define TT_UCR_SUPERSCRIPTS_SUBSCRIPTS (1L << 0) /* U+2070-U+209F */ /* Bit 33 Currency Symbols */ #define TT_UCR_CURRENCY_SYMBOLS (1L << 1) /* U+20A0-U+20CF */ /* Bit 34 Combining Diacritical Marks For Symbols */ #define TT_UCR_COMBINING_DIACRITICS_SYMB (1L << 2) /* U+20D0-U+20FF */ /* Bit 35 Letterlike Symbols */ #define TT_UCR_LETTERLIKE_SYMBOLS (1L << 3) /* U+2100-U+214F */ /* Bit 36 Number Forms */ #define TT_UCR_NUMBER_FORMS (1L << 4) /* U+2150-U+218F */ /* Bit 37 Arrows */ /* Supplemental Arrows-A */ /* Supplemental Arrows-B */ /* Miscellaneous Symbols and Arrows */ #define TT_UCR_ARROWS (1L << 5) /* U+2190-U+21FF */ /* U+27F0-U+27FF */ /* U+2900-U+297F */ /* U+2B00-U+2BFF */ /* Bit 38 Mathematical Operators */ /* Supplemental Mathematical Operators */ /* Miscellaneous Mathematical Symbols-A */ /* Miscellaneous Mathematical Symbols-B */ #define TT_UCR_MATHEMATICAL_OPERATORS (1L << 6) /* U+2200-U+22FF */ /* U+2A00-U+2AFF */ /* U+27C0-U+27EF */ /* U+2980-U+29FF */ /* Bit 39 Miscellaneous Technical */ #define TT_UCR_MISCELLANEOUS_TECHNICAL (1L << 7) /* U+2300-U+23FF */ /* Bit 40 Control Pictures */ #define TT_UCR_CONTROL_PICTURES (1L << 8) /* U+2400-U+243F */ /* Bit 41 Optical Character Recognition */ #define TT_UCR_OCR (1L << 9) /* U+2440-U+245F */ /* Bit 42 Enclosed Alphanumerics */ #define TT_UCR_ENCLOSED_ALPHANUMERICS (1L << 10) /* U+2460-U+24FF */ /* Bit 43 Box Drawing */ #define TT_UCR_BOX_DRAWING (1L << 11) /* U+2500-U+257F */ /* Bit 44 Block Elements */ #define TT_UCR_BLOCK_ELEMENTS (1L << 12) /* U+2580-U+259F */ /* Bit 45 Geometric Shapes */ #define TT_UCR_GEOMETRIC_SHAPES (1L << 13) /* U+25A0-U+25FF */ /* Bit 46 Miscellaneous Symbols */ #define TT_UCR_MISCELLANEOUS_SYMBOLS (1L << 14) /* U+2600-U+26FF */ /* Bit 47 Dingbats */ #define TT_UCR_DINGBATS (1L << 15) /* U+2700-U+27BF */ /* Bit 48 CJK Symbols and Punctuation */ #define TT_UCR_CJK_SYMBOLS (1L << 16) /* U+3000-U+303F */ /* Bit 49 Hiragana */ #define TT_UCR_HIRAGANA (1L << 17) /* U+3040-U+309F */ /* Bit 50 Katakana */ /* Katakana Phonetic Extensions */ #define TT_UCR_KATAKANA (1L << 18) /* U+30A0-U+30FF */ /* U+31F0-U+31FF */ /* Bit 51 Bopomofo */ /* Bopomofo Extended */ #define TT_UCR_BOPOMOFO (1L << 19) /* U+3100-U+312F */ /* U+31A0-U+31BF */ /* Bit 52 Hangul Compatibility Jamo */ #define TT_UCR_HANGUL_COMPATIBILITY_JAMO (1L << 20) /* U+3130-U+318F */ /* Bit 53 Phags-Pa */ #define TT_UCR_CJK_MISC (1L << 21) /* U+A840-U+A87F */ #define TT_UCR_KANBUN TT_UCR_CJK_MISC /* deprecated */ #define TT_UCR_PHAGSPA /* Bit 54 Enclosed CJK Letters and Months */ #define TT_UCR_ENCLOSED_CJK_LETTERS_MONTHS (1L << 22) /* U+3200-U+32FF */ /* Bit 55 CJK Compatibility */ #define TT_UCR_CJK_COMPATIBILITY (1L << 23) /* U+3300-U+33FF */ /* Bit 56 Hangul Syllables */ #define TT_UCR_HANGUL (1L << 24) /* U+AC00-U+D7A3 */ /* Bit 57 High Surrogates */ /* High Private Use Surrogates */ /* Low Surrogates */ /* */ /* According to OpenType specs v.1.3+, */ /* setting bit 57 implies that there is */ /* at least one codepoint beyond the */ /* Basic Multilingual Plane that is */ /* supported by this font. So it really */ /* means >= U+10000 */ #define TT_UCR_SURROGATES (1L << 25) /* U+D800-U+DB7F */ /* U+DB80-U+DBFF */ /* U+DC00-U+DFFF */ #define TT_UCR_NON_PLANE_0 TT_UCR_SURROGATES /* Bit 58 Phoenician */ #define TT_UCR_PHOENICIAN (1L << 26) /*U+10900-U+1091F*/ /* Bit 59 CJK Unified Ideographs */ /* CJK Radicals Supplement */ /* Kangxi Radicals */ /* Ideographic Description Characters */ /* CJK Unified Ideographs Extension A */ /* CJK Unified Ideographs Extension B */ /* Kanbun */ #define TT_UCR_CJK_UNIFIED_IDEOGRAPHS (1L << 27) /* U+4E00-U+9FFF */ /* U+2E80-U+2EFF */ /* U+2F00-U+2FDF */ /* U+2FF0-U+2FFF */ /* U+3400-U+4DB5 */ /*U+20000-U+2A6DF*/ /* U+3190-U+319F */ /* Bit 60 Private Use */ #define TT_UCR_PRIVATE_USE (1L << 28) /* U+E000-U+F8FF */ /* Bit 61 CJK Strokes */ /* CJK Compatibility Ideographs */ /* CJK Compatibility Ideographs Supplement */ #define TT_UCR_CJK_COMPATIBILITY_IDEOGRAPHS (1L << 29) /* U+31C0-U+31EF */ /* U+F900-U+FAFF */ /*U+2F800-U+2FA1F*/ /* Bit 62 Alphabetic Presentation Forms */ #define TT_UCR_ALPHABETIC_PRESENTATION_FORMS (1L << 30) /* U+FB00-U+FB4F */ /* Bit 63 Arabic Presentation Forms-A */ #define TT_UCR_ARABIC_PRESENTATIONS_A (1L << 31) /* U+FB50-U+FDFF */ /* Bit 64 Combining Half Marks */ #define TT_UCR_COMBINING_HALF_MARKS (1L << 0) /* U+FE20-U+FE2F */ /* Bit 65 Vertical forms */ /* CJK Compatibility Forms */ #define TT_UCR_CJK_COMPATIBILITY_FORMS (1L << 1) /* U+FE10-U+FE1F */ /* U+FE30-U+FE4F */ /* Bit 66 Small Form Variants */ #define TT_UCR_SMALL_FORM_VARIANTS (1L << 2) /* U+FE50-U+FE6F */ /* Bit 67 Arabic Presentation Forms-B */ #define TT_UCR_ARABIC_PRESENTATIONS_B (1L << 3) /* U+FE70-U+FEFE */ /* Bit 68 Halfwidth and Fullwidth Forms */ #define TT_UCR_HALFWIDTH_FULLWIDTH_FORMS (1L << 4) /* U+FF00-U+FFEF */ /* Bit 69 Specials */ #define TT_UCR_SPECIALS (1L << 5) /* U+FFF0-U+FFFD */ /* Bit 70 Tibetan */ #define TT_UCR_TIBETAN (1L << 6) /* U+0F00-U+0FFF */ /* Bit 71 Syriac */ #define TT_UCR_SYRIAC (1L << 7) /* U+0700-U+074F */ /* Bit 72 Thaana */ #define TT_UCR_THAANA (1L << 8) /* U+0780-U+07BF */ /* Bit 73 Sinhala */ #define TT_UCR_SINHALA (1L << 9) /* U+0D80-U+0DFF */ /* Bit 74 Myanmar */ #define TT_UCR_MYANMAR (1L << 10) /* U+1000-U+109F */ /* Bit 75 Ethiopic */ /* Ethiopic Supplement */ /* Ethiopic Extended */ #define TT_UCR_ETHIOPIC (1L << 11) /* U+1200-U+137F */ /* U+1380-U+139F */ /* U+2D80-U+2DDF */ /* Bit 76 Cherokee */ #define TT_UCR_CHEROKEE (1L << 12) /* U+13A0-U+13FF */ /* Bit 77 Unified Canadian Aboriginal Syllabics */ #define TT_UCR_CANADIAN_ABORIGINAL_SYLLABICS (1L << 13) /* U+1400-U+167F */ /* Bit 78 Ogham */ #define TT_UCR_OGHAM (1L << 14) /* U+1680-U+169F */ /* Bit 79 Runic */ #define TT_UCR_RUNIC (1L << 15) /* U+16A0-U+16FF */ /* Bit 80 Khmer */ /* Khmer Symbols */ #define TT_UCR_KHMER (1L << 16) /* U+1780-U+17FF */ /* U+19E0-U+19FF */ /* Bit 81 Mongolian */ #define TT_UCR_MONGOLIAN (1L << 17) /* U+1800-U+18AF */ /* Bit 82 Braille Patterns */ #define TT_UCR_BRAILLE (1L << 18) /* U+2800-U+28FF */ /* Bit 83 Yi Syllables */ /* Yi Radicals */ #define TT_UCR_YI (1L << 19) /* U+A000-U+A48F */ /* U+A490-U+A4CF */ /* Bit 84 Tagalog */ /* Hanunoo */ /* Buhid */ /* Tagbanwa */ #define TT_UCR_PHILIPPINE (1L << 20) /* U+1700-U+171F */ /* U+1720-U+173F */ /* U+1740-U+175F */ /* U+1760-U+177F */ /* Bit 85 Old Italic */ #define TT_UCR_OLD_ITALIC (1L << 21) /*U+10300-U+1032F*/ /* Bit 86 Gothic */ #define TT_UCR_GOTHIC (1L << 22) /*U+10330-U+1034F*/ /* Bit 87 Deseret */ #define TT_UCR_DESERET (1L << 23) /*U+10400-U+1044F*/ /* Bit 88 Byzantine Musical Symbols */ /* Musical Symbols */ /* Ancient Greek Musical Notation */ #define TT_UCR_MUSICAL_SYMBOLS (1L << 24) /*U+1D000-U+1D0FF*/ /*U+1D100-U+1D1FF*/ /*U+1D200-U+1D24F*/ /* Bit 89 Mathematical Alphanumeric Symbols */ #define TT_UCR_MATH_ALPHANUMERIC_SYMBOLS (1L << 25) /*U+1D400-U+1D7FF*/ /* Bit 90 Private Use (plane 15) */ /* Private Use (plane 16) */ #define TT_UCR_PRIVATE_USE_SUPPLEMENTARY (1L << 26) /*U+F0000-U+FFFFD*/ /*U+100000-U+10FFFD*/ /* Bit 91 Variation Selectors */ /* Variation Selectors Supplement */ #define TT_UCR_VARIATION_SELECTORS (1L << 27) /* U+FE00-U+FE0F */ /*U+E0100-U+E01EF*/ /* Bit 92 Tags */ #define TT_UCR_TAGS (1L << 28) /*U+E0000-U+E007F*/ /* Bit 93 Limbu */ #define TT_UCR_LIMBU (1L << 29) /* U+1900-U+194F */ /* Bit 94 Tai Le */ #define TT_UCR_TAI_LE (1L << 30) /* U+1950-U+197F */ /* Bit 95 New Tai Lue */ #define TT_UCR_NEW_TAI_LUE (1L << 31) /* U+1980-U+19DF */ /* Bit 96 Buginese */ #define TT_UCR_BUGINESE (1L << 0) /* U+1A00-U+1A1F */ /* Bit 97 Glagolitic */ #define TT_UCR_GLAGOLITIC (1L << 1) /* U+2C00-U+2C5F */ /* Bit 98 Tifinagh */ #define TT_UCR_TIFINAGH (1L << 2) /* U+2D30-U+2D7F */ /* Bit 99 Yijing Hexagram Symbols */ #define TT_UCR_YIJING (1L << 3) /* U+4DC0-U+4DFF */ /* Bit 100 Syloti Nagri */ #define TT_UCR_SYLOTI_NAGRI (1L << 4) /* U+A800-U+A82F */ /* Bit 101 Linear B Syllabary */ /* Linear B Ideograms */ /* Aegean Numbers */ #define TT_UCR_LINEAR_B (1L << 5) /*U+10000-U+1007F*/ /*U+10080-U+100FF*/ /*U+10100-U+1013F*/ /* Bit 102 Ancient Greek Numbers */ #define TT_UCR_ANCIENT_GREEK_NUMBERS (1L << 6) /*U+10140-U+1018F*/ /* Bit 103 Ugaritic */ #define TT_UCR_UGARITIC (1L << 7) /*U+10380-U+1039F*/ /* Bit 104 Old Persian */ #define TT_UCR_OLD_PERSIAN (1L << 8) /*U+103A0-U+103DF*/ /* Bit 105 Shavian */ #define TT_UCR_SHAVIAN (1L << 9) /*U+10450-U+1047F*/ /* Bit 106 Osmanya */ #define TT_UCR_OSMANYA (1L << 10) /*U+10480-U+104AF*/ /* Bit 107 Cypriot Syllabary */ #define TT_UCR_CYPRIOT_SYLLABARY (1L << 11) /*U+10800-U+1083F*/ /* Bit 108 Kharoshthi */ #define TT_UCR_KHAROSHTHI (1L << 12) /*U+10A00-U+10A5F*/ /* Bit 109 Tai Xuan Jing Symbols */ #define TT_UCR_TAI_XUAN_JING (1L << 13) /*U+1D300-U+1D35F*/ /* Bit 110 Cuneiform */ /* Cuneiform Numbers and Punctuation */ #define TT_UCR_CUNEIFORM (1L << 14) /*U+12000-U+123FF*/ /*U+12400-U+1247F*/ /* Bit 111 Counting Rod Numerals */ #define TT_UCR_COUNTING_ROD_NUMERALS (1L << 15) /*U+1D360-U+1D37F*/ /* Bit 112 Sundanese */ #define TT_UCR_SUNDANESE (1L << 16) /* U+1B80-U+1BBF */ /* Bit 113 Lepcha */ #define TT_UCR_LEPCHA (1L << 17) /* U+1C00-U+1C4F */ /* Bit 114 Ol Chiki */ #define TT_UCR_OL_CHIKI (1L << 18) /* U+1C50-U+1C7F */ /* Bit 115 Saurashtra */ #define TT_UCR_SAURASHTRA (1L << 19) /* U+A880-U+A8DF */ /* Bit 116 Kayah Li */ #define TT_UCR_KAYAH_LI (1L << 20) /* U+A900-U+A92F */ /* Bit 117 Rejang */ #define TT_UCR_REJANG (1L << 21) /* U+A930-U+A95F */ /* Bit 118 Cham */ #define TT_UCR_CHAM (1L << 22) /* U+AA00-U+AA5F */ /* Bit 119 Ancient Symbols */ #define TT_UCR_ANCIENT_SYMBOLS (1L << 23) /*U+10190-U+101CF*/ /* Bit 120 Phaistos Disc */ #define TT_UCR_PHAISTOS_DISC (1L << 24) /*U+101D0-U+101FF*/ /* Bit 121 Carian */ /* Lycian */ /* Lydian */ #define TT_UCR_OLD_ANATOLIAN (1L << 25) /*U+102A0-U+102DF*/ /*U+10280-U+1029F*/ /*U+10920-U+1093F*/ /* Bit 122 Domino Tiles */ /* Mahjong Tiles */ #define TT_UCR_GAME_TILES (1L << 26) /*U+1F030-U+1F09F*/ /*U+1F000-U+1F02F*/ /* Bit 123-127 Reserved for process-internal usage */ /*************************************************************************/ /* */ /* Some compilers have a very limited length of identifiers. */ /* */ #if defined( __TURBOC__ ) && __TURBOC__ < 0x0410 || defined( __PACIFIC__ ) #define HAVE_LIMIT_ON_IDENTS #endif #ifndef HAVE_LIMIT_ON_IDENTS /*************************************************************************/ /* */ /* Here some alias #defines in order to be clearer. */ /* */ /* These are not always #defined to stay within the 31~character limit */ /* which some compilers have. */ /* */ /* Credits go to Dave Hoo <dhoo@flash.net> for pointing out that modern */ /* Borland compilers (read: from BC++ 3.1 on) can increase this limit. */ /* If you get a warning with such a compiler, use the -i40 switch. */ /* */ #define TT_UCR_ARABIC_PRESENTATION_FORMS_A \ TT_UCR_ARABIC_PRESENTATIONS_A #define TT_UCR_ARABIC_PRESENTATION_FORMS_B \ TT_UCR_ARABIC_PRESENTATIONS_B #define TT_UCR_COMBINING_DIACRITICAL_MARKS \ TT_UCR_COMBINING_DIACRITICS #define TT_UCR_COMBINING_DIACRITICAL_MARKS_SYMB \ TT_UCR_COMBINING_DIACRITICS_SYMB #endif /* !HAVE_LIMIT_ON_IDENTS */ FT_END_HEADER #endif /* __TTNAMEID_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/tttables.h ================================================ /***************************************************************************/ /* */ /* tttables.h */ /* */ /* Basic SFNT/TrueType tables definitions and interface */ /* (specification only). */ /* */ /* Copyright 1996-2005, 2008-2011 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __TTTABLES_H__ #define __TTTABLES_H__ #include <ft2build.h> #include FT_FREETYPE_H #ifdef FREETYPE_H #error "freetype.h of FreeType 1 has been loaded!" #error "Please fix the directory search order for header files" #error "so that freetype.h of FreeType 2 is found first." #endif FT_BEGIN_HEADER /*************************************************************************/ /* */ /* <Section> */ /* truetype_tables */ /* */ /* <Title> */ /* TrueType Tables */ /* */ /* <Abstract> */ /* TrueType specific table types and functions. */ /* */ /* <Description> */ /* This section contains the definition of TrueType-specific tables */ /* as well as some routines used to access and process them. */ /* */ /*************************************************************************/ /*************************************************************************/ /* */ /* <Struct> */ /* TT_Header */ /* */ /* <Description> */ /* A structure used to model a TrueType font header table. All */ /* fields follow the TrueType specification. */ /* */ typedef struct TT_Header_ { FT_Fixed Table_Version; FT_Fixed Font_Revision; FT_Long CheckSum_Adjust; FT_Long Magic_Number; FT_UShort Flags; FT_UShort Units_Per_EM; FT_Long Created [2]; FT_Long Modified[2]; FT_Short xMin; FT_Short yMin; FT_Short xMax; FT_Short yMax; FT_UShort Mac_Style; FT_UShort Lowest_Rec_PPEM; FT_Short Font_Direction; FT_Short Index_To_Loc_Format; FT_Short Glyph_Data_Format; } TT_Header; /*************************************************************************/ /* */ /* <Struct> */ /* TT_HoriHeader */ /* */ /* <Description> */ /* A structure used to model a TrueType horizontal header, the `hhea' */ /* table, as well as the corresponding horizontal metrics table, */ /* i.e., the `hmtx' table. */ /* */ /* <Fields> */ /* Version :: The table version. */ /* */ /* Ascender :: The font's ascender, i.e., the distance */ /* from the baseline to the top-most of all */ /* glyph points found in the font. */ /* */ /* This value is invalid in many fonts, as */ /* it is usually set by the font designer, */ /* and often reflects only a portion of the */ /* glyphs found in the font (maybe ASCII). */ /* */ /* You should use the `sTypoAscender' field */ /* of the OS/2 table instead if you want */ /* the correct one. */ /* */ /* Descender :: The font's descender, i.e., the distance */ /* from the baseline to the bottom-most of */ /* all glyph points found in the font. It */ /* is negative. */ /* */ /* This value is invalid in many fonts, as */ /* it is usually set by the font designer, */ /* and often reflects only a portion of the */ /* glyphs found in the font (maybe ASCII). */ /* */ /* You should use the `sTypoDescender' */ /* field of the OS/2 table instead if you */ /* want the correct one. */ /* */ /* Line_Gap :: The font's line gap, i.e., the distance */ /* to add to the ascender and descender to */ /* get the BTB, i.e., the */ /* baseline-to-baseline distance for the */ /* font. */ /* */ /* advance_Width_Max :: This field is the maximum of all advance */ /* widths found in the font. It can be */ /* used to compute the maximum width of an */ /* arbitrary string of text. */ /* */ /* min_Left_Side_Bearing :: The minimum left side bearing of all */ /* glyphs within the font. */ /* */ /* min_Right_Side_Bearing :: The minimum right side bearing of all */ /* glyphs within the font. */ /* */ /* xMax_Extent :: The maximum horizontal extent (i.e., the */ /* `width' of a glyph's bounding box) for */ /* all glyphs in the font. */ /* */ /* caret_Slope_Rise :: The rise coefficient of the cursor's */ /* slope of the cursor (slope=rise/run). */ /* */ /* caret_Slope_Run :: The run coefficient of the cursor's */ /* slope. */ /* */ /* Reserved :: 8~reserved bytes. */ /* */ /* metric_Data_Format :: Always~0. */ /* */ /* number_Of_HMetrics :: Number of HMetrics entries in the `hmtx' */ /* table -- this value can be smaller than */ /* the total number of glyphs in the font. */ /* */ /* long_metrics :: A pointer into the `hmtx' table. */ /* */ /* short_metrics :: A pointer into the `hmtx' table. */ /* */ /* <Note> */ /* IMPORTANT: The TT_HoriHeader and TT_VertHeader structures should */ /* be identical except for the names of their fields which */ /* are different. */ /* */ /* This ensures that a single function in the `ttload' */ /* module is able to read both the horizontal and vertical */ /* headers. */ /* */ typedef struct TT_HoriHeader_ { FT_Fixed Version; FT_Short Ascender; FT_Short Descender; FT_Short Line_Gap; FT_UShort advance_Width_Max; /* advance width maximum */ FT_Short min_Left_Side_Bearing; /* minimum left-sb */ FT_Short min_Right_Side_Bearing; /* minimum right-sb */ FT_Short xMax_Extent; /* xmax extents */ FT_Short caret_Slope_Rise; FT_Short caret_Slope_Run; FT_Short caret_Offset; FT_Short Reserved[4]; FT_Short metric_Data_Format; FT_UShort number_Of_HMetrics; /* The following fields are not defined by the TrueType specification */ /* but they are used to connect the metrics header to the relevant */ /* `HMTX' table. */ void* long_metrics; void* short_metrics; } TT_HoriHeader; /*************************************************************************/ /* */ /* <Struct> */ /* TT_VertHeader */ /* */ /* <Description> */ /* A structure used to model a TrueType vertical header, the `vhea' */ /* table, as well as the corresponding vertical metrics table, i.e., */ /* the `vmtx' table. */ /* */ /* <Fields> */ /* Version :: The table version. */ /* */ /* Ascender :: The font's ascender, i.e., the distance */ /* from the baseline to the top-most of */ /* all glyph points found in the font. */ /* */ /* This value is invalid in many fonts, as */ /* it is usually set by the font designer, */ /* and often reflects only a portion of */ /* the glyphs found in the font (maybe */ /* ASCII). */ /* */ /* You should use the `sTypoAscender' */ /* field of the OS/2 table instead if you */ /* want the correct one. */ /* */ /* Descender :: The font's descender, i.e., the */ /* distance from the baseline to the */ /* bottom-most of all glyph points found */ /* in the font. It is negative. */ /* */ /* This value is invalid in many fonts, as */ /* it is usually set by the font designer, */ /* and often reflects only a portion of */ /* the glyphs found in the font (maybe */ /* ASCII). */ /* */ /* You should use the `sTypoDescender' */ /* field of the OS/2 table instead if you */ /* want the correct one. */ /* */ /* Line_Gap :: The font's line gap, i.e., the distance */ /* to add to the ascender and descender to */ /* get the BTB, i.e., the */ /* baseline-to-baseline distance for the */ /* font. */ /* */ /* advance_Height_Max :: This field is the maximum of all */ /* advance heights found in the font. It */ /* can be used to compute the maximum */ /* height of an arbitrary string of text. */ /* */ /* min_Top_Side_Bearing :: The minimum top side bearing of all */ /* glyphs within the font. */ /* */ /* min_Bottom_Side_Bearing :: The minimum bottom side bearing of all */ /* glyphs within the font. */ /* */ /* yMax_Extent :: The maximum vertical extent (i.e., the */ /* `height' of a glyph's bounding box) for */ /* all glyphs in the font. */ /* */ /* caret_Slope_Rise :: The rise coefficient of the cursor's */ /* slope of the cursor (slope=rise/run). */ /* */ /* caret_Slope_Run :: The run coefficient of the cursor's */ /* slope. */ /* */ /* caret_Offset :: The cursor's offset for slanted fonts. */ /* This value is `reserved' in vmtx */ /* version 1.0. */ /* */ /* Reserved :: 8~reserved bytes. */ /* */ /* metric_Data_Format :: Always~0. */ /* */ /* number_Of_HMetrics :: Number of VMetrics entries in the */ /* `vmtx' table -- this value can be */ /* smaller than the total number of glyphs */ /* in the font. */ /* */ /* long_metrics :: A pointer into the `vmtx' table. */ /* */ /* short_metrics :: A pointer into the `vmtx' table. */ /* */ /* <Note> */ /* IMPORTANT: The TT_HoriHeader and TT_VertHeader structures should */ /* be identical except for the names of their fields which */ /* are different. */ /* */ /* This ensures that a single function in the `ttload' */ /* module is able to read both the horizontal and vertical */ /* headers. */ /* */ typedef struct TT_VertHeader_ { FT_Fixed Version; FT_Short Ascender; FT_Short Descender; FT_Short Line_Gap; FT_UShort advance_Height_Max; /* advance height maximum */ FT_Short min_Top_Side_Bearing; /* minimum left-sb or top-sb */ FT_Short min_Bottom_Side_Bearing; /* minimum right-sb or bottom-sb */ FT_Short yMax_Extent; /* xmax or ymax extents */ FT_Short caret_Slope_Rise; FT_Short caret_Slope_Run; FT_Short caret_Offset; FT_Short Reserved[4]; FT_Short metric_Data_Format; FT_UShort number_Of_VMetrics; /* The following fields are not defined by the TrueType specification */ /* but they're used to connect the metrics header to the relevant */ /* `HMTX' or `VMTX' table. */ void* long_metrics; void* short_metrics; } TT_VertHeader; /*************************************************************************/ /* */ /* <Struct> */ /* TT_OS2 */ /* */ /* <Description> */ /* A structure used to model a TrueType OS/2 table. This is the long */ /* table version. All fields comply to the TrueType specification. */ /* */ /* Note that we now support old Mac fonts which do not include an */ /* OS/2 table. In this case, the `version' field is always set to */ /* 0xFFFF. */ /* */ typedef struct TT_OS2_ { FT_UShort version; /* 0x0001 - more or 0xFFFF */ FT_Short xAvgCharWidth; FT_UShort usWeightClass; FT_UShort usWidthClass; FT_Short fsType; FT_Short ySubscriptXSize; FT_Short ySubscriptYSize; FT_Short ySubscriptXOffset; FT_Short ySubscriptYOffset; FT_Short ySuperscriptXSize; FT_Short ySuperscriptYSize; FT_Short ySuperscriptXOffset; FT_Short ySuperscriptYOffset; FT_Short yStrikeoutSize; FT_Short yStrikeoutPosition; FT_Short sFamilyClass; FT_Byte panose[10]; FT_ULong ulUnicodeRange1; /* Bits 0-31 */ FT_ULong ulUnicodeRange2; /* Bits 32-63 */ FT_ULong ulUnicodeRange3; /* Bits 64-95 */ FT_ULong ulUnicodeRange4; /* Bits 96-127 */ FT_Char achVendID[4]; FT_UShort fsSelection; FT_UShort usFirstCharIndex; FT_UShort usLastCharIndex; FT_Short sTypoAscender; FT_Short sTypoDescender; FT_Short sTypoLineGap; FT_UShort usWinAscent; FT_UShort usWinDescent; /* only version 1 tables: */ FT_ULong ulCodePageRange1; /* Bits 0-31 */ FT_ULong ulCodePageRange2; /* Bits 32-63 */ /* only version 2 tables: */ FT_Short sxHeight; FT_Short sCapHeight; FT_UShort usDefaultChar; FT_UShort usBreakChar; FT_UShort usMaxContext; } TT_OS2; /*************************************************************************/ /* */ /* <Struct> */ /* TT_Postscript */ /* */ /* <Description> */ /* A structure used to model a TrueType PostScript table. All fields */ /* comply to the TrueType specification. This structure does not */ /* reference the PostScript glyph names, which can be nevertheless */ /* accessed with the `ttpost' module. */ /* */ typedef struct TT_Postscript_ { FT_Fixed FormatType; FT_Fixed italicAngle; FT_Short underlinePosition; FT_Short underlineThickness; FT_ULong isFixedPitch; FT_ULong minMemType42; FT_ULong maxMemType42; FT_ULong minMemType1; FT_ULong maxMemType1; /* Glyph names follow in the file, but we don't */ /* load them by default. See the ttpost.c file. */ } TT_Postscript; /*************************************************************************/ /* */ /* <Struct> */ /* TT_PCLT */ /* */ /* <Description> */ /* A structure used to model a TrueType PCLT table. All fields */ /* comply to the TrueType specification. */ /* */ typedef struct TT_PCLT_ { FT_Fixed Version; FT_ULong FontNumber; FT_UShort Pitch; FT_UShort xHeight; FT_UShort Style; FT_UShort TypeFamily; FT_UShort CapHeight; FT_UShort SymbolSet; FT_Char TypeFace[16]; FT_Char CharacterComplement[8]; FT_Char FileName[6]; FT_Char StrokeWeight; FT_Char WidthType; FT_Byte SerifStyle; FT_Byte Reserved; } TT_PCLT; /*************************************************************************/ /* */ /* <Struct> */ /* TT_MaxProfile */ /* */ /* <Description> */ /* The maximum profile is a table containing many max values which */ /* can be used to pre-allocate arrays. This ensures that no memory */ /* allocation occurs during a glyph load. */ /* */ /* <Fields> */ /* version :: The version number. */ /* */ /* numGlyphs :: The number of glyphs in this TrueType */ /* font. */ /* */ /* maxPoints :: The maximum number of points in a */ /* non-composite TrueType glyph. See also */ /* the structure element */ /* `maxCompositePoints'. */ /* */ /* maxContours :: The maximum number of contours in a */ /* non-composite TrueType glyph. See also */ /* the structure element */ /* `maxCompositeContours'. */ /* */ /* maxCompositePoints :: The maximum number of points in a */ /* composite TrueType glyph. See also the */ /* structure element `maxPoints'. */ /* */ /* maxCompositeContours :: The maximum number of contours in a */ /* composite TrueType glyph. See also the */ /* structure element `maxContours'. */ /* */ /* maxZones :: The maximum number of zones used for */ /* glyph hinting. */ /* */ /* maxTwilightPoints :: The maximum number of points in the */ /* twilight zone used for glyph hinting. */ /* */ /* maxStorage :: The maximum number of elements in the */ /* storage area used for glyph hinting. */ /* */ /* maxFunctionDefs :: The maximum number of function */ /* definitions in the TrueType bytecode for */ /* this font. */ /* */ /* maxInstructionDefs :: The maximum number of instruction */ /* definitions in the TrueType bytecode for */ /* this font. */ /* */ /* maxStackElements :: The maximum number of stack elements used */ /* during bytecode interpretation. */ /* */ /* maxSizeOfInstructions :: The maximum number of TrueType opcodes */ /* used for glyph hinting. */ /* */ /* maxComponentElements :: The maximum number of simple (i.e., non- */ /* composite) glyphs in a composite glyph. */ /* */ /* maxComponentDepth :: The maximum nesting depth of composite */ /* glyphs. */ /* */ /* <Note> */ /* This structure is only used during font loading. */ /* */ typedef struct TT_MaxProfile_ { FT_Fixed version; FT_UShort numGlyphs; FT_UShort maxPoints; FT_UShort maxContours; FT_UShort maxCompositePoints; FT_UShort maxCompositeContours; FT_UShort maxZones; FT_UShort maxTwilightPoints; FT_UShort maxStorage; FT_UShort maxFunctionDefs; FT_UShort maxInstructionDefs; FT_UShort maxStackElements; FT_UShort maxSizeOfInstructions; FT_UShort maxComponentElements; FT_UShort maxComponentDepth; } TT_MaxProfile; /*************************************************************************/ /* */ /* <Enum> */ /* FT_Sfnt_Tag */ /* */ /* <Description> */ /* An enumeration used to specify the index of an SFNT table. */ /* Used in the @FT_Get_Sfnt_Table API function. */ /* */ typedef enum FT_Sfnt_Tag_ { ft_sfnt_head = 0, /* TT_Header */ ft_sfnt_maxp = 1, /* TT_MaxProfile */ ft_sfnt_os2 = 2, /* TT_OS2 */ ft_sfnt_hhea = 3, /* TT_HoriHeader */ ft_sfnt_vhea = 4, /* TT_VertHeader */ ft_sfnt_post = 5, /* TT_Postscript */ ft_sfnt_pclt = 6, /* TT_PCLT */ sfnt_max /* internal end mark */ } FT_Sfnt_Tag; /* */ /*************************************************************************/ /* */ /* <Function> */ /* FT_Get_Sfnt_Table */ /* */ /* <Description> */ /* Return a pointer to a given SFNT table within a face. */ /* */ /* <Input> */ /* face :: A handle to the source. */ /* */ /* tag :: The index of the SFNT table. */ /* */ /* <Return> */ /* A type-less pointer to the table. This will be~0 in case of */ /* error, or if the corresponding table was not found *OR* loaded */ /* from the file. */ /* */ /* Use a typecast according to `tag' to access the structure */ /* elements. */ /* */ /* <Note> */ /* The table is owned by the face object and disappears with it. */ /* */ /* This function is only useful to access SFNT tables that are loaded */ /* by the sfnt, truetype, and opentype drivers. See @FT_Sfnt_Tag for */ /* a list. */ /* */ FT_EXPORT( void* ) FT_Get_Sfnt_Table( FT_Face face, FT_Sfnt_Tag tag ); /************************************************************************** * * @function: * FT_Load_Sfnt_Table * * @description: * Load any font table into client memory. * * @input: * face :: * A handle to the source face. * * tag :: * The four-byte tag of the table to load. Use the value~0 if you want * to access the whole font file. Otherwise, you can use one of the * definitions found in the @FT_TRUETYPE_TAGS_H file, or forge a new * one with @FT_MAKE_TAG. * * offset :: * The starting offset in the table (or file if tag == 0). * * @output: * buffer :: * The target buffer address. The client must ensure that the memory * array is big enough to hold the data. * * @inout: * length :: * If the `length' parameter is NULL, then try to load the whole table. * Return an error code if it fails. * * Else, if `*length' is~0, exit immediately while returning the * table's (or file) full size in it. * * Else the number of bytes to read from the table or file, from the * starting offset. * * @return: * FreeType error code. 0~means success. * * @note: * If you need to determine the table's length you should first call this * function with `*length' set to~0, as in the following example: * * { * FT_ULong length = 0; * * * error = FT_Load_Sfnt_Table( face, tag, 0, NULL, &length ); * if ( error ) { ... table does not exist ... } * * buffer = malloc( length ); * if ( buffer == NULL ) { ... not enough memory ... } * * error = FT_Load_Sfnt_Table( face, tag, 0, buffer, &length ); * if ( error ) { ... could not load table ... } * } */ FT_EXPORT( FT_Error ) FT_Load_Sfnt_Table( FT_Face face, FT_ULong tag, FT_Long offset, FT_Byte* buffer, FT_ULong* length ); /************************************************************************** * * @function: * FT_Sfnt_Table_Info * * @description: * Return information on an SFNT table. * * @input: * face :: * A handle to the source face. * * table_index :: * The index of an SFNT table. The function returns * FT_Err_Table_Missing for an invalid value. * * @inout: * tag :: * The name tag of the SFNT table. If the value is NULL, `table_index' * is ignored, and `length' returns the number of SFNT tables in the * font. * * @output: * length :: * The length of the SFNT table (or the number of SFNT tables, depending * on `tag'). * * @return: * FreeType error code. 0~means success. * * @note: * SFNT tables with length zero are treated as missing. * */ FT_EXPORT( FT_Error ) FT_Sfnt_Table_Info( FT_Face face, FT_UInt table_index, FT_ULong *tag, FT_ULong *length ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Get_CMap_Language_ID */ /* */ /* <Description> */ /* Return TrueType/sfnt specific cmap language ID. Definitions of */ /* language ID values are in `freetype/ttnameid.h'. */ /* */ /* <Input> */ /* charmap :: */ /* The target charmap. */ /* */ /* <Return> */ /* The language ID of `charmap'. If `charmap' doesn't belong to a */ /* TrueType/sfnt face, just return~0 as the default value. */ /* */ FT_EXPORT( FT_ULong ) FT_Get_CMap_Language_ID( FT_CharMap charmap ); /*************************************************************************/ /* */ /* <Function> */ /* FT_Get_CMap_Format */ /* */ /* <Description> */ /* Return TrueType/sfnt specific cmap format. */ /* */ /* <Input> */ /* charmap :: */ /* The target charmap. */ /* */ /* <Return> */ /* The format of `charmap'. If `charmap' doesn't belong to a */ /* TrueType/sfnt face, return -1. */ /* */ FT_EXPORT( FT_Long ) FT_Get_CMap_Format( FT_CharMap charmap ); /* */ FT_END_HEADER #endif /* __TTTABLES_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/tttags.h ================================================ /***************************************************************************/ /* */ /* tttags.h */ /* */ /* Tags for TrueType and OpenType tables (specification only). */ /* */ /* Copyright 1996-2001, 2004, 2005, 2007, 2008 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __TTAGS_H__ #define __TTAGS_H__ #include <ft2build.h> #include FT_FREETYPE_H #ifdef FREETYPE_H #error "freetype.h of FreeType 1 has been loaded!" #error "Please fix the directory search order for header files" #error "so that freetype.h of FreeType 2 is found first." #endif FT_BEGIN_HEADER #define TTAG_avar FT_MAKE_TAG( 'a', 'v', 'a', 'r' ) #define TTAG_BASE FT_MAKE_TAG( 'B', 'A', 'S', 'E' ) #define TTAG_bdat FT_MAKE_TAG( 'b', 'd', 'a', 't' ) #define TTAG_BDF FT_MAKE_TAG( 'B', 'D', 'F', ' ' ) #define TTAG_bhed FT_MAKE_TAG( 'b', 'h', 'e', 'd' ) #define TTAG_bloc FT_MAKE_TAG( 'b', 'l', 'o', 'c' ) #define TTAG_bsln FT_MAKE_TAG( 'b', 's', 'l', 'n' ) #define TTAG_CFF FT_MAKE_TAG( 'C', 'F', 'F', ' ' ) #define TTAG_CID FT_MAKE_TAG( 'C', 'I', 'D', ' ' ) #define TTAG_cmap FT_MAKE_TAG( 'c', 'm', 'a', 'p' ) #define TTAG_cvar FT_MAKE_TAG( 'c', 'v', 'a', 'r' ) #define TTAG_cvt FT_MAKE_TAG( 'c', 'v', 't', ' ' ) #define TTAG_DSIG FT_MAKE_TAG( 'D', 'S', 'I', 'G' ) #define TTAG_EBDT FT_MAKE_TAG( 'E', 'B', 'D', 'T' ) #define TTAG_EBLC FT_MAKE_TAG( 'E', 'B', 'L', 'C' ) #define TTAG_EBSC FT_MAKE_TAG( 'E', 'B', 'S', 'C' ) #define TTAG_feat FT_MAKE_TAG( 'f', 'e', 'a', 't' ) #define TTAG_FOND FT_MAKE_TAG( 'F', 'O', 'N', 'D' ) #define TTAG_fpgm FT_MAKE_TAG( 'f', 'p', 'g', 'm' ) #define TTAG_fvar FT_MAKE_TAG( 'f', 'v', 'a', 'r' ) #define TTAG_gasp FT_MAKE_TAG( 'g', 'a', 's', 'p' ) #define TTAG_GDEF FT_MAKE_TAG( 'G', 'D', 'E', 'F' ) #define TTAG_glyf FT_MAKE_TAG( 'g', 'l', 'y', 'f' ) #define TTAG_GPOS FT_MAKE_TAG( 'G', 'P', 'O', 'S' ) #define TTAG_GSUB FT_MAKE_TAG( 'G', 'S', 'U', 'B' ) #define TTAG_gvar FT_MAKE_TAG( 'g', 'v', 'a', 'r' ) #define TTAG_hdmx FT_MAKE_TAG( 'h', 'd', 'm', 'x' ) #define TTAG_head FT_MAKE_TAG( 'h', 'e', 'a', 'd' ) #define TTAG_hhea FT_MAKE_TAG( 'h', 'h', 'e', 'a' ) #define TTAG_hmtx FT_MAKE_TAG( 'h', 'm', 't', 'x' ) #define TTAG_JSTF FT_MAKE_TAG( 'J', 'S', 'T', 'F' ) #define TTAG_just FT_MAKE_TAG( 'j', 'u', 's', 't' ) #define TTAG_kern FT_MAKE_TAG( 'k', 'e', 'r', 'n' ) #define TTAG_lcar FT_MAKE_TAG( 'l', 'c', 'a', 'r' ) #define TTAG_loca FT_MAKE_TAG( 'l', 'o', 'c', 'a' ) #define TTAG_LTSH FT_MAKE_TAG( 'L', 'T', 'S', 'H' ) #define TTAG_LWFN FT_MAKE_TAG( 'L', 'W', 'F', 'N' ) #define TTAG_MATH FT_MAKE_TAG( 'M', 'A', 'T', 'H' ) #define TTAG_maxp FT_MAKE_TAG( 'm', 'a', 'x', 'p' ) #define TTAG_META FT_MAKE_TAG( 'M', 'E', 'T', 'A' ) #define TTAG_MMFX FT_MAKE_TAG( 'M', 'M', 'F', 'X' ) #define TTAG_MMSD FT_MAKE_TAG( 'M', 'M', 'S', 'D' ) #define TTAG_mort FT_MAKE_TAG( 'm', 'o', 'r', 't' ) #define TTAG_morx FT_MAKE_TAG( 'm', 'o', 'r', 'x' ) #define TTAG_name FT_MAKE_TAG( 'n', 'a', 'm', 'e' ) #define TTAG_opbd FT_MAKE_TAG( 'o', 'p', 'b', 'd' ) #define TTAG_OS2 FT_MAKE_TAG( 'O', 'S', '/', '2' ) #define TTAG_OTTO FT_MAKE_TAG( 'O', 'T', 'T', 'O' ) #define TTAG_PCLT FT_MAKE_TAG( 'P', 'C', 'L', 'T' ) #define TTAG_POST FT_MAKE_TAG( 'P', 'O', 'S', 'T' ) #define TTAG_post FT_MAKE_TAG( 'p', 'o', 's', 't' ) #define TTAG_prep FT_MAKE_TAG( 'p', 'r', 'e', 'p' ) #define TTAG_prop FT_MAKE_TAG( 'p', 'r', 'o', 'p' ) #define TTAG_sfnt FT_MAKE_TAG( 's', 'f', 'n', 't' ) #define TTAG_SING FT_MAKE_TAG( 'S', 'I', 'N', 'G' ) #define TTAG_trak FT_MAKE_TAG( 't', 'r', 'a', 'k' ) #define TTAG_true FT_MAKE_TAG( 't', 'r', 'u', 'e' ) #define TTAG_ttc FT_MAKE_TAG( 't', 't', 'c', ' ' ) #define TTAG_ttcf FT_MAKE_TAG( 't', 't', 'c', 'f' ) #define TTAG_TYP1 FT_MAKE_TAG( 'T', 'Y', 'P', '1' ) #define TTAG_typ1 FT_MAKE_TAG( 't', 'y', 'p', '1' ) #define TTAG_VDMX FT_MAKE_TAG( 'V', 'D', 'M', 'X' ) #define TTAG_vhea FT_MAKE_TAG( 'v', 'h', 'e', 'a' ) #define TTAG_vmtx FT_MAKE_TAG( 'v', 'm', 't', 'x' ) FT_END_HEADER #endif /* __TTAGS_H__ */ /* END */ ================================================ FILE: other/freetype/include/freetype/ttunpat.h ================================================ /***************************************************************************/ /* */ /* ttunpat.h */ /* */ /* Definitions for the unpatented TrueType hinting system */ /* */ /* Copyright 2003, 2006 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* Written by Graham Asher <graham.asher@btinternet.com> */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #ifndef __TTUNPAT_H__ #define __TTUNPAT_H__ #include <ft2build.h> #include FT_FREETYPE_H #ifdef FREETYPE_H #error "freetype.h of FreeType 1 has been loaded!" #error "Please fix the directory search order for header files" #error "so that freetype.h of FreeType 2 is found first." #endif FT_BEGIN_HEADER /*************************************************************************** * * @constant: * FT_PARAM_TAG_UNPATENTED_HINTING * * @description: * A constant used as the tag of an @FT_Parameter structure to indicate * that unpatented methods only should be used by the TrueType bytecode * interpreter for a typeface opened by @FT_Open_Face. * */ #define FT_PARAM_TAG_UNPATENTED_HINTING FT_MAKE_TAG( 'u', 'n', 'p', 'a' ) /* */ FT_END_HEADER #endif /* __TTUNPAT_H__ */ /* END */ ================================================ FILE: other/freetype/include/ft2build.h ================================================ /***************************************************************************/ /* */ /* ft2build.h */ /* */ /* FreeType 2 build and setup macros. */ /* (Generic version) */ /* */ /* Copyright 1996-2001, 2006 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /*************************************************************************/ /* */ /* This file corresponds to the default `ft2build.h' file for */ /* FreeType 2. It uses the `freetype' include root. */ /* */ /* Note that specific platforms might use a different configuration. */ /* See builds/unix/ft2unix.h for an example. */ /* */ /*************************************************************************/ #ifndef __FT2_BUILD_GENERIC_H__ #define __FT2_BUILD_GENERIC_H__ #include <freetype/config/ftheader.h> #endif /* __FT2_BUILD_GENERIC_H__ */ /* END */ ================================================ FILE: other/icons/teeworlds_cl.rc ================================================ 50h ICON "teeworlds.ico" ================================================ FILE: other/icons/teeworlds_gcc.rc ================================================ ID ICON "teeworlds.ico" ================================================ FILE: other/icons/teeworlds_srv_cl.rc ================================================ 50h ICON "Teeworlds_srv.ico" ================================================ FILE: other/icons/teeworlds_srv_gcc.rc ================================================ ID ICON "Teeworlds_srv.ico" ================================================ FILE: other/sdl/include/SDL.h ================================================ /* SDL - Simple DirectMedia Layer Copyright (C) 1997-2009 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org */ /** @file SDL.h * Main include header for the SDL library */ #ifndef _SDL_H #define _SDL_H #include "SDL_main.h" #include "SDL_stdinc.h" #include "SDL_audio.h" #include "SDL_cdrom.h" #include "SDL_cpuinfo.h" #include "SDL_endian.h" #include "SDL_error.h" #include "SDL_events.h" #include "SDL_loadso.h" #include "SDL_mutex.h" #include "SDL_rwops.h" #include "SDL_thread.h" #include "SDL_timer.h" #include "SDL_video.h" #include "SDL_version.h" #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif /** @file SDL.h * @note As of version 0.5, SDL is loaded dynamically into the application */ /** @name SDL_INIT Flags * These are the flags which may be passed to SDL_Init() -- you should * specify the subsystems which you will be using in your application. */ /*@{*/ #define SDL_INIT_TIMER 0x00000001 #define SDL_INIT_AUDIO 0x00000010 #define SDL_INIT_VIDEO 0x00000020 #define SDL_INIT_CDROM 0x00000100 #define SDL_INIT_JOYSTICK 0x00000200 #define SDL_INIT_NOPARACHUTE 0x00100000 /**< Don't catch fatal signals */ #define SDL_INIT_EVENTTHREAD 0x01000000 /**< Not supported on all OS's */ #define SDL_INIT_EVERYTHING 0x0000FFFF /*@}*/ /** This function loads the SDL dynamically linked library and initializes * the subsystems specified by 'flags' (and those satisfying dependencies) * Unless the SDL_INIT_NOPARACHUTE flag is set, it will install cleanup * signal handlers for some commonly ignored fatal signals (like SIGSEGV) */ extern DECLSPEC int SDLCALL SDL_Init(Uint32 flags); /** This function initializes specific SDL subsystems */ extern DECLSPEC int SDLCALL SDL_InitSubSystem(Uint32 flags); /** This function cleans up specific SDL subsystems */ extern DECLSPEC void SDLCALL SDL_QuitSubSystem(Uint32 flags); /** This function returns mask of the specified subsystems which have * been initialized. * If 'flags' is 0, it returns a mask of all initialized subsystems. */ extern DECLSPEC Uint32 SDLCALL SDL_WasInit(Uint32 flags); /** This function cleans up all initialized subsystems and unloads the * dynamically linked library. You should call it upon all exit conditions. */ extern DECLSPEC void SDLCALL SDL_Quit(void); /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* _SDL_H */ ================================================ FILE: other/sdl/include/SDL_active.h ================================================ /* SDL - Simple DirectMedia Layer Copyright (C) 1997-2009 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org */ /** * @file SDL_active.h * Include file for SDL application focus event handling */ #ifndef _SDL_active_h #define _SDL_active_h #include "SDL_stdinc.h" #include "SDL_error.h" #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif /** @name The available application states */ /*@{*/ #define SDL_APPMOUSEFOCUS 0x01 /**< The app has mouse coverage */ #define SDL_APPINPUTFOCUS 0x02 /**< The app has input focus */ #define SDL_APPACTIVE 0x04 /**< The application is active */ /*@}*/ /* Function prototypes */ /** * This function returns the current state of the application, which is a * bitwise combination of SDL_APPMOUSEFOCUS, SDL_APPINPUTFOCUS, and * SDL_APPACTIVE. If SDL_APPACTIVE is set, then the user is able to * see your application, otherwise it has been iconified or disabled. */ extern DECLSPEC Uint8 SDLCALL SDL_GetAppState(void); /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* _SDL_active_h */ ================================================ FILE: other/sdl/include/SDL_audio.h ================================================ /* SDL - Simple DirectMedia Layer Copyright (C) 1997-2009 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org */ /** * @file SDL_audio.h * Access to the raw audio mixing buffer for the SDL library */ #ifndef _SDL_audio_h #define _SDL_audio_h #include "SDL_stdinc.h" #include "SDL_error.h" #include "SDL_endian.h" #include "SDL_mutex.h" #include "SDL_thread.h" #include "SDL_rwops.h" #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif /** * When filling in the desired audio spec structure, * - 'desired->freq' should be the desired audio frequency in samples-per-second. * - 'desired->format' should be the desired audio format. * - 'desired->samples' is the desired size of the audio buffer, in samples. * This number should be a power of two, and may be adjusted by the audio * driver to a value more suitable for the hardware. Good values seem to * range between 512 and 8096 inclusive, depending on the application and * CPU speed. Smaller values yield faster response time, but can lead * to underflow if the application is doing heavy processing and cannot * fill the audio buffer in time. A stereo sample consists of both right * and left channels in LR ordering. * Note that the number of samples is directly related to time by the * following formula: ms = (samples*1000)/freq * - 'desired->size' is the size in bytes of the audio buffer, and is * calculated by SDL_OpenAudio(). * - 'desired->silence' is the value used to set the buffer to silence, * and is calculated by SDL_OpenAudio(). * - 'desired->callback' should be set to a function that will be called * when the audio device is ready for more data. It is passed a pointer * to the audio buffer, and the length in bytes of the audio buffer. * This function usually runs in a separate thread, and so you should * protect data structures that it accesses by calling SDL_LockAudio() * and SDL_UnlockAudio() in your code. * - 'desired->userdata' is passed as the first parameter to your callback * function. * * @note The calculated values in this structure are calculated by SDL_OpenAudio() * */ typedef struct SDL_AudioSpec { int freq; /**< DSP frequency -- samples per second */ Uint16 format; /**< Audio data format */ Uint8 channels; /**< Number of channels: 1 mono, 2 stereo */ Uint8 silence; /**< Audio buffer silence value (calculated) */ Uint16 samples; /**< Audio buffer size in samples (power of 2) */ Uint16 padding; /**< Necessary for some compile environments */ Uint32 size; /**< Audio buffer size in bytes (calculated) */ /** * This function is called when the audio device needs more data. * * @param[out] stream A pointer to the audio data buffer * @param[in] len The length of the audio buffer in bytes. * * Once the callback returns, the buffer will no longer be valid. * Stereo samples are stored in a LRLRLR ordering. */ void (SDLCALL *callback)(void *userdata, Uint8 *stream, int len); void *userdata; } SDL_AudioSpec; /** * @name Audio format flags * defaults to LSB byte order */ /*@{*/ #define AUDIO_U8 0x0008 /**< Unsigned 8-bit samples */ #define AUDIO_S8 0x8008 /**< Signed 8-bit samples */ #define AUDIO_U16LSB 0x0010 /**< Unsigned 16-bit samples */ #define AUDIO_S16LSB 0x8010 /**< Signed 16-bit samples */ #define AUDIO_U16MSB 0x1010 /**< As above, but big-endian byte order */ #define AUDIO_S16MSB 0x9010 /**< As above, but big-endian byte order */ #define AUDIO_U16 AUDIO_U16LSB #define AUDIO_S16 AUDIO_S16LSB /** * @name Native audio byte ordering */ /*@{*/ #if SDL_BYTEORDER == SDL_LIL_ENDIAN #define AUDIO_U16SYS AUDIO_U16LSB #define AUDIO_S16SYS AUDIO_S16LSB #else #define AUDIO_U16SYS AUDIO_U16MSB #define AUDIO_S16SYS AUDIO_S16MSB #endif /*@}*/ /*@}*/ /** A structure to hold a set of audio conversion filters and buffers */ typedef struct SDL_AudioCVT { int needed; /**< Set to 1 if conversion possible */ Uint16 src_format; /**< Source audio format */ Uint16 dst_format; /**< Target audio format */ double rate_incr; /**< Rate conversion increment */ Uint8 *buf; /**< Buffer to hold entire audio data */ int len; /**< Length of original audio buffer */ int len_cvt; /**< Length of converted audio buffer */ int len_mult; /**< buffer must be len*len_mult big */ double len_ratio; /**< Given len, final size is len*len_ratio */ void (SDLCALL *filters[10])(struct SDL_AudioCVT *cvt, Uint16 format); int filter_index; /**< Current audio conversion function */ } SDL_AudioCVT; /* Function prototypes */ /** * @name Audio Init and Quit * These functions are used internally, and should not be used unless you * have a specific need to specify the audio driver you want to use. * You should normally use SDL_Init() or SDL_InitSubSystem(). */ /*@{*/ extern DECLSPEC int SDLCALL SDL_AudioInit(const char *driver_name); extern DECLSPEC void SDLCALL SDL_AudioQuit(void); /*@}*/ /** * This function fills the given character buffer with the name of the * current audio driver, and returns a pointer to it if the audio driver has * been initialized. It returns NULL if no driver has been initialized. */ extern DECLSPEC char * SDLCALL SDL_AudioDriverName(char *namebuf, int maxlen); /** * This function opens the audio device with the desired parameters, and * returns 0 if successful, placing the actual hardware parameters in the * structure pointed to by 'obtained'. If 'obtained' is NULL, the audio * data passed to the callback function will be guaranteed to be in the * requested format, and will be automatically converted to the hardware * audio format if necessary. This function returns -1 if it failed * to open the audio device, or couldn't set up the audio thread. * * The audio device starts out playing silence when it's opened, and should * be enabled for playing by calling SDL_PauseAudio(0) when you are ready * for your audio callback function to be called. Since the audio driver * may modify the requested size of the audio buffer, you should allocate * any local mixing buffers after you open the audio device. * * @sa SDL_AudioSpec */ extern DECLSPEC int SDLCALL SDL_OpenAudio(SDL_AudioSpec *desired, SDL_AudioSpec *obtained); typedef enum { SDL_AUDIO_STOPPED = 0, SDL_AUDIO_PLAYING, SDL_AUDIO_PAUSED } SDL_audiostatus; /** Get the current audio state */ extern DECLSPEC SDL_audiostatus SDLCALL SDL_GetAudioStatus(void); /** * This function pauses and unpauses the audio callback processing. * It should be called with a parameter of 0 after opening the audio * device to start playing sound. This is so you can safely initialize * data for your callback function after opening the audio device. * Silence will be written to the audio device during the pause. */ extern DECLSPEC void SDLCALL SDL_PauseAudio(int pause_on); /** * This function loads a WAVE from the data source, automatically freeing * that source if 'freesrc' is non-zero. For example, to load a WAVE file, * you could do: * @code SDL_LoadWAV_RW(SDL_RWFromFile("sample.wav", "rb"), 1, ...); @endcode * * If this function succeeds, it returns the given SDL_AudioSpec, * filled with the audio data format of the wave data, and sets * 'audio_buf' to a malloc()'d buffer containing the audio data, * and sets 'audio_len' to the length of that audio buffer, in bytes. * You need to free the audio buffer with SDL_FreeWAV() when you are * done with it. * * This function returns NULL and sets the SDL error message if the * wave file cannot be opened, uses an unknown data format, or is * corrupt. Currently raw and MS-ADPCM WAVE files are supported. */ extern DECLSPEC SDL_AudioSpec * SDLCALL SDL_LoadWAV_RW(SDL_RWops *src, int freesrc, SDL_AudioSpec *spec, Uint8 **audio_buf, Uint32 *audio_len); /** Compatibility convenience function -- loads a WAV from a file */ #define SDL_LoadWAV(file, spec, audio_buf, audio_len) \ SDL_LoadWAV_RW(SDL_RWFromFile(file, "rb"),1, spec,audio_buf,audio_len) /** * This function frees data previously allocated with SDL_LoadWAV_RW() */ extern DECLSPEC void SDLCALL SDL_FreeWAV(Uint8 *audio_buf); /** * This function takes a source format and rate and a destination format * and rate, and initializes the 'cvt' structure with information needed * by SDL_ConvertAudio() to convert a buffer of audio data from one format * to the other. * * @return This function returns 0, or -1 if there was an error. */ extern DECLSPEC int SDLCALL SDL_BuildAudioCVT(SDL_AudioCVT *cvt, Uint16 src_format, Uint8 src_channels, int src_rate, Uint16 dst_format, Uint8 dst_channels, int dst_rate); /** * Once you have initialized the 'cvt' structure using SDL_BuildAudioCVT(), * created an audio buffer cvt->buf, and filled it with cvt->len bytes of * audio data in the source format, this function will convert it in-place * to the desired format. * The data conversion may expand the size of the audio data, so the buffer * cvt->buf should be allocated after the cvt structure is initialized by * SDL_BuildAudioCVT(), and should be cvt->len*cvt->len_mult bytes long. */ extern DECLSPEC int SDLCALL SDL_ConvertAudio(SDL_AudioCVT *cvt); #define SDL_MIX_MAXVOLUME 128 /** * This takes two audio buffers of the playing audio format and mixes * them, performing addition, volume adjustment, and overflow clipping. * The volume ranges from 0 - 128, and should be set to SDL_MIX_MAXVOLUME * for full audio volume. Note this does not change hardware volume. * This is provided for convenience -- you can mix your own audio data. */ extern DECLSPEC void SDLCALL SDL_MixAudio(Uint8 *dst, const Uint8 *src, Uint32 len, int volume); /** * @name Audio Locks * The lock manipulated by these functions protects the callback function. * During a LockAudio/UnlockAudio pair, you can be guaranteed that the * callback function is not running. Do not call these from the callback * function or you will cause deadlock. */ /*@{*/ extern DECLSPEC void SDLCALL SDL_LockAudio(void); extern DECLSPEC void SDLCALL SDL_UnlockAudio(void); /*@}*/ /** * This function shuts down audio processing and closes the audio device. */ extern DECLSPEC void SDLCALL SDL_CloseAudio(void); /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* _SDL_audio_h */ ================================================ FILE: other/sdl/include/SDL_byteorder.h ================================================ /* SDL - Simple DirectMedia Layer Copyright (C) 1997-2009 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org */ /** * @file SDL_byteorder.h * @deprecated Use SDL_endian.h instead */ /* DEPRECATED */ #include "SDL_endian.h" ================================================ FILE: other/sdl/include/SDL_cdrom.h ================================================ /* SDL - Simple DirectMedia Layer Copyright (C) 1997-2009 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org */ /** * @file SDL_cdrom.h * This is the CD-audio control API for Simple DirectMedia Layer */ #ifndef _SDL_cdrom_h #define _SDL_cdrom_h #include "SDL_stdinc.h" #include "SDL_error.h" #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif /** * @file SDL_cdrom.h * In order to use these functions, SDL_Init() must have been called * with the SDL_INIT_CDROM flag. This causes SDL to scan the system * for CD-ROM drives, and load appropriate drivers. */ /** The maximum number of CD-ROM tracks on a disk */ #define SDL_MAX_TRACKS 99 /** @name Track Types * The types of CD-ROM track possible */ /*@{*/ #define SDL_AUDIO_TRACK 0x00 #define SDL_DATA_TRACK 0x04 /*@}*/ /** The possible states which a CD-ROM drive can be in. */ typedef enum { CD_TRAYEMPTY, CD_STOPPED, CD_PLAYING, CD_PAUSED, CD_ERROR = -1 } CDstatus; /** Given a status, returns true if there's a disk in the drive */ #define CD_INDRIVE(status) ((int)(status) > 0) typedef struct SDL_CDtrack { Uint8 id; /**< Track number */ Uint8 type; /**< Data or audio track */ Uint16 unused; Uint32 length; /**< Length, in frames, of this track */ Uint32 offset; /**< Offset, in frames, from start of disk */ } SDL_CDtrack; /** This structure is only current as of the last call to SDL_CDStatus() */ typedef struct SDL_CD { int id; /**< Private drive identifier */ CDstatus status; /**< Current drive status */ /** The rest of this structure is only valid if there's a CD in drive */ /*@{*/ int numtracks; /**< Number of tracks on disk */ int cur_track; /**< Current track position */ int cur_frame; /**< Current frame offset within current track */ SDL_CDtrack track[SDL_MAX_TRACKS+1]; /*@}*/ } SDL_CD; /** @name Frames / MSF Conversion Functions * Conversion functions from frames to Minute/Second/Frames and vice versa */ /*@{*/ #define CD_FPS 75 #define FRAMES_TO_MSF(f, M,S,F) { \ int value = f; \ *(F) = value%CD_FPS; \ value /= CD_FPS; \ *(S) = value%60; \ value /= 60; \ *(M) = value; \ } #define MSF_TO_FRAMES(M, S, F) ((M)*60*CD_FPS+(S)*CD_FPS+(F)) /*@}*/ /* CD-audio API functions: */ /** * Returns the number of CD-ROM drives on the system, or -1 if * SDL_Init() has not been called with the SDL_INIT_CDROM flag. */ extern DECLSPEC int SDLCALL SDL_CDNumDrives(void); /** * Returns a human-readable, system-dependent identifier for the CD-ROM. * Example: * - "/dev/cdrom" * - "E:" * - "/dev/disk/ide/1/master" */ extern DECLSPEC const char * SDLCALL SDL_CDName(int drive); /** * Opens a CD-ROM drive for access. It returns a drive handle on success, * or NULL if the drive was invalid or busy. This newly opened CD-ROM * becomes the default CD used when other CD functions are passed a NULL * CD-ROM handle. * Drives are numbered starting with 0. Drive 0 is the system default CD-ROM. */ extern DECLSPEC SDL_CD * SDLCALL SDL_CDOpen(int drive); /** * This function returns the current status of the given drive. * If the drive has a CD in it, the table of contents of the CD and current * play position of the CD will be stored in the SDL_CD structure. */ extern DECLSPEC CDstatus SDLCALL SDL_CDStatus(SDL_CD *cdrom); /** * Play the given CD starting at 'start_track' and 'start_frame' for 'ntracks' * tracks and 'nframes' frames. If both 'ntrack' and 'nframe' are 0, play * until the end of the CD. This function will skip data tracks. * This function should only be called after calling SDL_CDStatus() to * get track information about the CD. * For example: * @code * // Play entire CD: * if ( CD_INDRIVE(SDL_CDStatus(cdrom)) ) * SDL_CDPlayTracks(cdrom, 0, 0, 0, 0); * // Play last track: * if ( CD_INDRIVE(SDL_CDStatus(cdrom)) ) { * SDL_CDPlayTracks(cdrom, cdrom->numtracks-1, 0, 0, 0); * } * // Play first and second track and 10 seconds of third track: * if ( CD_INDRIVE(SDL_CDStatus(cdrom)) ) * SDL_CDPlayTracks(cdrom, 0, 0, 2, 10); * @endcode * * @return This function returns 0, or -1 if there was an error. */ extern DECLSPEC int SDLCALL SDL_CDPlayTracks(SDL_CD *cdrom, int start_track, int start_frame, int ntracks, int nframes); /** * Play the given CD starting at 'start' frame for 'length' frames. * @return It returns 0, or -1 if there was an error. */ extern DECLSPEC int SDLCALL SDL_CDPlay(SDL_CD *cdrom, int start, int length); /** Pause play * @return returns 0, or -1 on error */ extern DECLSPEC int SDLCALL SDL_CDPause(SDL_CD *cdrom); /** Resume play * @return returns 0, or -1 on error */ extern DECLSPEC int SDLCALL SDL_CDResume(SDL_CD *cdrom); /** Stop play * @return returns 0, or -1 on error */ extern DECLSPEC int SDLCALL SDL_CDStop(SDL_CD *cdrom); /** Eject CD-ROM * @return returns 0, or -1 on error */ extern DECLSPEC int SDLCALL SDL_CDEject(SDL_CD *cdrom); /** Closes the handle for the CD-ROM drive */ extern DECLSPEC void SDLCALL SDL_CDClose(SDL_CD *cdrom); /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* _SDL_video_h */ ================================================ FILE: other/sdl/include/SDL_config.h ================================================ /* SDL - Simple DirectMedia Layer Copyright (C) 1997-2009 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org */ #ifndef _SDL_config_h #define _SDL_config_h #include "SDL_platform.h" /* Add any platform that doesn't build using the configure system */ #if defined(__DREAMCAST__) #include "SDL_config_dreamcast.h" #elif defined(__MACOS__) #include "SDL_config_macos.h" #elif defined(__MACOSX__) #include "SDL_config_macosx.h" #elif defined(__SYMBIAN32__) #include "SDL_config_symbian.h" /* must be before win32! */ #elif defined(__WIN32__) #include "SDL_config_win32.h" #elif defined(__OS2__) #include "SDL_config_os2.h" #else #include "SDL_config_minimal.h" #endif /* platform config */ #endif /* _SDL_config_h */ ================================================ FILE: other/sdl/include/SDL_config.h.default ================================================ /* SDL - Simple DirectMedia Layer Copyright (C) 1997-2006 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org */ #ifndef _SDL_config_h #define _SDL_config_h #include "SDL_platform.h" /* Add any platform that doesn't build using the configure system */ #if defined(__DREAMCAST__) #include "SDL_config_dreamcast.h" #elif defined(__MACOS__) #include "SDL_config_macos.h" #elif defined(__MACOSX__) #include "SDL_config_macosx.h" #elif defined(__SYMBIAN32__) #include "SDL_config_symbian.h" /* must be before win32! */ #elif defined(__WIN32__) #include "SDL_config_win32.h" #elif defined(__OS2__) #include "SDL_config_os2.h" #else #include "SDL_config_minimal.h" #endif /* platform config */ #endif /* _SDL_config_h */ ================================================ FILE: other/sdl/include/SDL_config.h.in ================================================ /* SDL - Simple DirectMedia Layer Copyright (C) 1997-2006 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org */ #ifndef _SDL_config_h #define _SDL_config_h /* This is a set of defines to configure the SDL features */ /* General platform specific identifiers */ #include "SDL_platform.h" /* Make sure that this isn't included by Visual C++ */ #ifdef _MSC_VER #error You should copy include/SDL_config.h.default to include/SDL_config.h #endif /* C language features */ #undef const #undef inline #undef volatile /* C datatypes */ #undef size_t #undef int8_t #undef uint8_t #undef int16_t #undef uint16_t #undef int32_t #undef uint32_t #undef int64_t #undef uint64_t #undef uintptr_t #undef SDL_HAS_64BIT_TYPE /* Endianness */ #undef SDL_BYTEORDER /* Comment this if you want to build without any C library requirements */ #undef HAVE_LIBC #if HAVE_LIBC /* Useful headers */ #undef HAVE_ALLOCA_H #undef HAVE_SYS_TYPES_H #undef HAVE_STDIO_H #undef STDC_HEADERS #undef HAVE_STDLIB_H #undef HAVE_STDARG_H #undef HAVE_MALLOC_H #undef HAVE_MEMORY_H #undef HAVE_STRING_H #undef HAVE_STRINGS_H #undef HAVE_INTTYPES_H #undef HAVE_STDINT_H #undef HAVE_CTYPE_H #undef HAVE_MATH_H #undef HAVE_ICONV_H #undef HAVE_SIGNAL_H #undef HAVE_ALTIVEC_H /* C library functions */ #undef HAVE_MALLOC #undef HAVE_CALLOC #undef HAVE_REALLOC #undef HAVE_FREE #undef HAVE_ALLOCA #ifndef _WIN32 /* Don't use C runtime versions of these on Windows */ #undef HAVE_GETENV #undef HAVE_PUTENV #undef HAVE_UNSETENV #endif #undef HAVE_QSORT #undef HAVE_ABS #undef HAVE_BCOPY #undef HAVE_MEMSET #undef HAVE_MEMCPY #undef HAVE_MEMMOVE #undef HAVE_MEMCMP #undef HAVE_STRLEN #undef HAVE_STRLCPY #undef HAVE_STRLCAT #undef HAVE_STRDUP #undef HAVE__STRREV #undef HAVE__STRUPR #undef HAVE__STRLWR #undef HAVE_INDEX #undef HAVE_RINDEX #undef HAVE_STRCHR #undef HAVE_STRRCHR #undef HAVE_STRSTR #undef HAVE_ITOA #undef HAVE__LTOA #undef HAVE__UITOA #undef HAVE__ULTOA #undef HAVE_STRTOL #undef HAVE_STRTOUL #undef HAVE__I64TOA #undef HAVE__UI64TOA #undef HAVE_STRTOLL #undef HAVE_STRTOULL #undef HAVE_STRTOD #undef HAVE_ATOI #undef HAVE_ATOF #undef HAVE_STRCMP #undef HAVE_STRNCMP #undef HAVE__STRICMP #undef HAVE_STRCASECMP #undef HAVE__STRNICMP #undef HAVE_STRNCASECMP #undef HAVE_SSCANF #undef HAVE_SNPRINTF #undef HAVE_VSNPRINTF #undef HAVE_ICONV #undef HAVE_SIGACTION #undef HAVE_SETJMP #undef HAVE_NANOSLEEP #undef HAVE_CLOCK_GETTIME #undef HAVE_DLVSYM #undef HAVE_GETPAGESIZE #else /* We may need some replacement for stdarg.h here */ #include <stdarg.h> #endif /* HAVE_LIBC */ /* Allow disabling of core subsystems */ #undef SDL_AUDIO_DISABLED #undef SDL_CDROM_DISABLED #undef SDL_CPUINFO_DISABLED #undef SDL_EVENTS_DISABLED #undef SDL_FILE_DISABLED #undef SDL_JOYSTICK_DISABLED #undef SDL_LOADSO_DISABLED #undef SDL_THREADS_DISABLED #undef SDL_TIMERS_DISABLED #undef SDL_VIDEO_DISABLED /* Enable various audio drivers */ #undef SDL_AUDIO_DRIVER_ALSA #undef SDL_AUDIO_DRIVER_ALSA_DYNAMIC #undef SDL_AUDIO_DRIVER_ARTS #undef SDL_AUDIO_DRIVER_ARTS_DYNAMIC #undef SDL_AUDIO_DRIVER_BAUDIO #undef SDL_AUDIO_DRIVER_BSD #undef SDL_AUDIO_DRIVER_COREAUDIO #undef SDL_AUDIO_DRIVER_DART #undef SDL_AUDIO_DRIVER_DC #undef SDL_AUDIO_DRIVER_DISK #undef SDL_AUDIO_DRIVER_DUMMY #undef SDL_AUDIO_DRIVER_DMEDIA #undef SDL_AUDIO_DRIVER_DSOUND #undef SDL_AUDIO_DRIVER_PULSE #undef SDL_AUDIO_DRIVER_PULSE_DYNAMIC #undef SDL_AUDIO_DRIVER_ESD #undef SDL_AUDIO_DRIVER_ESD_DYNAMIC #undef SDL_AUDIO_DRIVER_MINT #undef SDL_AUDIO_DRIVER_MMEAUDIO #undef SDL_AUDIO_DRIVER_NAS #undef SDL_AUDIO_DRIVER_OSS #undef SDL_AUDIO_DRIVER_OSS_SOUNDCARD_H #undef SDL_AUDIO_DRIVER_PAUD #undef SDL_AUDIO_DRIVER_QNXNTO #undef SDL_AUDIO_DRIVER_SNDMGR #undef SDL_AUDIO_DRIVER_SUNAUDIO #undef SDL_AUDIO_DRIVER_WAVEOUT /* Enable various cdrom drivers */ #undef SDL_CDROM_AIX #undef SDL_CDROM_BEOS #undef SDL_CDROM_BSDI #undef SDL_CDROM_DC #undef SDL_CDROM_DUMMY #undef SDL_CDROM_FREEBSD #undef SDL_CDROM_LINUX #undef SDL_CDROM_MACOS #undef SDL_CDROM_MACOSX #undef SDL_CDROM_MINT #undef SDL_CDROM_OPENBSD #undef SDL_CDROM_OS2 #undef SDL_CDROM_OSF #undef SDL_CDROM_QNX #undef SDL_CDROM_WIN32 /* Enable various input drivers */ #undef SDL_INPUT_TSLIB #undef SDL_JOYSTICK_BEOS #undef SDL_JOYSTICK_DC #undef SDL_JOYSTICK_DUMMY #undef SDL_JOYSTICK_IOKIT #undef SDL_JOYSTICK_LINUX #undef SDL_JOYSTICK_LINUXEV #undef SDL_JOYSTICK_MACOS #undef SDL_JOYSTICK_MINT #undef SDL_JOYSTICK_OS2 #undef SDL_JOYSTICK_RISCOS #undef SDL_JOYSTICK_WINMM #undef SDL_JOYSTICK_USBHID #undef SDL_JOYSTICK_USBHID_MACHINE_JOYSTICK_H /* Enable various shared object loading systems */ #undef SDL_LOADSO_BEOS #undef SDL_LOADSO_DLCOMPAT #undef SDL_LOADSO_DLOPEN #undef SDL_LOADSO_DUMMY #undef SDL_LOADSO_LDG #undef SDL_LOADSO_MACOS #undef SDL_LOADSO_OS2 #undef SDL_LOADSO_WIN32 /* Enable various threading systems */ #undef SDL_THREAD_BEOS #undef SDL_THREAD_DC #undef SDL_THREAD_OS2 #undef SDL_THREAD_PTH #undef SDL_THREAD_PTHREAD #undef SDL_THREAD_PTHREAD_RECURSIVE_MUTEX #undef SDL_THREAD_PTHREAD_RECURSIVE_MUTEX_NP #undef SDL_THREAD_SPROC #undef SDL_THREAD_WIN32 /* Enable various timer systems */ #undef SDL_TIMER_BEOS #undef SDL_TIMER_DC #undef SDL_TIMER_DUMMY #undef SDL_TIMER_MACOS #undef SDL_TIMER_MINT #undef SDL_TIMER_OS2 #undef SDL_TIMER_RISCOS #undef SDL_TIMER_UNIX #undef SDL_TIMER_WIN32 #undef SDL_TIMER_WINCE /* Enable various video drivers */ #undef SDL_VIDEO_DRIVER_AALIB #undef SDL_VIDEO_DRIVER_BWINDOW #undef SDL_VIDEO_DRIVER_DC #undef SDL_VIDEO_DRIVER_DDRAW #undef SDL_VIDEO_DRIVER_DGA #undef SDL_VIDEO_DRIVER_DIRECTFB #undef SDL_VIDEO_DRIVER_DRAWSPROCKET #undef SDL_VIDEO_DRIVER_DUMMY #undef SDL_VIDEO_DRIVER_FBCON #undef SDL_VIDEO_DRIVER_GAPI #undef SDL_VIDEO_DRIVER_GEM #undef SDL_VIDEO_DRIVER_GGI #undef SDL_VIDEO_DRIVER_IPOD #undef SDL_VIDEO_DRIVER_NANOX #undef SDL_VIDEO_DRIVER_OS2FS #undef SDL_VIDEO_DRIVER_PHOTON #undef SDL_VIDEO_DRIVER_PICOGUI #undef SDL_VIDEO_DRIVER_PS2GS #undef SDL_VIDEO_DRIVER_QTOPIA #undef SDL_VIDEO_DRIVER_QUARTZ #undef SDL_VIDEO_DRIVER_RISCOS #undef SDL_VIDEO_DRIVER_SVGALIB #undef SDL_VIDEO_DRIVER_TOOLBOX #undef SDL_VIDEO_DRIVER_VGL #undef SDL_VIDEO_DRIVER_WINDIB #undef SDL_VIDEO_DRIVER_WSCONS #undef SDL_VIDEO_DRIVER_X11 #undef SDL_VIDEO_DRIVER_X11_DGAMOUSE #undef SDL_VIDEO_DRIVER_X11_DPMS #undef SDL_VIDEO_DRIVER_X11_DYNAMIC #undef SDL_VIDEO_DRIVER_X11_DYNAMIC_XEXT #undef SDL_VIDEO_DRIVER_X11_DYNAMIC_XRANDR #undef SDL_VIDEO_DRIVER_X11_DYNAMIC_XRENDER #undef SDL_VIDEO_DRIVER_X11_VIDMODE #undef SDL_VIDEO_DRIVER_X11_XINERAMA #undef SDL_VIDEO_DRIVER_X11_XME #undef SDL_VIDEO_DRIVER_X11_XRANDR #undef SDL_VIDEO_DRIVER_X11_XV #undef SDL_VIDEO_DRIVER_XBIOS /* Enable OpenGL support */ #undef SDL_VIDEO_OPENGL #undef SDL_VIDEO_OPENGL_GLX #undef SDL_VIDEO_OPENGL_WGL #undef SDL_VIDEO_OPENGL_OSMESA #undef SDL_VIDEO_OPENGL_OSMESA_DYNAMIC /* Enable assembly routines */ #undef SDL_ASSEMBLY_ROUTINES #undef SDL_HERMES_BLITTERS #undef SDL_ALTIVEC_BLITTERS #endif /* _SDL_config_h */ ================================================ FILE: other/sdl/include/SDL_config_amiga.h ================================================ /* SDL - Simple DirectMedia Layer Copyright (C) 1997-2006 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org */ #ifndef _SDL_config_amiga_h #define _SDL_config_amiga_h #include "SDL_platform.h" /* This is a set of defines to configure the SDL features */ #define SDL_HAS_64BIT_TYPE 1 /* Useful headers */ #define HAVE_SYS_TYPES_H 1 #define HAVE_STDIO_H 1 #define STDC_HEADERS 1 #define HAVE_STRING_H 1 #define HAVE_INTTYPES_H 1 #define HAVE_SIGNAL_H 1 /* C library functions */ #define HAVE_MALLOC 1 #define HAVE_CALLOC 1 #define HAVE_REALLOC 1 #define HAVE_FREE 1 #define HAVE_ALLOCA 1 #define HAVE_GETENV 1 #define HAVE_PUTENV 1 #define HAVE_MEMSET 1 #define HAVE_MEMCPY 1 #define HAVE_MEMMOVE 1 #define HAVE_MEMCMP 1 /* Enable various audio drivers */ #define SDL_AUDIO_DRIVER_AHI 1 #define SDL_AUDIO_DRIVER_DISK 1 #define SDL_AUDIO_DRIVER_DUMMY 1 /* Enable various cdrom drivers */ #define SDL_CDROM_DUMMY 1 /* Enable various input drivers */ #define SDL_JOYSTICK_AMIGA 1 /* Enable various shared object loading systems */ #define SDL_LOADSO_DUMMY 1 /* Enable various threading systems */ #define SDL_THREAD_AMIGA 1 /* Enable various timer systems */ #define SDL_TIMER_AMIGA 1 /* Enable various video drivers */ #define SDL_VIDEO_DRIVER_CYBERGRAPHICS 1 #define SDL_VIDEO_DRIVER_DUMMY 1 /* Enable OpenGL support */ #define SDL_VIDEO_OPENGL 1 #endif /* _SDL_config_amiga_h */ ================================================ FILE: other/sdl/include/SDL_config_dreamcast.h ================================================ /* SDL - Simple DirectMedia Layer Copyright (C) 1997-2009 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org */ #ifndef _SDL_config_dreamcast_h #define _SDL_config_dreamcast_h #include "SDL_platform.h" /* This is a set of defines to configure the SDL features */ typedef signed char int8_t; typedef unsigned char uint8_t; typedef signed short int16_t; typedef unsigned short uint16_t; typedef signed int int32_t; typedef unsigned int uint32_t; typedef signed long long int64_t; typedef unsigned long long uint64_t; typedef unsigned long uintptr_t; #define SDL_HAS_64BIT_TYPE 1 /* Useful headers */ #define HAVE_SYS_TYPES_H 1 #define HAVE_STDIO_H 1 #define STDC_HEADERS 1 #define HAVE_STRING_H 1 #define HAVE_CTYPE_H 1 /* C library functions */ #define HAVE_MALLOC 1 #define HAVE_CALLOC 1 #define HAVE_REALLOC 1 #define HAVE_FREE 1 #define HAVE_ALLOCA 1 #define HAVE_GETENV 1 #define HAVE_PUTENV 1 #define HAVE_QSORT 1 #define HAVE_ABS 1 #define HAVE_BCOPY 1 #define HAVE_MEMSET 1 #define HAVE_MEMCPY 1 #define HAVE_MEMMOVE 1 #define HAVE_MEMCMP 1 #define HAVE_STRLEN 1 #define HAVE_STRDUP 1 #define HAVE_INDEX 1 #define HAVE_RINDEX 1 #define HAVE_STRCHR 1 #define HAVE_STRRCHR 1 #define HAVE_STRSTR 1 #define HAVE_STRTOL 1 #define HAVE_STRTOD 1 #define HAVE_ATOI 1 #define HAVE_ATOF 1 #define HAVE_STRCMP 1 #define HAVE_STRNCMP 1 #define HAVE_STRICMP 1 #define HAVE_STRCASECMP 1 #define HAVE_SSCANF 1 #define HAVE_SNPRINTF 1 #define HAVE_VSNPRINTF 1 /* Enable various audio drivers */ #define SDL_AUDIO_DRIVER_DC 1 #define SDL_AUDIO_DRIVER_DISK 1 #define SDL_AUDIO_DRIVER_DUMMY 1 /* Enable various cdrom drivers */ #define SDL_CDROM_DC 1 /* Enable various input drivers */ #define SDL_JOYSTICK_DC 1 /* Enable various shared object loading systems */ #define SDL_LOADSO_DUMMY 1 /* Enable various threading systems */ #define SDL_THREAD_DC 1 /* Enable various timer systems */ #define SDL_TIMER_DC 1 /* Enable various video drivers */ #define SDL_VIDEO_DRIVER_DC 1 #define SDL_VIDEO_DRIVER_DUMMY 1 #endif /* _SDL_config_dreamcast_h */ ================================================ FILE: other/sdl/include/SDL_config_macos.h ================================================ /* SDL - Simple DirectMedia Layer Copyright (C) 1997-2009 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org */ #ifndef _SDL_config_macos_h #define _SDL_config_macos_h #include "SDL_platform.h" /* This is a set of defines to configure the SDL features */ #include <MacTypes.h> typedef SInt8 int8_t; typedef UInt8 uint8_t; typedef SInt16 int16_t; typedef UInt16 uint16_t; typedef SInt32 int32_t; typedef UInt32 uint32_t; typedef SInt64 int64_t; typedef UInt64 uint64_t; typedef unsigned long uintptr_t; #define SDL_HAS_64BIT_TYPE 1 /* Useful headers */ #define HAVE_STDIO_H 1 #define STDC_HEADERS 1 #define HAVE_STRING_H 1 #define HAVE_CTYPE_H 1 #define HAVE_MATH_H 1 #define HAVE_SIGNAL_H 1 /* C library functions */ #define HAVE_MALLOC 1 #define HAVE_CALLOC 1 #define HAVE_REALLOC 1 #define HAVE_FREE 1 #define HAVE_ALLOCA 1 #define HAVE_ABS 1 #define HAVE_MEMSET 1 #define HAVE_MEMCPY 1 #define HAVE_MEMMOVE 1 #define HAVE_MEMCMP 1 #define HAVE_STRLEN 1 #define HAVE_STRCHR 1 #define HAVE_STRRCHR 1 #define HAVE_STRSTR 1 #define HAVE_ITOA 1 #define HAVE_STRTOL 1 #define HAVE_STRTOD 1 #define HAVE_ATOI 1 #define HAVE_ATOF 1 #define HAVE_STRCMP 1 #define HAVE_STRNCMP 1 #define HAVE_SSCANF 1 /* Enable various audio drivers */ #define SDL_AUDIO_DRIVER_SNDMGR 1 #define SDL_AUDIO_DRIVER_DISK 1 #define SDL_AUDIO_DRIVER_DUMMY 1 /* Enable various cdrom drivers */ #if TARGET_API_MAC_CARBON #define SDL_CDROM_DUMMY 1 #else #define SDL_CDROM_MACOS 1 #endif /* Enable various input drivers */ #if TARGET_API_MAC_CARBON #define SDL_JOYSTICK_DUMMY 1 #else #define SDL_JOYSTICK_MACOS 1 #endif /* Enable various shared object loading systems */ #define SDL_LOADSO_MACOS 1 /* Enable various threading systems */ #define SDL_THREADS_DISABLED 1 /* Enable various timer systems */ #define SDL_TIMER_MACOS 1 /* Enable various video drivers */ #define SDL_VIDEO_DRIVER_DUMMY 1 #define SDL_VIDEO_DRIVER_DRAWSPROCKET 1 #define SDL_VIDEO_DRIVER_TOOLBOX 1 /* Enable OpenGL support */ #define SDL_VIDEO_OPENGL 1 #endif /* _SDL_config_macos_h */ ================================================ FILE: other/sdl/include/SDL_config_macosx.h ================================================ /* SDL - Simple DirectMedia Layer Copyright (C) 1997-2009 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org */ #ifndef _SDL_config_macosx_h #define _SDL_config_macosx_h #include "SDL_platform.h" /* This gets us MAC_OS_X_VERSION_MIN_REQUIRED... */ #include <AvailabilityMacros.h> /* This is a set of defines to configure the SDL features */ #define SDL_HAS_64BIT_TYPE 1 /* Useful headers */ /* If we specified an SDK or have a post-PowerPC chip, then alloca.h exists. */ #if ( (MAC_OS_X_VERSION_MIN_REQUIRED >= 1030) || (!defined(__POWERPC__)) ) #define HAVE_ALLOCA_H 1 #endif #define HAVE_SYS_TYPES_H 1 #define HAVE_STDIO_H 1 #define STDC_HEADERS 1 #define HAVE_STRING_H 1 #define HAVE_INTTYPES_H 1 #define HAVE_STDINT_H 1 #define HAVE_CTYPE_H 1 #define HAVE_MATH_H 1 #define HAVE_SIGNAL_H 1 /* C library functions */ #define HAVE_MALLOC 1 #define HAVE_CALLOC 1 #define HAVE_REALLOC 1 #define HAVE_FREE 1 #define HAVE_ALLOCA 1 #define HAVE_GETENV 1 #define HAVE_PUTENV 1 #define HAVE_UNSETENV 1 #define HAVE_QSORT 1 #define HAVE_ABS 1 #define HAVE_BCOPY 1 #define HAVE_MEMSET 1 #define HAVE_MEMCPY 1 #define HAVE_MEMMOVE 1 #define HAVE_MEMCMP 1 #define HAVE_STRLEN 1 #define HAVE_STRLCPY 1 #define HAVE_STRLCAT 1 #define HAVE_STRDUP 1 #define HAVE_STRCHR 1 #define HAVE_STRRCHR 1 #define HAVE_STRSTR 1 #define HAVE_STRTOL 1 #define HAVE_STRTOUL 1 #define HAVE_STRTOLL 1 #define HAVE_STRTOULL 1 #define HAVE_STRTOD 1 #define HAVE_ATOI 1 #define HAVE_ATOF 1 #define HAVE_STRCMP 1 #define HAVE_STRNCMP 1 #define HAVE_STRCASECMP 1 #define HAVE_STRNCASECMP 1 #define HAVE_SSCANF 1 #define HAVE_SNPRINTF 1 #define HAVE_VSNPRINTF 1 #define HAVE_SIGACTION 1 #define HAVE_SETJMP 1 #define HAVE_NANOSLEEP 1 /* Enable various audio drivers */ #define SDL_AUDIO_DRIVER_COREAUDIO 1 #define SDL_AUDIO_DRIVER_DISK 1 #define SDL_AUDIO_DRIVER_DUMMY 1 /* Enable various cdrom drivers */ #define SDL_CDROM_MACOSX 1 /* Enable various input drivers */ #define SDL_JOYSTICK_IOKIT 1 /* Enable various shared object loading systems */ #ifdef __ppc__ /* For Mac OS X 10.2 compatibility */ #define SDL_LOADSO_DLCOMPAT 1 #else #define SDL_LOADSO_DLOPEN 1 #endif /* Enable various threading systems */ #define SDL_THREAD_PTHREAD 1 #define SDL_THREAD_PTHREAD_RECURSIVE_MUTEX 1 /* Enable various timer systems */ #define SDL_TIMER_UNIX 1 /* Enable various video drivers */ #define SDL_VIDEO_DRIVER_DUMMY 1 #if ((defined TARGET_API_MAC_CARBON) && (TARGET_API_MAC_CARBON)) #define SDL_VIDEO_DRIVER_TOOLBOX 1 #else #define SDL_VIDEO_DRIVER_QUARTZ 1 #endif #define SDL_VIDEO_DRIVER_DGA 1 #define SDL_VIDEO_DRIVER_X11 1 #define SDL_VIDEO_DRIVER_X11_DGAMOUSE 1 #define SDL_VIDEO_DRIVER_X11_DYNAMIC "/usr/X11R6/lib/libX11.6.dylib" #define SDL_VIDEO_DRIVER_X11_DYNAMIC_XEXT "/usr/X11R6/lib/libXext.6.dylib" #define SDL_VIDEO_DRIVER_X11_DYNAMIC_XRANDR "/usr/X11R6/lib/libXrandr.2.dylib" #define SDL_VIDEO_DRIVER_X11_DYNAMIC_XRENDER "/usr/X11R6/lib/libXrender.1.dylib" #define SDL_VIDEO_DRIVER_X11_VIDMODE 1 #define SDL_VIDEO_DRIVER_X11_XINERAMA 1 #define SDL_VIDEO_DRIVER_X11_XME 1 #define SDL_VIDEO_DRIVER_X11_XRANDR 1 #define SDL_VIDEO_DRIVER_X11_XV 1 /* Enable OpenGL support */ #define SDL_VIDEO_OPENGL 1 #define SDL_VIDEO_OPENGL_GLX 1 /* Disable screensaver */ #define SDL_VIDEO_DISABLE_SCREENSAVER 1 /* Enable assembly routines */ #define SDL_ASSEMBLY_ROUTINES 1 #ifdef __ppc__ #define SDL_ALTIVEC_BLITTERS 1 #endif #endif /* _SDL_config_macosx_h */ ================================================ FILE: other/sdl/include/SDL_config_minimal.h ================================================ /* SDL - Simple DirectMedia Layer Copyright (C) 1997-2009 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org */ #ifndef _SDL_config_minimal_h #define _SDL_config_minimal_h #include "SDL_platform.h" /* This is the minimal configuration that can be used to build SDL */ #include <stdarg.h> typedef signed char int8_t; typedef unsigned char uint8_t; typedef signed short int16_t; typedef unsigned short uint16_t; typedef signed int int32_t; typedef unsigned int uint32_t; typedef unsigned int size_t; typedef unsigned long uintptr_t; /* Enable the dummy audio driver (src/audio/dummy/\*.c) */ #define SDL_AUDIO_DRIVER_DUMMY 1 /* Enable the stub cdrom driver (src/cdrom/dummy/\*.c) */ #define SDL_CDROM_DISABLED 1 /* Enable the stub joystick driver (src/joystick/dummy/\*.c) */ #define SDL_JOYSTICK_DISABLED 1 /* Enable the stub shared object loader (src/loadso/dummy/\*.c) */ #define SDL_LOADSO_DISABLED 1 /* Enable the stub thread support (src/thread/generic/\*.c) */ #define SDL_THREADS_DISABLED 1 /* Enable the stub timer support (src/timer/dummy/\*.c) */ #define SDL_TIMERS_DISABLED 1 /* Enable the dummy video driver (src/video/dummy/\*.c) */ #define SDL_VIDEO_DRIVER_DUMMY 1 #endif /* _SDL_config_minimal_h */ ================================================ FILE: other/sdl/include/SDL_config_nds.h ================================================ /* SDL - Simple DirectMedia Layer Copyright (C) 1997-2009 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org */ #ifndef _SDL_config_nds_h #define _SDL_config_nds_h #include "SDL_platform.h" /* This is a set of defines to configure the SDL features */ /* General platform specific identifiers */ #include "SDL_platform.h" /* C datatypes */ #define SDL_HAS_64BIT_TYPE 1 /* Endianness */ #define SDL_BYTEORDER 1234 /* Useful headers */ #define HAVE_ALLOCA_H 1 #define HAVE_SYS_TYPES_H 1 #define HAVE_STDIO_H 1 #define STDC_HEADERS 1 #define HAVE_STDLIB_H 1 #define HAVE_STDARG_H 1 #define HAVE_MALLOC_H 1 #define HAVE_STRING_H 1 #define HAVE_INTTYPES_H 1 #define HAVE_STDINT_H 1 #define HAVE_CTYPE_H 1 #define HAVE_MATH_H 1 #define HAVE_ICONV_H 1 #define HAVE_SIGNAL_H 1 /* C library functions */ #define HAVE_MALLOC 1 #define HAVE_CALLOC 1 #define HAVE_REALLOC 1 #define HAVE_FREE 1 #define HAVE_ALLOCA 1 #define HAVE_GETENV 1 #define HAVE_PUTENV 1 #define HAVE_UNSETENV 1 #define HAVE_QSORT 1 #define HAVE_ABS 1 #define HAVE_BCOPY 1 #define HAVE_MEMSET 1 #define HAVE_MEMCPY 1 #define HAVE_MEMMOVE 1 #define HAVE_STRLEN 1 #define HAVE_STRLCPY 1 #define HAVE_STRLCAT 1 #define HAVE_STRDUP 1 #define HAVE_STRCHR 1 #define HAVE_STRRCHR 1 #define HAVE_STRSTR 1 #define HAVE_STRTOL 1 #define HAVE_STRTOUL 1 #define HAVE_STRTOLL 1 #define HAVE_STRTOULL 1 #define HAVE_ATOI 1 #define HAVE_ATOF 1 #define HAVE_STRCMP 1 #define HAVE_STRNCMP 1 #define HAVE_STRCASECMP 1 #define HAVE_STRNCASECMP 1 #define HAVE_SSCANF 1 #define HAVE_SNPRINTF 1 #define HAVE_VSNPRINTF 1 #define HAVE_SETJMP 1 /* Enable various audio drivers */ #define SDL_AUDIO_DRIVER_NDS 1 #define SDL_AUDIO_DRIVER_DUMMY 1 /* Enable the stub cdrom driver (src/cdrom/dummy/\*.c) */ #define SDL_CDROM_DISABLED 1 /* Enable various input drivers */ #define SDL_JOYSTICK_NDS 1 /* Enable the stub shared object loader (src/loadso/dummy/\*.c) */ #define SDL_LOADSO_DISABLED 1 /* Enable the stub thread support (src/thread/generic/\*.c) */ #define SDL_THREADS_DISABLED 1 /* Enable various timer systems */ #define SDL_TIMER_NDS 1 /* Enable various video drivers */ #define SDL_VIDEO_DRIVER_NDS 1 #define SDL_VIDEO_DRIVER_DUMMY 1 #endif /* _SDL_config_nds_h */ ================================================ FILE: other/sdl/include/SDL_config_os2.h ================================================ /* SDL - Simple DirectMedia Layer Copyright (C) 1997-2009 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org */ #ifndef _SDL_config_os2_h #define _SDL_config_os2_h #include "SDL_platform.h" /* This is a set of defines to configure the SDL features */ typedef signed char int8_t; typedef unsigned char uint8_t; typedef signed short int16_t; typedef unsigned short uint16_t; typedef signed int int32_t; typedef unsigned int uint32_t; typedef unsigned int size_t; typedef unsigned long uintptr_t; typedef signed long long int64_t; typedef unsigned long long uint64_t; #define SDL_HAS_64BIT_TYPE 1 /* Use Watcom's LIBC */ #define HAVE_LIBC 1 /* Useful headers */ #define HAVE_SYS_TYPES_H 1 #define HAVE_STDIO_H 1 #define STDC_HEADERS 1 #define HAVE_STDLIB_H 1 #define HAVE_STDARG_H 1 #define HAVE_MALLOC_H 1 #define HAVE_MEMORY_H 1 #define HAVE_STRING_H 1 #define HAVE_STRINGS_H 1 #define HAVE_INTTYPES_H 1 #define HAVE_STDINT_H 1 #define HAVE_CTYPE_H 1 #define HAVE_MATH_H 1 #define HAVE_SIGNAL_H 1 /* C library functions */ #define HAVE_MALLOC 1 #define HAVE_CALLOC 1 #define HAVE_REALLOC 1 #define HAVE_FREE 1 #define HAVE_ALLOCA 1 #define HAVE_GETENV 1 #define HAVE_PUTENV 1 #define HAVE_UNSETENV 1 #define HAVE_QSORT 1 #define HAVE_ABS 1 #define HAVE_BCOPY 1 #define HAVE_MEMSET 1 #define HAVE_MEMCPY 1 #define HAVE_MEMMOVE 1 #define HAVE_MEMCMP 1 #define HAVE_STRLEN 1 #define HAVE_STRLCPY 1 #define HAVE_STRLCAT 1 #define HAVE_STRDUP 1 #define HAVE__STRREV 1 #define HAVE__STRUPR 1 #define HAVE__STRLWR 1 #define HAVE_INDEX 1 #define HAVE_RINDEX 1 #define HAVE_STRCHR 1 #define HAVE_STRRCHR 1 #define HAVE_STRSTR 1 #define HAVE_ITOA 1 #define HAVE__LTOA 1 #define HAVE__UITOA 1 #define HAVE__ULTOA 1 #define HAVE_STRTOL 1 #define HAVE__I64TOA 1 #define HAVE__UI64TOA 1 #define HAVE_STRTOLL 1 #define HAVE_STRTOD 1 #define HAVE_ATOI 1 #define HAVE_ATOF 1 #define HAVE_STRCMP 1 #define HAVE_STRNCMP 1 #define HAVE_STRICMP 1 #define HAVE_STRCASECMP 1 #define HAVE_SSCANF 1 #define HAVE_SNPRINTF 1 #define HAVE_VSNPRINTF 1 #define HAVE_SETJMP 1 #define HAVE_CLOCK_GETTIME 1 /* Enable various audio drivers */ #define SDL_AUDIO_DRIVER_DART 1 #define SDL_AUDIO_DRIVER_DISK 1 #define SDL_AUDIO_DRIVER_DUMMY 1 /* Enable various cdrom drivers */ #define SDL_CDROM_OS2 1 /* Enable various input drivers */ #define SDL_JOYSTICK_OS2 1 /* Enable various shared object loading systems */ #define SDL_LOADSO_OS2 1 /* Enable various threading systems */ #define SDL_THREAD_OS2 1 /* Enable various timer systems */ #define SDL_TIMER_OS2 1 /* Enable various video drivers */ #define SDL_VIDEO_DRIVER_DUMMY 1 #define SDL_VIDEO_DRIVER_OS2FS 1 /* Enable OpenGL support */ /* Nothing here yet for OS/2... :( */ /* Enable assembly routines where available */ #define SDL_ASSEMBLY_ROUTINES 1 #endif /* _SDL_config_os2_h */ ================================================ FILE: other/sdl/include/SDL_config_symbian.h ================================================ /* SDL - Simple DirectMedia Layer Copyright (C) 1997-2009 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org */ /* Symbian version Markus Mertama */ #ifndef _SDL_CONFIG_SYMBIAN_H #define _SDL_CONFIG_SYMBIAN_H #include "SDL_platform.h" /* This is the minimal configuration that can be used to build SDL */ #include <stdarg.h> #include <stddef.h> #ifdef __GCCE__ #define SYMBIAN32_GCCE #endif #ifndef _SIZE_T_DEFINED typedef unsigned int size_t; #endif #ifndef _INTPTR_T_DECLARED typedef unsigned int uintptr_t; #endif #ifndef _INT8_T_DECLARED typedef signed char int8_t; #endif #ifndef _UINT8_T_DECLARED typedef unsigned char uint8_t; #endif #ifndef _INT16_T_DECLARED typedef signed short int16_t; #endif #ifndef _UINT16_T_DECLARED typedef unsigned short uint16_t; #endif #ifndef _INT32_T_DECLARED typedef signed int int32_t; #endif #ifndef _UINT32_T_DECLARED typedef unsigned int uint32_t; #endif #ifndef _INT64_T_DECLARED typedef signed long long int64_t; #endif #ifndef _UINT64_T_DECLARED typedef unsigned long long uint64_t; #endif #define SDL_AUDIO_DRIVER_EPOCAUDIO 1 /* Enable the stub cdrom driver (src/cdrom/dummy/\*.c) */ #define SDL_CDROM_DISABLED 1 /* Enable the stub joystick driver (src/joystick/dummy/\*.c) */ #define SDL_JOYSTICK_DISABLED 1 /* Enable the stub shared object loader (src/loadso/dummy/\*.c) */ #define SDL_LOADSO_DISABLED 1 #define SDL_THREAD_SYMBIAN 1 #define SDL_VIDEO_DRIVER_EPOC 1 #define SDL_VIDEO_OPENGL 0 #define SDL_HAS_64BIT_TYPE 1 #define HAVE_LIBC 1 #define HAVE_STDIO_H 1 #define STDC_HEADERS 1 #define HAVE_STRING_H 1 #define HAVE_CTYPE_H 1 #define HAVE_MATH_H 1 #define HAVE_MALLOC 1 #define HAVE_CALLOC 1 #define HAVE_REALLOC 1 #define HAVE_FREE 1 /*#define HAVE_ALLOCA 1*/ #define HAVE_QSORT 1 #define HAVE_ABS 1 #define HAVE_MEMSET 1 #define HAVE_MEMCPY 1 #define HAVE_MEMMOVE 1 #define HAVE_MEMCMP 1 #define HAVE_STRLEN 1 #define HAVE__STRUPR 1 #define HAVE_STRCHR 1 #define HAVE_STRRCHR 1 #define HAVE_STRSTR 1 #define HAVE_ITOA 1 #define HAVE_STRTOL 1 #define HAVE_STRTOUL 1 #define HAVE_STRTOLL 1 #define HAVE_STRTOD 1 #define HAVE_ATOI 1 #define HAVE_ATOF 1 #define HAVE_STRCMP 1 #define HAVE_STRNCMP 1 /*#define HAVE__STRICMP 1*/ #define HAVE__STRNICMP 1 #define HAVE_SSCANF 1 #define HAVE_STDARG_H 1 #define HAVE_STDDEF_H 1 #endif /* _SDL_CONFIG_SYMBIAN_H */ ================================================ FILE: other/sdl/include/SDL_config_win32.h ================================================ /* SDL - Simple DirectMedia Layer Copyright (C) 1997-2009 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org */ #ifndef _SDL_config_win32_h #define _SDL_config_win32_h #include "SDL_platform.h" /* This is a set of defines to configure the SDL features */ #if defined(__GNUC__) || defined(__DMC__) #define HAVE_STDINT_H 1 #elif defined(_MSC_VER) typedef signed __int8 int8_t; typedef unsigned __int8 uint8_t; typedef signed __int16 int16_t; typedef unsigned __int16 uint16_t; typedef signed __int32 int32_t; typedef unsigned __int32 uint32_t; typedef signed __int64 int64_t; typedef unsigned __int64 uint64_t; #ifndef _UINTPTR_T_DEFINED #ifdef _WIN64 typedef unsigned __int64 uintptr_t; #else typedef unsigned int uintptr_t; #endif #define _UINTPTR_T_DEFINED #endif /* Older Visual C++ headers don't have the Win64-compatible typedefs... */ #if ((_MSC_VER <= 1200) && (!defined(DWORD_PTR))) #define DWORD_PTR DWORD #endif #if ((_MSC_VER <= 1200) && (!defined(LONG_PTR))) #define LONG_PTR LONG #endif #else /* !__GNUC__ && !_MSC_VER */ typedef signed char int8_t; typedef unsigned char uint8_t; typedef signed short int16_t; typedef unsigned short uint16_t; typedef signed int int32_t; typedef unsigned int uint32_t; typedef signed long long int64_t; typedef unsigned long long uint64_t; #ifndef _SIZE_T_DEFINED_ #define _SIZE_T_DEFINED_ typedef unsigned int size_t; #endif typedef unsigned int uintptr_t; #endif /* __GNUC__ || _MSC_VER */ #define SDL_HAS_64BIT_TYPE 1 /* Enabled for SDL 1.2 (binary compatibility) */ #define HAVE_LIBC 1 #ifdef HAVE_LIBC /* Useful headers */ #define HAVE_STDIO_H 1 #define STDC_HEADERS 1 #define HAVE_STRING_H 1 #define HAVE_CTYPE_H 1 #define HAVE_MATH_H 1 #ifndef _WIN32_WCE #define HAVE_SIGNAL_H 1 #endif /* C library functions */ #define HAVE_MALLOC 1 #define HAVE_CALLOC 1 #define HAVE_REALLOC 1 #define HAVE_FREE 1 #define HAVE_ALLOCA 1 #define HAVE_QSORT 1 #define HAVE_ABS 1 #define HAVE_MEMSET 1 #define HAVE_MEMCPY 1 #define HAVE_MEMMOVE 1 #define HAVE_MEMCMP 1 #define HAVE_STRLEN 1 #define HAVE__STRREV 1 #define HAVE__STRUPR 1 #define HAVE__STRLWR 1 #define HAVE_STRCHR 1 #define HAVE_STRRCHR 1 #define HAVE_STRSTR 1 #define HAVE_ITOA 1 #define HAVE__LTOA 1 #define HAVE__ULTOA 1 #define HAVE_STRTOL 1 #define HAVE_STRTOUL 1 #define HAVE_STRTOLL 1 #define HAVE_STRTOD 1 #define HAVE_ATOI 1 #define HAVE_ATOF 1 #define HAVE_STRCMP 1 #define HAVE_STRNCMP 1 #define HAVE__STRICMP 1 #define HAVE__STRNICMP 1 #define HAVE_SSCANF 1 #else #define HAVE_STDARG_H 1 #define HAVE_STDDEF_H 1 #endif /* Enable various audio drivers */ #ifndef _WIN32_WCE #define SDL_AUDIO_DRIVER_DSOUND 1 #endif #define SDL_AUDIO_DRIVER_WAVEOUT 1 #define SDL_AUDIO_DRIVER_DISK 1 #define SDL_AUDIO_DRIVER_DUMMY 1 /* Enable various cdrom drivers */ #ifdef _WIN32_WCE #define SDL_CDROM_DISABLED 1 #else #define SDL_CDROM_WIN32 1 #endif /* Enable various input drivers */ #ifdef _WIN32_WCE #define SDL_JOYSTICK_DISABLED 1 #else #define SDL_JOYSTICK_WINMM 1 #endif /* Enable various shared object loading systems */ #define SDL_LOADSO_WIN32 1 /* Enable various threading systems */ #define SDL_THREAD_WIN32 1 /* Enable various timer systems */ #ifdef _WIN32_WCE #define SDL_TIMER_WINCE 1 #else #define SDL_TIMER_WIN32 1 #endif /* Enable various video drivers */ #ifdef _WIN32_WCE #define SDL_VIDEO_DRIVER_GAPI 1 #endif #ifndef _WIN32_WCE #define SDL_VIDEO_DRIVER_DDRAW 1 #endif #define SDL_VIDEO_DRIVER_DUMMY 1 #define SDL_VIDEO_DRIVER_WINDIB 1 /* Enable OpenGL support */ #ifndef _WIN32_WCE #define SDL_VIDEO_OPENGL 1 #define SDL_VIDEO_OPENGL_WGL 1 #endif /* Disable screensaver */ #define SDL_VIDEO_DISABLE_SCREENSAVER 1 /* Enable assembly routines (Win64 doesn't have inline asm) */ #ifndef _WIN64 #define SDL_ASSEMBLY_ROUTINES 1 #endif #endif /* _SDL_config_win32_h */ ================================================ FILE: other/sdl/include/SDL_copying.h ================================================ /* SDL - Simple DirectMedia Layer Copyright (C) 1997-2009 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org */ ================================================ FILE: other/sdl/include/SDL_cpuinfo.h ================================================ /* SDL - Simple DirectMedia Layer Copyright (C) 1997-2009 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org */ /** * @file SDL_cpuinfo.h * CPU feature detection for SDL */ #ifndef _SDL_cpuinfo_h #define _SDL_cpuinfo_h #include "SDL_stdinc.h" #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif /** This function returns true if the CPU has the RDTSC instruction */ extern DECLSPEC SDL_bool SDLCALL SDL_HasRDTSC(void); /** This function returns true if the CPU has MMX features */ extern DECLSPEC SDL_bool SDLCALL SDL_HasMMX(void); /** This function returns true if the CPU has MMX Ext. features */ extern DECLSPEC SDL_bool SDLCALL SDL_HasMMXExt(void); /** This function returns true if the CPU has 3DNow features */ extern DECLSPEC SDL_bool SDLCALL SDL_Has3DNow(void); /** This function returns true if the CPU has 3DNow! Ext. features */ extern DECLSPEC SDL_bool SDLCALL SDL_Has3DNowExt(void); /** This function returns true if the CPU has SSE features */ extern DECLSPEC SDL_bool SDLCALL SDL_HasSSE(void); /** This function returns true if the CPU has SSE2 features */ extern DECLSPEC SDL_bool SDLCALL SDL_HasSSE2(void); /** This function returns true if the CPU has AltiVec features */ extern DECLSPEC SDL_bool SDLCALL SDL_HasAltiVec(void); /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* _SDL_cpuinfo_h */ ================================================ FILE: other/sdl/include/SDL_endian.h ================================================ /* SDL - Simple DirectMedia Layer Copyright (C) 1997-2009 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org */ /** * @file SDL_endian.h * Functions for reading and writing endian-specific values */ #ifndef _SDL_endian_h #define _SDL_endian_h #include "SDL_stdinc.h" /** @name SDL_ENDIANs * The two types of endianness */ /*@{*/ #define SDL_LIL_ENDIAN 1234 #define SDL_BIG_ENDIAN 4321 /*@}*/ #ifndef SDL_BYTEORDER /* Not defined in SDL_config.h? */ #if defined(__hppa__) || \ defined(__m68k__) || defined(mc68000) || defined(_M_M68K) || \ (defined(__MIPS__) && defined(__MISPEB__)) || \ defined(__ppc__) || defined(__POWERPC__) || defined(_M_PPC) || \ defined(__sparc__) #define SDL_BYTEORDER SDL_BIG_ENDIAN #else #define SDL_BYTEORDER SDL_LIL_ENDIAN #endif #endif /* !SDL_BYTEORDER */ #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif /** * @name SDL_Swap Functions * Use inline functions for compilers that support them, and static * functions for those that do not. Because these functions become * static for compilers that do not support inline functions, this * header should only be included in files that actually use them. */ /*@{*/ #if defined(__GNUC__) && defined(__i386__) && \ !(__GNUC__ == 2 && __GNUC_MINOR__ <= 95 /* broken gcc version */) static __inline__ Uint16 SDL_Swap16(Uint16 x) { __asm__("xchgb %b0,%h0" : "=q" (x) : "0" (x)); return x; } #elif defined(__GNUC__) && defined(__x86_64__) static __inline__ Uint16 SDL_Swap16(Uint16 x) { __asm__("xchgb %b0,%h0" : "=Q" (x) : "0" (x)); return x; } #elif defined(__GNUC__) && (defined(__powerpc__) || defined(__ppc__)) static __inline__ Uint16 SDL_Swap16(Uint16 x) { Uint16 result; __asm__("rlwimi %0,%2,8,16,23" : "=&r" (result) : "0" (x >> 8), "r" (x)); return result; } #elif defined(__GNUC__) && (defined(__M68000__) || defined(__M68020__)) static __inline__ Uint16 SDL_Swap16(Uint16 x) { __asm__("rorw #8,%0" : "=d" (x) : "0" (x) : "cc"); return x; } #else static __inline__ Uint16 SDL_Swap16(Uint16 x) { return((x<<8)|(x>>8)); } #endif #if defined(__GNUC__) && defined(__i386__) && \ !(__GNUC__ == 2 && __GNUC_MINOR__ <= 95 /* broken gcc version */) static __inline__ Uint32 SDL_Swap32(Uint32 x) { __asm__("bswap %0" : "=r" (x) : "0" (x)); return x; } #elif defined(__GNUC__) && defined(__x86_64__) static __inline__ Uint32 SDL_Swap32(Uint32 x) { __asm__("bswapl %0" : "=r" (x) : "0" (x)); return x; } #elif defined(__GNUC__) && (defined(__powerpc__) || defined(__ppc__)) static __inline__ Uint32 SDL_Swap32(Uint32 x) { Uint32 result; __asm__("rlwimi %0,%2,24,16,23" : "=&r" (result) : "0" (x>>24), "r" (x)); __asm__("rlwimi %0,%2,8,8,15" : "=&r" (result) : "0" (result), "r" (x)); __asm__("rlwimi %0,%2,24,0,7" : "=&r" (result) : "0" (result), "r" (x)); return result; } #elif defined(__GNUC__) && (defined(__M68000__) || defined(__M68020__)) static __inline__ Uint32 SDL_Swap32(Uint32 x) { __asm__("rorw #8,%0\n\tswap %0\n\trorw #8,%0" : "=d" (x) : "0" (x) : "cc"); return x; } #else static __inline__ Uint32 SDL_Swap32(Uint32 x) { return((x<<24)|((x<<8)&0x00FF0000)|((x>>8)&0x0000FF00)|(x>>24)); } #endif #ifdef SDL_HAS_64BIT_TYPE #if defined(__GNUC__) && defined(__i386__) && \ !(__GNUC__ == 2 && __GNUC_MINOR__ <= 95 /* broken gcc version */) static __inline__ Uint64 SDL_Swap64(Uint64 x) { union { struct { Uint32 a,b; } s; Uint64 u; } v; v.u = x; __asm__("bswapl %0 ; bswapl %1 ; xchgl %0,%1" : "=r" (v.s.a), "=r" (v.s.b) : "0" (v.s.a), "1" (v.s.b)); return v.u; } #elif defined(__GNUC__) && defined(__x86_64__) static __inline__ Uint64 SDL_Swap64(Uint64 x) { __asm__("bswapq %0" : "=r" (x) : "0" (x)); return x; } #else static __inline__ Uint64 SDL_Swap64(Uint64 x) { Uint32 hi, lo; /* Separate into high and low 32-bit values and swap them */ lo = SDL_static_cast(Uint32, x & 0xFFFFFFFF); x >>= 32; hi = SDL_static_cast(Uint32, x & 0xFFFFFFFF); x = SDL_Swap32(lo); x <<= 32; x |= SDL_Swap32(hi); return(x); } #endif #else /* This is mainly to keep compilers from complaining in SDL code. * If there is no real 64-bit datatype, then compilers will complain about * the fake 64-bit datatype that SDL provides when it compiles user code. */ #define SDL_Swap64(X) (X) #endif /* SDL_HAS_64BIT_TYPE */ /*@}*/ /** * @name SDL_SwapLE and SDL_SwapBE Functions * Byteswap item from the specified endianness to the native endianness */ /*@{*/ #if SDL_BYTEORDER == SDL_LIL_ENDIAN #define SDL_SwapLE16(X) (X) #define SDL_SwapLE32(X) (X) #define SDL_SwapLE64(X) (X) #define SDL_SwapBE16(X) SDL_Swap16(X) #define SDL_SwapBE32(X) SDL_Swap32(X) #define SDL_SwapBE64(X) SDL_Swap64(X) #else #define SDL_SwapLE16(X) SDL_Swap16(X) #define SDL_SwapLE32(X) SDL_Swap32(X) #define SDL_SwapLE64(X) SDL_Swap64(X) #define SDL_SwapBE16(X) (X) #define SDL_SwapBE32(X) (X) #define SDL_SwapBE64(X) (X) #endif /*@}*/ /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* _SDL_endian_h */ ================================================ FILE: other/sdl/include/SDL_error.h ================================================ /* SDL - Simple DirectMedia Layer Copyright (C) 1997-2009 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org */ /** * @file SDL_error.h * Simple error message routines for SDL */ #ifndef _SDL_error_h #define _SDL_error_h #include "SDL_stdinc.h" #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif /** * @name Public functions */ /*@{*/ extern DECLSPEC void SDLCALL SDL_SetError(const char *fmt, ...); extern DECLSPEC char * SDLCALL SDL_GetError(void); extern DECLSPEC void SDLCALL SDL_ClearError(void); /*@}*/ /** * @name Private functions * @internal Private error message function - used internally */ /*@{*/ #define SDL_OutOfMemory() SDL_Error(SDL_ENOMEM) #define SDL_Unsupported() SDL_Error(SDL_UNSUPPORTED) typedef enum { SDL_ENOMEM, SDL_EFREAD, SDL_EFWRITE, SDL_EFSEEK, SDL_UNSUPPORTED, SDL_LASTERROR } SDL_errorcode; extern DECLSPEC void SDLCALL SDL_Error(SDL_errorcode code); /*@}*/ /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* _SDL_error_h */ ================================================ FILE: other/sdl/include/SDL_events.h ================================================ /* SDL - Simple DirectMedia Layer Copyright (C) 1997-2009 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org */ /** * @file SDL_events.h * Include file for SDL event handling */ #ifndef _SDL_events_h #define _SDL_events_h #include "SDL_stdinc.h" #include "SDL_error.h" #include "SDL_active.h" #include "SDL_keyboard.h" #include "SDL_mouse.h" #include "SDL_joystick.h" #include "SDL_quit.h" #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif /** @name General keyboard/mouse state definitions */ /*@{*/ #define SDL_RELEASED 0 #define SDL_PRESSED 1 /*@}*/ /** Event enumerations */ typedef enum { SDL_NOEVENT = 0, /**< Unused (do not remove) */ SDL_ACTIVEEVENT, /**< Application loses/gains visibility */ SDL_KEYDOWN, /**< Keys pressed */ SDL_KEYUP, /**< Keys released */ SDL_MOUSEMOTION, /**< Mouse moved */ SDL_MOUSEBUTTONDOWN, /**< Mouse button pressed */ SDL_MOUSEBUTTONUP, /**< Mouse button released */ SDL_JOYAXISMOTION, /**< Joystick axis motion */ SDL_JOYBALLMOTION, /**< Joystick trackball motion */ SDL_JOYHATMOTION, /**< Joystick hat position change */ SDL_JOYBUTTONDOWN, /**< Joystick button pressed */ SDL_JOYBUTTONUP, /**< Joystick button released */ SDL_QUIT, /**< User-requested quit */ SDL_SYSWMEVENT, /**< System specific event */ SDL_EVENT_RESERVEDA, /**< Reserved for future use.. */ SDL_EVENT_RESERVEDB, /**< Reserved for future use.. */ SDL_VIDEORESIZE, /**< User resized video mode */ SDL_VIDEOEXPOSE, /**< Screen needs to be redrawn */ SDL_EVENT_RESERVED2, /**< Reserved for future use.. */ SDL_EVENT_RESERVED3, /**< Reserved for future use.. */ SDL_EVENT_RESERVED4, /**< Reserved for future use.. */ SDL_EVENT_RESERVED5, /**< Reserved for future use.. */ SDL_EVENT_RESERVED6, /**< Reserved for future use.. */ SDL_EVENT_RESERVED7, /**< Reserved for future use.. */ /** Events SDL_USEREVENT through SDL_MAXEVENTS-1 are for your use */ SDL_USEREVENT = 24, /** This last event is only for bounding internal arrays * It is the number of bits in the event mask datatype -- Uint32 */ SDL_NUMEVENTS = 32 } SDL_EventType; /** @name Predefined event masks */ /*@{*/ #define SDL_EVENTMASK(X) (1<<(X)) typedef enum { SDL_ACTIVEEVENTMASK = SDL_EVENTMASK(SDL_ACTIVEEVENT), SDL_KEYDOWNMASK = SDL_EVENTMASK(SDL_KEYDOWN), SDL_KEYUPMASK = SDL_EVENTMASK(SDL_KEYUP), SDL_KEYEVENTMASK = SDL_EVENTMASK(SDL_KEYDOWN)| SDL_EVENTMASK(SDL_KEYUP), SDL_MOUSEMOTIONMASK = SDL_EVENTMASK(SDL_MOUSEMOTION), SDL_MOUSEBUTTONDOWNMASK = SDL_EVENTMASK(SDL_MOUSEBUTTONDOWN), SDL_MOUSEBUTTONUPMASK = SDL_EVENTMASK(SDL_MOUSEBUTTONUP), SDL_MOUSEEVENTMASK = SDL_EVENTMASK(SDL_MOUSEMOTION)| SDL_EVENTMASK(SDL_MOUSEBUTTONDOWN)| SDL_EVENTMASK(SDL_MOUSEBUTTONUP), SDL_JOYAXISMOTIONMASK = SDL_EVENTMASK(SDL_JOYAXISMOTION), SDL_JOYBALLMOTIONMASK = SDL_EVENTMASK(SDL_JOYBALLMOTION), SDL_JOYHATMOTIONMASK = SDL_EVENTMASK(SDL_JOYHATMOTION), SDL_JOYBUTTONDOWNMASK = SDL_EVENTMASK(SDL_JOYBUTTONDOWN), SDL_JOYBUTTONUPMASK = SDL_EVENTMASK(SDL_JOYBUTTONUP), SDL_JOYEVENTMASK = SDL_EVENTMASK(SDL_JOYAXISMOTION)| SDL_EVENTMASK(SDL_JOYBALLMOTION)| SDL_EVENTMASK(SDL_JOYHATMOTION)| SDL_EVENTMASK(SDL_JOYBUTTONDOWN)| SDL_EVENTMASK(SDL_JOYBUTTONUP), SDL_VIDEORESIZEMASK = SDL_EVENTMASK(SDL_VIDEORESIZE), SDL_VIDEOEXPOSEMASK = SDL_EVENTMASK(SDL_VIDEOEXPOSE), SDL_QUITMASK = SDL_EVENTMASK(SDL_QUIT), SDL_SYSWMEVENTMASK = SDL_EVENTMASK(SDL_SYSWMEVENT) } SDL_EventMask ; #define SDL_ALLEVENTS 0xFFFFFFFF /*@}*/ /** Application visibility event structure */ typedef struct SDL_ActiveEvent { Uint8 type; /**< SDL_ACTIVEEVENT */ Uint8 gain; /**< Whether given states were gained or lost (1/0) */ Uint8 state; /**< A mask of the focus states */ } SDL_ActiveEvent; /** Keyboard event structure */ typedef struct SDL_KeyboardEvent { Uint8 type; /**< SDL_KEYDOWN or SDL_KEYUP */ Uint8 which; /**< The keyboard device index */ Uint8 state; /**< SDL_PRESSED or SDL_RELEASED */ SDL_keysym keysym; } SDL_KeyboardEvent; /** Mouse motion event structure */ typedef struct SDL_MouseMotionEvent { Uint8 type; /**< SDL_MOUSEMOTION */ Uint8 which; /**< The mouse device index */ Uint8 state; /**< The current button state */ Uint16 x, y; /**< The X/Y coordinates of the mouse */ Sint16 xrel; /**< The relative motion in the X direction */ Sint16 yrel; /**< The relative motion in the Y direction */ } SDL_MouseMotionEvent; /** Mouse button event structure */ typedef struct SDL_MouseButtonEvent { Uint8 type; /**< SDL_MOUSEBUTTONDOWN or SDL_MOUSEBUTTONUP */ Uint8 which; /**< The mouse device index */ Uint8 button; /**< The mouse button index */ Uint8 state; /**< SDL_PRESSED or SDL_RELEASED */ Uint16 x, y; /**< The X/Y coordinates of the mouse at press time */ } SDL_MouseButtonEvent; /** Joystick axis motion event structure */ typedef struct SDL_JoyAxisEvent { Uint8 type; /**< SDL_JOYAXISMOTION */ Uint8 which; /**< The joystick device index */ Uint8 axis; /**< The joystick axis index */ Sint16 value; /**< The axis value (range: -32768 to 32767) */ } SDL_JoyAxisEvent; /** Joystick trackball motion event structure */ typedef struct SDL_JoyBallEvent { Uint8 type; /**< SDL_JOYBALLMOTION */ Uint8 which; /**< The joystick device index */ Uint8 ball; /**< The joystick trackball index */ Sint16 xrel; /**< The relative motion in the X direction */ Sint16 yrel; /**< The relative motion in the Y direction */ } SDL_JoyBallEvent; /** Joystick hat position change event structure */ typedef struct SDL_JoyHatEvent { Uint8 type; /**< SDL_JOYHATMOTION */ Uint8 which; /**< The joystick device index */ Uint8 hat; /**< The joystick hat index */ Uint8 value; /**< The hat position value: * SDL_HAT_LEFTUP SDL_HAT_UP SDL_HAT_RIGHTUP * SDL_HAT_LEFT SDL_HAT_CENTERED SDL_HAT_RIGHT * SDL_HAT_LEFTDOWN SDL_HAT_DOWN SDL_HAT_RIGHTDOWN * Note that zero means the POV is centered. */ } SDL_JoyHatEvent; /** Joystick button event structure */ typedef struct SDL_JoyButtonEvent { Uint8 type; /**< SDL_JOYBUTTONDOWN or SDL_JOYBUTTONUP */ Uint8 which; /**< The joystick device index */ Uint8 button; /**< The joystick button index */ Uint8 state; /**< SDL_PRESSED or SDL_RELEASED */ } SDL_JoyButtonEvent; /** The "window resized" event * When you get this event, you are responsible for setting a new video * mode with the new width and height. */ typedef struct SDL_ResizeEvent { Uint8 type; /**< SDL_VIDEORESIZE */ int w; /**< New width */ int h; /**< New height */ } SDL_ResizeEvent; /** The "screen redraw" event */ typedef struct SDL_ExposeEvent { Uint8 type; /**< SDL_VIDEOEXPOSE */ } SDL_ExposeEvent; /** The "quit requested" event */ typedef struct SDL_QuitEvent { Uint8 type; /**< SDL_QUIT */ } SDL_QuitEvent; /** A user-defined event type */ typedef struct SDL_UserEvent { Uint8 type; /**< SDL_USEREVENT through SDL_NUMEVENTS-1 */ int code; /**< User defined event code */ void *data1; /**< User defined data pointer */ void *data2; /**< User defined data pointer */ } SDL_UserEvent; /** If you want to use this event, you should include SDL_syswm.h */ struct SDL_SysWMmsg; typedef struct SDL_SysWMmsg SDL_SysWMmsg; typedef struct SDL_SysWMEvent { Uint8 type; SDL_SysWMmsg *msg; } SDL_SysWMEvent; /** General event structure */ typedef union SDL_Event { Uint8 type; SDL_ActiveEvent active; SDL_KeyboardEvent key; SDL_MouseMotionEvent motion; SDL_MouseButtonEvent button; SDL_JoyAxisEvent jaxis; SDL_JoyBallEvent jball; SDL_JoyHatEvent jhat; SDL_JoyButtonEvent jbutton; SDL_ResizeEvent resize; SDL_ExposeEvent expose; SDL_QuitEvent quit; SDL_UserEvent user; SDL_SysWMEvent syswm; } SDL_Event; /* Function prototypes */ /** Pumps the event loop, gathering events from the input devices. * This function updates the event queue and internal input device state. * This should only be run in the thread that sets the video mode. */ extern DECLSPEC void SDLCALL SDL_PumpEvents(void); typedef enum { SDL_ADDEVENT, SDL_PEEKEVENT, SDL_GETEVENT } SDL_eventaction; /** * Checks the event queue for messages and optionally returns them. * * If 'action' is SDL_ADDEVENT, up to 'numevents' events will be added to * the back of the event queue. * If 'action' is SDL_PEEKEVENT, up to 'numevents' events at the front * of the event queue, matching 'mask', will be returned and will not * be removed from the queue. * If 'action' is SDL_GETEVENT, up to 'numevents' events at the front * of the event queue, matching 'mask', will be returned and will be * removed from the queue. * * @return * This function returns the number of events actually stored, or -1 * if there was an error. * * This function is thread-safe. */ extern DECLSPEC int SDLCALL SDL_PeepEvents(SDL_Event *events, int numevents, SDL_eventaction action, Uint32 mask); /** Polls for currently pending events, and returns 1 if there are any pending * events, or 0 if there are none available. If 'event' is not NULL, the next * event is removed from the queue and stored in that area. */ extern DECLSPEC int SDLCALL SDL_PollEvent(SDL_Event *event); /** Waits indefinitely for the next available event, returning 1, or 0 if there * was an error while waiting for events. If 'event' is not NULL, the next * event is removed from the queue and stored in that area. */ extern DECLSPEC int SDLCALL SDL_WaitEvent(SDL_Event *event); /** Add an event to the event queue. * This function returns 0 on success, or -1 if the event queue was full * or there was some other error. */ extern DECLSPEC int SDLCALL SDL_PushEvent(SDL_Event *event); /** @name Event Filtering */ /*@{*/ typedef int (SDLCALL *SDL_EventFilter)(const SDL_Event *event); /** * This function sets up a filter to process all events before they * change internal state and are posted to the internal event queue. * * The filter is protypted as: * @code typedef int (SDLCALL *SDL_EventFilter)(const SDL_Event *event); @endcode * * If the filter returns 1, then the event will be added to the internal queue. * If it returns 0, then the event will be dropped from the queue, but the * internal state will still be updated. This allows selective filtering of * dynamically arriving events. * * @warning Be very careful of what you do in the event filter function, as * it may run in a different thread! * * There is one caveat when dealing with the SDL_QUITEVENT event type. The * event filter is only called when the window manager desires to close the * application window. If the event filter returns 1, then the window will * be closed, otherwise the window will remain open if possible. * If the quit event is generated by an interrupt signal, it will bypass the * internal queue and be delivered to the application at the next event poll. */ extern DECLSPEC void SDLCALL SDL_SetEventFilter(SDL_EventFilter filter); /** * Return the current event filter - can be used to "chain" filters. * If there is no event filter set, this function returns NULL. */ extern DECLSPEC SDL_EventFilter SDLCALL SDL_GetEventFilter(void); /*@}*/ /** @name Event State */ /*@{*/ #define SDL_QUERY -1 #define SDL_IGNORE 0 #define SDL_DISABLE 0 #define SDL_ENABLE 1 /*@}*/ /** * This function allows you to set the state of processing certain events. * If 'state' is set to SDL_IGNORE, that event will be automatically dropped * from the event queue and will not event be filtered. * If 'state' is set to SDL_ENABLE, that event will be processed normally. * If 'state' is set to SDL_QUERY, SDL_EventState() will return the * current processing state of the specified event. */ extern DECLSPEC Uint8 SDLCALL SDL_EventState(Uint8 type, int state); /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* _SDL_events_h */ ================================================ FILE: other/sdl/include/SDL_getenv.h ================================================ /* SDL - Simple DirectMedia Layer Copyright (C) 1997-2009 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org */ /** @file SDL_getenv.h * @deprecated Use SDL_stdinc.h instead */ /* DEPRECATED */ #include "SDL_stdinc.h" ================================================ FILE: other/sdl/include/SDL_joystick.h ================================================ /* SDL - Simple DirectMedia Layer Copyright (C) 1997-2009 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org */ /** @file SDL_joystick.h * Include file for SDL joystick event handling */ #ifndef _SDL_joystick_h #define _SDL_joystick_h #include "SDL_stdinc.h" #include "SDL_error.h" #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif /** @file SDL_joystick.h * @note In order to use these functions, SDL_Init() must have been called * with the SDL_INIT_JOYSTICK flag. This causes SDL to scan the system * for joysticks, and load appropriate drivers. */ /** The joystick structure used to identify an SDL joystick */ struct _SDL_Joystick; typedef struct _SDL_Joystick SDL_Joystick; /* Function prototypes */ /** * Count the number of joysticks attached to the system */ extern DECLSPEC int SDLCALL SDL_NumJoysticks(void); /** * Get the implementation dependent name of a joystick. * * This can be called before any joysticks are opened. * If no name can be found, this function returns NULL. */ extern DECLSPEC const char * SDLCALL SDL_JoystickName(int device_index); /** * Open a joystick for use. * * @param[in] device_index * The index passed as an argument refers to * the N'th joystick on the system. This index is the value which will * identify this joystick in future joystick events. * * @return This function returns a joystick identifier, or NULL if an error occurred. */ extern DECLSPEC SDL_Joystick * SDLCALL SDL_JoystickOpen(int device_index); /** * Returns 1 if the joystick has been opened, or 0 if it has not. */ extern DECLSPEC int SDLCALL SDL_JoystickOpened(int device_index); /** * Get the device index of an opened joystick. */ extern DECLSPEC int SDLCALL SDL_JoystickIndex(SDL_Joystick *joystick); /** * Get the number of general axis controls on a joystick */ extern DECLSPEC int SDLCALL SDL_JoystickNumAxes(SDL_Joystick *joystick); /** * Get the number of trackballs on a joystick * * Joystick trackballs have only relative motion events associated * with them and their state cannot be polled. */ extern DECLSPEC int SDLCALL SDL_JoystickNumBalls(SDL_Joystick *joystick); /** * Get the number of POV hats on a joystick */ extern DECLSPEC int SDLCALL SDL_JoystickNumHats(SDL_Joystick *joystick); /** * Get the number of buttons on a joystick */ extern DECLSPEC int SDLCALL SDL_JoystickNumButtons(SDL_Joystick *joystick); /** * Update the current state of the open joysticks. * * This is called automatically by the event loop if any joystick * events are enabled. */ extern DECLSPEC void SDLCALL SDL_JoystickUpdate(void); /** * Enable/disable joystick event polling. * * If joystick events are disabled, you must call SDL_JoystickUpdate() * yourself and check the state of the joystick when you want joystick * information. * * @param[in] state The state can be one of SDL_QUERY, SDL_ENABLE or SDL_IGNORE. */ extern DECLSPEC int SDLCALL SDL_JoystickEventState(int state); /** * Get the current state of an axis control on a joystick * * @param[in] axis The axis indices start at index 0. * * @return The state is a value ranging from -32768 to 32767. */ extern DECLSPEC Sint16 SDLCALL SDL_JoystickGetAxis(SDL_Joystick *joystick, int axis); /** * @name Hat Positions * The return value of SDL_JoystickGetHat() is one of the following positions: */ /*@{*/ #define SDL_HAT_CENTERED 0x00 #define SDL_HAT_UP 0x01 #define SDL_HAT_RIGHT 0x02 #define SDL_HAT_DOWN 0x04 #define SDL_HAT_LEFT 0x08 #define SDL_HAT_RIGHTUP (SDL_HAT_RIGHT|SDL_HAT_UP) #define SDL_HAT_RIGHTDOWN (SDL_HAT_RIGHT|SDL_HAT_DOWN) #define SDL_HAT_LEFTUP (SDL_HAT_LEFT|SDL_HAT_UP) #define SDL_HAT_LEFTDOWN (SDL_HAT_LEFT|SDL_HAT_DOWN) /*@}*/ /** * Get the current state of a POV hat on a joystick * * @param[in] hat The hat indices start at index 0. */ extern DECLSPEC Uint8 SDLCALL SDL_JoystickGetHat(SDL_Joystick *joystick, int hat); /** * Get the ball axis change since the last poll * * @param[in] ball The ball indices start at index 0. * * @return This returns 0, or -1 if you passed it invalid parameters. */ extern DECLSPEC int SDLCALL SDL_JoystickGetBall(SDL_Joystick *joystick, int ball, int *dx, int *dy); /** * Get the current state of a button on a joystick * * @param[in] button The button indices start at index 0. */ extern DECLSPEC Uint8 SDLCALL SDL_JoystickGetButton(SDL_Joystick *joystick, int button); /** * Close a joystick previously opened with SDL_JoystickOpen() */ extern DECLSPEC void SDLCALL SDL_JoystickClose(SDL_Joystick *joystick); /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* _SDL_joystick_h */ ================================================ FILE: other/sdl/include/SDL_keyboard.h ================================================ /* SDL - Simple DirectMedia Layer Copyright (C) 1997-2009 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org */ /** @file SDL_keyboard.h * Include file for SDL keyboard event handling */ #ifndef _SDL_keyboard_h #define _SDL_keyboard_h #include "SDL_stdinc.h" #include "SDL_error.h" #include "SDL_keysym.h" #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif /** Keysym structure * * - The scancode is hardware dependent, and should not be used by general * applications. If no hardware scancode is available, it will be 0. * * - The 'unicode' translated character is only available when character * translation is enabled by the SDL_EnableUNICODE() API. If non-zero, * this is a UNICODE character corresponding to the keypress. If the * high 9 bits of the character are 0, then this maps to the equivalent * ASCII character: * @code * char ch; * if ( (keysym.unicode & 0xFF80) == 0 ) { * ch = keysym.unicode & 0x7F; * } else { * An international character.. * } * @endcode */ typedef struct SDL_keysym { Uint8 scancode; /**< hardware specific scancode */ SDLKey sym; /**< SDL virtual keysym */ SDLMod mod; /**< current key modifiers */ Uint16 unicode; /**< translated character */ } SDL_keysym; /** This is the mask which refers to all hotkey bindings */ #define SDL_ALL_HOTKEYS 0xFFFFFFFF /* Function prototypes */ /** * Enable/Disable UNICODE translation of keyboard input. * * This translation has some overhead, so translation defaults off. * * @param[in] enable * If 'enable' is 1, translation is enabled. * If 'enable' is 0, translation is disabled. * If 'enable' is -1, the translation state is not changed. * * @return It returns the previous state of keyboard translation. */ extern DECLSPEC int SDLCALL SDL_EnableUNICODE(int enable); #define SDL_DEFAULT_REPEAT_DELAY 500 #define SDL_DEFAULT_REPEAT_INTERVAL 30 /** * Enable/Disable keyboard repeat. Keyboard repeat defaults to off. * * @param[in] delay * 'delay' is the initial delay in ms between the time when a key is * pressed, and keyboard repeat begins. * * @param[in] interval * 'interval' is the time in ms between keyboard repeat events. * * If 'delay' is set to 0, keyboard repeat is disabled. */ extern DECLSPEC int SDLCALL SDL_EnableKeyRepeat(int delay, int interval); extern DECLSPEC void SDLCALL SDL_GetKeyRepeat(int *delay, int *interval); /** * Get a snapshot of the current state of the keyboard. * Returns an array of keystates, indexed by the SDLK_* syms. * Usage: * @code * Uint8 *keystate = SDL_GetKeyState(NULL); * if ( keystate[SDLK_RETURN] ) //... \<RETURN> is pressed. * @endcode */ extern DECLSPEC Uint8 * SDLCALL SDL_GetKeyState(int *numkeys); /** * Get the current key modifier state */ extern DECLSPEC SDLMod SDLCALL SDL_GetModState(void); /** * Set the current key modifier state. * This does not change the keyboard state, only the key modifier flags. */ extern DECLSPEC void SDLCALL SDL_SetModState(SDLMod modstate); /** * Get the name of an SDL virtual keysym */ extern DECLSPEC char * SDLCALL SDL_GetKeyName(SDLKey key); /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* _SDL_keyboard_h */ ================================================ FILE: other/sdl/include/SDL_keysym.h ================================================ /* SDL - Simple DirectMedia Layer Copyright (C) 1997-2009 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org */ #ifndef _SDL_keysym_h #define _SDL_keysym_h /** What we really want is a mapping of every raw key on the keyboard. * To support international keyboards, we use the range 0xA1 - 0xFF * as international virtual keycodes. We'll follow in the footsteps of X11... * @brief The names of the keys */ typedef enum { /** @name ASCII mapped keysyms * The keyboard syms have been cleverly chosen to map to ASCII */ /*@{*/ SDLK_UNKNOWN = 0, SDLK_FIRST = 0, SDLK_BACKSPACE = 8, SDLK_TAB = 9, SDLK_CLEAR = 12, SDLK_RETURN = 13, SDLK_PAUSE = 19, SDLK_ESCAPE = 27, SDLK_SPACE = 32, SDLK_EXCLAIM = 33, SDLK_QUOTEDBL = 34, SDLK_HASH = 35, SDLK_DOLLAR = 36, SDLK_AMPERSAND = 38, SDLK_QUOTE = 39, SDLK_LEFTPAREN = 40, SDLK_RIGHTPAREN = 41, SDLK_ASTERISK = 42, SDLK_PLUS = 43, SDLK_COMMA = 44, SDLK_MINUS = 45, SDLK_PERIOD = 46, SDLK_SLASH = 47, SDLK_0 = 48, SDLK_1 = 49, SDLK_2 = 50, SDLK_3 = 51, SDLK_4 = 52, SDLK_5 = 53, SDLK_6 = 54, SDLK_7 = 55, SDLK_8 = 56, SDLK_9 = 57, SDLK_COLON = 58, SDLK_SEMICOLON = 59, SDLK_LESS = 60, SDLK_EQUALS = 61, SDLK_GREATER = 62, SDLK_QUESTION = 63, SDLK_AT = 64, /* Skip uppercase letters */ SDLK_LEFTBRACKET = 91, SDLK_BACKSLASH = 92, SDLK_RIGHTBRACKET = 93, SDLK_CARET = 94, SDLK_UNDERSCORE = 95, SDLK_BACKQUOTE = 96, SDLK_a = 97, SDLK_b = 98, SDLK_c = 99, SDLK_d = 100, SDLK_e = 101, SDLK_f = 102, SDLK_g = 103, SDLK_h = 104, SDLK_i = 105, SDLK_j = 106, SDLK_k = 107, SDLK_l = 108, SDLK_m = 109, SDLK_n = 110, SDLK_o = 111, SDLK_p = 112, SDLK_q = 113, SDLK_r = 114, SDLK_s = 115, SDLK_t = 116, SDLK_u = 117, SDLK_v = 118, SDLK_w = 119, SDLK_x = 120, SDLK_y = 121, SDLK_z = 122, SDLK_DELETE = 127, /* End of ASCII mapped keysyms */ /*@}*/ /** @name International keyboard syms */ /*@{*/ SDLK_WORLD_0 = 160, /* 0xA0 */ SDLK_WORLD_1 = 161, SDLK_WORLD_2 = 162, SDLK_WORLD_3 = 163, SDLK_WORLD_4 = 164, SDLK_WORLD_5 = 165, SDLK_WORLD_6 = 166, SDLK_WORLD_7 = 167, SDLK_WORLD_8 = 168, SDLK_WORLD_9 = 169, SDLK_WORLD_10 = 170, SDLK_WORLD_11 = 171, SDLK_WORLD_12 = 172, SDLK_WORLD_13 = 173, SDLK_WORLD_14 = 174, SDLK_WORLD_15 = 175, SDLK_WORLD_16 = 176, SDLK_WORLD_17 = 177, SDLK_WORLD_18 = 178, SDLK_WORLD_19 = 179, SDLK_WORLD_20 = 180, SDLK_WORLD_21 = 181, SDLK_WORLD_22 = 182, SDLK_WORLD_23 = 183, SDLK_WORLD_24 = 184, SDLK_WORLD_25 = 185, SDLK_WORLD_26 = 186, SDLK_WORLD_27 = 187, SDLK_WORLD_28 = 188, SDLK_WORLD_29 = 189, SDLK_WORLD_30 = 190, SDLK_WORLD_31 = 191, SDLK_WORLD_32 = 192, SDLK_WORLD_33 = 193, SDLK_WORLD_34 = 194, SDLK_WORLD_35 = 195, SDLK_WORLD_36 = 196, SDLK_WORLD_37 = 197, SDLK_WORLD_38 = 198, SDLK_WORLD_39 = 199, SDLK_WORLD_40 = 200, SDLK_WORLD_41 = 201, SDLK_WORLD_42 = 202, SDLK_WORLD_43 = 203, SDLK_WORLD_44 = 204, SDLK_WORLD_45 = 205, SDLK_WORLD_46 = 206, SDLK_WORLD_47 = 207, SDLK_WORLD_48 = 208, SDLK_WORLD_49 = 209, SDLK_WORLD_50 = 210, SDLK_WORLD_51 = 211, SDLK_WORLD_52 = 212, SDLK_WORLD_53 = 213, SDLK_WORLD_54 = 214, SDLK_WORLD_55 = 215, SDLK_WORLD_56 = 216, SDLK_WORLD_57 = 217, SDLK_WORLD_58 = 218, SDLK_WORLD_59 = 219, SDLK_WORLD_60 = 220, SDLK_WORLD_61 = 221, SDLK_WORLD_62 = 222, SDLK_WORLD_63 = 223, SDLK_WORLD_64 = 224, SDLK_WORLD_65 = 225, SDLK_WORLD_66 = 226, SDLK_WORLD_67 = 227, SDLK_WORLD_68 = 228, SDLK_WORLD_69 = 229, SDLK_WORLD_70 = 230, SDLK_WORLD_71 = 231, SDLK_WORLD_72 = 232, SDLK_WORLD_73 = 233, SDLK_WORLD_74 = 234, SDLK_WORLD_75 = 235, SDLK_WORLD_76 = 236, SDLK_WORLD_77 = 237, SDLK_WORLD_78 = 238, SDLK_WORLD_79 = 239, SDLK_WORLD_80 = 240, SDLK_WORLD_81 = 241, SDLK_WORLD_82 = 242, SDLK_WORLD_83 = 243, SDLK_WORLD_84 = 244, SDLK_WORLD_85 = 245, SDLK_WORLD_86 = 246, SDLK_WORLD_87 = 247, SDLK_WORLD_88 = 248, SDLK_WORLD_89 = 249, SDLK_WORLD_90 = 250, SDLK_WORLD_91 = 251, SDLK_WORLD_92 = 252, SDLK_WORLD_93 = 253, SDLK_WORLD_94 = 254, SDLK_WORLD_95 = 255, /* 0xFF */ /*@}*/ /** @name Numeric keypad */ /*@{*/ SDLK_KP0 = 256, SDLK_KP1 = 257, SDLK_KP2 = 258, SDLK_KP3 = 259, SDLK_KP4 = 260, SDLK_KP5 = 261, SDLK_KP6 = 262, SDLK_KP7 = 263, SDLK_KP8 = 264, SDLK_KP9 = 265, SDLK_KP_PERIOD = 266, SDLK_KP_DIVIDE = 267, SDLK_KP_MULTIPLY = 268, SDLK_KP_MINUS = 269, SDLK_KP_PLUS = 270, SDLK_KP_ENTER = 271, SDLK_KP_EQUALS = 272, /*@}*/ /** @name Arrows + Home/End pad */ /*@{*/ SDLK_UP = 273, SDLK_DOWN = 274, SDLK_RIGHT = 275, SDLK_LEFT = 276, SDLK_INSERT = 277, SDLK_HOME = 278, SDLK_END = 279, SDLK_PAGEUP = 280, SDLK_PAGEDOWN = 281, /*@}*/ /** @name Function keys */ /*@{*/ SDLK_F1 = 282, SDLK_F2 = 283, SDLK_F3 = 284, SDLK_F4 = 285, SDLK_F5 = 286, SDLK_F6 = 287, SDLK_F7 = 288, SDLK_F8 = 289, SDLK_F9 = 290, SDLK_F10 = 291, SDLK_F11 = 292, SDLK_F12 = 293, SDLK_F13 = 294, SDLK_F14 = 295, SDLK_F15 = 296, /*@}*/ /** @name Key state modifier keys */ /*@{*/ SDLK_NUMLOCK = 300, SDLK_CAPSLOCK = 301, SDLK_SCROLLOCK = 302, SDLK_RSHIFT = 303, SDLK_LSHIFT = 304, SDLK_RCTRL = 305, SDLK_LCTRL = 306, SDLK_RALT = 307, SDLK_LALT = 308, SDLK_RMETA = 309, SDLK_LMETA = 310, SDLK_LSUPER = 311, /**< Left "Windows" key */ SDLK_RSUPER = 312, /**< Right "Windows" key */ SDLK_MODE = 313, /**< "Alt Gr" key */ SDLK_COMPOSE = 314, /**< Multi-key compose key */ /*@}*/ /** @name Miscellaneous function keys */ /*@{*/ SDLK_HELP = 315, SDLK_PRINT = 316, SDLK_SYSREQ = 317, SDLK_BREAK = 318, SDLK_MENU = 319, SDLK_POWER = 320, /**< Power Macintosh power key */ SDLK_EURO = 321, /**< Some european keyboards */ SDLK_UNDO = 322, /**< Atari keyboard has Undo */ /*@}*/ /* Add any other keys here */ SDLK_LAST } SDLKey; /** Enumeration of valid key mods (possibly OR'd together) */ typedef enum { KMOD_NONE = 0x0000, KMOD_LSHIFT= 0x0001, KMOD_RSHIFT= 0x0002, KMOD_LCTRL = 0x0040, KMOD_RCTRL = 0x0080, KMOD_LALT = 0x0100, KMOD_RALT = 0x0200, KMOD_LMETA = 0x0400, KMOD_RMETA = 0x0800, KMOD_NUM = 0x1000, KMOD_CAPS = 0x2000, KMOD_MODE = 0x4000, KMOD_RESERVED = 0x8000 } SDLMod; #define KMOD_CTRL (KMOD_LCTRL|KMOD_RCTRL) #define KMOD_SHIFT (KMOD_LSHIFT|KMOD_RSHIFT) #define KMOD_ALT (KMOD_LALT|KMOD_RALT) #define KMOD_META (KMOD_LMETA|KMOD_RMETA) #endif /* _SDL_keysym_h */ ================================================ FILE: other/sdl/include/SDL_loadso.h ================================================ /* SDL - Simple DirectMedia Layer Copyright (C) 1997-2009 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org */ /** @file SDL_loadso.h * System dependent library loading routines */ /** @file SDL_loadso.h * Some things to keep in mind: * - These functions only work on C function names. Other languages may * have name mangling and intrinsic language support that varies from * compiler to compiler. * - Make sure you declare your function pointers with the same calling * convention as the actual library function. Your code will crash * mysteriously if you do not do this. * - Avoid namespace collisions. If you load a symbol from the library, * it is not defined whether or not it goes into the global symbol * namespace for the application. If it does and it conflicts with * symbols in your code or other shared libraries, you will not get * the results you expect. :) */ #ifndef _SDL_loadso_h #define _SDL_loadso_h #include "SDL_stdinc.h" #include "SDL_error.h" #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif /** * This function dynamically loads a shared object and returns a pointer * to the object handle (or NULL if there was an error). * The 'sofile' parameter is a system dependent name of the object file. */ extern DECLSPEC void * SDLCALL SDL_LoadObject(const char *sofile); /** * Given an object handle, this function looks up the address of the * named function in the shared object and returns it. This address * is no longer valid after calling SDL_UnloadObject(). */ extern DECLSPEC void * SDLCALL SDL_LoadFunction(void *handle, const char *name); /** Unload a shared object from memory */ extern DECLSPEC void SDLCALL SDL_UnloadObject(void *handle); /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* _SDL_loadso_h */ ================================================ FILE: other/sdl/include/SDL_main.h ================================================ /* SDL - Simple DirectMedia Layer Copyright (C) 1997-2009 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org */ #ifndef _SDL_main_h #define _SDL_main_h #include "SDL_stdinc.h" /** @file SDL_main.h * Redefine main() on Win32 and MacOS so that it is called by winmain.c */ #if defined(__WIN32__) || \ (defined(__MWERKS__) && !defined(__BEOS__)) || \ defined(__MACOS__) || defined(__MACOSX__) || \ defined(__SYMBIAN32__) || defined(QWS) #ifdef __cplusplus #define C_LINKAGE "C" #else #define C_LINKAGE #endif /* __cplusplus */ /** The application's main() function must be called with C linkage, * and should be declared like this: * @code * #ifdef __cplusplus * extern "C" * #endif * int main(int argc, char *argv[]) * { * } * @endcode */ #define main SDL_main /** The prototype for the application's main() function */ extern C_LINKAGE int SDL_main(int argc, char *argv[]); /** @name From the SDL library code -- needed for registering the app on Win32 */ /*@{*/ #ifdef __WIN32__ #include "begin_code.h" #ifdef __cplusplus extern "C" { #endif /** This should be called from your WinMain() function, if any */ extern DECLSPEC void SDLCALL SDL_SetModuleHandle(void *hInst); /** This can also be called, but is no longer necessary */ extern DECLSPEC int SDLCALL SDL_RegisterApp(char *name, Uint32 style, void *hInst); /** This can also be called, but is no longer necessary (SDL_Quit calls it) */ extern DECLSPEC void SDLCALL SDL_UnregisterApp(void); #ifdef __cplusplus } #endif #include "close_code.h" #endif /*@}*/ /** @name From the SDL library code -- needed for registering QuickDraw on MacOS */ /*@{*/ #if defined(__MACOS__) #include "begin_code.h" #ifdef __cplusplus extern "C" { #endif /** Forward declaration so we don't need to include QuickDraw.h */ struct QDGlobals; /** This should be called from your main() function, if any */ extern DECLSPEC void SDLCALL SDL_InitQuickDraw(struct QDGlobals *the_qd); #ifdef __cplusplus } #endif #include "close_code.h" #endif /*@}*/ #endif /* Need to redefine main()? */ #endif /* _SDL_main_h */ ================================================ FILE: other/sdl/include/SDL_mouse.h ================================================ /* SDL - Simple DirectMedia Layer Copyright (C) 1997-2009 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org */ /** @file SDL_mouse.h * Include file for SDL mouse event handling */ #ifndef _SDL_mouse_h #define _SDL_mouse_h #include "SDL_stdinc.h" #include "SDL_error.h" #include "SDL_video.h" #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif typedef struct WMcursor WMcursor; /**< Implementation dependent */ typedef struct SDL_Cursor { SDL_Rect area; /**< The area of the mouse cursor */ Sint16 hot_x, hot_y; /**< The "tip" of the cursor */ Uint8 *data; /**< B/W cursor data */ Uint8 *mask; /**< B/W cursor mask */ Uint8 *save[2]; /**< Place to save cursor area */ WMcursor *wm_cursor; /**< Window-manager cursor */ } SDL_Cursor; /* Function prototypes */ /** * Retrieve the current state of the mouse. * The current button state is returned as a button bitmask, which can * be tested using the SDL_BUTTON(X) macros, and x and y are set to the * current mouse cursor position. You can pass NULL for either x or y. */ extern DECLSPEC Uint8 SDLCALL SDL_GetMouseState(int *x, int *y); /** * Retrieve the current state of the mouse. * The current button state is returned as a button bitmask, which can * be tested using the SDL_BUTTON(X) macros, and x and y are set to the * mouse deltas since the last call to SDL_GetRelativeMouseState(). */ extern DECLSPEC Uint8 SDLCALL SDL_GetRelativeMouseState(int *x, int *y); /** * Set the position of the mouse cursor (generates a mouse motion event) */ extern DECLSPEC void SDLCALL SDL_WarpMouse(Uint16 x, Uint16 y); /** * Create a cursor using the specified data and mask (in MSB format). * The cursor width must be a multiple of 8 bits. * * The cursor is created in black and white according to the following: * data mask resulting pixel on screen * 0 1 White * 1 1 Black * 0 0 Transparent * 1 0 Inverted color if possible, black if not. * * Cursors created with this function must be freed with SDL_FreeCursor(). */ extern DECLSPEC SDL_Cursor * SDLCALL SDL_CreateCursor (Uint8 *data, Uint8 *mask, int w, int h, int hot_x, int hot_y); /** * Set the currently active cursor to the specified one. * If the cursor is currently visible, the change will be immediately * represented on the display. */ extern DECLSPEC void SDLCALL SDL_SetCursor(SDL_Cursor *cursor); /** * Returns the currently active cursor. */ extern DECLSPEC SDL_Cursor * SDLCALL SDL_GetCursor(void); /** * Deallocates a cursor created with SDL_CreateCursor(). */ extern DECLSPEC void SDLCALL SDL_FreeCursor(SDL_Cursor *cursor); /** * Toggle whether or not the cursor is shown on the screen. * The cursor start off displayed, but can be turned off. * SDL_ShowCursor() returns 1 if the cursor was being displayed * before the call, or 0 if it was not. You can query the current * state by passing a 'toggle' value of -1. */ extern DECLSPEC int SDLCALL SDL_ShowCursor(int toggle); /*@{*/ /** Used as a mask when testing buttons in buttonstate * Button 1: Left mouse button * Button 2: Middle mouse button * Button 3: Right mouse button * Button 4: Mouse wheel up (may also be a real button) * Button 5: Mouse wheel down (may also be a real button) */ #define SDL_BUTTON(X) (1 << ((X)-1)) #define SDL_BUTTON_LEFT 1 #define SDL_BUTTON_MIDDLE 2 #define SDL_BUTTON_RIGHT 3 #define SDL_BUTTON_WHEELUP 4 #define SDL_BUTTON_WHEELDOWN 5 #define SDL_BUTTON_X1 6 #define SDL_BUTTON_X2 7 #define SDL_BUTTON_LMASK SDL_BUTTON(SDL_BUTTON_LEFT) #define SDL_BUTTON_MMASK SDL_BUTTON(SDL_BUTTON_MIDDLE) #define SDL_BUTTON_RMASK SDL_BUTTON(SDL_BUTTON_RIGHT) #define SDL_BUTTON_X1MASK SDL_BUTTON(SDL_BUTTON_X1) #define SDL_BUTTON_X2MASK SDL_BUTTON(SDL_BUTTON_X2) /*@}*/ /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* _SDL_mouse_h */ ================================================ FILE: other/sdl/include/SDL_mutex.h ================================================ /* SDL - Simple DirectMedia Layer Copyright (C) 1997-2009 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org */ #ifndef _SDL_mutex_h #define _SDL_mutex_h /** @file SDL_mutex.h * Functions to provide thread synchronization primitives * * @note These are independent of the other SDL routines. */ #include "SDL_stdinc.h" #include "SDL_error.h" #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif /** Synchronization functions which can time out return this value * if they time out. */ #define SDL_MUTEX_TIMEDOUT 1 /** This is the timeout value which corresponds to never time out */ #define SDL_MUTEX_MAXWAIT (~(Uint32)0) /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** @name Mutex functions */ /*@{*/ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** The SDL mutex structure, defined in SDL_mutex.c */ struct SDL_mutex; typedef struct SDL_mutex SDL_mutex; /** Create a mutex, initialized unlocked */ extern DECLSPEC SDL_mutex * SDLCALL SDL_CreateMutex(void); #define SDL_LockMutex(m) SDL_mutexP(m) /** Lock the mutex * @return 0, or -1 on error */ extern DECLSPEC int SDLCALL SDL_mutexP(SDL_mutex *mutex); #define SDL_UnlockMutex(m) SDL_mutexV(m) /** Unlock the mutex * @return 0, or -1 on error * * It is an error to unlock a mutex that has not been locked by * the current thread, and doing so results in undefined behavior. */ extern DECLSPEC int SDLCALL SDL_mutexV(SDL_mutex *mutex); /** Destroy a mutex */ extern DECLSPEC void SDLCALL SDL_DestroyMutex(SDL_mutex *mutex); /*@}*/ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** @name Semaphore functions */ /*@{*/ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** The SDL semaphore structure, defined in SDL_sem.c */ struct SDL_semaphore; typedef struct SDL_semaphore SDL_sem; /** Create a semaphore, initialized with value, returns NULL on failure. */ extern DECLSPEC SDL_sem * SDLCALL SDL_CreateSemaphore(Uint32 initial_value); /** Destroy a semaphore */ extern DECLSPEC void SDLCALL SDL_DestroySemaphore(SDL_sem *sem); /** * This function suspends the calling thread until the semaphore pointed * to by sem has a positive count. It then atomically decreases the semaphore * count. */ extern DECLSPEC int SDLCALL SDL_SemWait(SDL_sem *sem); /** Non-blocking variant of SDL_SemWait(). * @return 0 if the wait succeeds, * SDL_MUTEX_TIMEDOUT if the wait would block, and -1 on error. */ extern DECLSPEC int SDLCALL SDL_SemTryWait(SDL_sem *sem); /** Variant of SDL_SemWait() with a timeout in milliseconds, returns 0 if * the wait succeeds, SDL_MUTEX_TIMEDOUT if the wait does not succeed in * the allotted time, and -1 on error. * * On some platforms this function is implemented by looping with a delay * of 1 ms, and so should be avoided if possible. */ extern DECLSPEC int SDLCALL SDL_SemWaitTimeout(SDL_sem *sem, Uint32 ms); /** Atomically increases the semaphore's count (not blocking). * @return 0, or -1 on error. */ extern DECLSPEC int SDLCALL SDL_SemPost(SDL_sem *sem); /** Returns the current count of the semaphore */ extern DECLSPEC Uint32 SDLCALL SDL_SemValue(SDL_sem *sem); /*@}*/ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** @name Condition_variable_functions */ /*@{*/ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /*@{*/ /** The SDL condition variable structure, defined in SDL_cond.c */ struct SDL_cond; typedef struct SDL_cond SDL_cond; /*@}*/ /** Create a condition variable */ extern DECLSPEC SDL_cond * SDLCALL SDL_CreateCond(void); /** Destroy a condition variable */ extern DECLSPEC void SDLCALL SDL_DestroyCond(SDL_cond *cond); /** Restart one of the threads that are waiting on the condition variable, * @return 0 or -1 on error. */ extern DECLSPEC int SDLCALL SDL_CondSignal(SDL_cond *cond); /** Restart all threads that are waiting on the condition variable, * @return 0 or -1 on error. */ extern DECLSPEC int SDLCALL SDL_CondBroadcast(SDL_cond *cond); /** Wait on the condition variable, unlocking the provided mutex. * The mutex must be locked before entering this function! * The mutex is re-locked once the condition variable is signaled. * @return 0 when it is signaled, or -1 on error. */ extern DECLSPEC int SDLCALL SDL_CondWait(SDL_cond *cond, SDL_mutex *mut); /** Waits for at most 'ms' milliseconds, and returns 0 if the condition * variable is signaled, SDL_MUTEX_TIMEDOUT if the condition is not * signaled in the allotted time, and -1 on error. * On some platforms this function is implemented by looping with a delay * of 1 ms, and so should be avoided if possible. */ extern DECLSPEC int SDLCALL SDL_CondWaitTimeout(SDL_cond *cond, SDL_mutex *mutex, Uint32 ms); /*@}*/ /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* _SDL_mutex_h */ ================================================ FILE: other/sdl/include/SDL_name.h ================================================ #ifndef _SDLname_h_ #define _SDLname_h_ #if defined(__STDC__) || defined(__cplusplus) #define NeedFunctionPrototypes 1 #endif #define SDL_NAME(X) SDL_##X #endif /* _SDLname_h_ */ ================================================ FILE: other/sdl/include/SDL_opengl.h ================================================ /* SDL - Simple DirectMedia Layer Copyright (C) 1997-2009 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org */ /** @file SDL_opengl.h * This is a simple file to encapsulate the OpenGL API headers */ #include "SDL_config.h" #ifdef __WIN32__ #define WIN32_LEAN_AND_MEAN #ifndef NOMINMAX #define NOMINMAX /* Don't defined min() and max() */ #endif #include <windows.h> #endif #ifndef NO_SDL_GLEXT #define __glext_h_ /* Don't let gl.h include glext.h */ #endif #if defined(__MACOSX__) #include <OpenGL/gl.h> /* Header File For The OpenGL Library */ #include <OpenGL/glu.h> /* Header File For The GLU Library */ #elif defined(__MACOS__) #include <gl.h> /* Header File For The OpenGL Library */ #include <glu.h> /* Header File For The GLU Library */ #else #include <GL/gl.h> /* Header File For The OpenGL Library */ #include <GL/glu.h> /* Header File For The GLU Library */ #endif #ifndef NO_SDL_GLEXT #undef __glext_h_ #endif /** @name GLext.h * This file taken from "GLext.h" from the Jeff Molofee OpenGL tutorials. * It is included here because glext.h is not available on some systems. * If you don't want this version included, simply define "NO_SDL_GLEXT" */ /*@{*/ #ifndef NO_SDL_GLEXT #if !defined(__glext_h_) && !defined(GL_GLEXT_LEGACY) #define __glext_h_ #ifdef __cplusplus extern "C" { #endif /* ** License Applicability. Except to the extent portions of this file are ** made subject to an alternative license as permitted in the SGI Free ** Software License B, Version 1.1 (the "License"), the contents of this ** file are subject only to the provisions of the License. You may not use ** this file except in compliance with the License. You may obtain a copy ** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600 ** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at: ** ** http://oss.sgi.com/projects/FreeB ** ** Note that, as provided in the License, the Software is distributed on an ** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS ** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND ** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A ** PARTICULAR PURPOSE, AND NON-INFRINGEMENT. ** ** Original Code. The Original Code is: OpenGL Sample Implementation, ** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics, ** Inc. The Original Code is Copyright (c) 1991-2004 Silicon Graphics, Inc. ** Copyright in any portions created by third parties is as indicated ** elsewhere herein. All Rights Reserved. ** ** Additional Notice Provisions: This software was created using the ** OpenGL(R) version 1.2.1 Sample Implementation published by SGI, but has ** not been independently verified as being compliant with the OpenGL(R) ** version 1.2.1 Specification. */ #if defined(_WIN32) && !defined(APIENTRY) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__) #define WIN32_LEAN_AND_MEAN 1 #include <windows.h> #endif #ifndef APIENTRY #define APIENTRY #endif #ifndef APIENTRYP #define APIENTRYP APIENTRY * #endif #ifndef GLAPI #define GLAPI extern #endif /*************************************************************/ /* Header file version number, required by OpenGL ABI for Linux */ /* glext.h last updated 2005/06/20 */ /* Current version at http://oss.sgi.com/projects/ogl-sample/registry/ */ #define GL_GLEXT_VERSION 29 #ifndef GL_VERSION_1_2 #define GL_UNSIGNED_BYTE_3_3_2 0x8032 #define GL_UNSIGNED_SHORT_4_4_4_4 0x8033 #define GL_UNSIGNED_SHORT_5_5_5_1 0x8034 #define GL_UNSIGNED_INT_8_8_8_8 0x8035 #define GL_UNSIGNED_INT_10_10_10_2 0x8036 #define GL_RESCALE_NORMAL 0x803A #define GL_TEXTURE_BINDING_3D 0x806A #define GL_PACK_SKIP_IMAGES 0x806B #define GL_PACK_IMAGE_HEIGHT 0x806C #define GL_UNPACK_SKIP_IMAGES 0x806D #define GL_UNPACK_IMAGE_HEIGHT 0x806E #define GL_TEXTURE_3D 0x806F #define GL_PROXY_TEXTURE_3D 0x8070 #define GL_TEXTURE_DEPTH 0x8071 #define GL_TEXTURE_WRAP_R 0x8072 #define GL_MAX_3D_TEXTURE_SIZE 0x8073 #define GL_UNSIGNED_BYTE_2_3_3_REV 0x8362 #define GL_UNSIGNED_SHORT_5_6_5 0x8363 #define GL_UNSIGNED_SHORT_5_6_5_REV 0x8364 #define GL_UNSIGNED_SHORT_4_4_4_4_REV 0x8365 #define GL_UNSIGNED_SHORT_1_5_5_5_REV 0x8366 #define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367 #define GL_UNSIGNED_INT_2_10_10_10_REV 0x8368 #define GL_BGR 0x80E0 #define GL_BGRA 0x80E1 #define GL_MAX_ELEMENTS_VERTICES 0x80E8 #define GL_MAX_ELEMENTS_INDICES 0x80E9 #define GL_CLAMP_TO_EDGE 0x812F #define GL_TEXTURE_MIN_LOD 0x813A #define GL_TEXTURE_MAX_LOD 0x813B #define GL_TEXTURE_BASE_LEVEL 0x813C #define GL_TEXTURE_MAX_LEVEL 0x813D #define GL_LIGHT_MODEL_COLOR_CONTROL 0x81F8 #define GL_SINGLE_COLOR 0x81F9 #define GL_SEPARATE_SPECULAR_COLOR 0x81FA #define GL_SMOOTH_POINT_SIZE_RANGE 0x0B12 #define GL_SMOOTH_POINT_SIZE_GRANULARITY 0x0B13 #define GL_SMOOTH_LINE_WIDTH_RANGE 0x0B22 #define GL_SMOOTH_LINE_WIDTH_GRANULARITY 0x0B23 #define GL_ALIASED_POINT_SIZE_RANGE 0x846D #define GL_ALIASED_LINE_WIDTH_RANGE 0x846E #endif #ifndef GL_ARB_imaging #define GL_CONSTANT_COLOR 0x8001 #define GL_ONE_MINUS_CONSTANT_COLOR 0x8002 #define GL_CONSTANT_ALPHA 0x8003 #define GL_ONE_MINUS_CONSTANT_ALPHA 0x8004 #define GL_BLEND_COLOR 0x8005 #define GL_FUNC_ADD 0x8006 #define GL_MIN 0x8007 #define GL_MAX 0x8008 #define GL_BLEND_EQUATION 0x8009 #define GL_FUNC_SUBTRACT 0x800A #define GL_FUNC_REVERSE_SUBTRACT 0x800B #define GL_CONVOLUTION_1D 0x8010 #define GL_CONVOLUTION_2D 0x8011 #define GL_SEPARABLE_2D 0x8012 #define GL_CONVOLUTION_BORDER_MODE 0x8013 #define GL_CONVOLUTION_FILTER_SCALE 0x8014 #define GL_CONVOLUTION_FILTER_BIAS 0x8015 #define GL_REDUCE 0x8016 #define GL_CONVOLUTION_FORMAT 0x8017 #define GL_CONVOLUTION_WIDTH 0x8018 #define GL_CONVOLUTION_HEIGHT 0x8019 #define GL_MAX_CONVOLUTION_WIDTH 0x801A #define GL_MAX_CONVOLUTION_HEIGHT 0x801B #define GL_POST_CONVOLUTION_RED_SCALE 0x801C #define GL_POST_CONVOLUTION_GREEN_SCALE 0x801D #define GL_POST_CONVOLUTION_BLUE_SCALE 0x801E #define GL_POST_CONVOLUTION_ALPHA_SCALE 0x801F #define GL_POST_CONVOLUTION_RED_BIAS 0x8020 #define GL_POST_CONVOLUTION_GREEN_BIAS 0x8021 #define GL_POST_CONVOLUTION_BLUE_BIAS 0x8022 #define GL_POST_CONVOLUTION_ALPHA_BIAS 0x8023 #define GL_HISTOGRAM 0x8024 #define GL_PROXY_HISTOGRAM 0x8025 #define GL_HISTOGRAM_WIDTH 0x8026 #define GL_HISTOGRAM_FORMAT 0x8027 #define GL_HISTOGRAM_RED_SIZE 0x8028 #define GL_HISTOGRAM_GREEN_SIZE 0x8029 #define GL_HISTOGRAM_BLUE_SIZE 0x802A #define GL_HISTOGRAM_ALPHA_SIZE 0x802B #define GL_HISTOGRAM_LUMINANCE_SIZE 0x802C #define GL_HISTOGRAM_SINK 0x802D #define GL_MINMAX 0x802E #define GL_MINMAX_FORMAT 0x802F #define GL_MINMAX_SINK 0x8030 #define GL_TABLE_TOO_LARGE 0x8031 #define GL_COLOR_MATRIX 0x80B1 #define GL_COLOR_MATRIX_STACK_DEPTH 0x80B2 #define GL_MAX_COLOR_MATRIX_STACK_DEPTH 0x80B3 #define GL_POST_COLOR_MATRIX_RED_SCALE 0x80B4 #define GL_POST_COLOR_MATRIX_GREEN_SCALE 0x80B5 #define GL_POST_COLOR_MATRIX_BLUE_SCALE 0x80B6 #define GL_POST_COLOR_MATRIX_ALPHA_SCALE 0x80B7 #define GL_POST_COLOR_MATRIX_RED_BIAS 0x80B8 #define GL_POST_COLOR_MATRIX_GREEN_BIAS 0x80B9 #define GL_POST_COLOR_MATRIX_BLUE_BIAS 0x80BA #define GL_POST_COLOR_MATRIX_ALPHA_BIAS 0x80BB #define GL_COLOR_TABLE 0x80D0 #define GL_POST_CONVOLUTION_COLOR_TABLE 0x80D1 #define GL_POST_COLOR_MATRIX_COLOR_TABLE 0x80D2 #define GL_PROXY_COLOR_TABLE 0x80D3 #define GL_PROXY_POST_CONVOLUTION_COLOR_TABLE 0x80D4 #define GL_PROXY_POST_COLOR_MATRIX_COLOR_TABLE 0x80D5 #define GL_COLOR_TABLE_SCALE 0x80D6 #define GL_COLOR_TABLE_BIAS 0x80D7 #define GL_COLOR_TABLE_FORMAT 0x80D8 #define GL_COLOR_TABLE_WIDTH 0x80D9 #define GL_COLOR_TABLE_RED_SIZE 0x80DA #define GL_COLOR_TABLE_GREEN_SIZE 0x80DB #define GL_COLOR_TABLE_BLUE_SIZE 0x80DC #define GL_COLOR_TABLE_ALPHA_SIZE 0x80DD #define GL_COLOR_TABLE_LUMINANCE_SIZE 0x80DE #define GL_COLOR_TABLE_INTENSITY_SIZE 0x80DF #define GL_CONSTANT_BORDER 0x8151 #define GL_REPLICATE_BORDER 0x8153 #define GL_CONVOLUTION_BORDER_COLOR 0x8154 #endif #ifndef GL_VERSION_1_3 #define GL_TEXTURE0 0x84C0 #define GL_TEXTURE1 0x84C1 #define GL_TEXTURE2 0x84C2 #define GL_TEXTURE3 0x84C3 #define GL_TEXTURE4 0x84C4 #define GL_TEXTURE5 0x84C5 #define GL_TEXTURE6 0x84C6 #define GL_TEXTURE7 0x84C7 #define GL_TEXTURE8 0x84C8 #define GL_TEXTURE9 0x84C9 #define GL_TEXTURE10 0x84CA #define GL_TEXTURE11 0x84CB #define GL_TEXTURE12 0x84CC #define GL_TEXTURE13 0x84CD #define GL_TEXTURE14 0x84CE #define GL_TEXTURE15 0x84CF #define GL_TEXTURE16 0x84D0 #define GL_TEXTURE17 0x84D1 #define GL_TEXTURE18 0x84D2 #define GL_TEXTURE19 0x84D3 #define GL_TEXTURE20 0x84D4 #define GL_TEXTURE21 0x84D5 #define GL_TEXTURE22 0x84D6 #define GL_TEXTURE23 0x84D7 #define GL_TEXTURE24 0x84D8 #define GL_TEXTURE25 0x84D9 #define GL_TEXTURE26 0x84DA #define GL_TEXTURE27 0x84DB #define GL_TEXTURE28 0x84DC #define GL_TEXTURE29 0x84DD #define GL_TEXTURE30 0x84DE #define GL_TEXTURE31 0x84DF #define GL_ACTIVE_TEXTURE 0x84E0 #define GL_CLIENT_ACTIVE_TEXTURE 0x84E1 #define GL_MAX_TEXTURE_UNITS 0x84E2 #define GL_TRANSPOSE_MODELVIEW_MATRIX 0x84E3 #define GL_TRANSPOSE_PROJECTION_MATRIX 0x84E4 #define GL_TRANSPOSE_TEXTURE_MATRIX 0x84E5 #define GL_TRANSPOSE_COLOR_MATRIX 0x84E6 #define GL_MULTISAMPLE 0x809D #define GL_SAMPLE_ALPHA_TO_COVERAGE 0x809E #define GL_SAMPLE_ALPHA_TO_ONE 0x809F #define GL_SAMPLE_COVERAGE 0x80A0 #define GL_SAMPLE_BUFFERS 0x80A8 #define GL_SAMPLES 0x80A9 #define GL_SAMPLE_COVERAGE_VALUE 0x80AA #define GL_SAMPLE_COVERAGE_INVERT 0x80AB #define GL_MULTISAMPLE_BIT 0x20000000 #define GL_NORMAL_MAP 0x8511 #define GL_REFLECTION_MAP 0x8512 #define GL_TEXTURE_CUBE_MAP 0x8513 #define GL_TEXTURE_BINDING_CUBE_MAP 0x8514 #define GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x8515 #define GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x8516 #define GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x8517 #define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x8518 #define GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x8519 #define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x851A #define GL_PROXY_TEXTURE_CUBE_MAP 0x851B #define GL_MAX_CUBE_MAP_TEXTURE_SIZE 0x851C #define GL_COMPRESSED_ALPHA 0x84E9 #define GL_COMPRESSED_LUMINANCE 0x84EA #define GL_COMPRESSED_LUMINANCE_ALPHA 0x84EB #define GL_COMPRESSED_INTENSITY 0x84EC #define GL_COMPRESSED_RGB 0x84ED #define GL_COMPRESSED_RGBA 0x84EE #define GL_TEXTURE_COMPRESSION_HINT 0x84EF #define GL_TEXTURE_COMPRESSED_IMAGE_SIZE 0x86A0 #define GL_TEXTURE_COMPRESSED 0x86A1 #define GL_NUM_COMPRESSED_TEXTURE_FORMATS 0x86A2 #define GL_COMPRESSED_TEXTURE_FORMATS 0x86A3 #define GL_CLAMP_TO_BORDER 0x812D #define GL_COMBINE 0x8570 #define GL_COMBINE_RGB 0x8571 #define GL_COMBINE_ALPHA 0x8572 #define GL_SOURCE0_RGB 0x8580 #define GL_SOURCE1_RGB 0x8581 #define GL_SOURCE2_RGB 0x8582 #define GL_SOURCE0_ALPHA 0x8588 #define GL_SOURCE1_ALPHA 0x8589 #define GL_SOURCE2_ALPHA 0x858A #define GL_OPERAND0_RGB 0x8590 #define GL_OPERAND1_RGB 0x8591 #define GL_OPERAND2_RGB 0x8592 #define GL_OPERAND0_ALPHA 0x8598 #define GL_OPERAND1_ALPHA 0x8599 #define GL_OPERAND2_ALPHA 0x859A #define GL_RGB_SCALE 0x8573 #define GL_ADD_SIGNED 0x8574 #define GL_INTERPOLATE 0x8575 #define GL_SUBTRACT 0x84E7 #define GL_CONSTANT 0x8576 #define GL_PRIMARY_COLOR 0x8577 #define GL_PREVIOUS 0x8578 #define GL_DOT3_RGB 0x86AE #define GL_DOT3_RGBA 0x86AF #endif #ifndef GL_VERSION_1_4 #define GL_BLEND_DST_RGB 0x80C8 #define GL_BLEND_SRC_RGB 0x80C9 #define GL_BLEND_DST_ALPHA 0x80CA #define GL_BLEND_SRC_ALPHA 0x80CB #define GL_POINT_SIZE_MIN 0x8126 #define GL_POINT_SIZE_MAX 0x8127 #define GL_POINT_FADE_THRESHOLD_SIZE 0x8128 #define GL_POINT_DISTANCE_ATTENUATION 0x8129 #define GL_GENERATE_MIPMAP 0x8191 #define GL_GENERATE_MIPMAP_HINT 0x8192 #define GL_DEPTH_COMPONENT16 0x81A5 #define GL_DEPTH_COMPONENT24 0x81A6 #define GL_DEPTH_COMPONENT32 0x81A7 #define GL_MIRRORED_REPEAT 0x8370 #define GL_FOG_COORDINATE_SOURCE 0x8450 #define GL_FOG_COORDINATE 0x8451 #define GL_FRAGMENT_DEPTH 0x8452 #define GL_CURRENT_FOG_COORDINATE 0x8453 #define GL_FOG_COORDINATE_ARRAY_TYPE 0x8454 #define GL_FOG_COORDINATE_ARRAY_STRIDE 0x8455 #define GL_FOG_COORDINATE_ARRAY_POINTER 0x8456 #define GL_FOG_COORDINATE_ARRAY 0x8457 #define GL_COLOR_SUM 0x8458 #define GL_CURRENT_SECONDARY_COLOR 0x8459 #define GL_SECONDARY_COLOR_ARRAY_SIZE 0x845A #define GL_SECONDARY_COLOR_ARRAY_TYPE 0x845B #define GL_SECONDARY_COLOR_ARRAY_STRIDE 0x845C #define GL_SECONDARY_COLOR_ARRAY_POINTER 0x845D #define GL_SECONDARY_COLOR_ARRAY 0x845E #define GL_MAX_TEXTURE_LOD_BIAS 0x84FD #define GL_TEXTURE_FILTER_CONTROL 0x8500 #define GL_TEXTURE_LOD_BIAS 0x8501 #define GL_INCR_WRAP 0x8507 #define GL_DECR_WRAP 0x8508 #define GL_TEXTURE_DEPTH_SIZE 0x884A #define GL_DEPTH_TEXTURE_MODE 0x884B #define GL_TEXTURE_COMPARE_MODE 0x884C #define GL_TEXTURE_COMPARE_FUNC 0x884D #define GL_COMPARE_R_TO_TEXTURE 0x884E #endif #ifndef GL_VERSION_1_5 #define GL_BUFFER_SIZE 0x8764 #define GL_BUFFER_USAGE 0x8765 #define GL_QUERY_COUNTER_BITS 0x8864 #define GL_CURRENT_QUERY 0x8865 #define GL_QUERY_RESULT 0x8866 #define GL_QUERY_RESULT_AVAILABLE 0x8867 #define GL_ARRAY_BUFFER 0x8892 #define GL_ELEMENT_ARRAY_BUFFER 0x8893 #define GL_ARRAY_BUFFER_BINDING 0x8894 #define GL_ELEMENT_ARRAY_BUFFER_BINDING 0x8895 #define GL_VERTEX_ARRAY_BUFFER_BINDING 0x8896 #define GL_NORMAL_ARRAY_BUFFER_BINDING 0x8897 #define GL_COLOR_ARRAY_BUFFER_BINDING 0x8898 #define GL_INDEX_ARRAY_BUFFER_BINDING 0x8899 #define GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING 0x889A #define GL_EDGE_FLAG_ARRAY_BUFFER_BINDING 0x889B #define GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING 0x889C #define GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING 0x889D #define GL_WEIGHT_ARRAY_BUFFER_BINDING 0x889E #define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING 0x889F #define GL_READ_ONLY 0x88B8 #define GL_WRITE_ONLY 0x88B9 #define GL_READ_WRITE 0x88BA #define GL_BUFFER_ACCESS 0x88BB #define GL_BUFFER_MAPPED 0x88BC #define GL_BUFFER_MAP_POINTER 0x88BD #define GL_STREAM_DRAW 0x88E0 #define GL_STREAM_READ 0x88E1 #define GL_STREAM_COPY 0x88E2 #define GL_STATIC_DRAW 0x88E4 #define GL_STATIC_READ 0x88E5 #define GL_STATIC_COPY 0x88E6 #define GL_DYNAMIC_DRAW 0x88E8 #define GL_DYNAMIC_READ 0x88E9 #define GL_DYNAMIC_COPY 0x88EA #define GL_SAMPLES_PASSED 0x8914 #define GL_FOG_COORD_SRC GL_FOG_COORDINATE_SOURCE #define GL_FOG_COORD GL_FOG_COORDINATE #define GL_CURRENT_FOG_COORD GL_CURRENT_FOG_COORDINATE #define GL_FOG_COORD_ARRAY_TYPE GL_FOG_COORDINATE_ARRAY_TYPE #define GL_FOG_COORD_ARRAY_STRIDE GL_FOG_COORDINATE_ARRAY_STRIDE #define GL_FOG_COORD_ARRAY_POINTER GL_FOG_COORDINATE_ARRAY_POINTER #define GL_FOG_COORD_ARRAY GL_FOG_COORDINATE_ARRAY #define GL_FOG_COORD_ARRAY_BUFFER_BINDING GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING #define GL_SRC0_RGB GL_SOURCE0_RGB #define GL_SRC1_RGB GL_SOURCE1_RGB #define GL_SRC2_RGB GL_SOURCE2_RGB #define GL_SRC0_ALPHA GL_SOURCE0_ALPHA #define GL_SRC1_ALPHA GL_SOURCE1_ALPHA #define GL_SRC2_ALPHA GL_SOURCE2_ALPHA #endif #ifndef GL_VERSION_2_0 #define GL_BLEND_EQUATION_RGB GL_BLEND_EQUATION #define GL_VERTEX_ATTRIB_ARRAY_ENABLED 0x8622 #define GL_VERTEX_ATTRIB_ARRAY_SIZE 0x8623 #define GL_VERTEX_ATTRIB_ARRAY_STRIDE 0x8624 #define GL_VERTEX_ATTRIB_ARRAY_TYPE 0x8625 #define GL_CURRENT_VERTEX_ATTRIB 0x8626 #define GL_VERTEX_PROGRAM_POINT_SIZE 0x8642 #define GL_VERTEX_PROGRAM_TWO_SIDE 0x8643 #define GL_VERTEX_ATTRIB_ARRAY_POINTER 0x8645 #define GL_STENCIL_BACK_FUNC 0x8800 #define GL_STENCIL_BACK_FAIL 0x8801 #define GL_STENCIL_BACK_PASS_DEPTH_FAIL 0x8802 #define GL_STENCIL_BACK_PASS_DEPTH_PASS 0x8803 #define GL_MAX_DRAW_BUFFERS 0x8824 #define GL_DRAW_BUFFER0 0x8825 #define GL_DRAW_BUFFER1 0x8826 #define GL_DRAW_BUFFER2 0x8827 #define GL_DRAW_BUFFER3 0x8828 #define GL_DRAW_BUFFER4 0x8829 #define GL_DRAW_BUFFER5 0x882A #define GL_DRAW_BUFFER6 0x882B #define GL_DRAW_BUFFER7 0x882C #define GL_DRAW_BUFFER8 0x882D #define GL_DRAW_BUFFER9 0x882E #define GL_DRAW_BUFFER10 0x882F #define GL_DRAW_BUFFER11 0x8830 #define GL_DRAW_BUFFER12 0x8831 #define GL_DRAW_BUFFER13 0x8832 #define GL_DRAW_BUFFER14 0x8833 #define GL_DRAW_BUFFER15 0x8834 #define GL_BLEND_EQUATION_ALPHA 0x883D #define GL_POINT_SPRITE 0x8861 #define GL_COORD_REPLACE 0x8862 #define GL_MAX_VERTEX_ATTRIBS 0x8869 #define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED 0x886A #define GL_MAX_TEXTURE_COORDS 0x8871 #define GL_MAX_TEXTURE_IMAGE_UNITS 0x8872 #define GL_FRAGMENT_SHADER 0x8B30 #define GL_VERTEX_SHADER 0x8B31 #define GL_MAX_FRAGMENT_UNIFORM_COMPONENTS 0x8B49 #define GL_MAX_VERTEX_UNIFORM_COMPONENTS 0x8B4A #define GL_MAX_VARYING_FLOATS 0x8B4B #define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS 0x8B4C #define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS 0x8B4D #define GL_SHADER_TYPE 0x8B4F #define GL_FLOAT_VEC2 0x8B50 #define GL_FLOAT_VEC3 0x8B51 #define GL_FLOAT_VEC4 0x8B52 #define GL_INT_VEC2 0x8B53 #define GL_INT_VEC3 0x8B54 #define GL_INT_VEC4 0x8B55 #define GL_BOOL 0x8B56 #define GL_BOOL_VEC2 0x8B57 #define GL_BOOL_VEC3 0x8B58 #define GL_BOOL_VEC4 0x8B59 #define GL_FLOAT_MAT2 0x8B5A #define GL_FLOAT_MAT3 0x8B5B #define GL_FLOAT_MAT4 0x8B5C #define GL_SAMPLER_1D 0x8B5D #define GL_SAMPLER_2D 0x8B5E #define GL_SAMPLER_3D 0x8B5F #define GL_SAMPLER_CUBE 0x8B60 #define GL_SAMPLER_1D_SHADOW 0x8B61 #define GL_SAMPLER_2D_SHADOW 0x8B62 #define GL_DELETE_STATUS 0x8B80 #define GL_COMPILE_STATUS 0x8B81 #define GL_LINK_STATUS 0x8B82 #define GL_VALIDATE_STATUS 0x8B83 #define GL_INFO_LOG_LENGTH 0x8B84 #define GL_ATTACHED_SHADERS 0x8B85 #define GL_ACTIVE_UNIFORMS 0x8B86 #define GL_ACTIVE_UNIFORM_MAX_LENGTH 0x8B87 #define GL_SHADER_SOURCE_LENGTH 0x8B88 #define GL_ACTIVE_ATTRIBUTES 0x8B89 #define GL_ACTIVE_ATTRIBUTE_MAX_LENGTH 0x8B8A #define GL_FRAGMENT_SHADER_DERIVATIVE_HINT 0x8B8B #define GL_SHADING_LANGUAGE_VERSION 0x8B8C #define GL_CURRENT_PROGRAM 0x8B8D #define GL_POINT_SPRITE_COORD_ORIGIN 0x8CA0 #define GL_LOWER_LEFT 0x8CA1 #define GL_UPPER_LEFT 0x8CA2 #define GL_STENCIL_BACK_REF 0x8CA3 #define GL_STENCIL_BACK_VALUE_MASK 0x8CA4 #define GL_STENCIL_BACK_WRITEMASK 0x8CA5 #endif #ifndef GL_ARB_multitexture #define GL_TEXTURE0_ARB 0x84C0 #define GL_TEXTURE1_ARB 0x84C1 #define GL_TEXTURE2_ARB 0x84C2 #define GL_TEXTURE3_ARB 0x84C3 #define GL_TEXTURE4_ARB 0x84C4 #define GL_TEXTURE5_ARB 0x84C5 #define GL_TEXTURE6_ARB 0x84C6 #define GL_TEXTURE7_ARB 0x84C7 #define GL_TEXTURE8_ARB 0x84C8 #define GL_TEXTURE9_ARB 0x84C9 #define GL_TEXTURE10_ARB 0x84CA #define GL_TEXTURE11_ARB 0x84CB #define GL_TEXTURE12_ARB 0x84CC #define GL_TEXTURE13_ARB 0x84CD #define GL_TEXTURE14_ARB 0x84CE #define GL_TEXTURE15_ARB 0x84CF #define GL_TEXTURE16_ARB 0x84D0 #define GL_TEXTURE17_ARB 0x84D1 #define GL_TEXTURE18_ARB 0x84D2 #define GL_TEXTURE19_ARB 0x84D3 #define GL_TEXTURE20_ARB 0x84D4 #define GL_TEXTURE21_ARB 0x84D5 #define GL_TEXTURE22_ARB 0x84D6 #define GL_TEXTURE23_ARB 0x84D7 #define GL_TEXTURE24_ARB 0x84D8 #define GL_TEXTURE25_ARB 0x84D9 #define GL_TEXTURE26_ARB 0x84DA #define GL_TEXTURE27_ARB 0x84DB #define GL_TEXTURE28_ARB 0x84DC #define GL_TEXTURE29_ARB 0x84DD #define GL_TEXTURE30_ARB 0x84DE #define GL_TEXTURE31_ARB 0x84DF #define GL_ACTIVE_TEXTURE_ARB 0x84E0 #define GL_CLIENT_ACTIVE_TEXTURE_ARB 0x84E1 #define GL_MAX_TEXTURE_UNITS_ARB 0x84E2 #endif #ifndef GL_ARB_transpose_matrix #define GL_TRANSPOSE_MODELVIEW_MATRIX_ARB 0x84E3 #define GL_TRANSPOSE_PROJECTION_MATRIX_ARB 0x84E4 #define GL_TRANSPOSE_TEXTURE_MATRIX_ARB 0x84E5 #define GL_TRANSPOSE_COLOR_MATRIX_ARB 0x84E6 #endif #ifndef GL_ARB_multisample #define GL_MULTISAMPLE_ARB 0x809D #define GL_SAMPLE_ALPHA_TO_COVERAGE_ARB 0x809E #define GL_SAMPLE_ALPHA_TO_ONE_ARB 0x809F #define GL_SAMPLE_COVERAGE_ARB 0x80A0 #define GL_SAMPLE_BUFFERS_ARB 0x80A8 #define GL_SAMPLES_ARB 0x80A9 #define GL_SAMPLE_COVERAGE_VALUE_ARB 0x80AA #define GL_SAMPLE_COVERAGE_INVERT_ARB 0x80AB #define GL_MULTISAMPLE_BIT_ARB 0x20000000 #endif #ifndef GL_ARB_texture_env_add #endif #ifndef GL_ARB_texture_cube_map #define GL_NORMAL_MAP_ARB 0x8511 #define GL_REFLECTION_MAP_ARB 0x8512 #define GL_TEXTURE_CUBE_MAP_ARB 0x8513 #define GL_TEXTURE_BINDING_CUBE_MAP_ARB 0x8514 #define GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB 0x8515 #define GL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB 0x8516 #define GL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB 0x8517 #define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB 0x8518 #define GL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB 0x8519 #define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB 0x851A #define GL_PROXY_TEXTURE_CUBE_MAP_ARB 0x851B #define GL_MAX_CUBE_MAP_TEXTURE_SIZE_ARB 0x851C #endif #ifndef GL_ARB_texture_compression #define GL_COMPRESSED_ALPHA_ARB 0x84E9 #define GL_COMPRESSED_LUMINANCE_ARB 0x84EA #define GL_COMPRESSED_LUMINANCE_ALPHA_ARB 0x84EB #define GL_COMPRESSED_INTENSITY_ARB 0x84EC #define GL_COMPRESSED_RGB_ARB 0x84ED #define GL_COMPRESSED_RGBA_ARB 0x84EE #define GL_TEXTURE_COMPRESSION_HINT_ARB 0x84EF #define GL_TEXTURE_COMPRESSED_IMAGE_SIZE_ARB 0x86A0 #define GL_TEXTURE_COMPRESSED_ARB 0x86A1 #define GL_NUM_COMPRESSED_TEXTURE_FORMATS_ARB 0x86A2 #define GL_COMPRESSED_TEXTURE_FORMATS_ARB 0x86A3 #endif #ifndef GL_ARB_texture_border_clamp #define GL_CLAMP_TO_BORDER_ARB 0x812D #endif #ifndef GL_ARB_point_parameters #define GL_POINT_SIZE_MIN_ARB 0x8126 #define GL_POINT_SIZE_MAX_ARB 0x8127 #define GL_POINT_FADE_THRESHOLD_SIZE_ARB 0x8128 #define GL_POINT_DISTANCE_ATTENUATION_ARB 0x8129 #endif #ifndef GL_ARB_vertex_blend #define GL_MAX_VERTEX_UNITS_ARB 0x86A4 #define GL_ACTIVE_VERTEX_UNITS_ARB 0x86A5 #define GL_WEIGHT_SUM_UNITY_ARB 0x86A6 #define GL_VERTEX_BLEND_ARB 0x86A7 #define GL_CURRENT_WEIGHT_ARB 0x86A8 #define GL_WEIGHT_ARRAY_TYPE_ARB 0x86A9 #define GL_WEIGHT_ARRAY_STRIDE_ARB 0x86AA #define GL_WEIGHT_ARRAY_SIZE_ARB 0x86AB #define GL_WEIGHT_ARRAY_POINTER_ARB 0x86AC #define GL_WEIGHT_ARRAY_ARB 0x86AD #define GL_MODELVIEW0_ARB 0x1700 #define GL_MODELVIEW1_ARB 0x850A #define GL_MODELVIEW2_ARB 0x8722 #define GL_MODELVIEW3_ARB 0x8723 #define GL_MODELVIEW4_ARB 0x8724 #define GL_MODELVIEW5_ARB 0x8725 #define GL_MODELVIEW6_ARB 0x8726 #define GL_MODELVIEW7_ARB 0x8727 #define GL_MODELVIEW8_ARB 0x8728 #define GL_MODELVIEW9_ARB 0x8729 #define GL_MODELVIEW10_ARB 0x872A #define GL_MODELVIEW11_ARB 0x872B #define GL_MODELVIEW12_ARB 0x872C #define GL_MODELVIEW13_ARB 0x872D #define GL_MODELVIEW14_ARB 0x872E #define GL_MODELVIEW15_ARB 0x872F #define GL_MODELVIEW16_ARB 0x8730 #define GL_MODELVIEW17_ARB 0x8731 #define GL_MODELVIEW18_ARB 0x8732 #define GL_MODELVIEW19_ARB 0x8733 #define GL_MODELVIEW20_ARB 0x8734 #define GL_MODELVIEW21_ARB 0x8735 #define GL_MODELVIEW22_ARB 0x8736 #define GL_MODELVIEW23_ARB 0x8737 #define GL_MODELVIEW24_ARB 0x8738 #define GL_MODELVIEW25_ARB 0x8739 #define GL_MODELVIEW26_ARB 0x873A #define GL_MODELVIEW27_ARB 0x873B #define GL_MODELVIEW28_ARB 0x873C #define GL_MODELVIEW29_ARB 0x873D #define GL_MODELVIEW30_ARB 0x873E #define GL_MODELVIEW31_ARB 0x873F #endif #ifndef GL_ARB_matrix_palette #define GL_MATRIX_PALETTE_ARB 0x8840 #define GL_MAX_MATRIX_PALETTE_STACK_DEPTH_ARB 0x8841 #define GL_MAX_PALETTE_MATRICES_ARB 0x8842 #define GL_CURRENT_PALETTE_MATRIX_ARB 0x8843 #define GL_MATRIX_INDEX_ARRAY_ARB 0x8844 #define GL_CURRENT_MATRIX_INDEX_ARB 0x8845 #define GL_MATRIX_INDEX_ARRAY_SIZE_ARB 0x8846 #define GL_MATRIX_INDEX_ARRAY_TYPE_ARB 0x8847 #define GL_MATRIX_INDEX_ARRAY_STRIDE_ARB 0x8848 #define GL_MATRIX_INDEX_ARRAY_POINTER_ARB 0x8849 #endif #ifndef GL_ARB_texture_env_combine #define GL_COMBINE_ARB 0x8570 #define GL_COMBINE_RGB_ARB 0x8571 #define GL_COMBINE_ALPHA_ARB 0x8572 #define GL_SOURCE0_RGB_ARB 0x8580 #define GL_SOURCE1_RGB_ARB 0x8581 #define GL_SOURCE2_RGB_ARB 0x8582 #define GL_SOURCE0_ALPHA_ARB 0x8588 #define GL_SOURCE1_ALPHA_ARB 0x8589 #define GL_SOURCE2_ALPHA_ARB 0x858A #define GL_OPERAND0_RGB_ARB 0x8590 #define GL_OPERAND1_RGB_ARB 0x8591 #define GL_OPERAND2_RGB_ARB 0x8592 #define GL_OPERAND0_ALPHA_ARB 0x8598 #define GL_OPERAND1_ALPHA_ARB 0x8599 #define GL_OPERAND2_ALPHA_ARB 0x859A #define GL_RGB_SCALE_ARB 0x8573 #define GL_ADD_SIGNED_ARB 0x8574 #define GL_INTERPOLATE_ARB 0x8575 #define GL_SUBTRACT_ARB 0x84E7 #define GL_CONSTANT_ARB 0x8576 #define GL_PRIMARY_COLOR_ARB 0x8577 #define GL_PREVIOUS_ARB 0x8578 #endif #ifndef GL_ARB_texture_env_crossbar #endif #ifndef GL_ARB_texture_env_dot3 #define GL_DOT3_RGB_ARB 0x86AE #define GL_DOT3_RGBA_ARB 0x86AF #endif #ifndef GL_ARB_texture_mirrored_repeat #define GL_MIRRORED_REPEAT_ARB 0x8370 #endif #ifndef GL_ARB_depth_texture #define GL_DEPTH_COMPONENT16_ARB 0x81A5 #define GL_DEPTH_COMPONENT24_ARB 0x81A6 #define GL_DEPTH_COMPONENT32_ARB 0x81A7 #define GL_TEXTURE_DEPTH_SIZE_ARB 0x884A #define GL_DEPTH_TEXTURE_MODE_ARB 0x884B #endif #ifndef GL_ARB_shadow #define GL_TEXTURE_COMPARE_MODE_ARB 0x884C #define GL_TEXTURE_COMPARE_FUNC_ARB 0x884D #define GL_COMPARE_R_TO_TEXTURE_ARB 0x884E #endif #ifndef GL_ARB_shadow_ambient #define GL_TEXTURE_COMPARE_FAIL_VALUE_ARB 0x80BF #endif #ifndef GL_ARB_window_pos #endif #ifndef GL_ARB_vertex_program #define GL_COLOR_SUM_ARB 0x8458 #define GL_VERTEX_PROGRAM_ARB 0x8620 #define GL_VERTEX_ATTRIB_ARRAY_ENABLED_ARB 0x8622 #define GL_VERTEX_ATTRIB_ARRAY_SIZE_ARB 0x8623 #define GL_VERTEX_ATTRIB_ARRAY_STRIDE_ARB 0x8624 #define GL_VERTEX_ATTRIB_ARRAY_TYPE_ARB 0x8625 #define GL_CURRENT_VERTEX_ATTRIB_ARB 0x8626 #define GL_PROGRAM_LENGTH_ARB 0x8627 #define GL_PROGRAM_STRING_ARB 0x8628 #define GL_MAX_PROGRAM_MATRIX_STACK_DEPTH_ARB 0x862E #define GL_MAX_PROGRAM_MATRICES_ARB 0x862F #define GL_CURRENT_MATRIX_STACK_DEPTH_ARB 0x8640 #define GL_CURRENT_MATRIX_ARB 0x8641 #define GL_VERTEX_PROGRAM_POINT_SIZE_ARB 0x8642 #define GL_VERTEX_PROGRAM_TWO_SIDE_ARB 0x8643 #define GL_VERTEX_ATTRIB_ARRAY_POINTER_ARB 0x8645 #define GL_PROGRAM_ERROR_POSITION_ARB 0x864B #define GL_PROGRAM_BINDING_ARB 0x8677 #define GL_MAX_VERTEX_ATTRIBS_ARB 0x8869 #define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED_ARB 0x886A #define GL_PROGRAM_ERROR_STRING_ARB 0x8874 #define GL_PROGRAM_FORMAT_ASCII_ARB 0x8875 #define GL_PROGRAM_FORMAT_ARB 0x8876 #define GL_PROGRAM_INSTRUCTIONS_ARB 0x88A0 #define GL_MAX_PROGRAM_INSTRUCTIONS_ARB 0x88A1 #define GL_PROGRAM_NATIVE_INSTRUCTIONS_ARB 0x88A2 #define GL_MAX_PROGRAM_NATIVE_INSTRUCTIONS_ARB 0x88A3 #define GL_PROGRAM_TEMPORARIES_ARB 0x88A4 #define GL_MAX_PROGRAM_TEMPORARIES_ARB 0x88A5 #define GL_PROGRAM_NATIVE_TEMPORARIES_ARB 0x88A6 #define GL_MAX_PROGRAM_NATIVE_TEMPORARIES_ARB 0x88A7 #define GL_PROGRAM_PARAMETERS_ARB 0x88A8 #define GL_MAX_PROGRAM_PARAMETERS_ARB 0x88A9 #define GL_PROGRAM_NATIVE_PARAMETERS_ARB 0x88AA #define GL_MAX_PROGRAM_NATIVE_PARAMETERS_ARB 0x88AB #define GL_PROGRAM_ATTRIBS_ARB 0x88AC #define GL_MAX_PROGRAM_ATTRIBS_ARB 0x88AD #define GL_PROGRAM_NATIVE_ATTRIBS_ARB 0x88AE #define GL_MAX_PROGRAM_NATIVE_ATTRIBS_ARB 0x88AF #define GL_PROGRAM_ADDRESS_REGISTERS_ARB 0x88B0 #define GL_MAX_PROGRAM_ADDRESS_REGISTERS_ARB 0x88B1 #define GL_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB 0x88B2 #define GL_MAX_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB 0x88B3 #define GL_MAX_PROGRAM_LOCAL_PARAMETERS_ARB 0x88B4 #define GL_MAX_PROGRAM_ENV_PARAMETERS_ARB 0x88B5 #define GL_PROGRAM_UNDER_NATIVE_LIMITS_ARB 0x88B6 #define GL_TRANSPOSE_CURRENT_MATRIX_ARB 0x88B7 #define GL_MATRIX0_ARB 0x88C0 #define GL_MATRIX1_ARB 0x88C1 #define GL_MATRIX2_ARB 0x88C2 #define GL_MATRIX3_ARB 0x88C3 #define GL_MATRIX4_ARB 0x88C4 #define GL_MATRIX5_ARB 0x88C5 #define GL_MATRIX6_ARB 0x88C6 #define GL_MATRIX7_ARB 0x88C7 #define GL_MATRIX8_ARB 0x88C8 #define GL_MATRIX9_ARB 0x88C9 #define GL_MATRIX10_ARB 0x88CA #define GL_MATRIX11_ARB 0x88CB #define GL_MATRIX12_ARB 0x88CC #define GL_MATRIX13_ARB 0x88CD #define GL_MATRIX14_ARB 0x88CE #define GL_MATRIX15_ARB 0x88CF #define GL_MATRIX16_ARB 0x88D0 #define GL_MATRIX17_ARB 0x88D1 #define GL_MATRIX18_ARB 0x88D2 #define GL_MATRIX19_ARB 0x88D3 #define GL_MATRIX20_ARB 0x88D4 #define GL_MATRIX21_ARB 0x88D5 #define GL_MATRIX22_ARB 0x88D6 #define GL_MATRIX23_ARB 0x88D7 #define GL_MATRIX24_ARB 0x88D8 #define GL_MATRIX25_ARB 0x88D9 #define GL_MATRIX26_ARB 0x88DA #define GL_MATRIX27_ARB 0x88DB #define GL_MATRIX28_ARB 0x88DC #define GL_MATRIX29_ARB 0x88DD #define GL_MATRIX30_ARB 0x88DE #define GL_MATRIX31_ARB 0x88DF #endif #ifndef GL_ARB_fragment_program #define GL_FRAGMENT_PROGRAM_ARB 0x8804 #define GL_PROGRAM_ALU_INSTRUCTIONS_ARB 0x8805 #define GL_PROGRAM_TEX_INSTRUCTIONS_ARB 0x8806 #define GL_PROGRAM_TEX_INDIRECTIONS_ARB 0x8807 #define GL_PROGRAM_NATIVE_ALU_INSTRUCTIONS_ARB 0x8808 #define GL_PROGRAM_NATIVE_TEX_INSTRUCTIONS_ARB 0x8809 #define GL_PROGRAM_NATIVE_TEX_INDIRECTIONS_ARB 0x880A #define GL_MAX_PROGRAM_ALU_INSTRUCTIONS_ARB 0x880B #define GL_MAX_PROGRAM_TEX_INSTRUCTIONS_ARB 0x880C #define GL_MAX_PROGRAM_TEX_INDIRECTIONS_ARB 0x880D #define GL_MAX_PROGRAM_NATIVE_ALU_INSTRUCTIONS_ARB 0x880E #define GL_MAX_PROGRAM_NATIVE_TEX_INSTRUCTIONS_ARB 0x880F #define GL_MAX_PROGRAM_NATIVE_TEX_INDIRECTIONS_ARB 0x8810 #define GL_MAX_TEXTURE_COORDS_ARB 0x8871 #define GL_MAX_TEXTURE_IMAGE_UNITS_ARB 0x8872 #endif #ifndef GL_ARB_vertex_buffer_object #define GL_BUFFER_SIZE_ARB 0x8764 #define GL_BUFFER_USAGE_ARB 0x8765 #define GL_ARRAY_BUFFER_ARB 0x8892 #define GL_ELEMENT_ARRAY_BUFFER_ARB 0x8893 #define GL_ARRAY_BUFFER_BINDING_ARB 0x8894 #define GL_ELEMENT_ARRAY_BUFFER_BINDING_ARB 0x8895 #define GL_VERTEX_ARRAY_BUFFER_BINDING_ARB 0x8896 #define GL_NORMAL_ARRAY_BUFFER_BINDING_ARB 0x8897 #define GL_COLOR_ARRAY_BUFFER_BINDING_ARB 0x8898 #define GL_INDEX_ARRAY_BUFFER_BINDING_ARB 0x8899 #define GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING_ARB 0x889A #define GL_EDGE_FLAG_ARRAY_BUFFER_BINDING_ARB 0x889B #define GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING_ARB 0x889C #define GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING_ARB 0x889D #define GL_WEIGHT_ARRAY_BUFFER_BINDING_ARB 0x889E #define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING_ARB 0x889F #define GL_READ_ONLY_ARB 0x88B8 #define GL_WRITE_ONLY_ARB 0x88B9 #define GL_READ_WRITE_ARB 0x88BA #define GL_BUFFER_ACCESS_ARB 0x88BB #define GL_BUFFER_MAPPED_ARB 0x88BC #define GL_BUFFER_MAP_POINTER_ARB 0x88BD #define GL_STREAM_DRAW_ARB 0x88E0 #define GL_STREAM_READ_ARB 0x88E1 #define GL_STREAM_COPY_ARB 0x88E2 #define GL_STATIC_DRAW_ARB 0x88E4 #define GL_STATIC_READ_ARB 0x88E5 #define GL_STATIC_COPY_ARB 0x88E6 #define GL_DYNAMIC_DRAW_ARB 0x88E8 #define GL_DYNAMIC_READ_ARB 0x88E9 #define GL_DYNAMIC_COPY_ARB 0x88EA #endif #ifndef GL_ARB_occlusion_query #define GL_QUERY_COUNTER_BITS_ARB 0x8864 #define GL_CURRENT_QUERY_ARB 0x8865 #define GL_QUERY_RESULT_ARB 0x8866 #define GL_QUERY_RESULT_AVAILABLE_ARB 0x8867 #define GL_SAMPLES_PASSED_ARB 0x8914 #endif #ifndef GL_ARB_shader_objects #define GL_PROGRAM_OBJECT_ARB 0x8B40 #define GL_SHADER_OBJECT_ARB 0x8B48 #define GL_OBJECT_TYPE_ARB 0x8B4E #define GL_OBJECT_SUBTYPE_ARB 0x8B4F #define GL_FLOAT_VEC2_ARB 0x8B50 #define GL_FLOAT_VEC3_ARB 0x8B51 #define GL_FLOAT_VEC4_ARB 0x8B52 #define GL_INT_VEC2_ARB 0x8B53 #define GL_INT_VEC3_ARB 0x8B54 #define GL_INT_VEC4_ARB 0x8B55 #define GL_BOOL_ARB 0x8B56 #define GL_BOOL_VEC2_ARB 0x8B57 #define GL_BOOL_VEC3_ARB 0x8B58 #define GL_BOOL_VEC4_ARB 0x8B59 #define GL_FLOAT_MAT2_ARB 0x8B5A #define GL_FLOAT_MAT3_ARB 0x8B5B #define GL_FLOAT_MAT4_ARB 0x8B5C #define GL_SAMPLER_1D_ARB 0x8B5D #define GL_SAMPLER_2D_ARB 0x8B5E #define GL_SAMPLER_3D_ARB 0x8B5F #define GL_SAMPLER_CUBE_ARB 0x8B60 #define GL_SAMPLER_1D_SHADOW_ARB 0x8B61 #define GL_SAMPLER_2D_SHADOW_ARB 0x8B62 #define GL_SAMPLER_2D_RECT_ARB 0x8B63 #define GL_SAMPLER_2D_RECT_SHADOW_ARB 0x8B64 #define GL_OBJECT_DELETE_STATUS_ARB 0x8B80 #define GL_OBJECT_COMPILE_STATUS_ARB 0x8B81 #define GL_OBJECT_LINK_STATUS_ARB 0x8B82 #define GL_OBJECT_VALIDATE_STATUS_ARB 0x8B83 #define GL_OBJECT_INFO_LOG_LENGTH_ARB 0x8B84 #define GL_OBJECT_ATTACHED_OBJECTS_ARB 0x8B85 #define GL_OBJECT_ACTIVE_UNIFORMS_ARB 0x8B86 #define GL_OBJECT_ACTIVE_UNIFORM_MAX_LENGTH_ARB 0x8B87 #define GL_OBJECT_SHADER_SOURCE_LENGTH_ARB 0x8B88 #endif #ifndef GL_ARB_vertex_shader #define GL_VERTEX_SHADER_ARB 0x8B31 #define GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB 0x8B4A #define GL_MAX_VARYING_FLOATS_ARB 0x8B4B #define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB 0x8B4C #define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB 0x8B4D #define GL_OBJECT_ACTIVE_ATTRIBUTES_ARB 0x8B89 #define GL_OBJECT_ACTIVE_ATTRIBUTE_MAX_LENGTH_ARB 0x8B8A #endif #ifndef GL_ARB_fragment_shader #define GL_FRAGMENT_SHADER_ARB 0x8B30 #define GL_MAX_FRAGMENT_UNIFORM_COMPONENTS_ARB 0x8B49 #define GL_FRAGMENT_SHADER_DERIVATIVE_HINT_ARB 0x8B8B #endif #ifndef GL_ARB_shading_language_100 #define GL_SHADING_LANGUAGE_VERSION_ARB 0x8B8C #endif #ifndef GL_ARB_texture_non_power_of_two #endif #ifndef GL_ARB_point_sprite #define GL_POINT_SPRITE_ARB 0x8861 #define GL_COORD_REPLACE_ARB 0x8862 #endif #ifndef GL_ARB_fragment_program_shadow #endif #ifndef GL_ARB_draw_buffers #define GL_MAX_DRAW_BUFFERS_ARB 0x8824 #define GL_DRAW_BUFFER0_ARB 0x8825 #define GL_DRAW_BUFFER1_ARB 0x8826 #define GL_DRAW_BUFFER2_ARB 0x8827 #define GL_DRAW_BUFFER3_ARB 0x8828 #define GL_DRAW_BUFFER4_ARB 0x8829 #define GL_DRAW_BUFFER5_ARB 0x882A #define GL_DRAW_BUFFER6_ARB 0x882B #define GL_DRAW_BUFFER7_ARB 0x882C #define GL_DRAW_BUFFER8_ARB 0x882D #define GL_DRAW_BUFFER9_ARB 0x882E #define GL_DRAW_BUFFER10_ARB 0x882F #define GL_DRAW_BUFFER11_ARB 0x8830 #define GL_DRAW_BUFFER12_ARB 0x8831 #define GL_DRAW_BUFFER13_ARB 0x8832 #define GL_DRAW_BUFFER14_ARB 0x8833 #define GL_DRAW_BUFFER15_ARB 0x8834 #endif #ifndef GL_ARB_texture_rectangle #define GL_TEXTURE_RECTANGLE_ARB 0x84F5 #define GL_TEXTURE_BINDING_RECTANGLE_ARB 0x84F6 #define GL_PROXY_TEXTURE_RECTANGLE_ARB 0x84F7 #define GL_MAX_RECTANGLE_TEXTURE_SIZE_ARB 0x84F8 #endif #ifndef GL_ARB_color_buffer_float #define GL_RGBA_FLOAT_MODE_ARB 0x8820 #define GL_CLAMP_VERTEX_COLOR_ARB 0x891A #define GL_CLAMP_FRAGMENT_COLOR_ARB 0x891B #define GL_CLAMP_READ_COLOR_ARB 0x891C #define GL_FIXED_ONLY_ARB 0x891D #endif #ifndef GL_ARB_half_float_pixel #define GL_HALF_FLOAT_ARB 0x140B #endif #ifndef GL_ARB_texture_float #define GL_TEXTURE_RED_TYPE_ARB 0x8C10 #define GL_TEXTURE_GREEN_TYPE_ARB 0x8C11 #define GL_TEXTURE_BLUE_TYPE_ARB 0x8C12 #define GL_TEXTURE_ALPHA_TYPE_ARB 0x8C13 #define GL_TEXTURE_LUMINANCE_TYPE_ARB 0x8C14 #define GL_TEXTURE_INTENSITY_TYPE_ARB 0x8C15 #define GL_TEXTURE_DEPTH_TYPE_ARB 0x8C16 #define GL_UNSIGNED_NORMALIZED_ARB 0x8C17 #define GL_RGBA32F_ARB 0x8814 #define GL_RGB32F_ARB 0x8815 #define GL_ALPHA32F_ARB 0x8816 #define GL_INTENSITY32F_ARB 0x8817 #define GL_LUMINANCE32F_ARB 0x8818 #define GL_LUMINANCE_ALPHA32F_ARB 0x8819 #define GL_RGBA16F_ARB 0x881A #define GL_RGB16F_ARB 0x881B #define GL_ALPHA16F_ARB 0x881C #define GL_INTENSITY16F_ARB 0x881D #define GL_LUMINANCE16F_ARB 0x881E #define GL_LUMINANCE_ALPHA16F_ARB 0x881F #endif #ifndef GL_ARB_pixel_buffer_object #define GL_PIXEL_PACK_BUFFER_ARB 0x88EB #define GL_PIXEL_UNPACK_BUFFER_ARB 0x88EC #define GL_PIXEL_PACK_BUFFER_BINDING_ARB 0x88ED #define GL_PIXEL_UNPACK_BUFFER_BINDING_ARB 0x88EF #endif #ifndef GL_EXT_abgr #define GL_ABGR_EXT 0x8000 #endif #ifndef GL_EXT_blend_color #define GL_CONSTANT_COLOR_EXT 0x8001 #define GL_ONE_MINUS_CONSTANT_COLOR_EXT 0x8002 #define GL_CONSTANT_ALPHA_EXT 0x8003 #define GL_ONE_MINUS_CONSTANT_ALPHA_EXT 0x8004 #define GL_BLEND_COLOR_EXT 0x8005 #endif #ifndef GL_EXT_polygon_offset #define GL_POLYGON_OFFSET_EXT 0x8037 #define GL_POLYGON_OFFSET_FACTOR_EXT 0x8038 #define GL_POLYGON_OFFSET_BIAS_EXT 0x8039 #endif #ifndef GL_EXT_texture #define GL_ALPHA4_EXT 0x803B #define GL_ALPHA8_EXT 0x803C #define GL_ALPHA12_EXT 0x803D #define GL_ALPHA16_EXT 0x803E #define GL_LUMINANCE4_EXT 0x803F #define GL_LUMINANCE8_EXT 0x8040 #define GL_LUMINANCE12_EXT 0x8041 #define GL_LUMINANCE16_EXT 0x8042 #define GL_LUMINANCE4_ALPHA4_EXT 0x8043 #define GL_LUMINANCE6_ALPHA2_EXT 0x8044 #define GL_LUMINANCE8_ALPHA8_EXT 0x8045 #define GL_LUMINANCE12_ALPHA4_EXT 0x8046 #define GL_LUMINANCE12_ALPHA12_EXT 0x8047 #define GL_LUMINANCE16_ALPHA16_EXT 0x8048 #define GL_INTENSITY_EXT 0x8049 #define GL_INTENSITY4_EXT 0x804A #define GL_INTENSITY8_EXT 0x804B #define GL_INTENSITY12_EXT 0x804C #define GL_INTENSITY16_EXT 0x804D #define GL_RGB2_EXT 0x804E #define GL_RGB4_EXT 0x804F #define GL_RGB5_EXT 0x8050 #define GL_RGB8_EXT 0x8051 #define GL_RGB10_EXT 0x8052 #define GL_RGB12_EXT 0x8053 #define GL_RGB16_EXT 0x8054 #define GL_RGBA2_EXT 0x8055 #define GL_RGBA4_EXT 0x8056 #define GL_RGB5_A1_EXT 0x8057 #define GL_RGBA8_EXT 0x8058 #define GL_RGB10_A2_EXT 0x8059 #define GL_RGBA12_EXT 0x805A #define GL_RGBA16_EXT 0x805B #define GL_TEXTURE_RED_SIZE_EXT 0x805C #define GL_TEXTURE_GREEN_SIZE_EXT 0x805D #define GL_TEXTURE_BLUE_SIZE_EXT 0x805E #define GL_TEXTURE_ALPHA_SIZE_EXT 0x805F #define GL_TEXTURE_LUMINANCE_SIZE_EXT 0x8060 #define GL_TEXTURE_INTENSITY_SIZE_EXT 0x8061 #define GL_REPLACE_EXT 0x8062 #define GL_PROXY_TEXTURE_1D_EXT 0x8063 #define GL_PROXY_TEXTURE_2D_EXT 0x8064 #define GL_TEXTURE_TOO_LARGE_EXT 0x8065 #endif #ifndef GL_EXT_texture3D #define GL_PACK_SKIP_IMAGES_EXT 0x806B #define GL_PACK_IMAGE_HEIGHT_EXT 0x806C #define GL_UNPACK_SKIP_IMAGES_EXT 0x806D #define GL_UNPACK_IMAGE_HEIGHT_EXT 0x806E #define GL_TEXTURE_3D_EXT 0x806F #define GL_PROXY_TEXTURE_3D_EXT 0x8070 #define GL_TEXTURE_DEPTH_EXT 0x8071 #define GL_TEXTURE_WRAP_R_EXT 0x8072 #define GL_MAX_3D_TEXTURE_SIZE_EXT 0x8073 #endif #ifndef GL_SGIS_texture_filter4 #define GL_FILTER4_SGIS 0x8146 #define GL_TEXTURE_FILTER4_SIZE_SGIS 0x8147 #endif #ifndef GL_EXT_subtexture #endif #ifndef GL_EXT_copy_texture #endif #ifndef GL_EXT_histogram #define GL_HISTOGRAM_EXT 0x8024 #define GL_PROXY_HISTOGRAM_EXT 0x8025 #define GL_HISTOGRAM_WIDTH_EXT 0x8026 #define GL_HISTOGRAM_FORMAT_EXT 0x8027 #define GL_HISTOGRAM_RED_SIZE_EXT 0x8028 #define GL_HISTOGRAM_GREEN_SIZE_EXT 0x8029 #define GL_HISTOGRAM_BLUE_SIZE_EXT 0x802A #define GL_HISTOGRAM_ALPHA_SIZE_EXT 0x802B #define GL_HISTOGRAM_LUMINANCE_SIZE_EXT 0x802C #define GL_HISTOGRAM_SINK_EXT 0x802D #define GL_MINMAX_EXT 0x802E #define GL_MINMAX_FORMAT_EXT 0x802F #define GL_MINMAX_SINK_EXT 0x8030 #define GL_TABLE_TOO_LARGE_EXT 0x8031 #endif #ifndef GL_EXT_convolution #define GL_CONVOLUTION_1D_EXT 0x8010 #define GL_CONVOLUTION_2D_EXT 0x8011 #define GL_SEPARABLE_2D_EXT 0x8012 #define GL_CONVOLUTION_BORDER_MODE_EXT 0x8013 #define GL_CONVOLUTION_FILTER_SCALE_EXT 0x8014 #define GL_CONVOLUTION_FILTER_BIAS_EXT 0x8015 #define GL_REDUCE_EXT 0x8016 #define GL_CONVOLUTION_FORMAT_EXT 0x8017 #define GL_CONVOLUTION_WIDTH_EXT 0x8018 #define GL_CONVOLUTION_HEIGHT_EXT 0x8019 #define GL_MAX_CONVOLUTION_WIDTH_EXT 0x801A #define GL_MAX_CONVOLUTION_HEIGHT_EXT 0x801B #define GL_POST_CONVOLUTION_RED_SCALE_EXT 0x801C #define GL_POST_CONVOLUTION_GREEN_SCALE_EXT 0x801D #define GL_POST_CONVOLUTION_BLUE_SCALE_EXT 0x801E #define GL_POST_CONVOLUTION_ALPHA_SCALE_EXT 0x801F #define GL_POST_CONVOLUTION_RED_BIAS_EXT 0x8020 #define GL_POST_CONVOLUTION_GREEN_BIAS_EXT 0x8021 #define GL_POST_CONVOLUTION_BLUE_BIAS_EXT 0x8022 #define GL_POST_CONVOLUTION_ALPHA_BIAS_EXT 0x8023 #endif #ifndef GL_SGI_color_matrix #define GL_COLOR_MATRIX_SGI 0x80B1 #define GL_COLOR_MATRIX_STACK_DEPTH_SGI 0x80B2 #define GL_MAX_COLOR_MATRIX_STACK_DEPTH_SGI 0x80B3 #define GL_POST_COLOR_MATRIX_RED_SCALE_SGI 0x80B4 #define GL_POST_COLOR_MATRIX_GREEN_SCALE_SGI 0x80B5 #define GL_POST_COLOR_MATRIX_BLUE_SCALE_SGI 0x80B6 #define GL_POST_COLOR_MATRIX_ALPHA_SCALE_SGI 0x80B7 #define GL_POST_COLOR_MATRIX_RED_BIAS_SGI 0x80B8 #define GL_POST_COLOR_MATRIX_GREEN_BIAS_SGI 0x80B9 #define GL_POST_COLOR_MATRIX_BLUE_BIAS_SGI 0x80BA #define GL_POST_COLOR_MATRIX_ALPHA_BIAS_SGI 0x80BB #endif #ifndef GL_SGI_color_table #define GL_COLOR_TABLE_SGI 0x80D0 #define GL_POST_CONVOLUTION_COLOR_TABLE_SGI 0x80D1 #define GL_POST_COLOR_MATRIX_COLOR_TABLE_SGI 0x80D2 #define GL_PROXY_COLOR_TABLE_SGI 0x80D3 #define GL_PROXY_POST_CONVOLUTION_COLOR_TABLE_SGI 0x80D4 #define GL_PROXY_POST_COLOR_MATRIX_COLOR_TABLE_SGI 0x80D5 #define GL_COLOR_TABLE_SCALE_SGI 0x80D6 #define GL_COLOR_TABLE_BIAS_SGI 0x80D7 #define GL_COLOR_TABLE_FORMAT_SGI 0x80D8 #define GL_COLOR_TABLE_WIDTH_SGI 0x80D9 #define GL_COLOR_TABLE_RED_SIZE_SGI 0x80DA #define GL_COLOR_TABLE_GREEN_SIZE_SGI 0x80DB #define GL_COLOR_TABLE_BLUE_SIZE_SGI 0x80DC #define GL_COLOR_TABLE_ALPHA_SIZE_SGI 0x80DD #define GL_COLOR_TABLE_LUMINANCE_SIZE_SGI 0x80DE #define GL_COLOR_TABLE_INTENSITY_SIZE_SGI 0x80DF #endif #ifndef GL_SGIS_pixel_texture #define GL_PIXEL_TEXTURE_SGIS 0x8353 #define GL_PIXEL_FRAGMENT_RGB_SOURCE_SGIS 0x8354 #define GL_PIXEL_FRAGMENT_ALPHA_SOURCE_SGIS 0x8355 #define GL_PIXEL_GROUP_COLOR_SGIS 0x8356 #endif #ifndef GL_SGIX_pixel_texture #define GL_PIXEL_TEX_GEN_SGIX 0x8139 #define GL_PIXEL_TEX_GEN_MODE_SGIX 0x832B #endif #ifndef GL_SGIS_texture4D #define GL_PACK_SKIP_VOLUMES_SGIS 0x8130 #define GL_PACK_IMAGE_DEPTH_SGIS 0x8131 #define GL_UNPACK_SKIP_VOLUMES_SGIS 0x8132 #define GL_UNPACK_IMAGE_DEPTH_SGIS 0x8133 #define GL_TEXTURE_4D_SGIS 0x8134 #define GL_PROXY_TEXTURE_4D_SGIS 0x8135 #define GL_TEXTURE_4DSIZE_SGIS 0x8136 #define GL_TEXTURE_WRAP_Q_SGIS 0x8137 #define GL_MAX_4D_TEXTURE_SIZE_SGIS 0x8138 #define GL_TEXTURE_4D_BINDING_SGIS 0x814F #endif #ifndef GL_SGI_texture_color_table #define GL_TEXTURE_COLOR_TABLE_SGI 0x80BC #define GL_PROXY_TEXTURE_COLOR_TABLE_SGI 0x80BD #endif #ifndef GL_EXT_cmyka #define GL_CMYK_EXT 0x800C #define GL_CMYKA_EXT 0x800D #define GL_PACK_CMYK_HINT_EXT 0x800E #define GL_UNPACK_CMYK_HINT_EXT 0x800F #endif #ifndef GL_EXT_texture_object #define GL_TEXTURE_PRIORITY_EXT 0x8066 #define GL_TEXTURE_RESIDENT_EXT 0x8067 #define GL_TEXTURE_1D_BINDING_EXT 0x8068 #define GL_TEXTURE_2D_BINDING_EXT 0x8069 #define GL_TEXTURE_3D_BINDING_EXT 0x806A #endif #ifndef GL_SGIS_detail_texture #define GL_DETAIL_TEXTURE_2D_SGIS 0x8095 #define GL_DETAIL_TEXTURE_2D_BINDING_SGIS 0x8096 #define GL_LINEAR_DETAIL_SGIS 0x8097 #define GL_LINEAR_DETAIL_ALPHA_SGIS 0x8098 #define GL_LINEAR_DETAIL_COLOR_SGIS 0x8099 #define GL_DETAIL_TEXTURE_LEVEL_SGIS 0x809A #define GL_DETAIL_TEXTURE_MODE_SGIS 0x809B #define GL_DETAIL_TEXTURE_FUNC_POINTS_SGIS 0x809C #endif #ifndef GL_SGIS_sharpen_texture #define GL_LINEAR_SHARPEN_SGIS 0x80AD #define GL_LINEAR_SHARPEN_ALPHA_SGIS 0x80AE #define GL_LINEAR_SHARPEN_COLOR_SGIS 0x80AF #define GL_SHARPEN_TEXTURE_FUNC_POINTS_SGIS 0x80B0 #endif #ifndef GL_EXT_packed_pixels #define GL_UNSIGNED_BYTE_3_3_2_EXT 0x8032 #define GL_UNSIGNED_SHORT_4_4_4_4_EXT 0x8033 #define GL_UNSIGNED_SHORT_5_5_5_1_EXT 0x8034 #define GL_UNSIGNED_INT_8_8_8_8_EXT 0x8035 #define GL_UNSIGNED_INT_10_10_10_2_EXT 0x8036 #endif #ifndef GL_SGIS_texture_lod #define GL_TEXTURE_MIN_LOD_SGIS 0x813A #define GL_TEXTURE_MAX_LOD_SGIS 0x813B #define GL_TEXTURE_BASE_LEVEL_SGIS 0x813C #define GL_TEXTURE_MAX_LEVEL_SGIS 0x813D #endif #ifndef GL_SGIS_multisample #define GL_MULTISAMPLE_SGIS 0x809D #define GL_SAMPLE_ALPHA_TO_MASK_SGIS 0x809E #define GL_SAMPLE_ALPHA_TO_ONE_SGIS 0x809F #define GL_SAMPLE_MASK_SGIS 0x80A0 #define GL_1PASS_SGIS 0x80A1 #define GL_2PASS_0_SGIS 0x80A2 #define GL_2PASS_1_SGIS 0x80A3 #define GL_4PASS_0_SGIS 0x80A4 #define GL_4PASS_1_SGIS 0x80A5 #define GL_4PASS_2_SGIS 0x80A6 #define GL_4PASS_3_SGIS 0x80A7 #define GL_SAMPLE_BUFFERS_SGIS 0x80A8 #define GL_SAMPLES_SGIS 0x80A9 #define GL_SAMPLE_MASK_VALUE_SGIS 0x80AA #define GL_SAMPLE_MASK_INVERT_SGIS 0x80AB #define GL_SAMPLE_PATTERN_SGIS 0x80AC #endif #ifndef GL_EXT_rescale_normal #define GL_RESCALE_NORMAL_EXT 0x803A #endif #ifndef GL_EXT_vertex_array #define GL_VERTEX_ARRAY_EXT 0x8074 #define GL_NORMAL_ARRAY_EXT 0x8075 #define GL_COLOR_ARRAY_EXT 0x8076 #define GL_INDEX_ARRAY_EXT 0x8077 #define GL_TEXTURE_COORD_ARRAY_EXT 0x8078 #define GL_EDGE_FLAG_ARRAY_EXT 0x8079 #define GL_VERTEX_ARRAY_SIZE_EXT 0x807A #define GL_VERTEX_ARRAY_TYPE_EXT 0x807B #define GL_VERTEX_ARRAY_STRIDE_EXT 0x807C #define GL_VERTEX_ARRAY_COUNT_EXT 0x807D #define GL_NORMAL_ARRAY_TYPE_EXT 0x807E #define GL_NORMAL_ARRAY_STRIDE_EXT 0x807F #define GL_NORMAL_ARRAY_COUNT_EXT 0x8080 #define GL_COLOR_ARRAY_SIZE_EXT 0x8081 #define GL_COLOR_ARRAY_TYPE_EXT 0x8082 #define GL_COLOR_ARRAY_STRIDE_EXT 0x8083 #define GL_COLOR_ARRAY_COUNT_EXT 0x8084 #define GL_INDEX_ARRAY_TYPE_EXT 0x8085 #define GL_INDEX_ARRAY_STRIDE_EXT 0x8086 #define GL_INDEX_ARRAY_COUNT_EXT 0x8087 #define GL_TEXTURE_COORD_ARRAY_SIZE_EXT 0x8088 #define GL_TEXTURE_COORD_ARRAY_TYPE_EXT 0x8089 #define GL_TEXTURE_COORD_ARRAY_STRIDE_EXT 0x808A #define GL_TEXTURE_COORD_ARRAY_COUNT_EXT 0x808B #define GL_EDGE_FLAG_ARRAY_STRIDE_EXT 0x808C #define GL_EDGE_FLAG_ARRAY_COUNT_EXT 0x808D #define GL_VERTEX_ARRAY_POINTER_EXT 0x808E #define GL_NORMAL_ARRAY_POINTER_EXT 0x808F #define GL_COLOR_ARRAY_POINTER_EXT 0x8090 #define GL_INDEX_ARRAY_POINTER_EXT 0x8091 #define GL_TEXTURE_COORD_ARRAY_POINTER_EXT 0x8092 #define GL_EDGE_FLAG_ARRAY_POINTER_EXT 0x8093 #endif #ifndef GL_EXT_misc_attribute #endif #ifndef GL_SGIS_generate_mipmap #define GL_GENERATE_MIPMAP_SGIS 0x8191 #define GL_GENERATE_MIPMAP_HINT_SGIS 0x8192 #endif #ifndef GL_SGIX_clipmap #define GL_LINEAR_CLIPMAP_LINEAR_SGIX 0x8170 #define GL_TEXTURE_CLIPMAP_CENTER_SGIX 0x8171 #define GL_TEXTURE_CLIPMAP_FRAME_SGIX 0x8172 #define GL_TEXTURE_CLIPMAP_OFFSET_SGIX 0x8173 #define GL_TEXTURE_CLIPMAP_VIRTUAL_DEPTH_SGIX 0x8174 #define GL_TEXTURE_CLIPMAP_LOD_OFFSET_SGIX 0x8175 #define GL_TEXTURE_CLIPMAP_DEPTH_SGIX 0x8176 #define GL_MAX_CLIPMAP_DEPTH_SGIX 0x8177 #define GL_MAX_CLIPMAP_VIRTUAL_DEPTH_SGIX 0x8178 #define GL_NEAREST_CLIPMAP_NEAREST_SGIX 0x844D #define GL_NEAREST_CLIPMAP_LINEAR_SGIX 0x844E #define GL_LINEAR_CLIPMAP_NEAREST_SGIX 0x844F #endif #ifndef GL_SGIX_shadow #define GL_TEXTURE_COMPARE_SGIX 0x819A #define GL_TEXTURE_COMPARE_OPERATOR_SGIX 0x819B #define GL_TEXTURE_LEQUAL_R_SGIX 0x819C #define GL_TEXTURE_GEQUAL_R_SGIX 0x819D #endif #ifndef GL_SGIS_texture_edge_clamp #define GL_CLAMP_TO_EDGE_SGIS 0x812F #endif #ifndef GL_SGIS_texture_border_clamp #define GL_CLAMP_TO_BORDER_SGIS 0x812D #endif #ifndef GL_EXT_blend_minmax #define GL_FUNC_ADD_EXT 0x8006 #define GL_MIN_EXT 0x8007 #define GL_MAX_EXT 0x8008 #define GL_BLEND_EQUATION_EXT 0x8009 #endif #ifndef GL_EXT_blend_subtract #define GL_FUNC_SUBTRACT_EXT 0x800A #define GL_FUNC_REVERSE_SUBTRACT_EXT 0x800B #endif #ifndef GL_EXT_blend_logic_op #endif #ifndef GL_SGIX_interlace #define GL_INTERLACE_SGIX 0x8094 #endif #ifndef GL_SGIX_pixel_tiles #define GL_PIXEL_TILE_BEST_ALIGNMENT_SGIX 0x813E #define GL_PIXEL_TILE_CACHE_INCREMENT_SGIX 0x813F #define GL_PIXEL_TILE_WIDTH_SGIX 0x8140 #define GL_PIXEL_TILE_HEIGHT_SGIX 0x8141 #define GL_PIXEL_TILE_GRID_WIDTH_SGIX 0x8142 #define GL_PIXEL_TILE_GRID_HEIGHT_SGIX 0x8143 #define GL_PIXEL_TILE_GRID_DEPTH_SGIX 0x8144 #define GL_PIXEL_TILE_CACHE_SIZE_SGIX 0x8145 #endif #ifndef GL_SGIS_texture_select #define GL_DUAL_ALPHA4_SGIS 0x8110 #define GL_DUAL_ALPHA8_SGIS 0x8111 #define GL_DUAL_ALPHA12_SGIS 0x8112 #define GL_DUAL_ALPHA16_SGIS 0x8113 #define GL_DUAL_LUMINANCE4_SGIS 0x8114 #define GL_DUAL_LUMINANCE8_SGIS 0x8115 #define GL_DUAL_LUMINANCE12_SGIS 0x8116 #define GL_DUAL_LUMINANCE16_SGIS 0x8117 #define GL_DUAL_INTENSITY4_SGIS 0x8118 #define GL_DUAL_INTENSITY8_SGIS 0x8119 #define GL_DUAL_INTENSITY12_SGIS 0x811A #define GL_DUAL_INTENSITY16_SGIS 0x811B #define GL_DUAL_LUMINANCE_ALPHA4_SGIS 0x811C #define GL_DUAL_LUMINANCE_ALPHA8_SGIS 0x811D #define GL_QUAD_ALPHA4_SGIS 0x811E #define GL_QUAD_ALPHA8_SGIS 0x811F #define GL_QUAD_LUMINANCE4_SGIS 0x8120 #define GL_QUAD_LUMINANCE8_SGIS 0x8121 #define GL_QUAD_INTENSITY4_SGIS 0x8122 #define GL_QUAD_INTENSITY8_SGIS 0x8123 #define GL_DUAL_TEXTURE_SELECT_SGIS 0x8124 #define GL_QUAD_TEXTURE_SELECT_SGIS 0x8125 #endif #ifndef GL_SGIX_sprite #define GL_SPRITE_SGIX 0x8148 #define GL_SPRITE_MODE_SGIX 0x8149 #define GL_SPRITE_AXIS_SGIX 0x814A #define GL_SPRITE_TRANSLATION_SGIX 0x814B #define GL_SPRITE_AXIAL_SGIX 0x814C #define GL_SPRITE_OBJECT_ALIGNED_SGIX 0x814D #define GL_SPRITE_EYE_ALIGNED_SGIX 0x814E #endif #ifndef GL_SGIX_texture_multi_buffer #define GL_TEXTURE_MULTI_BUFFER_HINT_SGIX 0x812E #endif #ifndef GL_EXT_point_parameters #define GL_POINT_SIZE_MIN_EXT 0x8126 #define GL_POINT_SIZE_MAX_EXT 0x8127 #define GL_POINT_FADE_THRESHOLD_SIZE_EXT 0x8128 #define GL_DISTANCE_ATTENUATION_EXT 0x8129 #endif #ifndef GL_SGIS_point_parameters #define GL_POINT_SIZE_MIN_SGIS 0x8126 #define GL_POINT_SIZE_MAX_SGIS 0x8127 #define GL_POINT_FADE_THRESHOLD_SIZE_SGIS 0x8128 #define GL_DISTANCE_ATTENUATION_SGIS 0x8129 #endif #ifndef GL_SGIX_instruments #define GL_INSTRUMENT_BUFFER_POINTER_SGIX 0x8180 #define GL_INSTRUMENT_MEASUREMENTS_SGIX 0x8181 #endif #ifndef GL_SGIX_texture_scale_bias #define GL_POST_TEXTURE_FILTER_BIAS_SGIX 0x8179 #define GL_POST_TEXTURE_FILTER_SCALE_SGIX 0x817A #define GL_POST_TEXTURE_FILTER_BIAS_RANGE_SGIX 0x817B #define GL_POST_TEXTURE_FILTER_SCALE_RANGE_SGIX 0x817C #endif #ifndef GL_SGIX_framezoom #define GL_FRAMEZOOM_SGIX 0x818B #define GL_FRAMEZOOM_FACTOR_SGIX 0x818C #define GL_MAX_FRAMEZOOM_FACTOR_SGIX 0x818D #endif #ifndef GL_SGIX_tag_sample_buffer #endif #ifndef GL_FfdMaskSGIX #define GL_TEXTURE_DEFORMATION_BIT_SGIX 0x00000001 #define GL_GEOMETRY_DEFORMATION_BIT_SGIX 0x00000002 #endif #ifndef GL_SGIX_polynomial_ffd #define GL_GEOMETRY_DEFORMATION_SGIX 0x8194 #define GL_TEXTURE_DEFORMATION_SGIX 0x8195 #define GL_DEFORMATIONS_MASK_SGIX 0x8196 #define GL_MAX_DEFORMATION_ORDER_SGIX 0x8197 #endif #ifndef GL_SGIX_reference_plane #define GL_REFERENCE_PLANE_SGIX 0x817D #define GL_REFERENCE_PLANE_EQUATION_SGIX 0x817E #endif #ifndef GL_SGIX_flush_raster #endif #ifndef GL_SGIX_depth_texture #define GL_DEPTH_COMPONENT16_SGIX 0x81A5 #define GL_DEPTH_COMPONENT24_SGIX 0x81A6 #define GL_DEPTH_COMPONENT32_SGIX 0x81A7 #endif #ifndef GL_SGIS_fog_function #define GL_FOG_FUNC_SGIS 0x812A #define GL_FOG_FUNC_POINTS_SGIS 0x812B #define GL_MAX_FOG_FUNC_POINTS_SGIS 0x812C #endif #ifndef GL_SGIX_fog_offset #define GL_FOG_OFFSET_SGIX 0x8198 #define GL_FOG_OFFSET_VALUE_SGIX 0x8199 #endif #ifndef GL_HP_image_transform #define GL_IMAGE_SCALE_X_HP 0x8155 #define GL_IMAGE_SCALE_Y_HP 0x8156 #define GL_IMAGE_TRANSLATE_X_HP 0x8157 #define GL_IMAGE_TRANSLATE_Y_HP 0x8158 #define GL_IMAGE_ROTATE_ANGLE_HP 0x8159 #define GL_IMAGE_ROTATE_ORIGIN_X_HP 0x815A #define GL_IMAGE_ROTATE_ORIGIN_Y_HP 0x815B #define GL_IMAGE_MAG_FILTER_HP 0x815C #define GL_IMAGE_MIN_FILTER_HP 0x815D #define GL_IMAGE_CUBIC_WEIGHT_HP 0x815E #define GL_CUBIC_HP 0x815F #define GL_AVERAGE_HP 0x8160 #define GL_IMAGE_TRANSFORM_2D_HP 0x8161 #define GL_POST_IMAGE_TRANSFORM_COLOR_TABLE_HP 0x8162 #define GL_PROXY_POST_IMAGE_TRANSFORM_COLOR_TABLE_HP 0x8163 #endif #ifndef GL_HP_convolution_border_modes #define GL_IGNORE_BORDER_HP 0x8150 #define GL_CONSTANT_BORDER_HP 0x8151 #define GL_REPLICATE_BORDER_HP 0x8153 #define GL_CONVOLUTION_BORDER_COLOR_HP 0x8154 #endif #ifndef GL_INGR_palette_buffer #endif #ifndef GL_SGIX_texture_add_env #define GL_TEXTURE_ENV_BIAS_SGIX 0x80BE #endif #ifndef GL_EXT_color_subtable #endif #ifndef GL_PGI_vertex_hints #define GL_VERTEX_DATA_HINT_PGI 0x1A22A #define GL_VERTEX_CONSISTENT_HINT_PGI 0x1A22B #define GL_MATERIAL_SIDE_HINT_PGI 0x1A22C #define GL_MAX_VERTEX_HINT_PGI 0x1A22D #define GL_COLOR3_BIT_PGI 0x00010000 #define GL_COLOR4_BIT_PGI 0x00020000 #define GL_EDGEFLAG_BIT_PGI 0x00040000 #define GL_INDEX_BIT_PGI 0x00080000 #define GL_MAT_AMBIENT_BIT_PGI 0x00100000 #define GL_MAT_AMBIENT_AND_DIFFUSE_BIT_PGI 0x00200000 #define GL_MAT_DIFFUSE_BIT_PGI 0x00400000 #define GL_MAT_EMISSION_BIT_PGI 0x00800000 #define GL_MAT_COLOR_INDEXES_BIT_PGI 0x01000000 #define GL_MAT_SHININESS_BIT_PGI 0x02000000 #define GL_MAT_SPECULAR_BIT_PGI 0x04000000 #define GL_NORMAL_BIT_PGI 0x08000000 #define GL_TEXCOORD1_BIT_PGI 0x10000000 #define GL_TEXCOORD2_BIT_PGI 0x20000000 #define GL_TEXCOORD3_BIT_PGI 0x40000000 #define GL_TEXCOORD4_BIT_PGI 0x80000000 #define GL_VERTEX23_BIT_PGI 0x00000004 #define GL_VERTEX4_BIT_PGI 0x00000008 #endif #ifndef GL_PGI_misc_hints #define GL_PREFER_DOUBLEBUFFER_HINT_PGI 0x1A1F8 #define GL_CONSERVE_MEMORY_HINT_PGI 0x1A1FD #define GL_RECLAIM_MEMORY_HINT_PGI 0x1A1FE #define GL_NATIVE_GRAPHICS_HANDLE_PGI 0x1A202 #define GL_NATIVE_GRAPHICS_BEGIN_HINT_PGI 0x1A203 #define GL_NATIVE_GRAPHICS_END_HINT_PGI 0x1A204 #define GL_ALWAYS_FAST_HINT_PGI 0x1A20C #define GL_ALWAYS_SOFT_HINT_PGI 0x1A20D #define GL_ALLOW_DRAW_OBJ_HINT_PGI 0x1A20E #define GL_ALLOW_DRAW_WIN_HINT_PGI 0x1A20F #define GL_ALLOW_DRAW_FRG_HINT_PGI 0x1A210 #define GL_ALLOW_DRAW_MEM_HINT_PGI 0x1A211 #define GL_STRICT_DEPTHFUNC_HINT_PGI 0x1A216 #define GL_STRICT_LIGHTING_HINT_PGI 0x1A217 #define GL_STRICT_SCISSOR_HINT_PGI 0x1A218 #define GL_FULL_STIPPLE_HINT_PGI 0x1A219 #define GL_CLIP_NEAR_HINT_PGI 0x1A220 #define GL_CLIP_FAR_HINT_PGI 0x1A221 #define GL_WIDE_LINE_HINT_PGI 0x1A222 #define GL_BACK_NORMALS_HINT_PGI 0x1A223 #endif #ifndef GL_EXT_paletted_texture #define GL_COLOR_INDEX1_EXT 0x80E2 #define GL_COLOR_INDEX2_EXT 0x80E3 #define GL_COLOR_INDEX4_EXT 0x80E4 #define GL_COLOR_INDEX8_EXT 0x80E5 #define GL_COLOR_INDEX12_EXT 0x80E6 #define GL_COLOR_INDEX16_EXT 0x80E7 #define GL_TEXTURE_INDEX_SIZE_EXT 0x80ED #endif #ifndef GL_EXT_clip_volume_hint #define GL_CLIP_VOLUME_CLIPPING_HINT_EXT 0x80F0 #endif #ifndef GL_SGIX_list_priority #define GL_LIST_PRIORITY_SGIX 0x8182 #endif #ifndef GL_SGIX_ir_instrument1 #define GL_IR_INSTRUMENT1_SGIX 0x817F #endif #ifndef GL_SGIX_calligraphic_fragment #define GL_CALLIGRAPHIC_FRAGMENT_SGIX 0x8183 #endif #ifndef GL_SGIX_texture_lod_bias #define GL_TEXTURE_LOD_BIAS_S_SGIX 0x818E #define GL_TEXTURE_LOD_BIAS_T_SGIX 0x818F #define GL_TEXTURE_LOD_BIAS_R_SGIX 0x8190 #endif #ifndef GL_SGIX_shadow_ambient #define GL_SHADOW_AMBIENT_SGIX 0x80BF #endif #ifndef GL_EXT_index_texture #endif #ifndef GL_EXT_index_material #define GL_INDEX_MATERIAL_EXT 0x81B8 #define GL_INDEX_MATERIAL_PARAMETER_EXT 0x81B9 #define GL_INDEX_MATERIAL_FACE_EXT 0x81BA #endif #ifndef GL_EXT_index_func #define GL_INDEX_TEST_EXT 0x81B5 #define GL_INDEX_TEST_FUNC_EXT 0x81B6 #define GL_INDEX_TEST_REF_EXT 0x81B7 #endif #ifndef GL_EXT_index_array_formats #define GL_IUI_V2F_EXT 0x81AD #define GL_IUI_V3F_EXT 0x81AE #define GL_IUI_N3F_V2F_EXT 0x81AF #define GL_IUI_N3F_V3F_EXT 0x81B0 #define GL_T2F_IUI_V2F_EXT 0x81B1 #define GL_T2F_IUI_V3F_EXT 0x81B2 #define GL_T2F_IUI_N3F_V2F_EXT 0x81B3 #define GL_T2F_IUI_N3F_V3F_EXT 0x81B4 #endif #ifndef GL_EXT_compiled_vertex_array #define GL_ARRAY_ELEMENT_LOCK_FIRST_EXT 0x81A8 #define GL_ARRAY_ELEMENT_LOCK_COUNT_EXT 0x81A9 #endif #ifndef GL_EXT_cull_vertex #define GL_CULL_VERTEX_EXT 0x81AA #define GL_CULL_VERTEX_EYE_POSITION_EXT 0x81AB #define GL_CULL_VERTEX_OBJECT_POSITION_EXT 0x81AC #endif #ifndef GL_SGIX_ycrcb #define GL_YCRCB_422_SGIX 0x81BB #define GL_YCRCB_444_SGIX 0x81BC #endif #ifndef GL_SGIX_fragment_lighting #define GL_FRAGMENT_LIGHTING_SGIX 0x8400 #define GL_FRAGMENT_COLOR_MATERIAL_SGIX 0x8401 #define GL_FRAGMENT_COLOR_MATERIAL_FACE_SGIX 0x8402 #define GL_FRAGMENT_COLOR_MATERIAL_PARAMETER_SGIX 0x8403 #define GL_MAX_FRAGMENT_LIGHTS_SGIX 0x8404 #define GL_MAX_ACTIVE_LIGHTS_SGIX 0x8405 #define GL_CURRENT_RASTER_NORMAL_SGIX 0x8406 #define GL_LIGHT_ENV_MODE_SGIX 0x8407 #define GL_FRAGMENT_LIGHT_MODEL_LOCAL_VIEWER_SGIX 0x8408 #define GL_FRAGMENT_LIGHT_MODEL_TWO_SIDE_SGIX 0x8409 #define GL_FRAGMENT_LIGHT_MODEL_AMBIENT_SGIX 0x840A #define GL_FRAGMENT_LIGHT_MODEL_NORMAL_INTERPOLATION_SGIX 0x840B #define GL_FRAGMENT_LIGHT0_SGIX 0x840C #define GL_FRAGMENT_LIGHT1_SGIX 0x840D #define GL_FRAGMENT_LIGHT2_SGIX 0x840E #define GL_FRAGMENT_LIGHT3_SGIX 0x840F #define GL_FRAGMENT_LIGHT4_SGIX 0x8410 #define GL_FRAGMENT_LIGHT5_SGIX 0x8411 #define GL_FRAGMENT_LIGHT6_SGIX 0x8412 #define GL_FRAGMENT_LIGHT7_SGIX 0x8413 #endif #ifndef GL_IBM_rasterpos_clip #define GL_RASTER_POSITION_UNCLIPPED_IBM 0x19262 #endif #ifndef GL_HP_texture_lighting #define GL_TEXTURE_LIGHTING_MODE_HP 0x8167 #define GL_TEXTURE_POST_SPECULAR_HP 0x8168 #define GL_TEXTURE_PRE_SPECULAR_HP 0x8169 #endif #ifndef GL_EXT_draw_range_elements #define GL_MAX_ELEMENTS_VERTICES_EXT 0x80E8 #define GL_MAX_ELEMENTS_INDICES_EXT 0x80E9 #endif #ifndef GL_WIN_phong_shading #define GL_PHONG_WIN 0x80EA #define GL_PHONG_HINT_WIN 0x80EB #endif #ifndef GL_WIN_specular_fog #define GL_FOG_SPECULAR_TEXTURE_WIN 0x80EC #endif #ifndef GL_EXT_light_texture #define GL_FRAGMENT_MATERIAL_EXT 0x8349 #define GL_FRAGMENT_NORMAL_EXT 0x834A #define GL_FRAGMENT_COLOR_EXT 0x834C #define GL_ATTENUATION_EXT 0x834D #define GL_SHADOW_ATTENUATION_EXT 0x834E #define GL_TEXTURE_APPLICATION_MODE_EXT 0x834F #define GL_TEXTURE_LIGHT_EXT 0x8350 #define GL_TEXTURE_MATERIAL_FACE_EXT 0x8351 #define GL_TEXTURE_MATERIAL_PARAMETER_EXT 0x8352 /* reuse GL_FRAGMENT_DEPTH_EXT */ #endif #ifndef GL_SGIX_blend_alpha_minmax #define GL_ALPHA_MIN_SGIX 0x8320 #define GL_ALPHA_MAX_SGIX 0x8321 #endif #ifndef GL_SGIX_impact_pixel_texture #define GL_PIXEL_TEX_GEN_Q_CEILING_SGIX 0x8184 #define GL_PIXEL_TEX_GEN_Q_ROUND_SGIX 0x8185 #define GL_PIXEL_TEX_GEN_Q_FLOOR_SGIX 0x8186 #define GL_PIXEL_TEX_GEN_ALPHA_REPLACE_SGIX 0x8187 #define GL_PIXEL_TEX_GEN_ALPHA_NO_REPLACE_SGIX 0x8188 #define GL_PIXEL_TEX_GEN_ALPHA_LS_SGIX 0x8189 #define GL_PIXEL_TEX_GEN_ALPHA_MS_SGIX 0x818A #endif #ifndef GL_EXT_bgra #define GL_BGR_EXT 0x80E0 #define GL_BGRA_EXT 0x80E1 #endif #ifndef GL_SGIX_async #define GL_ASYNC_MARKER_SGIX 0x8329 #endif #ifndef GL_SGIX_async_pixel #define GL_ASYNC_TEX_IMAGE_SGIX 0x835C #define GL_ASYNC_DRAW_PIXELS_SGIX 0x835D #define GL_ASYNC_READ_PIXELS_SGIX 0x835E #define GL_MAX_ASYNC_TEX_IMAGE_SGIX 0x835F #define GL_MAX_ASYNC_DRAW_PIXELS_SGIX 0x8360 #define GL_MAX_ASYNC_READ_PIXELS_SGIX 0x8361 #endif #ifndef GL_SGIX_async_histogram #define GL_ASYNC_HISTOGRAM_SGIX 0x832C #define GL_MAX_ASYNC_HISTOGRAM_SGIX 0x832D #endif #ifndef GL_INTEL_texture_scissor #endif #ifndef GL_INTEL_parallel_arrays #define GL_PARALLEL_ARRAYS_INTEL 0x83F4 #define GL_VERTEX_ARRAY_PARALLEL_POINTERS_INTEL 0x83F5 #define GL_NORMAL_ARRAY_PARALLEL_POINTERS_INTEL 0x83F6 #define GL_COLOR_ARRAY_PARALLEL_POINTERS_INTEL 0x83F7 #define GL_TEXTURE_COORD_ARRAY_PARALLEL_POINTERS_INTEL 0x83F8 #endif #ifndef GL_HP_occlusion_test #define GL_OCCLUSION_TEST_HP 0x8165 #define GL_OCCLUSION_TEST_RESULT_HP 0x8166 #endif #ifndef GL_EXT_pixel_transform #define GL_PIXEL_TRANSFORM_2D_EXT 0x8330 #define GL_PIXEL_MAG_FILTER_EXT 0x8331 #define GL_PIXEL_MIN_FILTER_EXT 0x8332 #define GL_PIXEL_CUBIC_WEIGHT_EXT 0x8333 #define GL_CUBIC_EXT 0x8334 #define GL_AVERAGE_EXT 0x8335 #define GL_PIXEL_TRANSFORM_2D_STACK_DEPTH_EXT 0x8336 #define GL_MAX_PIXEL_TRANSFORM_2D_STACK_DEPTH_EXT 0x8337 #define GL_PIXEL_TRANSFORM_2D_MATRIX_EXT 0x8338 #endif #ifndef GL_EXT_pixel_transform_color_table #endif #ifndef GL_EXT_shared_texture_palette #define GL_SHARED_TEXTURE_PALETTE_EXT 0x81FB #endif #ifndef GL_EXT_separate_specular_color #define GL_LIGHT_MODEL_COLOR_CONTROL_EXT 0x81F8 #define GL_SINGLE_COLOR_EXT 0x81F9 #define GL_SEPARATE_SPECULAR_COLOR_EXT 0x81FA #endif #ifndef GL_EXT_secondary_color #define GL_COLOR_SUM_EXT 0x8458 #define GL_CURRENT_SECONDARY_COLOR_EXT 0x8459 #define GL_SECONDARY_COLOR_ARRAY_SIZE_EXT 0x845A #define GL_SECONDARY_COLOR_ARRAY_TYPE_EXT 0x845B #define GL_SECONDARY_COLOR_ARRAY_STRIDE_EXT 0x845C #define GL_SECONDARY_COLOR_ARRAY_POINTER_EXT 0x845D #define GL_SECONDARY_COLOR_ARRAY_EXT 0x845E #endif #ifndef GL_EXT_texture_perturb_normal #define GL_PERTURB_EXT 0x85AE #define GL_TEXTURE_NORMAL_EXT 0x85AF #endif #ifndef GL_EXT_multi_draw_arrays #endif #ifndef GL_EXT_fog_coord #define GL_FOG_COORDINATE_SOURCE_EXT 0x8450 #define GL_FOG_COORDINATE_EXT 0x8451 #define GL_FRAGMENT_DEPTH_EXT 0x8452 #define GL_CURRENT_FOG_COORDINATE_EXT 0x8453 #define GL_FOG_COORDINATE_ARRAY_TYPE_EXT 0x8454 #define GL_FOG_COORDINATE_ARRAY_STRIDE_EXT 0x8455 #define GL_FOG_COORDINATE_ARRAY_POINTER_EXT 0x8456 #define GL_FOG_COORDINATE_ARRAY_EXT 0x8457 #endif #ifndef GL_REND_screen_coordinates #define GL_SCREEN_COORDINATES_REND 0x8490 #define GL_INVERTED_SCREEN_W_REND 0x8491 #endif #ifndef GL_EXT_coordinate_frame #define GL_TANGENT_ARRAY_EXT 0x8439 #define GL_BINORMAL_ARRAY_EXT 0x843A #define GL_CURRENT_TANGENT_EXT 0x843B #define GL_CURRENT_BINORMAL_EXT 0x843C #define GL_TANGENT_ARRAY_TYPE_EXT 0x843E #define GL_TANGENT_ARRAY_STRIDE_EXT 0x843F #define GL_BINORMAL_ARRAY_TYPE_EXT 0x8440 #define GL_BINORMAL_ARRAY_STRIDE_EXT 0x8441 #define GL_TANGENT_ARRAY_POINTER_EXT 0x8442 #define GL_BINORMAL_ARRAY_POINTER_EXT 0x8443 #define GL_MAP1_TANGENT_EXT 0x8444 #define GL_MAP2_TANGENT_EXT 0x8445 #define GL_MAP1_BINORMAL_EXT 0x8446 #define GL_MAP2_BINORMAL_EXT 0x8447 #endif #ifndef GL_EXT_texture_env_combine #define GL_COMBINE_EXT 0x8570 #define GL_COMBINE_RGB_EXT 0x8571 #define GL_COMBINE_ALPHA_EXT 0x8572 #define GL_RGB_SCALE_EXT 0x8573 #define GL_ADD_SIGNED_EXT 0x8574 #define GL_INTERPOLATE_EXT 0x8575 #define GL_CONSTANT_EXT 0x8576 #define GL_PRIMARY_COLOR_EXT 0x8577 #define GL_PREVIOUS_EXT 0x8578 #define GL_SOURCE0_RGB_EXT 0x8580 #define GL_SOURCE1_RGB_EXT 0x8581 #define GL_SOURCE2_RGB_EXT 0x8582 #define GL_SOURCE0_ALPHA_EXT 0x8588 #define GL_SOURCE1_ALPHA_EXT 0x8589 #define GL_SOURCE2_ALPHA_EXT 0x858A #define GL_OPERAND0_RGB_EXT 0x8590 #define GL_OPERAND1_RGB_EXT 0x8591 #define GL_OPERAND2_RGB_EXT 0x8592 #define GL_OPERAND0_ALPHA_EXT 0x8598 #define GL_OPERAND1_ALPHA_EXT 0x8599 #define GL_OPERAND2_ALPHA_EXT 0x859A #endif #ifndef GL_APPLE_specular_vector #define GL_LIGHT_MODEL_SPECULAR_VECTOR_APPLE 0x85B0 #endif #ifndef GL_APPLE_transform_hint #define GL_TRANSFORM_HINT_APPLE 0x85B1 #endif #ifndef GL_SGIX_fog_scale #define GL_FOG_SCALE_SGIX 0x81FC #define GL_FOG_SCALE_VALUE_SGIX 0x81FD #endif #ifndef GL_SUNX_constant_data #define GL_UNPACK_CONSTANT_DATA_SUNX 0x81D5 #define GL_TEXTURE_CONSTANT_DATA_SUNX 0x81D6 #endif #ifndef GL_SUN_global_alpha #define GL_GLOBAL_ALPHA_SUN 0x81D9 #define GL_GLOBAL_ALPHA_FACTOR_SUN 0x81DA #endif #ifndef GL_SUN_triangle_list #define GL_RESTART_SUN 0x0001 #define GL_REPLACE_MIDDLE_SUN 0x0002 #define GL_REPLACE_OLDEST_SUN 0x0003 #define GL_TRIANGLE_LIST_SUN 0x81D7 #define GL_REPLACEMENT_CODE_SUN 0x81D8 #define GL_REPLACEMENT_CODE_ARRAY_SUN 0x85C0 #define GL_REPLACEMENT_CODE_ARRAY_TYPE_SUN 0x85C1 #define GL_REPLACEMENT_CODE_ARRAY_STRIDE_SUN 0x85C2 #define GL_REPLACEMENT_CODE_ARRAY_POINTER_SUN 0x85C3 #define GL_R1UI_V3F_SUN 0x85C4 #define GL_R1UI_C4UB_V3F_SUN 0x85C5 #define GL_R1UI_C3F_V3F_SUN 0x85C6 #define GL_R1UI_N3F_V3F_SUN 0x85C7 #define GL_R1UI_C4F_N3F_V3F_SUN 0x85C8 #define GL_R1UI_T2F_V3F_SUN 0x85C9 #define GL_R1UI_T2F_N3F_V3F_SUN 0x85CA #define GL_R1UI_T2F_C4F_N3F_V3F_SUN 0x85CB #endif #ifndef GL_SUN_vertex #endif #ifndef GL_EXT_blend_func_separate #define GL_BLEND_DST_RGB_EXT 0x80C8 #define GL_BLEND_SRC_RGB_EXT 0x80C9 #define GL_BLEND_DST_ALPHA_EXT 0x80CA #define GL_BLEND_SRC_ALPHA_EXT 0x80CB #endif #ifndef GL_INGR_color_clamp #define GL_RED_MIN_CLAMP_INGR 0x8560 #define GL_GREEN_MIN_CLAMP_INGR 0x8561 #define GL_BLUE_MIN_CLAMP_INGR 0x8562 #define GL_ALPHA_MIN_CLAMP_INGR 0x8563 #define GL_RED_MAX_CLAMP_INGR 0x8564 #define GL_GREEN_MAX_CLAMP_INGR 0x8565 #define GL_BLUE_MAX_CLAMP_INGR 0x8566 #define GL_ALPHA_MAX_CLAMP_INGR 0x8567 #endif #ifndef GL_INGR_interlace_read #define GL_INTERLACE_READ_INGR 0x8568 #endif #ifndef GL_EXT_stencil_wrap #define GL_INCR_WRAP_EXT 0x8507 #define GL_DECR_WRAP_EXT 0x8508 #endif #ifndef GL_EXT_422_pixels #define GL_422_EXT 0x80CC #define GL_422_REV_EXT 0x80CD #define GL_422_AVERAGE_EXT 0x80CE #define GL_422_REV_AVERAGE_EXT 0x80CF #endif #ifndef GL_NV_texgen_reflection #define GL_NORMAL_MAP_NV 0x8511 #define GL_REFLECTION_MAP_NV 0x8512 #endif #ifndef GL_EXT_texture_cube_map #define GL_NORMAL_MAP_EXT 0x8511 #define GL_REFLECTION_MAP_EXT 0x8512 #define GL_TEXTURE_CUBE_MAP_EXT 0x8513 #define GL_TEXTURE_BINDING_CUBE_MAP_EXT 0x8514 #define GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT 0x8515 #define GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT 0x8516 #define GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT 0x8517 #define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT 0x8518 #define GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT 0x8519 #define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT 0x851A #define GL_PROXY_TEXTURE_CUBE_MAP_EXT 0x851B #define GL_MAX_CUBE_MAP_TEXTURE_SIZE_EXT 0x851C #endif #ifndef GL_SUN_convolution_border_modes #define GL_WRAP_BORDER_SUN 0x81D4 #endif #ifndef GL_EXT_texture_env_add #endif #ifndef GL_EXT_texture_lod_bias #define GL_MAX_TEXTURE_LOD_BIAS_EXT 0x84FD #define GL_TEXTURE_FILTER_CONTROL_EXT 0x8500 #define GL_TEXTURE_LOD_BIAS_EXT 0x8501 #endif #ifndef GL_EXT_texture_filter_anisotropic #define GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE #define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF #endif #ifndef GL_EXT_vertex_weighting #define GL_MODELVIEW0_STACK_DEPTH_EXT GL_MODELVIEW_STACK_DEPTH #define GL_MODELVIEW1_STACK_DEPTH_EXT 0x8502 #define GL_MODELVIEW0_MATRIX_EXT GL_MODELVIEW_MATRIX #define GL_MODELVIEW1_MATRIX_EXT 0x8506 #define GL_VERTEX_WEIGHTING_EXT 0x8509 #define GL_MODELVIEW0_EXT GL_MODELVIEW #define GL_MODELVIEW1_EXT 0x850A #define GL_CURRENT_VERTEX_WEIGHT_EXT 0x850B #define GL_VERTEX_WEIGHT_ARRAY_EXT 0x850C #define GL_VERTEX_WEIGHT_ARRAY_SIZE_EXT 0x850D #define GL_VERTEX_WEIGHT_ARRAY_TYPE_EXT 0x850E #define GL_VERTEX_WEIGHT_ARRAY_STRIDE_EXT 0x850F #define GL_VERTEX_WEIGHT_ARRAY_POINTER_EXT 0x8510 #endif #ifndef GL_NV_light_max_exponent #define GL_MAX_SHININESS_NV 0x8504 #define GL_MAX_SPOT_EXPONENT_NV 0x8505 #endif #ifndef GL_NV_vertex_array_range #define GL_VERTEX_ARRAY_RANGE_NV 0x851D #define GL_VERTEX_ARRAY_RANGE_LENGTH_NV 0x851E #define GL_VERTEX_ARRAY_RANGE_VALID_NV 0x851F #define GL_MAX_VERTEX_ARRAY_RANGE_ELEMENT_NV 0x8520 #define GL_VERTEX_ARRAY_RANGE_POINTER_NV 0x8521 #endif #ifndef GL_NV_register_combiners #define GL_REGISTER_COMBINERS_NV 0x8522 #define GL_VARIABLE_A_NV 0x8523 #define GL_VARIABLE_B_NV 0x8524 #define GL_VARIABLE_C_NV 0x8525 #define GL_VARIABLE_D_NV 0x8526 #define GL_VARIABLE_E_NV 0x8527 #define GL_VARIABLE_F_NV 0x8528 #define GL_VARIABLE_G_NV 0x8529 #define GL_CONSTANT_COLOR0_NV 0x852A #define GL_CONSTANT_COLOR1_NV 0x852B #define GL_PRIMARY_COLOR_NV 0x852C #define GL_SECONDARY_COLOR_NV 0x852D #define GL_SPARE0_NV 0x852E #define GL_SPARE1_NV 0x852F #define GL_DISCARD_NV 0x8530 #define GL_E_TIMES_F_NV 0x8531 #define GL_SPARE0_PLUS_SECONDARY_COLOR_NV 0x8532 #define GL_UNSIGNED_IDENTITY_NV 0x8536 #define GL_UNSIGNED_INVERT_NV 0x8537 #define GL_EXPAND_NORMAL_NV 0x8538 #define GL_EXPAND_NEGATE_NV 0x8539 #define GL_HALF_BIAS_NORMAL_NV 0x853A #define GL_HALF_BIAS_NEGATE_NV 0x853B #define GL_SIGNED_IDENTITY_NV 0x853C #define GL_SIGNED_NEGATE_NV 0x853D #define GL_SCALE_BY_TWO_NV 0x853E #define GL_SCALE_BY_FOUR_NV 0x853F #define GL_SCALE_BY_ONE_HALF_NV 0x8540 #define GL_BIAS_BY_NEGATIVE_ONE_HALF_NV 0x8541 #define GL_COMBINER_INPUT_NV 0x8542 #define GL_COMBINER_MAPPING_NV 0x8543 #define GL_COMBINER_COMPONENT_USAGE_NV 0x8544 #define GL_COMBINER_AB_DOT_PRODUCT_NV 0x8545 #define GL_COMBINER_CD_DOT_PRODUCT_NV 0x8546 #define GL_COMBINER_MUX_SUM_NV 0x8547 #define GL_COMBINER_SCALE_NV 0x8548 #define GL_COMBINER_BIAS_NV 0x8549 #define GL_COMBINER_AB_OUTPUT_NV 0x854A #define GL_COMBINER_CD_OUTPUT_NV 0x854B #define GL_COMBINER_SUM_OUTPUT_NV 0x854C #define GL_MAX_GENERAL_COMBINERS_NV 0x854D #define GL_NUM_GENERAL_COMBINERS_NV 0x854E #define GL_COLOR_SUM_CLAMP_NV 0x854F #define GL_COMBINER0_NV 0x8550 #define GL_COMBINER1_NV 0x8551 #define GL_COMBINER2_NV 0x8552 #define GL_COMBINER3_NV 0x8553 #define GL_COMBINER4_NV 0x8554 #define GL_COMBINER5_NV 0x8555 #define GL_COMBINER6_NV 0x8556 #define GL_COMBINER7_NV 0x8557 /* reuse GL_TEXTURE0_ARB */ /* reuse GL_TEXTURE1_ARB */ /* reuse GL_ZERO */ /* reuse GL_NONE */ /* reuse GL_FOG */ #endif #ifndef GL_NV_fog_distance #define GL_FOG_DISTANCE_MODE_NV 0x855A #define GL_EYE_RADIAL_NV 0x855B #define GL_EYE_PLANE_ABSOLUTE_NV 0x855C /* reuse GL_EYE_PLANE */ #endif #ifndef GL_NV_texgen_emboss #define GL_EMBOSS_LIGHT_NV 0x855D #define GL_EMBOSS_CONSTANT_NV 0x855E #define GL_EMBOSS_MAP_NV 0x855F #endif #ifndef GL_NV_blend_square #endif #ifndef GL_NV_texture_env_combine4 #define GL_COMBINE4_NV 0x8503 #define GL_SOURCE3_RGB_NV 0x8583 #define GL_SOURCE3_ALPHA_NV 0x858B #define GL_OPERAND3_RGB_NV 0x8593 #define GL_OPERAND3_ALPHA_NV 0x859B #endif #ifndef GL_MESA_resize_buffers #endif #ifndef GL_MESA_window_pos #endif #ifndef GL_EXT_texture_compression_s3tc #define GL_COMPRESSED_RGB_S3TC_DXT1_EXT 0x83F0 #define GL_COMPRESSED_RGBA_S3TC_DXT1_EXT 0x83F1 #define GL_COMPRESSED_RGBA_S3TC_DXT3_EXT 0x83F2 #define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT 0x83F3 #endif #ifndef GL_IBM_cull_vertex #define GL_CULL_VERTEX_IBM 103050 #endif #ifndef GL_IBM_multimode_draw_arrays #endif #ifndef GL_IBM_vertex_array_lists #define GL_VERTEX_ARRAY_LIST_IBM 103070 #define GL_NORMAL_ARRAY_LIST_IBM 103071 #define GL_COLOR_ARRAY_LIST_IBM 103072 #define GL_INDEX_ARRAY_LIST_IBM 103073 #define GL_TEXTURE_COORD_ARRAY_LIST_IBM 103074 #define GL_EDGE_FLAG_ARRAY_LIST_IBM 103075 #define GL_FOG_COORDINATE_ARRAY_LIST_IBM 103076 #define GL_SECONDARY_COLOR_ARRAY_LIST_IBM 103077 #define GL_VERTEX_ARRAY_LIST_STRIDE_IBM 103080 #define GL_NORMAL_ARRAY_LIST_STRIDE_IBM 103081 #define GL_COLOR_ARRAY_LIST_STRIDE_IBM 103082 #define GL_INDEX_ARRAY_LIST_STRIDE_IBM 103083 #define GL_TEXTURE_COORD_ARRAY_LIST_STRIDE_IBM 103084 #define GL_EDGE_FLAG_ARRAY_LIST_STRIDE_IBM 103085 #define GL_FOG_COORDINATE_ARRAY_LIST_STRIDE_IBM 103086 #define GL_SECONDARY_COLOR_ARRAY_LIST_STRIDE_IBM 103087 #endif #ifndef GL_SGIX_subsample #define GL_PACK_SUBSAMPLE_RATE_SGIX 0x85A0 #define GL_UNPACK_SUBSAMPLE_RATE_SGIX 0x85A1 #define GL_PIXEL_SUBSAMPLE_4444_SGIX 0x85A2 #define GL_PIXEL_SUBSAMPLE_2424_SGIX 0x85A3 #define GL_PIXEL_SUBSAMPLE_4242_SGIX 0x85A4 #endif #ifndef GL_SGIX_ycrcb_subsample #endif #ifndef GL_SGIX_ycrcba #define GL_YCRCB_SGIX 0x8318 #define GL_YCRCBA_SGIX 0x8319 #endif #ifndef GL_SGI_depth_pass_instrument #define GL_DEPTH_PASS_INSTRUMENT_SGIX 0x8310 #define GL_DEPTH_PASS_INSTRUMENT_COUNTERS_SGIX 0x8311 #define GL_DEPTH_PASS_INSTRUMENT_MAX_SGIX 0x8312 #endif #ifndef GL_3DFX_texture_compression_FXT1 #define GL_COMPRESSED_RGB_FXT1_3DFX 0x86B0 #define GL_COMPRESSED_RGBA_FXT1_3DFX 0x86B1 #endif #ifndef GL_3DFX_multisample #define GL_MULTISAMPLE_3DFX 0x86B2 #define GL_SAMPLE_BUFFERS_3DFX 0x86B3 #define GL_SAMPLES_3DFX 0x86B4 #define GL_MULTISAMPLE_BIT_3DFX 0x20000000 #endif #ifndef GL_3DFX_tbuffer #endif #ifndef GL_EXT_multisample #define GL_MULTISAMPLE_EXT 0x809D #define GL_SAMPLE_ALPHA_TO_MASK_EXT 0x809E #define GL_SAMPLE_ALPHA_TO_ONE_EXT 0x809F #define GL_SAMPLE_MASK_EXT 0x80A0 #define GL_1PASS_EXT 0x80A1 #define GL_2PASS_0_EXT 0x80A2 #define GL_2PASS_1_EXT 0x80A3 #define GL_4PASS_0_EXT 0x80A4 #define GL_4PASS_1_EXT 0x80A5 #define GL_4PASS_2_EXT 0x80A6 #define GL_4PASS_3_EXT 0x80A7 #define GL_SAMPLE_BUFFERS_EXT 0x80A8 #define GL_SAMPLES_EXT 0x80A9 #define GL_SAMPLE_MASK_VALUE_EXT 0x80AA #define GL_SAMPLE_MASK_INVERT_EXT 0x80AB #define GL_SAMPLE_PATTERN_EXT 0x80AC #define GL_MULTISAMPLE_BIT_EXT 0x20000000 #endif #ifndef GL_SGIX_vertex_preclip #define GL_VERTEX_PRECLIP_SGIX 0x83EE #define GL_VERTEX_PRECLIP_HINT_SGIX 0x83EF #endif #ifndef GL_SGIX_convolution_accuracy #define GL_CONVOLUTION_HINT_SGIX 0x8316 #endif #ifndef GL_SGIX_resample #define GL_PACK_RESAMPLE_SGIX 0x842C #define GL_UNPACK_RESAMPLE_SGIX 0x842D #define GL_RESAMPLE_REPLICATE_SGIX 0x842E #define GL_RESAMPLE_ZERO_FILL_SGIX 0x842F #define GL_RESAMPLE_DECIMATE_SGIX 0x8430 #endif #ifndef GL_SGIS_point_line_texgen #define GL_EYE_DISTANCE_TO_POINT_SGIS 0x81F0 #define GL_OBJECT_DISTANCE_TO_POINT_SGIS 0x81F1 #define GL_EYE_DISTANCE_TO_LINE_SGIS 0x81F2 #define GL_OBJECT_DISTANCE_TO_LINE_SGIS 0x81F3 #define GL_EYE_POINT_SGIS 0x81F4 #define GL_OBJECT_POINT_SGIS 0x81F5 #define GL_EYE_LINE_SGIS 0x81F6 #define GL_OBJECT_LINE_SGIS 0x81F7 #endif #ifndef GL_SGIS_texture_color_mask #define GL_TEXTURE_COLOR_WRITEMASK_SGIS 0x81EF #endif #ifndef GL_EXT_texture_env_dot3 #define GL_DOT3_RGB_EXT 0x8740 #define GL_DOT3_RGBA_EXT 0x8741 #endif #ifndef GL_ATI_texture_mirror_once #define GL_MIRROR_CLAMP_ATI 0x8742 #define GL_MIRROR_CLAMP_TO_EDGE_ATI 0x8743 #endif #ifndef GL_NV_fence #define GL_ALL_COMPLETED_NV 0x84F2 #define GL_FENCE_STATUS_NV 0x84F3 #define GL_FENCE_CONDITION_NV 0x84F4 #endif #ifndef GL_IBM_texture_mirrored_repeat #define GL_MIRRORED_REPEAT_IBM 0x8370 #endif #ifndef GL_NV_evaluators #define GL_EVAL_2D_NV 0x86C0 #define GL_EVAL_TRIANGULAR_2D_NV 0x86C1 #define GL_MAP_TESSELLATION_NV 0x86C2 #define GL_MAP_ATTRIB_U_ORDER_NV 0x86C3 #define GL_MAP_ATTRIB_V_ORDER_NV 0x86C4 #define GL_EVAL_FRACTIONAL_TESSELLATION_NV 0x86C5 #define GL_EVAL_VERTEX_ATTRIB0_NV 0x86C6 #define GL_EVAL_VERTEX_ATTRIB1_NV 0x86C7 #define GL_EVAL_VERTEX_ATTRIB2_NV 0x86C8 #define GL_EVAL_VERTEX_ATTRIB3_NV 0x86C9 #define GL_EVAL_VERTEX_ATTRIB4_NV 0x86CA #define GL_EVAL_VERTEX_ATTRIB5_NV 0x86CB #define GL_EVAL_VERTEX_ATTRIB6_NV 0x86CC #define GL_EVAL_VERTEX_ATTRIB7_NV 0x86CD #define GL_EVAL_VERTEX_ATTRIB8_NV 0x86CE #define GL_EVAL_VERTEX_ATTRIB9_NV 0x86CF #define GL_EVAL_VERTEX_ATTRIB10_NV 0x86D0 #define GL_EVAL_VERTEX_ATTRIB11_NV 0x86D1 #define GL_EVAL_VERTEX_ATTRIB12_NV 0x86D2 #define GL_EVAL_VERTEX_ATTRIB13_NV 0x86D3 #define GL_EVAL_VERTEX_ATTRIB14_NV 0x86D4 #define GL_EVAL_VERTEX_ATTRIB15_NV 0x86D5 #define GL_MAX_MAP_TESSELLATION_NV 0x86D6 #define GL_MAX_RATIONAL_EVAL_ORDER_NV 0x86D7 #endif #ifndef GL_NV_packed_depth_stencil #define GL_DEPTH_STENCIL_NV 0x84F9 #define GL_UNSIGNED_INT_24_8_NV 0x84FA #endif #ifndef GL_NV_register_combiners2 #define GL_PER_STAGE_CONSTANTS_NV 0x8535 #endif #ifndef GL_NV_texture_compression_vtc #endif #ifndef GL_NV_texture_rectangle #define GL_TEXTURE_RECTANGLE_NV 0x84F5 #define GL_TEXTURE_BINDING_RECTANGLE_NV 0x84F6 #define GL_PROXY_TEXTURE_RECTANGLE_NV 0x84F7 #define GL_MAX_RECTANGLE_TEXTURE_SIZE_NV 0x84F8 #endif #ifndef GL_NV_texture_shader #define GL_OFFSET_TEXTURE_RECTANGLE_NV 0x864C #define GL_OFFSET_TEXTURE_RECTANGLE_SCALE_NV 0x864D #define GL_DOT_PRODUCT_TEXTURE_RECTANGLE_NV 0x864E #define GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV 0x86D9 #define GL_UNSIGNED_INT_S8_S8_8_8_NV 0x86DA #define GL_UNSIGNED_INT_8_8_S8_S8_REV_NV 0x86DB #define GL_DSDT_MAG_INTENSITY_NV 0x86DC #define GL_SHADER_CONSISTENT_NV 0x86DD #define GL_TEXTURE_SHADER_NV 0x86DE #define GL_SHADER_OPERATION_NV 0x86DF #define GL_CULL_MODES_NV 0x86E0 #define GL_OFFSET_TEXTURE_MATRIX_NV 0x86E1 #define GL_OFFSET_TEXTURE_SCALE_NV 0x86E2 #define GL_OFFSET_TEXTURE_BIAS_NV 0x86E3 #define GL_OFFSET_TEXTURE_2D_MATRIX_NV GL_OFFSET_TEXTURE_MATRIX_NV #define GL_OFFSET_TEXTURE_2D_SCALE_NV GL_OFFSET_TEXTURE_SCALE_NV #define GL_OFFSET_TEXTURE_2D_BIAS_NV GL_OFFSET_TEXTURE_BIAS_NV #define GL_PREVIOUS_TEXTURE_INPUT_NV 0x86E4 #define GL_CONST_EYE_NV 0x86E5 #define GL_PASS_THROUGH_NV 0x86E6 #define GL_CULL_FRAGMENT_NV 0x86E7 #define GL_OFFSET_TEXTURE_2D_NV 0x86E8 #define GL_DEPENDENT_AR_TEXTURE_2D_NV 0x86E9 #define GL_DEPENDENT_GB_TEXTURE_2D_NV 0x86EA #define GL_DOT_PRODUCT_NV 0x86EC #define GL_DOT_PRODUCT_DEPTH_REPLACE_NV 0x86ED #define GL_DOT_PRODUCT_TEXTURE_2D_NV 0x86EE #define GL_DOT_PRODUCT_TEXTURE_CUBE_MAP_NV 0x86F0 #define GL_DOT_PRODUCT_DIFFUSE_CUBE_MAP_NV 0x86F1 #define GL_DOT_PRODUCT_REFLECT_CUBE_MAP_NV 0x86F2 #define GL_DOT_PRODUCT_CONST_EYE_REFLECT_CUBE_MAP_NV 0x86F3 #define GL_HILO_NV 0x86F4 #define GL_DSDT_NV 0x86F5 #define GL_DSDT_MAG_NV 0x86F6 #define GL_DSDT_MAG_VIB_NV 0x86F7 #define GL_HILO16_NV 0x86F8 #define GL_SIGNED_HILO_NV 0x86F9 #define GL_SIGNED_HILO16_NV 0x86FA #define GL_SIGNED_RGBA_NV 0x86FB #define GL_SIGNED_RGBA8_NV 0x86FC #define GL_SIGNED_RGB_NV 0x86FE #define GL_SIGNED_RGB8_NV 0x86FF #define GL_SIGNED_LUMINANCE_NV 0x8701 #define GL_SIGNED_LUMINANCE8_NV 0x8702 #define GL_SIGNED_LUMINANCE_ALPHA_NV 0x8703 #define GL_SIGNED_LUMINANCE8_ALPHA8_NV 0x8704 #define GL_SIGNED_ALPHA_NV 0x8705 #define GL_SIGNED_ALPHA8_NV 0x8706 #define GL_SIGNED_INTENSITY_NV 0x8707 #define GL_SIGNED_INTENSITY8_NV 0x8708 #define GL_DSDT8_NV 0x8709 #define GL_DSDT8_MAG8_NV 0x870A #define GL_DSDT8_MAG8_INTENSITY8_NV 0x870B #define GL_SIGNED_RGB_UNSIGNED_ALPHA_NV 0x870C #define GL_SIGNED_RGB8_UNSIGNED_ALPHA8_NV 0x870D #define GL_HI_SCALE_NV 0x870E #define GL_LO_SCALE_NV 0x870F #define GL_DS_SCALE_NV 0x8710 #define GL_DT_SCALE_NV 0x8711 #define GL_MAGNITUDE_SCALE_NV 0x8712 #define GL_VIBRANCE_SCALE_NV 0x8713 #define GL_HI_BIAS_NV 0x8714 #define GL_LO_BIAS_NV 0x8715 #define GL_DS_BIAS_NV 0x8716 #define GL_DT_BIAS_NV 0x8717 #define GL_MAGNITUDE_BIAS_NV 0x8718 #define GL_VIBRANCE_BIAS_NV 0x8719 #define GL_TEXTURE_BORDER_VALUES_NV 0x871A #define GL_TEXTURE_HI_SIZE_NV 0x871B #define GL_TEXTURE_LO_SIZE_NV 0x871C #define GL_TEXTURE_DS_SIZE_NV 0x871D #define GL_TEXTURE_DT_SIZE_NV 0x871E #define GL_TEXTURE_MAG_SIZE_NV 0x871F #endif #ifndef GL_NV_texture_shader2 #define GL_DOT_PRODUCT_TEXTURE_3D_NV 0x86EF #endif #ifndef GL_NV_vertex_array_range2 #define GL_VERTEX_ARRAY_RANGE_WITHOUT_FLUSH_NV 0x8533 #endif #ifndef GL_NV_vertex_program #define GL_VERTEX_PROGRAM_NV 0x8620 #define GL_VERTEX_STATE_PROGRAM_NV 0x8621 #define GL_ATTRIB_ARRAY_SIZE_NV 0x8623 #define GL_ATTRIB_ARRAY_STRIDE_NV 0x8624 #define GL_ATTRIB_ARRAY_TYPE_NV 0x8625 #define GL_CURRENT_ATTRIB_NV 0x8626 #define GL_PROGRAM_LENGTH_NV 0x8627 #define GL_PROGRAM_STRING_NV 0x8628 #define GL_MODELVIEW_PROJECTION_NV 0x8629 #define GL_IDENTITY_NV 0x862A #define GL_INVERSE_NV 0x862B #define GL_TRANSPOSE_NV 0x862C #define GL_INVERSE_TRANSPOSE_NV 0x862D #define GL_MAX_TRACK_MATRIX_STACK_DEPTH_NV 0x862E #define GL_MAX_TRACK_MATRICES_NV 0x862F #define GL_MATRIX0_NV 0x8630 #define GL_MATRIX1_NV 0x8631 #define GL_MATRIX2_NV 0x8632 #define GL_MATRIX3_NV 0x8633 #define GL_MATRIX4_NV 0x8634 #define GL_MATRIX5_NV 0x8635 #define GL_MATRIX6_NV 0x8636 #define GL_MATRIX7_NV 0x8637 #define GL_CURRENT_MATRIX_STACK_DEPTH_NV 0x8640 #define GL_CURRENT_MATRIX_NV 0x8641 #define GL_VERTEX_PROGRAM_POINT_SIZE_NV 0x8642 #define GL_VERTEX_PROGRAM_TWO_SIDE_NV 0x8643 #define GL_PROGRAM_PARAMETER_NV 0x8644 #define GL_ATTRIB_ARRAY_POINTER_NV 0x8645 #define GL_PROGRAM_TARGET_NV 0x8646 #define GL_PROGRAM_RESIDENT_NV 0x8647 #define GL_TRACK_MATRIX_NV 0x8648 #define GL_TRACK_MATRIX_TRANSFORM_NV 0x8649 #define GL_VERTEX_PROGRAM_BINDING_NV 0x864A #define GL_PROGRAM_ERROR_POSITION_NV 0x864B #define GL_VERTEX_ATTRIB_ARRAY0_NV 0x8650 #define GL_VERTEX_ATTRIB_ARRAY1_NV 0x8651 #define GL_VERTEX_ATTRIB_ARRAY2_NV 0x8652 #define GL_VERTEX_ATTRIB_ARRAY3_NV 0x8653 #define GL_VERTEX_ATTRIB_ARRAY4_NV 0x8654 #define GL_VERTEX_ATTRIB_ARRAY5_NV 0x8655 #define GL_VERTEX_ATTRIB_ARRAY6_NV 0x8656 #define GL_VERTEX_ATTRIB_ARRAY7_NV 0x8657 #define GL_VERTEX_ATTRIB_ARRAY8_NV 0x8658 #define GL_VERTEX_ATTRIB_ARRAY9_NV 0x8659 #define GL_VERTEX_ATTRIB_ARRAY10_NV 0x865A #define GL_VERTEX_ATTRIB_ARRAY11_NV 0x865B #define GL_VERTEX_ATTRIB_ARRAY12_NV 0x865C #define GL_VERTEX_ATTRIB_ARRAY13_NV 0x865D #define GL_VERTEX_ATTRIB_ARRAY14_NV 0x865E #define GL_VERTEX_ATTRIB_ARRAY15_NV 0x865F #define GL_MAP1_VERTEX_ATTRIB0_4_NV 0x8660 #define GL_MAP1_VERTEX_ATTRIB1_4_NV 0x8661 #define GL_MAP1_VERTEX_ATTRIB2_4_NV 0x8662 #define GL_MAP1_VERTEX_ATTRIB3_4_NV 0x8663 #define GL_MAP1_VERTEX_ATTRIB4_4_NV 0x8664 #define GL_MAP1_VERTEX_ATTRIB5_4_NV 0x8665 #define GL_MAP1_VERTEX_ATTRIB6_4_NV 0x8666 #define GL_MAP1_VERTEX_ATTRIB7_4_NV 0x8667 #define GL_MAP1_VERTEX_ATTRIB8_4_NV 0x8668 #define GL_MAP1_VERTEX_ATTRIB9_4_NV 0x8669 #define GL_MAP1_VERTEX_ATTRIB10_4_NV 0x866A #define GL_MAP1_VERTEX_ATTRIB11_4_NV 0x866B #define GL_MAP1_VERTEX_ATTRIB12_4_NV 0x866C #define GL_MAP1_VERTEX_ATTRIB13_4_NV 0x866D #define GL_MAP1_VERTEX_ATTRIB14_4_NV 0x866E #define GL_MAP1_VERTEX_ATTRIB15_4_NV 0x866F #define GL_MAP2_VERTEX_ATTRIB0_4_NV 0x8670 #define GL_MAP2_VERTEX_ATTRIB1_4_NV 0x8671 #define GL_MAP2_VERTEX_ATTRIB2_4_NV 0x8672 #define GL_MAP2_VERTEX_ATTRIB3_4_NV 0x8673 #define GL_MAP2_VERTEX_ATTRIB4_4_NV 0x8674 #define GL_MAP2_VERTEX_ATTRIB5_4_NV 0x8675 #define GL_MAP2_VERTEX_ATTRIB6_4_NV 0x8676 #define GL_MAP2_VERTEX_ATTRIB7_4_NV 0x8677 #define GL_MAP2_VERTEX_ATTRIB8_4_NV 0x8678 #define GL_MAP2_VERTEX_ATTRIB9_4_NV 0x8679 #define GL_MAP2_VERTEX_ATTRIB10_4_NV 0x867A #define GL_MAP2_VERTEX_ATTRIB11_4_NV 0x867B #define GL_MAP2_VERTEX_ATTRIB12_4_NV 0x867C #define GL_MAP2_VERTEX_ATTRIB13_4_NV 0x867D #define GL_MAP2_VERTEX_ATTRIB14_4_NV 0x867E #define GL_MAP2_VERTEX_ATTRIB15_4_NV 0x867F #endif #ifndef GL_SGIX_texture_coordinate_clamp #define GL_TEXTURE_MAX_CLAMP_S_SGIX 0x8369 #define GL_TEXTURE_MAX_CLAMP_T_SGIX 0x836A #define GL_TEXTURE_MAX_CLAMP_R_SGIX 0x836B #endif #ifndef GL_SGIX_scalebias_hint #define GL_SCALEBIAS_HINT_SGIX 0x8322 #endif #ifndef GL_OML_interlace #define GL_INTERLACE_OML 0x8980 #define GL_INTERLACE_READ_OML 0x8981 #endif #ifndef GL_OML_subsample #define GL_FORMAT_SUBSAMPLE_24_24_OML 0x8982 #define GL_FORMAT_SUBSAMPLE_244_244_OML 0x8983 #endif #ifndef GL_OML_resample #define GL_PACK_RESAMPLE_OML 0x8984 #define GL_UNPACK_RESAMPLE_OML 0x8985 #define GL_RESAMPLE_REPLICATE_OML 0x8986 #define GL_RESAMPLE_ZERO_FILL_OML 0x8987 #define GL_RESAMPLE_AVERAGE_OML 0x8988 #define GL_RESAMPLE_DECIMATE_OML 0x8989 #endif #ifndef GL_NV_copy_depth_to_color #define GL_DEPTH_STENCIL_TO_RGBA_NV 0x886E #define GL_DEPTH_STENCIL_TO_BGRA_NV 0x886F #endif #ifndef GL_ATI_envmap_bumpmap #define GL_BUMP_ROT_MATRIX_ATI 0x8775 #define GL_BUMP_ROT_MATRIX_SIZE_ATI 0x8776 #define GL_BUMP_NUM_TEX_UNITS_ATI 0x8777 #define GL_BUMP_TEX_UNITS_ATI 0x8778 #define GL_DUDV_ATI 0x8779 #define GL_DU8DV8_ATI 0x877A #define GL_BUMP_ENVMAP_ATI 0x877B #define GL_BUMP_TARGET_ATI 0x877C #endif #ifndef GL_ATI_fragment_shader #define GL_FRAGMENT_SHADER_ATI 0x8920 #define GL_REG_0_ATI 0x8921 #define GL_REG_1_ATI 0x8922 #define GL_REG_2_ATI 0x8923 #define GL_REG_3_ATI 0x8924 #define GL_REG_4_ATI 0x8925 #define GL_REG_5_ATI 0x8926 #define GL_REG_6_ATI 0x8927 #define GL_REG_7_ATI 0x8928 #define GL_REG_8_ATI 0x8929 #define GL_REG_9_ATI 0x892A #define GL_REG_10_ATI 0x892B #define GL_REG_11_ATI 0x892C #define GL_REG_12_ATI 0x892D #define GL_REG_13_ATI 0x892E #define GL_REG_14_ATI 0x892F #define GL_REG_15_ATI 0x8930 #define GL_REG_16_ATI 0x8931 #define GL_REG_17_ATI 0x8932 #define GL_REG_18_ATI 0x8933 #define GL_REG_19_ATI 0x8934 #define GL_REG_20_ATI 0x8935 #define GL_REG_21_ATI 0x8936 #define GL_REG_22_ATI 0x8937 #define GL_REG_23_ATI 0x8938 #define GL_REG_24_ATI 0x8939 #define GL_REG_25_ATI 0x893A #define GL_REG_26_ATI 0x893B #define GL_REG_27_ATI 0x893C #define GL_REG_28_ATI 0x893D #define GL_REG_29_ATI 0x893E #define GL_REG_30_ATI 0x893F #define GL_REG_31_ATI 0x8940 #define GL_CON_0_ATI 0x8941 #define GL_CON_1_ATI 0x8942 #define GL_CON_2_ATI 0x8943 #define GL_CON_3_ATI 0x8944 #define GL_CON_4_ATI 0x8945 #define GL_CON_5_ATI 0x8946 #define GL_CON_6_ATI 0x8947 #define GL_CON_7_ATI 0x8948 #define GL_CON_8_ATI 0x8949 #define GL_CON_9_ATI 0x894A #define GL_CON_10_ATI 0x894B #define GL_CON_11_ATI 0x894C #define GL_CON_12_ATI 0x894D #define GL_CON_13_ATI 0x894E #define GL_CON_14_ATI 0x894F #define GL_CON_15_ATI 0x8950 #define GL_CON_16_ATI 0x8951 #define GL_CON_17_ATI 0x8952 #define GL_CON_18_ATI 0x8953 #define GL_CON_19_ATI 0x8954 #define GL_CON_20_ATI 0x8955 #define GL_CON_21_ATI 0x8956 #define GL_CON_22_ATI 0x8957 #define GL_CON_23_ATI 0x8958 #define GL_CON_24_ATI 0x8959 #define GL_CON_25_ATI 0x895A #define GL_CON_26_ATI 0x895B #define GL_CON_27_ATI 0x895C #define GL_CON_28_ATI 0x895D #define GL_CON_29_ATI 0x895E #define GL_CON_30_ATI 0x895F #define GL_CON_31_ATI 0x8960 #define GL_MOV_ATI 0x8961 #define GL_ADD_ATI 0x8963 #define GL_MUL_ATI 0x8964 #define GL_SUB_ATI 0x8965 #define GL_DOT3_ATI 0x8966 #define GL_DOT4_ATI 0x8967 #define GL_MAD_ATI 0x8968 #define GL_LERP_ATI 0x8969 #define GL_CND_ATI 0x896A #define GL_CND0_ATI 0x896B #define GL_DOT2_ADD_ATI 0x896C #define GL_SECONDARY_INTERPOLATOR_ATI 0x896D #define GL_NUM_FRAGMENT_REGISTERS_ATI 0x896E #define GL_NUM_FRAGMENT_CONSTANTS_ATI 0x896F #define GL_NUM_PASSES_ATI 0x8970 #define GL_NUM_INSTRUCTIONS_PER_PASS_ATI 0x8971 #define GL_NUM_INSTRUCTIONS_TOTAL_ATI 0x8972 #define GL_NUM_INPUT_INTERPOLATOR_COMPONENTS_ATI 0x8973 #define GL_NUM_LOOPBACK_COMPONENTS_ATI 0x8974 #define GL_COLOR_ALPHA_PAIRING_ATI 0x8975 #define GL_SWIZZLE_STR_ATI 0x8976 #define GL_SWIZZLE_STQ_ATI 0x8977 #define GL_SWIZZLE_STR_DR_ATI 0x8978 #define GL_SWIZZLE_STQ_DQ_ATI 0x8979 #define GL_SWIZZLE_STRQ_ATI 0x897A #define GL_SWIZZLE_STRQ_DQ_ATI 0x897B #define GL_RED_BIT_ATI 0x00000001 #define GL_GREEN_BIT_ATI 0x00000002 #define GL_BLUE_BIT_ATI 0x00000004 #define GL_2X_BIT_ATI 0x00000001 #define GL_4X_BIT_ATI 0x00000002 #define GL_8X_BIT_ATI 0x00000004 #define GL_HALF_BIT_ATI 0x00000008 #define GL_QUARTER_BIT_ATI 0x00000010 #define GL_EIGHTH_BIT_ATI 0x00000020 #define GL_SATURATE_BIT_ATI 0x00000040 #define GL_COMP_BIT_ATI 0x00000002 #define GL_NEGATE_BIT_ATI 0x00000004 #define GL_BIAS_BIT_ATI 0x00000008 #endif #ifndef GL_ATI_pn_triangles #define GL_PN_TRIANGLES_ATI 0x87F0 #define GL_MAX_PN_TRIANGLES_TESSELATION_LEVEL_ATI 0x87F1 #define GL_PN_TRIANGLES_POINT_MODE_ATI 0x87F2 #define GL_PN_TRIANGLES_NORMAL_MODE_ATI 0x87F3 #define GL_PN_TRIANGLES_TESSELATION_LEVEL_ATI 0x87F4 #define GL_PN_TRIANGLES_POINT_MODE_LINEAR_ATI 0x87F5 #define GL_PN_TRIANGLES_POINT_MODE_CUBIC_ATI 0x87F6 #define GL_PN_TRIANGLES_NORMAL_MODE_LINEAR_ATI 0x87F7 #define GL_PN_TRIANGLES_NORMAL_MODE_QUADRATIC_ATI 0x87F8 #endif #ifndef GL_ATI_vertex_array_object #define GL_STATIC_ATI 0x8760 #define GL_DYNAMIC_ATI 0x8761 #define GL_PRESERVE_ATI 0x8762 #define GL_DISCARD_ATI 0x8763 #define GL_OBJECT_BUFFER_SIZE_ATI 0x8764 #define GL_OBJECT_BUFFER_USAGE_ATI 0x8765 #define GL_ARRAY_OBJECT_BUFFER_ATI 0x8766 #define GL_ARRAY_OBJECT_OFFSET_ATI 0x8767 #endif #ifndef GL_EXT_vertex_shader #define GL_VERTEX_SHADER_EXT 0x8780 #define GL_VERTEX_SHADER_BINDING_EXT 0x8781 #define GL_OP_INDEX_EXT 0x8782 #define GL_OP_NEGATE_EXT 0x8783 #define GL_OP_DOT3_EXT 0x8784 #define GL_OP_DOT4_EXT 0x8785 #define GL_OP_MUL_EXT 0x8786 #define GL_OP_ADD_EXT 0x8787 #define GL_OP_MADD_EXT 0x8788 #define GL_OP_FRAC_EXT 0x8789 #define GL_OP_MAX_EXT 0x878A #define GL_OP_MIN_EXT 0x878B #define GL_OP_SET_GE_EXT 0x878C #define GL_OP_SET_LT_EXT 0x878D #define GL_OP_CLAMP_EXT 0x878E #define GL_OP_FLOOR_EXT 0x878F #define GL_OP_ROUND_EXT 0x8790 #define GL_OP_EXP_BASE_2_EXT 0x8791 #define GL_OP_LOG_BASE_2_EXT 0x8792 #define GL_OP_POWER_EXT 0x8793 #define GL_OP_RECIP_EXT 0x8794 #define GL_OP_RECIP_SQRT_EXT 0x8795 #define GL_OP_SUB_EXT 0x8796 #define GL_OP_CROSS_PRODUCT_EXT 0x8797 #define GL_OP_MULTIPLY_MATRIX_EXT 0x8798 #define GL_OP_MOV_EXT 0x8799 #define GL_OUTPUT_VERTEX_EXT 0x879A #define GL_OUTPUT_COLOR0_EXT 0x879B #define GL_OUTPUT_COLOR1_EXT 0x879C #define GL_OUTPUT_TEXTURE_COORD0_EXT 0x879D #define GL_OUTPUT_TEXTURE_COORD1_EXT 0x879E #define GL_OUTPUT_TEXTURE_COORD2_EXT 0x879F #define GL_OUTPUT_TEXTURE_COORD3_EXT 0x87A0 #define GL_OUTPUT_TEXTURE_COORD4_EXT 0x87A1 #define GL_OUTPUT_TEXTURE_COORD5_EXT 0x87A2 #define GL_OUTPUT_TEXTURE_COORD6_EXT 0x87A3 #define GL_OUTPUT_TEXTURE_COORD7_EXT 0x87A4 #define GL_OUTPUT_TEXTURE_COORD8_EXT 0x87A5 #define GL_OUTPUT_TEXTURE_COORD9_EXT 0x87A6 #define GL_OUTPUT_TEXTURE_COORD10_EXT 0x87A7 #define GL_OUTPUT_TEXTURE_COORD11_EXT 0x87A8 #define GL_OUTPUT_TEXTURE_COORD12_EXT 0x87A9 #define GL_OUTPUT_TEXTURE_COORD13_EXT 0x87AA #define GL_OUTPUT_TEXTURE_COORD14_EXT 0x87AB #define GL_OUTPUT_TEXTURE_COORD15_EXT 0x87AC #define GL_OUTPUT_TEXTURE_COORD16_EXT 0x87AD #define GL_OUTPUT_TEXTURE_COORD17_EXT 0x87AE #define GL_OUTPUT_TEXTURE_COORD18_EXT 0x87AF #define GL_OUTPUT_TEXTURE_COORD19_EXT 0x87B0 #define GL_OUTPUT_TEXTURE_COORD20_EXT 0x87B1 #define GL_OUTPUT_TEXTURE_COORD21_EXT 0x87B2 #define GL_OUTPUT_TEXTURE_COORD22_EXT 0x87B3 #define GL_OUTPUT_TEXTURE_COORD23_EXT 0x87B4 #define GL_OUTPUT_TEXTURE_COORD24_EXT 0x87B5 #define GL_OUTPUT_TEXTURE_COORD25_EXT 0x87B6 #define GL_OUTPUT_TEXTURE_COORD26_EXT 0x87B7 #define GL_OUTPUT_TEXTURE_COORD27_EXT 0x87B8 #define GL_OUTPUT_TEXTURE_COORD28_EXT 0x87B9 #define GL_OUTPUT_TEXTURE_COORD29_EXT 0x87BA #define GL_OUTPUT_TEXTURE_COORD30_EXT 0x87BB #define GL_OUTPUT_TEXTURE_COORD31_EXT 0x87BC #define GL_OUTPUT_FOG_EXT 0x87BD #define GL_SCALAR_EXT 0x87BE #define GL_VECTOR_EXT 0x87BF #define GL_MATRIX_EXT 0x87C0 #define GL_VARIANT_EXT 0x87C1 #define GL_INVARIANT_EXT 0x87C2 #define GL_LOCAL_CONSTANT_EXT 0x87C3 #define GL_LOCAL_EXT 0x87C4 #define GL_MAX_VERTEX_SHADER_INSTRUCTIONS_EXT 0x87C5 #define GL_MAX_VERTEX_SHADER_VARIANTS_EXT 0x87C6 #define GL_MAX_VERTEX_SHADER_INVARIANTS_EXT 0x87C7 #define GL_MAX_VERTEX_SHADER_LOCAL_CONSTANTS_EXT 0x87C8 #define GL_MAX_VERTEX_SHADER_LOCALS_EXT 0x87C9 #define GL_MAX_OPTIMIZED_VERTEX_SHADER_INSTRUCTIONS_EXT 0x87CA #define GL_MAX_OPTIMIZED_VERTEX_SHADER_VARIANTS_EXT 0x87CB #define GL_MAX_OPTIMIZED_VERTEX_SHADER_LOCAL_CONSTANTS_EXT 0x87CC #define GL_MAX_OPTIMIZED_VERTEX_SHADER_INVARIANTS_EXT 0x87CD #define GL_MAX_OPTIMIZED_VERTEX_SHADER_LOCALS_EXT 0x87CE #define GL_VERTEX_SHADER_INSTRUCTIONS_EXT 0x87CF #define GL_VERTEX_SHADER_VARIANTS_EXT 0x87D0 #define GL_VERTEX_SHADER_INVARIANTS_EXT 0x87D1 #define GL_VERTEX_SHADER_LOCAL_CONSTANTS_EXT 0x87D2 #define GL_VERTEX_SHADER_LOCALS_EXT 0x87D3 #define GL_VERTEX_SHADER_OPTIMIZED_EXT 0x87D4 #define GL_X_EXT 0x87D5 #define GL_Y_EXT 0x87D6 #define GL_Z_EXT 0x87D7 #define GL_W_EXT 0x87D8 #define GL_NEGATIVE_X_EXT 0x87D9 #define GL_NEGATIVE_Y_EXT 0x87DA #define GL_NEGATIVE_Z_EXT 0x87DB #define GL_NEGATIVE_W_EXT 0x87DC #define GL_ZERO_EXT 0x87DD #define GL_ONE_EXT 0x87DE #define GL_NEGATIVE_ONE_EXT 0x87DF #define GL_NORMALIZED_RANGE_EXT 0x87E0 #define GL_FULL_RANGE_EXT 0x87E1 #define GL_CURRENT_VERTEX_EXT 0x87E2 #define GL_MVP_MATRIX_EXT 0x87E3 #define GL_VARIANT_VALUE_EXT 0x87E4 #define GL_VARIANT_DATATYPE_EXT 0x87E5 #define GL_VARIANT_ARRAY_STRIDE_EXT 0x87E6 #define GL_VARIANT_ARRAY_TYPE_EXT 0x87E7 #define GL_VARIANT_ARRAY_EXT 0x87E8 #define GL_VARIANT_ARRAY_POINTER_EXT 0x87E9 #define GL_INVARIANT_VALUE_EXT 0x87EA #define GL_INVARIANT_DATATYPE_EXT 0x87EB #define GL_LOCAL_CONSTANT_VALUE_EXT 0x87EC #define GL_LOCAL_CONSTANT_DATATYPE_EXT 0x87ED #endif #ifndef GL_ATI_vertex_streams #define GL_MAX_VERTEX_STREAMS_ATI 0x876B #define GL_VERTEX_STREAM0_ATI 0x876C #define GL_VERTEX_STREAM1_ATI 0x876D #define GL_VERTEX_STREAM2_ATI 0x876E #define GL_VERTEX_STREAM3_ATI 0x876F #define GL_VERTEX_STREAM4_ATI 0x8770 #define GL_VERTEX_STREAM5_ATI 0x8771 #define GL_VERTEX_STREAM6_ATI 0x8772 #define GL_VERTEX_STREAM7_ATI 0x8773 #define GL_VERTEX_SOURCE_ATI 0x8774 #endif #ifndef GL_ATI_element_array #define GL_ELEMENT_ARRAY_ATI 0x8768 #define GL_ELEMENT_ARRAY_TYPE_ATI 0x8769 #define GL_ELEMENT_ARRAY_POINTER_ATI 0x876A #endif #ifndef GL_SUN_mesh_array #define GL_QUAD_MESH_SUN 0x8614 #define GL_TRIANGLE_MESH_SUN 0x8615 #endif #ifndef GL_SUN_slice_accum #define GL_SLICE_ACCUM_SUN 0x85CC #endif #ifndef GL_NV_multisample_filter_hint #define GL_MULTISAMPLE_FILTER_HINT_NV 0x8534 #endif #ifndef GL_NV_depth_clamp #define GL_DEPTH_CLAMP_NV 0x864F #endif #ifndef GL_NV_occlusion_query #define GL_PIXEL_COUNTER_BITS_NV 0x8864 #define GL_CURRENT_OCCLUSION_QUERY_ID_NV 0x8865 #define GL_PIXEL_COUNT_NV 0x8866 #define GL_PIXEL_COUNT_AVAILABLE_NV 0x8867 #endif #ifndef GL_NV_point_sprite #define GL_POINT_SPRITE_NV 0x8861 #define GL_COORD_REPLACE_NV 0x8862 #define GL_POINT_SPRITE_R_MODE_NV 0x8863 #endif #ifndef GL_NV_texture_shader3 #define GL_OFFSET_PROJECTIVE_TEXTURE_2D_NV 0x8850 #define GL_OFFSET_PROJECTIVE_TEXTURE_2D_SCALE_NV 0x8851 #define GL_OFFSET_PROJECTIVE_TEXTURE_RECTANGLE_NV 0x8852 #define GL_OFFSET_PROJECTIVE_TEXTURE_RECTANGLE_SCALE_NV 0x8853 #define GL_OFFSET_HILO_TEXTURE_2D_NV 0x8854 #define GL_OFFSET_HILO_TEXTURE_RECTANGLE_NV 0x8855 #define GL_OFFSET_HILO_PROJECTIVE_TEXTURE_2D_NV 0x8856 #define GL_OFFSET_HILO_PROJECTIVE_TEXTURE_RECTANGLE_NV 0x8857 #define GL_DEPENDENT_HILO_TEXTURE_2D_NV 0x8858 #define GL_DEPENDENT_RGB_TEXTURE_3D_NV 0x8859 #define GL_DEPENDENT_RGB_TEXTURE_CUBE_MAP_NV 0x885A #define GL_DOT_PRODUCT_PASS_THROUGH_NV 0x885B #define GL_DOT_PRODUCT_TEXTURE_1D_NV 0x885C #define GL_DOT_PRODUCT_AFFINE_DEPTH_REPLACE_NV 0x885D #define GL_HILO8_NV 0x885E #define GL_SIGNED_HILO8_NV 0x885F #define GL_FORCE_BLUE_TO_ONE_NV 0x8860 #endif #ifndef GL_NV_vertex_program1_1 #endif #ifndef GL_EXT_shadow_funcs #endif #ifndef GL_EXT_stencil_two_side #define GL_STENCIL_TEST_TWO_SIDE_EXT 0x8910 #define GL_ACTIVE_STENCIL_FACE_EXT 0x8911 #endif #ifndef GL_ATI_text_fragment_shader #define GL_TEXT_FRAGMENT_SHADER_ATI 0x8200 #endif #ifndef GL_APPLE_client_storage #define GL_UNPACK_CLIENT_STORAGE_APPLE 0x85B2 #endif #ifndef GL_APPLE_element_array #define GL_ELEMENT_ARRAY_APPLE 0x8768 #define GL_ELEMENT_ARRAY_TYPE_APPLE 0x8769 #define GL_ELEMENT_ARRAY_POINTER_APPLE 0x876A #endif #ifndef GL_APPLE_fence #define GL_DRAW_PIXELS_APPLE 0x8A0A #define GL_FENCE_APPLE 0x8A0B #endif #ifndef GL_APPLE_vertex_array_object #define GL_VERTEX_ARRAY_BINDING_APPLE 0x85B5 #endif #ifndef GL_APPLE_vertex_array_range #define GL_VERTEX_ARRAY_RANGE_APPLE 0x851D #define GL_VERTEX_ARRAY_RANGE_LENGTH_APPLE 0x851E #define GL_VERTEX_ARRAY_STORAGE_HINT_APPLE 0x851F #define GL_VERTEX_ARRAY_RANGE_POINTER_APPLE 0x8521 #define GL_STORAGE_CACHED_APPLE 0x85BE #define GL_STORAGE_SHARED_APPLE 0x85BF #endif #ifndef GL_APPLE_ycbcr_422 #define GL_YCBCR_422_APPLE 0x85B9 #define GL_UNSIGNED_SHORT_8_8_APPLE 0x85BA #define GL_UNSIGNED_SHORT_8_8_REV_APPLE 0x85BB #endif #ifndef GL_S3_s3tc #define GL_RGB_S3TC 0x83A0 #define GL_RGB4_S3TC 0x83A1 #define GL_RGBA_S3TC 0x83A2 #define GL_RGBA4_S3TC 0x83A3 #endif #ifndef GL_ATI_draw_buffers #define GL_MAX_DRAW_BUFFERS_ATI 0x8824 #define GL_DRAW_BUFFER0_ATI 0x8825 #define GL_DRAW_BUFFER1_ATI 0x8826 #define GL_DRAW_BUFFER2_ATI 0x8827 #define GL_DRAW_BUFFER3_ATI 0x8828 #define GL_DRAW_BUFFER4_ATI 0x8829 #define GL_DRAW_BUFFER5_ATI 0x882A #define GL_DRAW_BUFFER6_ATI 0x882B #define GL_DRAW_BUFFER7_ATI 0x882C #define GL_DRAW_BUFFER8_ATI 0x882D #define GL_DRAW_BUFFER9_ATI 0x882E #define GL_DRAW_BUFFER10_ATI 0x882F #define GL_DRAW_BUFFER11_ATI 0x8830 #define GL_DRAW_BUFFER12_ATI 0x8831 #define GL_DRAW_BUFFER13_ATI 0x8832 #define GL_DRAW_BUFFER14_ATI 0x8833 #define GL_DRAW_BUFFER15_ATI 0x8834 #endif #ifndef GL_ATI_pixel_format_float #define GL_TYPE_RGBA_FLOAT_ATI 0x8820 #define GL_COLOR_CLEAR_UNCLAMPED_VALUE_ATI 0x8835 #endif #ifndef GL_ATI_texture_env_combine3 #define GL_MODULATE_ADD_ATI 0x8744 #define GL_MODULATE_SIGNED_ADD_ATI 0x8745 #define GL_MODULATE_SUBTRACT_ATI 0x8746 #endif #ifndef GL_ATI_texture_float #define GL_RGBA_FLOAT32_ATI 0x8814 #define GL_RGB_FLOAT32_ATI 0x8815 #define GL_ALPHA_FLOAT32_ATI 0x8816 #define GL_INTENSITY_FLOAT32_ATI 0x8817 #define GL_LUMINANCE_FLOAT32_ATI 0x8818 #define GL_LUMINANCE_ALPHA_FLOAT32_ATI 0x8819 #define GL_RGBA_FLOAT16_ATI 0x881A #define GL_RGB_FLOAT16_ATI 0x881B #define GL_ALPHA_FLOAT16_ATI 0x881C #define GL_INTENSITY_FLOAT16_ATI 0x881D #define GL_LUMINANCE_FLOAT16_ATI 0x881E #define GL_LUMINANCE_ALPHA_FLOAT16_ATI 0x881F #endif #ifndef GL_NV_float_buffer #define GL_FLOAT_R_NV 0x8880 #define GL_FLOAT_RG_NV 0x8881 #define GL_FLOAT_RGB_NV 0x8882 #define GL_FLOAT_RGBA_NV 0x8883 #define GL_FLOAT_R16_NV 0x8884 #define GL_FLOAT_R32_NV 0x8885 #define GL_FLOAT_RG16_NV 0x8886 #define GL_FLOAT_RG32_NV 0x8887 #define GL_FLOAT_RGB16_NV 0x8888 #define GL_FLOAT_RGB32_NV 0x8889 #define GL_FLOAT_RGBA16_NV 0x888A #define GL_FLOAT_RGBA32_NV 0x888B #define GL_TEXTURE_FLOAT_COMPONENTS_NV 0x888C #define GL_FLOAT_CLEAR_COLOR_VALUE_NV 0x888D #define GL_FLOAT_RGBA_MODE_NV 0x888E #endif #ifndef GL_NV_fragment_program #define GL_MAX_FRAGMENT_PROGRAM_LOCAL_PARAMETERS_NV 0x8868 #define GL_FRAGMENT_PROGRAM_NV 0x8870 #define GL_MAX_TEXTURE_COORDS_NV 0x8871 #define GL_MAX_TEXTURE_IMAGE_UNITS_NV 0x8872 #define GL_FRAGMENT_PROGRAM_BINDING_NV 0x8873 #define GL_PROGRAM_ERROR_STRING_NV 0x8874 #endif #ifndef GL_NV_half_float #define GL_HALF_FLOAT_NV 0x140B #endif #ifndef GL_NV_pixel_data_range #define GL_WRITE_PIXEL_DATA_RANGE_NV 0x8878 #define GL_READ_PIXEL_DATA_RANGE_NV 0x8879 #define GL_WRITE_PIXEL_DATA_RANGE_LENGTH_NV 0x887A #define GL_READ_PIXEL_DATA_RANGE_LENGTH_NV 0x887B #define GL_WRITE_PIXEL_DATA_RANGE_POINTER_NV 0x887C #define GL_READ_PIXEL_DATA_RANGE_POINTER_NV 0x887D #endif #ifndef GL_NV_primitive_restart #define GL_PRIMITIVE_RESTART_NV 0x8558 #define GL_PRIMITIVE_RESTART_INDEX_NV 0x8559 #endif #ifndef GL_NV_texture_expand_normal #define GL_TEXTURE_UNSIGNED_REMAP_MODE_NV 0x888F #endif #ifndef GL_NV_vertex_program2 #endif #ifndef GL_ATI_map_object_buffer #endif #ifndef GL_ATI_separate_stencil #define GL_STENCIL_BACK_FUNC_ATI 0x8800 #define GL_STENCIL_BACK_FAIL_ATI 0x8801 #define GL_STENCIL_BACK_PASS_DEPTH_FAIL_ATI 0x8802 #define GL_STENCIL_BACK_PASS_DEPTH_PASS_ATI 0x8803 #endif #ifndef GL_ATI_vertex_attrib_array_object #endif #ifndef GL_OES_read_format #define GL_IMPLEMENTATION_COLOR_READ_TYPE_OES 0x8B9A #define GL_IMPLEMENTATION_COLOR_READ_FORMAT_OES 0x8B9B #endif #ifndef GL_EXT_depth_bounds_test #define GL_DEPTH_BOUNDS_TEST_EXT 0x8890 #define GL_DEPTH_BOUNDS_EXT 0x8891 #endif #ifndef GL_EXT_texture_mirror_clamp #define GL_MIRROR_CLAMP_EXT 0x8742 #define GL_MIRROR_CLAMP_TO_EDGE_EXT 0x8743 #define GL_MIRROR_CLAMP_TO_BORDER_EXT 0x8912 #endif #ifndef GL_EXT_blend_equation_separate #define GL_BLEND_EQUATION_RGB_EXT GL_BLEND_EQUATION #define GL_BLEND_EQUATION_ALPHA_EXT 0x883D #endif #ifndef GL_MESA_pack_invert #define GL_PACK_INVERT_MESA 0x8758 #endif #ifndef GL_MESA_ycbcr_texture #define GL_UNSIGNED_SHORT_8_8_MESA 0x85BA #define GL_UNSIGNED_SHORT_8_8_REV_MESA 0x85BB #define GL_YCBCR_MESA 0x8757 #endif #ifndef GL_EXT_pixel_buffer_object #define GL_PIXEL_PACK_BUFFER_EXT 0x88EB #define GL_PIXEL_UNPACK_BUFFER_EXT 0x88EC #define GL_PIXEL_PACK_BUFFER_BINDING_EXT 0x88ED #define GL_PIXEL_UNPACK_BUFFER_BINDING_EXT 0x88EF #endif #ifndef GL_NV_fragment_program_option #endif #ifndef GL_NV_fragment_program2 #define GL_MAX_PROGRAM_EXEC_INSTRUCTIONS_NV 0x88F4 #define GL_MAX_PROGRAM_CALL_DEPTH_NV 0x88F5 #define GL_MAX_PROGRAM_IF_DEPTH_NV 0x88F6 #define GL_MAX_PROGRAM_LOOP_DEPTH_NV 0x88F7 #define GL_MAX_PROGRAM_LOOP_COUNT_NV 0x88F8 #endif #ifndef GL_NV_vertex_program2_option /* reuse GL_MAX_PROGRAM_EXEC_INSTRUCTIONS_NV */ /* reuse GL_MAX_PROGRAM_CALL_DEPTH_NV */ #endif #ifndef GL_NV_vertex_program3 /* reuse GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB */ #endif #ifndef GL_EXT_framebuffer_object #define GL_INVALID_FRAMEBUFFER_OPERATION_EXT 0x0506 #define GL_MAX_RENDERBUFFER_SIZE_EXT 0x84E8 #define GL_FRAMEBUFFER_BINDING_EXT 0x8CA6 #define GL_RENDERBUFFER_BINDING_EXT 0x8CA7 #define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE_EXT 0x8CD0 #define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_EXT 0x8CD1 #define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL_EXT 0x8CD2 #define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE_EXT 0x8CD3 #define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_3D_ZOFFSET_EXT 0x8CD4 #define GL_FRAMEBUFFER_COMPLETE_EXT 0x8CD5 #define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT 0x8CD6 #define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT 0x8CD7 #define GL_FRAMEBUFFER_INCOMPLETE_DUPLICATE_ATTACHMENT_EXT 0x8CD8 #define GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT 0x8CD9 #define GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT 0x8CDA #define GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT 0x8CDB #define GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT 0x8CDC #define GL_FRAMEBUFFER_UNSUPPORTED_EXT 0x8CDD #define GL_MAX_COLOR_ATTACHMENTS_EXT 0x8CDF #define GL_COLOR_ATTACHMENT0_EXT 0x8CE0 #define GL_COLOR_ATTACHMENT1_EXT 0x8CE1 #define GL_COLOR_ATTACHMENT2_EXT 0x8CE2 #define GL_COLOR_ATTACHMENT3_EXT 0x8CE3 #define GL_COLOR_ATTACHMENT4_EXT 0x8CE4 #define GL_COLOR_ATTACHMENT5_EXT 0x8CE5 #define GL_COLOR_ATTACHMENT6_EXT 0x8CE6 #define GL_COLOR_ATTACHMENT7_EXT 0x8CE7 #define GL_COLOR_ATTACHMENT8_EXT 0x8CE8 #define GL_COLOR_ATTACHMENT9_EXT 0x8CE9 #define GL_COLOR_ATTACHMENT10_EXT 0x8CEA #define GL_COLOR_ATTACHMENT11_EXT 0x8CEB #define GL_COLOR_ATTACHMENT12_EXT 0x8CEC #define GL_COLOR_ATTACHMENT13_EXT 0x8CED #define GL_COLOR_ATTACHMENT14_EXT 0x8CEE #define GL_COLOR_ATTACHMENT15_EXT 0x8CEF #define GL_DEPTH_ATTACHMENT_EXT 0x8D00 #define GL_STENCIL_ATTACHMENT_EXT 0x8D20 #define GL_FRAMEBUFFER_EXT 0x8D40 #define GL_RENDERBUFFER_EXT 0x8D41 #define GL_RENDERBUFFER_WIDTH_EXT 0x8D42 #define GL_RENDERBUFFER_HEIGHT_EXT 0x8D43 #define GL_RENDERBUFFER_INTERNAL_FORMAT_EXT 0x8D44 #define GL_STENCIL_INDEX1_EXT 0x8D46 #define GL_STENCIL_INDEX4_EXT 0x8D47 #define GL_STENCIL_INDEX8_EXT 0x8D48 #define GL_STENCIL_INDEX16_EXT 0x8D49 #define GL_RENDERBUFFER_RED_SIZE_EXT 0x8D50 #define GL_RENDERBUFFER_GREEN_SIZE_EXT 0x8D51 #define GL_RENDERBUFFER_BLUE_SIZE_EXT 0x8D52 #define GL_RENDERBUFFER_ALPHA_SIZE_EXT 0x8D53 #define GL_RENDERBUFFER_DEPTH_SIZE_EXT 0x8D54 #define GL_RENDERBUFFER_STENCIL_SIZE_EXT 0x8D55 #endif #ifndef GL_GREMEDY_string_marker #endif /*************************************************************/ #include <stddef.h> #ifndef GL_VERSION_2_0 /* GL type for program/shader text */ typedef char GLchar; /* native character */ #endif #ifndef GL_VERSION_1_5 /* GL types for handling large vertex buffer objects */ typedef ptrdiff_t GLintptr; typedef ptrdiff_t GLsizeiptr; #endif #ifndef GL_ARB_vertex_buffer_object /* GL types for handling large vertex buffer objects */ typedef ptrdiff_t GLintptrARB; typedef ptrdiff_t GLsizeiptrARB; #endif #ifndef GL_ARB_shader_objects /* GL types for handling shader object handles and program/shader text */ typedef char GLcharARB; /* native character */ typedef unsigned int GLhandleARB; /* shader object handle */ #endif /* GL types for "half" precision (s10e5) float data in host memory */ #ifndef GL_ARB_half_float_pixel typedef unsigned short GLhalfARB; #endif #ifndef GL_NV_half_float typedef unsigned short GLhalfNV; #endif #ifndef GL_VERSION_1_2 #define GL_VERSION_1_2 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glBlendColor (GLclampf, GLclampf, GLclampf, GLclampf); GLAPI void APIENTRY glBlendEquation (GLenum); GLAPI void APIENTRY glDrawRangeElements (GLenum, GLuint, GLuint, GLsizei, GLenum, const GLvoid *); GLAPI void APIENTRY glColorTable (GLenum, GLenum, GLsizei, GLenum, GLenum, const GLvoid *); GLAPI void APIENTRY glColorTableParameterfv (GLenum, GLenum, const GLfloat *); GLAPI void APIENTRY glColorTableParameteriv (GLenum, GLenum, const GLint *); GLAPI void APIENTRY glCopyColorTable (GLenum, GLenum, GLint, GLint, GLsizei); GLAPI void APIENTRY glGetColorTable (GLenum, GLenum, GLenum, GLvoid *); GLAPI void APIENTRY glGetColorTableParameterfv (GLenum, GLenum, GLfloat *); GLAPI void APIENTRY glGetColorTableParameteriv (GLenum, GLenum, GLint *); GLAPI void APIENTRY glColorSubTable (GLenum, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *); GLAPI void APIENTRY glCopyColorSubTable (GLenum, GLsizei, GLint, GLint, GLsizei); GLAPI void APIENTRY glConvolutionFilter1D (GLenum, GLenum, GLsizei, GLenum, GLenum, const GLvoid *); GLAPI void APIENTRY glConvolutionFilter2D (GLenum, GLenum, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *); GLAPI void APIENTRY glConvolutionParameterf (GLenum, GLenum, GLfloat); GLAPI void APIENTRY glConvolutionParameterfv (GLenum, GLenum, const GLfloat *); GLAPI void APIENTRY glConvolutionParameteri (GLenum, GLenum, GLint); GLAPI void APIENTRY glConvolutionParameteriv (GLenum, GLenum, const GLint *); GLAPI void APIENTRY glCopyConvolutionFilter1D (GLenum, GLenum, GLint, GLint, GLsizei); GLAPI void APIENTRY glCopyConvolutionFilter2D (GLenum, GLenum, GLint, GLint, GLsizei, GLsizei); GLAPI void APIENTRY glGetConvolutionFilter (GLenum, GLenum, GLenum, GLvoid *); GLAPI void APIENTRY glGetConvolutionParameterfv (GLenum, GLenum, GLfloat *); GLAPI void APIENTRY glGetConvolutionParameteriv (GLenum, GLenum, GLint *); GLAPI void APIENTRY glGetSeparableFilter (GLenum, GLenum, GLenum, GLvoid *, GLvoid *, GLvoid *); GLAPI void APIENTRY glSeparableFilter2D (GLenum, GLenum, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *, const GLvoid *); GLAPI void APIENTRY glGetHistogram (GLenum, GLboolean, GLenum, GLenum, GLvoid *); GLAPI void APIENTRY glGetHistogramParameterfv (GLenum, GLenum, GLfloat *); GLAPI void APIENTRY glGetHistogramParameteriv (GLenum, GLenum, GLint *); GLAPI void APIENTRY glGetMinmax (GLenum, GLboolean, GLenum, GLenum, GLvoid *); GLAPI void APIENTRY glGetMinmaxParameterfv (GLenum, GLenum, GLfloat *); GLAPI void APIENTRY glGetMinmaxParameteriv (GLenum, GLenum, GLint *); GLAPI void APIENTRY glHistogram (GLenum, GLsizei, GLenum, GLboolean); GLAPI void APIENTRY glMinmax (GLenum, GLenum, GLboolean); GLAPI void APIENTRY glResetHistogram (GLenum); GLAPI void APIENTRY glResetMinmax (GLenum); GLAPI void APIENTRY glTexImage3D (GLenum, GLint, GLint, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid *); GLAPI void APIENTRY glTexSubImage3D (GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *); GLAPI void APIENTRY glCopyTexSubImage3D (GLenum, GLint, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLBLENDCOLORPROC) (GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha); typedef void (APIENTRYP PFNGLBLENDEQUATIONPROC) (GLenum mode); typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTSPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid *indices); typedef void (APIENTRYP PFNGLCOLORTABLEPROC) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *table); typedef void (APIENTRYP PFNGLCOLORTABLEPARAMETERFVPROC) (GLenum target, GLenum pname, const GLfloat *params); typedef void (APIENTRYP PFNGLCOLORTABLEPARAMETERIVPROC) (GLenum target, GLenum pname, const GLint *params); typedef void (APIENTRYP PFNGLCOPYCOLORTABLEPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width); typedef void (APIENTRYP PFNGLGETCOLORTABLEPROC) (GLenum target, GLenum format, GLenum type, GLvoid *table); typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERFVPROC) (GLenum target, GLenum pname, GLfloat *params); typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params); typedef void (APIENTRYP PFNGLCOLORSUBTABLEPROC) (GLenum target, GLsizei start, GLsizei count, GLenum format, GLenum type, const GLvoid *data); typedef void (APIENTRYP PFNGLCOPYCOLORSUBTABLEPROC) (GLenum target, GLsizei start, GLint x, GLint y, GLsizei width); typedef void (APIENTRYP PFNGLCONVOLUTIONFILTER1DPROC) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *image); typedef void (APIENTRYP PFNGLCONVOLUTIONFILTER2DPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *image); typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERFPROC) (GLenum target, GLenum pname, GLfloat params); typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERFVPROC) (GLenum target, GLenum pname, const GLfloat *params); typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERIPROC) (GLenum target, GLenum pname, GLint params); typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERIVPROC) (GLenum target, GLenum pname, const GLint *params); typedef void (APIENTRYP PFNGLCOPYCONVOLUTIONFILTER1DPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width); typedef void (APIENTRYP PFNGLCOPYCONVOLUTIONFILTER2DPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height); typedef void (APIENTRYP PFNGLGETCONVOLUTIONFILTERPROC) (GLenum target, GLenum format, GLenum type, GLvoid *image); typedef void (APIENTRYP PFNGLGETCONVOLUTIONPARAMETERFVPROC) (GLenum target, GLenum pname, GLfloat *params); typedef void (APIENTRYP PFNGLGETCONVOLUTIONPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params); typedef void (APIENTRYP PFNGLGETSEPARABLEFILTERPROC) (GLenum target, GLenum format, GLenum type, GLvoid *row, GLvoid *column, GLvoid *span); typedef void (APIENTRYP PFNGLSEPARABLEFILTER2DPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *row, const GLvoid *column); typedef void (APIENTRYP PFNGLGETHISTOGRAMPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLvoid *values); typedef void (APIENTRYP PFNGLGETHISTOGRAMPARAMETERFVPROC) (GLenum target, GLenum pname, GLfloat *params); typedef void (APIENTRYP PFNGLGETHISTOGRAMPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params); typedef void (APIENTRYP PFNGLGETMINMAXPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLvoid *values); typedef void (APIENTRYP PFNGLGETMINMAXPARAMETERFVPROC) (GLenum target, GLenum pname, GLfloat *params); typedef void (APIENTRYP PFNGLGETMINMAXPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params); typedef void (APIENTRYP PFNGLHISTOGRAMPROC) (GLenum target, GLsizei width, GLenum internalformat, GLboolean sink); typedef void (APIENTRYP PFNGLMINMAXPROC) (GLenum target, GLenum internalformat, GLboolean sink); typedef void (APIENTRYP PFNGLRESETHISTOGRAMPROC) (GLenum target); typedef void (APIENTRYP PFNGLRESETMINMAXPROC) (GLenum target); typedef void (APIENTRYP PFNGLTEXIMAGE3DPROC) (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *pixels); typedef void (APIENTRYP PFNGLTEXSUBIMAGE3DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid *pixels); typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE3DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); #endif #ifndef GL_VERSION_1_3 #define GL_VERSION_1_3 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glActiveTexture (GLenum); GLAPI void APIENTRY glClientActiveTexture (GLenum); GLAPI void APIENTRY glMultiTexCoord1d (GLenum, GLdouble); GLAPI void APIENTRY glMultiTexCoord1dv (GLenum, const GLdouble *); GLAPI void APIENTRY glMultiTexCoord1f (GLenum, GLfloat); GLAPI void APIENTRY glMultiTexCoord1fv (GLenum, const GLfloat *); GLAPI void APIENTRY glMultiTexCoord1i (GLenum, GLint); GLAPI void APIENTRY glMultiTexCoord1iv (GLenum, const GLint *); GLAPI void APIENTRY glMultiTexCoord1s (GLenum, GLshort); GLAPI void APIENTRY glMultiTexCoord1sv (GLenum, const GLshort *); GLAPI void APIENTRY glMultiTexCoord2d (GLenum, GLdouble, GLdouble); GLAPI void APIENTRY glMultiTexCoord2dv (GLenum, const GLdouble *); GLAPI void APIENTRY glMultiTexCoord2f (GLenum, GLfloat, GLfloat); GLAPI void APIENTRY glMultiTexCoord2fv (GLenum, const GLfloat *); GLAPI void APIENTRY glMultiTexCoord2i (GLenum, GLint, GLint); GLAPI void APIENTRY glMultiTexCoord2iv (GLenum, const GLint *); GLAPI void APIENTRY glMultiTexCoord2s (GLenum, GLshort, GLshort); GLAPI void APIENTRY glMultiTexCoord2sv (GLenum, const GLshort *); GLAPI void APIENTRY glMultiTexCoord3d (GLenum, GLdouble, GLdouble, GLdouble); GLAPI void APIENTRY glMultiTexCoord3dv (GLenum, const GLdouble *); GLAPI void APIENTRY glMultiTexCoord3f (GLenum, GLfloat, GLfloat, GLfloat); GLAPI void APIENTRY glMultiTexCoord3fv (GLenum, const GLfloat *); GLAPI void APIENTRY glMultiTexCoord3i (GLenum, GLint, GLint, GLint); GLAPI void APIENTRY glMultiTexCoord3iv (GLenum, const GLint *); GLAPI void APIENTRY glMultiTexCoord3s (GLenum, GLshort, GLshort, GLshort); GLAPI void APIENTRY glMultiTexCoord3sv (GLenum, const GLshort *); GLAPI void APIENTRY glMultiTexCoord4d (GLenum, GLdouble, GLdouble, GLdouble, GLdouble); GLAPI void APIENTRY glMultiTexCoord4dv (GLenum, const GLdouble *); GLAPI void APIENTRY glMultiTexCoord4f (GLenum, GLfloat, GLfloat, GLfloat, GLfloat); GLAPI void APIENTRY glMultiTexCoord4fv (GLenum, const GLfloat *); GLAPI void APIENTRY glMultiTexCoord4i (GLenum, GLint, GLint, GLint, GLint); GLAPI void APIENTRY glMultiTexCoord4iv (GLenum, const GLint *); GLAPI void APIENTRY glMultiTexCoord4s (GLenum, GLshort, GLshort, GLshort, GLshort); GLAPI void APIENTRY glMultiTexCoord4sv (GLenum, const GLshort *); GLAPI void APIENTRY glLoadTransposeMatrixf (const GLfloat *); GLAPI void APIENTRY glLoadTransposeMatrixd (const GLdouble *); GLAPI void APIENTRY glMultTransposeMatrixf (const GLfloat *); GLAPI void APIENTRY glMultTransposeMatrixd (const GLdouble *); GLAPI void APIENTRY glSampleCoverage (GLclampf, GLboolean); GLAPI void APIENTRY glCompressedTexImage3D (GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLsizei, const GLvoid *); GLAPI void APIENTRY glCompressedTexImage2D (GLenum, GLint, GLenum, GLsizei, GLsizei, GLint, GLsizei, const GLvoid *); GLAPI void APIENTRY glCompressedTexImage1D (GLenum, GLint, GLenum, GLsizei, GLint, GLsizei, const GLvoid *); GLAPI void APIENTRY glCompressedTexSubImage3D (GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid *); GLAPI void APIENTRY glCompressedTexSubImage2D (GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid *); GLAPI void APIENTRY glCompressedTexSubImage1D (GLenum, GLint, GLint, GLsizei, GLenum, GLsizei, const GLvoid *); GLAPI void APIENTRY glGetCompressedTexImage (GLenum, GLint, GLvoid *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLACTIVETEXTUREPROC) (GLenum texture); typedef void (APIENTRYP PFNGLCLIENTACTIVETEXTUREPROC) (GLenum texture); typedef void (APIENTRYP PFNGLMULTITEXCOORD1DPROC) (GLenum target, GLdouble s); typedef void (APIENTRYP PFNGLMULTITEXCOORD1DVPROC) (GLenum target, const GLdouble *v); typedef void (APIENTRYP PFNGLMULTITEXCOORD1FPROC) (GLenum target, GLfloat s); typedef void (APIENTRYP PFNGLMULTITEXCOORD1FVPROC) (GLenum target, const GLfloat *v); typedef void (APIENTRYP PFNGLMULTITEXCOORD1IPROC) (GLenum target, GLint s); typedef void (APIENTRYP PFNGLMULTITEXCOORD1IVPROC) (GLenum target, const GLint *v); typedef void (APIENTRYP PFNGLMULTITEXCOORD1SPROC) (GLenum target, GLshort s); typedef void (APIENTRYP PFNGLMULTITEXCOORD1SVPROC) (GLenum target, const GLshort *v); typedef void (APIENTRYP PFNGLMULTITEXCOORD2DPROC) (GLenum target, GLdouble s, GLdouble t); typedef void (APIENTRYP PFNGLMULTITEXCOORD2DVPROC) (GLenum target, const GLdouble *v); typedef void (APIENTRYP PFNGLMULTITEXCOORD2FPROC) (GLenum target, GLfloat s, GLfloat t); typedef void (APIENTRYP PFNGLMULTITEXCOORD2FVPROC) (GLenum target, const GLfloat *v); typedef void (APIENTRYP PFNGLMULTITEXCOORD2IPROC) (GLenum target, GLint s, GLint t); typedef void (APIENTRYP PFNGLMULTITEXCOORD2IVPROC) (GLenum target, const GLint *v); typedef void (APIENTRYP PFNGLMULTITEXCOORD2SPROC) (GLenum target, GLshort s, GLshort t); typedef void (APIENTRYP PFNGLMULTITEXCOORD2SVPROC) (GLenum target, const GLshort *v); typedef void (APIENTRYP PFNGLMULTITEXCOORD3DPROC) (GLenum target, GLdouble s, GLdouble t, GLdouble r); typedef void (APIENTRYP PFNGLMULTITEXCOORD3DVPROC) (GLenum target, const GLdouble *v); typedef void (APIENTRYP PFNGLMULTITEXCOORD3FPROC) (GLenum target, GLfloat s, GLfloat t, GLfloat r); typedef void (APIENTRYP PFNGLMULTITEXCOORD3FVPROC) (GLenum target, const GLfloat *v); typedef void (APIENTRYP PFNGLMULTITEXCOORD3IPROC) (GLenum target, GLint s, GLint t, GLint r); typedef void (APIENTRYP PFNGLMULTITEXCOORD3IVPROC) (GLenum target, const GLint *v); typedef void (APIENTRYP PFNGLMULTITEXCOORD3SPROC) (GLenum target, GLshort s, GLshort t, GLshort r); typedef void (APIENTRYP PFNGLMULTITEXCOORD3SVPROC) (GLenum target, const GLshort *v); typedef void (APIENTRYP PFNGLMULTITEXCOORD4DPROC) (GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q); typedef void (APIENTRYP PFNGLMULTITEXCOORD4DVPROC) (GLenum target, const GLdouble *v); typedef void (APIENTRYP PFNGLMULTITEXCOORD4FPROC) (GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q); typedef void (APIENTRYP PFNGLMULTITEXCOORD4FVPROC) (GLenum target, const GLfloat *v); typedef void (APIENTRYP PFNGLMULTITEXCOORD4IPROC) (GLenum target, GLint s, GLint t, GLint r, GLint q); typedef void (APIENTRYP PFNGLMULTITEXCOORD4IVPROC) (GLenum target, const GLint *v); typedef void (APIENTRYP PFNGLMULTITEXCOORD4SPROC) (GLenum target, GLshort s, GLshort t, GLshort r, GLshort q); typedef void (APIENTRYP PFNGLMULTITEXCOORD4SVPROC) (GLenum target, const GLshort *v); typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXFPROC) (const GLfloat *m); typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXDPROC) (const GLdouble *m); typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXFPROC) (const GLfloat *m); typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXDPROC) (const GLdouble *m); typedef void (APIENTRYP PFNGLSAMPLECOVERAGEPROC) (GLclampf value, GLboolean invert); typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE3DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid *data); typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE2DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *data); typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE1DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const GLvoid *data); typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid *data); typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *data); typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC) (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const GLvoid *data); typedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXIMAGEPROC) (GLenum target, GLint level, GLvoid *img); #endif #ifndef GL_VERSION_1_4 #define GL_VERSION_1_4 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glBlendFuncSeparate (GLenum, GLenum, GLenum, GLenum); GLAPI void APIENTRY glFogCoordf (GLfloat); GLAPI void APIENTRY glFogCoordfv (const GLfloat *); GLAPI void APIENTRY glFogCoordd (GLdouble); GLAPI void APIENTRY glFogCoorddv (const GLdouble *); GLAPI void APIENTRY glFogCoordPointer (GLenum, GLsizei, const GLvoid *); GLAPI void APIENTRY glMultiDrawArrays (GLenum, GLint *, GLsizei *, GLsizei); GLAPI void APIENTRY glMultiDrawElements (GLenum, const GLsizei *, GLenum, const GLvoid* *, GLsizei); GLAPI void APIENTRY glPointParameterf (GLenum, GLfloat); GLAPI void APIENTRY glPointParameterfv (GLenum, const GLfloat *); GLAPI void APIENTRY glPointParameteri (GLenum, GLint); GLAPI void APIENTRY glPointParameteriv (GLenum, const GLint *); GLAPI void APIENTRY glSecondaryColor3b (GLbyte, GLbyte, GLbyte); GLAPI void APIENTRY glSecondaryColor3bv (const GLbyte *); GLAPI void APIENTRY glSecondaryColor3d (GLdouble, GLdouble, GLdouble); GLAPI void APIENTRY glSecondaryColor3dv (const GLdouble *); GLAPI void APIENTRY glSecondaryColor3f (GLfloat, GLfloat, GLfloat); GLAPI void APIENTRY glSecondaryColor3fv (const GLfloat *); GLAPI void APIENTRY glSecondaryColor3i (GLint, GLint, GLint); GLAPI void APIENTRY glSecondaryColor3iv (const GLint *); GLAPI void APIENTRY glSecondaryColor3s (GLshort, GLshort, GLshort); GLAPI void APIENTRY glSecondaryColor3sv (const GLshort *); GLAPI void APIENTRY glSecondaryColor3ub (GLubyte, GLubyte, GLubyte); GLAPI void APIENTRY glSecondaryColor3ubv (const GLubyte *); GLAPI void APIENTRY glSecondaryColor3ui (GLuint, GLuint, GLuint); GLAPI void APIENTRY glSecondaryColor3uiv (const GLuint *); GLAPI void APIENTRY glSecondaryColor3us (GLushort, GLushort, GLushort); GLAPI void APIENTRY glSecondaryColor3usv (const GLushort *); GLAPI void APIENTRY glSecondaryColorPointer (GLint, GLenum, GLsizei, const GLvoid *); GLAPI void APIENTRY glWindowPos2d (GLdouble, GLdouble); GLAPI void APIENTRY glWindowPos2dv (const GLdouble *); GLAPI void APIENTRY glWindowPos2f (GLfloat, GLfloat); GLAPI void APIENTRY glWindowPos2fv (const GLfloat *); GLAPI void APIENTRY glWindowPos2i (GLint, GLint); GLAPI void APIENTRY glWindowPos2iv (const GLint *); GLAPI void APIENTRY glWindowPos2s (GLshort, GLshort); GLAPI void APIENTRY glWindowPos2sv (const GLshort *); GLAPI void APIENTRY glWindowPos3d (GLdouble, GLdouble, GLdouble); GLAPI void APIENTRY glWindowPos3dv (const GLdouble *); GLAPI void APIENTRY glWindowPos3f (GLfloat, GLfloat, GLfloat); GLAPI void APIENTRY glWindowPos3fv (const GLfloat *); GLAPI void APIENTRY glWindowPos3i (GLint, GLint, GLint); GLAPI void APIENTRY glWindowPos3iv (const GLint *); GLAPI void APIENTRY glWindowPos3s (GLshort, GLshort, GLshort); GLAPI void APIENTRY glWindowPos3sv (const GLshort *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); typedef void (APIENTRYP PFNGLFOGCOORDFPROC) (GLfloat coord); typedef void (APIENTRYP PFNGLFOGCOORDFVPROC) (const GLfloat *coord); typedef void (APIENTRYP PFNGLFOGCOORDDPROC) (GLdouble coord); typedef void (APIENTRYP PFNGLFOGCOORDDVPROC) (const GLdouble *coord); typedef void (APIENTRYP PFNGLFOGCOORDPOINTERPROC) (GLenum type, GLsizei stride, const GLvoid *pointer); typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSPROC) (GLenum mode, GLint *first, GLsizei *count, GLsizei primcount); typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSPROC) (GLenum mode, const GLsizei *count, GLenum type, const GLvoid* *indices, GLsizei primcount); typedef void (APIENTRYP PFNGLPOINTPARAMETERFPROC) (GLenum pname, GLfloat param); typedef void (APIENTRYP PFNGLPOINTPARAMETERFVPROC) (GLenum pname, const GLfloat *params); typedef void (APIENTRYP PFNGLPOINTPARAMETERIPROC) (GLenum pname, GLint param); typedef void (APIENTRYP PFNGLPOINTPARAMETERIVPROC) (GLenum pname, const GLint *params); typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BPROC) (GLbyte red, GLbyte green, GLbyte blue); typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BVPROC) (const GLbyte *v); typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DPROC) (GLdouble red, GLdouble green, GLdouble blue); typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DVPROC) (const GLdouble *v); typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FPROC) (GLfloat red, GLfloat green, GLfloat blue); typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FVPROC) (const GLfloat *v); typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IPROC) (GLint red, GLint green, GLint blue); typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IVPROC) (const GLint *v); typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SPROC) (GLshort red, GLshort green, GLshort blue); typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SVPROC) (const GLshort *v); typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBPROC) (GLubyte red, GLubyte green, GLubyte blue); typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBVPROC) (const GLubyte *v); typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIPROC) (GLuint red, GLuint green, GLuint blue); typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIVPROC) (const GLuint *v); typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USPROC) (GLushort red, GLushort green, GLushort blue); typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USVPROC) (const GLushort *v); typedef void (APIENTRYP PFNGLSECONDARYCOLORPOINTERPROC) (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer); typedef void (APIENTRYP PFNGLWINDOWPOS2DPROC) (GLdouble x, GLdouble y); typedef void (APIENTRYP PFNGLWINDOWPOS2DVPROC) (const GLdouble *v); typedef void (APIENTRYP PFNGLWINDOWPOS2FPROC) (GLfloat x, GLfloat y); typedef void (APIENTRYP PFNGLWINDOWPOS2FVPROC) (const GLfloat *v); typedef void (APIENTRYP PFNGLWINDOWPOS2IPROC) (GLint x, GLint y); typedef void (APIENTRYP PFNGLWINDOWPOS2IVPROC) (const GLint *v); typedef void (APIENTRYP PFNGLWINDOWPOS2SPROC) (GLshort x, GLshort y); typedef void (APIENTRYP PFNGLWINDOWPOS2SVPROC) (const GLshort *v); typedef void (APIENTRYP PFNGLWINDOWPOS3DPROC) (GLdouble x, GLdouble y, GLdouble z); typedef void (APIENTRYP PFNGLWINDOWPOS3DVPROC) (const GLdouble *v); typedef void (APIENTRYP PFNGLWINDOWPOS3FPROC) (GLfloat x, GLfloat y, GLfloat z); typedef void (APIENTRYP PFNGLWINDOWPOS3FVPROC) (const GLfloat *v); typedef void (APIENTRYP PFNGLWINDOWPOS3IPROC) (GLint x, GLint y, GLint z); typedef void (APIENTRYP PFNGLWINDOWPOS3IVPROC) (const GLint *v); typedef void (APIENTRYP PFNGLWINDOWPOS3SPROC) (GLshort x, GLshort y, GLshort z); typedef void (APIENTRYP PFNGLWINDOWPOS3SVPROC) (const GLshort *v); #endif #ifndef GL_VERSION_1_5 #define GL_VERSION_1_5 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glGenQueries (GLsizei, GLuint *); GLAPI void APIENTRY glDeleteQueries (GLsizei, const GLuint *); GLAPI GLboolean APIENTRY glIsQuery (GLuint); GLAPI void APIENTRY glBeginQuery (GLenum, GLuint); GLAPI void APIENTRY glEndQuery (GLenum); GLAPI void APIENTRY glGetQueryiv (GLenum, GLenum, GLint *); GLAPI void APIENTRY glGetQueryObjectiv (GLuint, GLenum, GLint *); GLAPI void APIENTRY glGetQueryObjectuiv (GLuint, GLenum, GLuint *); GLAPI void APIENTRY glBindBuffer (GLenum, GLuint); GLAPI void APIENTRY glDeleteBuffers (GLsizei, const GLuint *); GLAPI void APIENTRY glGenBuffers (GLsizei, GLuint *); GLAPI GLboolean APIENTRY glIsBuffer (GLuint); GLAPI void APIENTRY glBufferData (GLenum, GLsizeiptr, const GLvoid *, GLenum); GLAPI void APIENTRY glBufferSubData (GLenum, GLintptr, GLsizeiptr, const GLvoid *); GLAPI void APIENTRY glGetBufferSubData (GLenum, GLintptr, GLsizeiptr, GLvoid *); GLAPI GLvoid* APIENTRY glMapBuffer (GLenum, GLenum); GLAPI GLboolean APIENTRY glUnmapBuffer (GLenum); GLAPI void APIENTRY glGetBufferParameteriv (GLenum, GLenum, GLint *); GLAPI void APIENTRY glGetBufferPointerv (GLenum, GLenum, GLvoid* *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLGENQUERIESPROC) (GLsizei n, GLuint *ids); typedef void (APIENTRYP PFNGLDELETEQUERIESPROC) (GLsizei n, const GLuint *ids); typedef GLboolean (APIENTRYP PFNGLISQUERYPROC) (GLuint id); typedef void (APIENTRYP PFNGLBEGINQUERYPROC) (GLenum target, GLuint id); typedef void (APIENTRYP PFNGLENDQUERYPROC) (GLenum target); typedef void (APIENTRYP PFNGLGETQUERYIVPROC) (GLenum target, GLenum pname, GLint *params); typedef void (APIENTRYP PFNGLGETQUERYOBJECTIVPROC) (GLuint id, GLenum pname, GLint *params); typedef void (APIENTRYP PFNGLGETQUERYOBJECTUIVPROC) (GLuint id, GLenum pname, GLuint *params); typedef void (APIENTRYP PFNGLBINDBUFFERPROC) (GLenum target, GLuint buffer); typedef void (APIENTRYP PFNGLDELETEBUFFERSPROC) (GLsizei n, const GLuint *buffers); typedef void (APIENTRYP PFNGLGENBUFFERSPROC) (GLsizei n, GLuint *buffers); typedef GLboolean (APIENTRYP PFNGLISBUFFERPROC) (GLuint buffer); typedef void (APIENTRYP PFNGLBUFFERDATAPROC) (GLenum target, GLsizeiptr size, const GLvoid *data, GLenum usage); typedef void (APIENTRYP PFNGLBUFFERSUBDATAPROC) (GLenum target, GLintptr offset, GLsizeiptr size, const GLvoid *data); typedef void (APIENTRYP PFNGLGETBUFFERSUBDATAPROC) (GLenum target, GLintptr offset, GLsizeiptr size, GLvoid *data); typedef GLvoid* (APIENTRYP PFNGLMAPBUFFERPROC) (GLenum target, GLenum access); typedef GLboolean (APIENTRYP PFNGLUNMAPBUFFERPROC) (GLenum target); typedef void (APIENTRYP PFNGLGETBUFFERPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params); typedef void (APIENTRYP PFNGLGETBUFFERPOINTERVPROC) (GLenum target, GLenum pname, GLvoid* *params); #endif #ifndef GL_VERSION_2_0 #define GL_VERSION_2_0 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glBlendEquationSeparate (GLenum, GLenum); GLAPI void APIENTRY glDrawBuffers (GLsizei, const GLenum *); GLAPI void APIENTRY glStencilOpSeparate (GLenum, GLenum, GLenum, GLenum); GLAPI void APIENTRY glStencilFuncSeparate (GLenum, GLenum, GLint, GLuint); GLAPI void APIENTRY glStencilMaskSeparate (GLenum, GLuint); GLAPI void APIENTRY glAttachShader (GLuint, GLuint); GLAPI void APIENTRY glBindAttribLocation (GLuint, GLuint, const GLchar *); GLAPI void APIENTRY glCompileShader (GLuint); GLAPI GLuint APIENTRY glCreateProgram (void); GLAPI GLuint APIENTRY glCreateShader (GLenum); GLAPI void APIENTRY glDeleteProgram (GLuint); GLAPI void APIENTRY glDeleteShader (GLuint); GLAPI void APIENTRY glDetachShader (GLuint, GLuint); GLAPI void APIENTRY glDisableVertexAttribArray (GLuint); GLAPI void APIENTRY glEnableVertexAttribArray (GLuint); GLAPI void APIENTRY glGetActiveAttrib (GLuint, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLchar *); GLAPI void APIENTRY glGetActiveUniform (GLuint, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLchar *); GLAPI void APIENTRY glGetAttachedShaders (GLuint, GLsizei, GLsizei *, GLuint *); GLAPI GLint APIENTRY glGetAttribLocation (GLuint, const GLchar *); GLAPI void APIENTRY glGetProgramiv (GLuint, GLenum, GLint *); GLAPI void APIENTRY glGetProgramInfoLog (GLuint, GLsizei, GLsizei *, GLchar *); GLAPI void APIENTRY glGetShaderiv (GLuint, GLenum, GLint *); GLAPI void APIENTRY glGetShaderInfoLog (GLuint, GLsizei, GLsizei *, GLchar *); GLAPI void APIENTRY glGetShaderSource (GLuint, GLsizei, GLsizei *, GLchar *); GLAPI GLint APIENTRY glGetUniformLocation (GLuint, const GLchar *); GLAPI void APIENTRY glGetUniformfv (GLuint, GLint, GLfloat *); GLAPI void APIENTRY glGetUniformiv (GLuint, GLint, GLint *); GLAPI void APIENTRY glGetVertexAttribdv (GLuint, GLenum, GLdouble *); GLAPI void APIENTRY glGetVertexAttribfv (GLuint, GLenum, GLfloat *); GLAPI void APIENTRY glGetVertexAttribiv (GLuint, GLenum, GLint *); GLAPI void APIENTRY glGetVertexAttribPointerv (GLuint, GLenum, GLvoid* *); GLAPI GLboolean APIENTRY glIsProgram (GLuint); GLAPI GLboolean APIENTRY glIsShader (GLuint); GLAPI void APIENTRY glLinkProgram (GLuint); GLAPI void APIENTRY glShaderSource (GLuint, GLsizei, const GLchar* *, const GLint *); GLAPI void APIENTRY glUseProgram (GLuint); GLAPI void APIENTRY glUniform1f (GLint, GLfloat); GLAPI void APIENTRY glUniform2f (GLint, GLfloat, GLfloat); GLAPI void APIENTRY glUniform3f (GLint, GLfloat, GLfloat, GLfloat); GLAPI void APIENTRY glUniform4f (GLint, GLfloat, GLfloat, GLfloat, GLfloat); GLAPI void APIENTRY glUniform1i (GLint, GLint); GLAPI void APIENTRY glUniform2i (GLint, GLint, GLint); GLAPI void APIENTRY glUniform3i (GLint, GLint, GLint, GLint); GLAPI void APIENTRY glUniform4i (GLint, GLint, GLint, GLint, GLint); GLAPI void APIENTRY glUniform1fv (GLint, GLsizei, const GLfloat *); GLAPI void APIENTRY glUniform2fv (GLint, GLsizei, const GLfloat *); GLAPI void APIENTRY glUniform3fv (GLint, GLsizei, const GLfloat *); GLAPI void APIENTRY glUniform4fv (GLint, GLsizei, const GLfloat *); GLAPI void APIENTRY glUniform1iv (GLint, GLsizei, const GLint *); GLAPI void APIENTRY glUniform2iv (GLint, GLsizei, const GLint *); GLAPI void APIENTRY glUniform3iv (GLint, GLsizei, const GLint *); GLAPI void APIENTRY glUniform4iv (GLint, GLsizei, const GLint *); GLAPI void APIENTRY glUniformMatrix2fv (GLint, GLsizei, GLboolean, const GLfloat *); GLAPI void APIENTRY glUniformMatrix3fv (GLint, GLsizei, GLboolean, const GLfloat *); GLAPI void APIENTRY glUniformMatrix4fv (GLint, GLsizei, GLboolean, const GLfloat *); GLAPI void APIENTRY glValidateProgram (GLuint); GLAPI void APIENTRY glVertexAttrib1d (GLuint, GLdouble); GLAPI void APIENTRY glVertexAttrib1dv (GLuint, const GLdouble *); GLAPI void APIENTRY glVertexAttrib1f (GLuint, GLfloat); GLAPI void APIENTRY glVertexAttrib1fv (GLuint, const GLfloat *); GLAPI void APIENTRY glVertexAttrib1s (GLuint, GLshort); GLAPI void APIENTRY glVertexAttrib1sv (GLuint, const GLshort *); GLAPI void APIENTRY glVertexAttrib2d (GLuint, GLdouble, GLdouble); GLAPI void APIENTRY glVertexAttrib2dv (GLuint, const GLdouble *); GLAPI void APIENTRY glVertexAttrib2f (GLuint, GLfloat, GLfloat); GLAPI void APIENTRY glVertexAttrib2fv (GLuint, const GLfloat *); GLAPI void APIENTRY glVertexAttrib2s (GLuint, GLshort, GLshort); GLAPI void APIENTRY glVertexAttrib2sv (GLuint, const GLshort *); GLAPI void APIENTRY glVertexAttrib3d (GLuint, GLdouble, GLdouble, GLdouble); GLAPI void APIENTRY glVertexAttrib3dv (GLuint, const GLdouble *); GLAPI void APIENTRY glVertexAttrib3f (GLuint, GLfloat, GLfloat, GLfloat); GLAPI void APIENTRY glVertexAttrib3fv (GLuint, const GLfloat *); GLAPI void APIENTRY glVertexAttrib3s (GLuint, GLshort, GLshort, GLshort); GLAPI void APIENTRY glVertexAttrib3sv (GLuint, const GLshort *); GLAPI void APIENTRY glVertexAttrib4Nbv (GLuint, const GLbyte *); GLAPI void APIENTRY glVertexAttrib4Niv (GLuint, const GLint *); GLAPI void APIENTRY glVertexAttrib4Nsv (GLuint, const GLshort *); GLAPI void APIENTRY glVertexAttrib4Nub (GLuint, GLubyte, GLubyte, GLubyte, GLubyte); GLAPI void APIENTRY glVertexAttrib4Nubv (GLuint, const GLubyte *); GLAPI void APIENTRY glVertexAttrib4Nuiv (GLuint, const GLuint *); GLAPI void APIENTRY glVertexAttrib4Nusv (GLuint, const GLushort *); GLAPI void APIENTRY glVertexAttrib4bv (GLuint, const GLbyte *); GLAPI void APIENTRY glVertexAttrib4d (GLuint, GLdouble, GLdouble, GLdouble, GLdouble); GLAPI void APIENTRY glVertexAttrib4dv (GLuint, const GLdouble *); GLAPI void APIENTRY glVertexAttrib4f (GLuint, GLfloat, GLfloat, GLfloat, GLfloat); GLAPI void APIENTRY glVertexAttrib4fv (GLuint, const GLfloat *); GLAPI void APIENTRY glVertexAttrib4iv (GLuint, const GLint *); GLAPI void APIENTRY glVertexAttrib4s (GLuint, GLshort, GLshort, GLshort, GLshort); GLAPI void APIENTRY glVertexAttrib4sv (GLuint, const GLshort *); GLAPI void APIENTRY glVertexAttrib4ubv (GLuint, const GLubyte *); GLAPI void APIENTRY glVertexAttrib4uiv (GLuint, const GLuint *); GLAPI void APIENTRY glVertexAttrib4usv (GLuint, const GLushort *); GLAPI void APIENTRY glVertexAttribPointer (GLuint, GLint, GLenum, GLboolean, GLsizei, const GLvoid *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEPROC) (GLenum modeRGB, GLenum modeAlpha); typedef void (APIENTRYP PFNGLDRAWBUFFERSPROC) (GLsizei n, const GLenum *bufs); typedef void (APIENTRYP PFNGLSTENCILOPSEPARATEPROC) (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass); typedef void (APIENTRYP PFNGLSTENCILFUNCSEPARATEPROC) (GLenum frontfunc, GLenum backfunc, GLint ref, GLuint mask); typedef void (APIENTRYP PFNGLSTENCILMASKSEPARATEPROC) (GLenum face, GLuint mask); typedef void (APIENTRYP PFNGLATTACHSHADERPROC) (GLuint program, GLuint shader); typedef void (APIENTRYP PFNGLBINDATTRIBLOCATIONPROC) (GLuint program, GLuint index, const GLchar *name); typedef void (APIENTRYP PFNGLCOMPILESHADERPROC) (GLuint shader); typedef GLuint (APIENTRYP PFNGLCREATEPROGRAMPROC) (void); typedef GLuint (APIENTRYP PFNGLCREATESHADERPROC) (GLenum type); typedef void (APIENTRYP PFNGLDELETEPROGRAMPROC) (GLuint program); typedef void (APIENTRYP PFNGLDELETESHADERPROC) (GLuint shader); typedef void (APIENTRYP PFNGLDETACHSHADERPROC) (GLuint program, GLuint shader); typedef void (APIENTRYP PFNGLDISABLEVERTEXATTRIBARRAYPROC) (GLuint index); typedef void (APIENTRYP PFNGLENABLEVERTEXATTRIBARRAYPROC) (GLuint index); typedef void (APIENTRYP PFNGLGETACTIVEATTRIBPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); typedef void (APIENTRYP PFNGLGETATTACHEDSHADERSPROC) (GLuint program, GLsizei maxCount, GLsizei *count, GLuint *obj); typedef GLint (APIENTRYP PFNGLGETATTRIBLOCATIONPROC) (GLuint program, const GLchar *name); typedef void (APIENTRYP PFNGLGETPROGRAMIVPROC) (GLuint program, GLenum pname, GLint *params); typedef void (APIENTRYP PFNGLGETPROGRAMINFOLOGPROC) (GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog); typedef void (APIENTRYP PFNGLGETSHADERIVPROC) (GLuint shader, GLenum pname, GLint *params); typedef void (APIENTRYP PFNGLGETSHADERINFOLOGPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog); typedef void (APIENTRYP PFNGLGETSHADERSOURCEPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *source); typedef GLint (APIENTRYP PFNGLGETUNIFORMLOCATIONPROC) (GLuint program, const GLchar *name); typedef void (APIENTRYP PFNGLGETUNIFORMFVPROC) (GLuint program, GLint location, GLfloat *params); typedef void (APIENTRYP PFNGLGETUNIFORMIVPROC) (GLuint program, GLint location, GLint *params); typedef void (APIENTRYP PFNGLGETVERTEXATTRIBDVPROC) (GLuint index, GLenum pname, GLdouble *params); typedef void (APIENTRYP PFNGLGETVERTEXATTRIBFVPROC) (GLuint index, GLenum pname, GLfloat *params); typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVPROC) (GLuint index, GLenum pname, GLint *params); typedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVPROC) (GLuint index, GLenum pname, GLvoid* *pointer); typedef GLboolean (APIENTRYP PFNGLISPROGRAMPROC) (GLuint program); typedef GLboolean (APIENTRYP PFNGLISSHADERPROC) (GLuint shader); typedef void (APIENTRYP PFNGLLINKPROGRAMPROC) (GLuint program); typedef void (APIENTRYP PFNGLSHADERSOURCEPROC) (GLuint shader, GLsizei count, const GLchar* *string, const GLint *length); typedef void (APIENTRYP PFNGLUSEPROGRAMPROC) (GLuint program); typedef void (APIENTRYP PFNGLUNIFORM1FPROC) (GLint location, GLfloat v0); typedef void (APIENTRYP PFNGLUNIFORM2FPROC) (GLint location, GLfloat v0, GLfloat v1); typedef void (APIENTRYP PFNGLUNIFORM3FPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2); typedef void (APIENTRYP PFNGLUNIFORM4FPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); typedef void (APIENTRYP PFNGLUNIFORM1IPROC) (GLint location, GLint v0); typedef void (APIENTRYP PFNGLUNIFORM2IPROC) (GLint location, GLint v0, GLint v1); typedef void (APIENTRYP PFNGLUNIFORM3IPROC) (GLint location, GLint v0, GLint v1, GLint v2); typedef void (APIENTRYP PFNGLUNIFORM4IPROC) (GLint location, GLint v0, GLint v1, GLint v2, GLint v3); typedef void (APIENTRYP PFNGLUNIFORM1FVPROC) (GLint location, GLsizei count, const GLfloat *value); typedef void (APIENTRYP PFNGLUNIFORM2FVPROC) (GLint location, GLsizei count, const GLfloat *value); typedef void (APIENTRYP PFNGLUNIFORM3FVPROC) (GLint location, GLsizei count, const GLfloat *value); typedef void (APIENTRYP PFNGLUNIFORM4FVPROC) (GLint location, GLsizei count, const GLfloat *value); typedef void (APIENTRYP PFNGLUNIFORM1IVPROC) (GLint location, GLsizei count, const GLint *value); typedef void (APIENTRYP PFNGLUNIFORM2IVPROC) (GLint location, GLsizei count, const GLint *value); typedef void (APIENTRYP PFNGLUNIFORM3IVPROC) (GLint location, GLsizei count, const GLint *value); typedef void (APIENTRYP PFNGLUNIFORM4IVPROC) (GLint location, GLsizei count, const GLint *value); typedef void (APIENTRYP PFNGLUNIFORMMATRIX2FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); typedef void (APIENTRYP PFNGLUNIFORMMATRIX3FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); typedef void (APIENTRYP PFNGLUNIFORMMATRIX4FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); typedef void (APIENTRYP PFNGLVALIDATEPROGRAMPROC) (GLuint program); typedef void (APIENTRYP PFNGLVERTEXATTRIB1DPROC) (GLuint index, GLdouble x); typedef void (APIENTRYP PFNGLVERTEXATTRIB1DVPROC) (GLuint index, const GLdouble *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB1FPROC) (GLuint index, GLfloat x); typedef void (APIENTRYP PFNGLVERTEXATTRIB1FVPROC) (GLuint index, const GLfloat *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB1SPROC) (GLuint index, GLshort x); typedef void (APIENTRYP PFNGLVERTEXATTRIB1SVPROC) (GLuint index, const GLshort *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB2DPROC) (GLuint index, GLdouble x, GLdouble y); typedef void (APIENTRYP PFNGLVERTEXATTRIB2DVPROC) (GLuint index, const GLdouble *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB2FPROC) (GLuint index, GLfloat x, GLfloat y); typedef void (APIENTRYP PFNGLVERTEXATTRIB2FVPROC) (GLuint index, const GLfloat *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB2SPROC) (GLuint index, GLshort x, GLshort y); typedef void (APIENTRYP PFNGLVERTEXATTRIB2SVPROC) (GLuint index, const GLshort *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB3DPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z); typedef void (APIENTRYP PFNGLVERTEXATTRIB3DVPROC) (GLuint index, const GLdouble *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB3FPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z); typedef void (APIENTRYP PFNGLVERTEXATTRIB3FVPROC) (GLuint index, const GLfloat *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB3SPROC) (GLuint index, GLshort x, GLshort y, GLshort z); typedef void (APIENTRYP PFNGLVERTEXATTRIB3SVPROC) (GLuint index, const GLshort *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB4NBVPROC) (GLuint index, const GLbyte *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB4NIVPROC) (GLuint index, const GLint *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB4NSVPROC) (GLuint index, const GLshort *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBPROC) (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w); typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBVPROC) (GLuint index, const GLubyte *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUIVPROC) (GLuint index, const GLuint *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUSVPROC) (GLuint index, const GLushort *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB4BVPROC) (GLuint index, const GLbyte *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB4DPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); typedef void (APIENTRYP PFNGLVERTEXATTRIB4DVPROC) (GLuint index, const GLdouble *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB4FPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); typedef void (APIENTRYP PFNGLVERTEXATTRIB4FVPROC) (GLuint index, const GLfloat *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB4IVPROC) (GLuint index, const GLint *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB4SPROC) (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w); typedef void (APIENTRYP PFNGLVERTEXATTRIB4SVPROC) (GLuint index, const GLshort *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB4UBVPROC) (GLuint index, const GLubyte *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB4UIVPROC) (GLuint index, const GLuint *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB4USVPROC) (GLuint index, const GLushort *v); typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *pointer); #endif #ifndef GL_ARB_multitexture #define GL_ARB_multitexture 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glActiveTextureARB (GLenum); GLAPI void APIENTRY glClientActiveTextureARB (GLenum); GLAPI void APIENTRY glMultiTexCoord1dARB (GLenum, GLdouble); GLAPI void APIENTRY glMultiTexCoord1dvARB (GLenum, const GLdouble *); GLAPI void APIENTRY glMultiTexCoord1fARB (GLenum, GLfloat); GLAPI void APIENTRY glMultiTexCoord1fvARB (GLenum, const GLfloat *); GLAPI void APIENTRY glMultiTexCoord1iARB (GLenum, GLint); GLAPI void APIENTRY glMultiTexCoord1ivARB (GLenum, const GLint *); GLAPI void APIENTRY glMultiTexCoord1sARB (GLenum, GLshort); GLAPI void APIENTRY glMultiTexCoord1svARB (GLenum, const GLshort *); GLAPI void APIENTRY glMultiTexCoord2dARB (GLenum, GLdouble, GLdouble); GLAPI void APIENTRY glMultiTexCoord2dvARB (GLenum, const GLdouble *); GLAPI void APIENTRY glMultiTexCoord2fARB (GLenum, GLfloat, GLfloat); GLAPI void APIENTRY glMultiTexCoord2fvARB (GLenum, const GLfloat *); GLAPI void APIENTRY glMultiTexCoord2iARB (GLenum, GLint, GLint); GLAPI void APIENTRY glMultiTexCoord2ivARB (GLenum, const GLint *); GLAPI void APIENTRY glMultiTexCoord2sARB (GLenum, GLshort, GLshort); GLAPI void APIENTRY glMultiTexCoord2svARB (GLenum, const GLshort *); GLAPI void APIENTRY glMultiTexCoord3dARB (GLenum, GLdouble, GLdouble, GLdouble); GLAPI void APIENTRY glMultiTexCoord3dvARB (GLenum, const GLdouble *); GLAPI void APIENTRY glMultiTexCoord3fARB (GLenum, GLfloat, GLfloat, GLfloat); GLAPI void APIENTRY glMultiTexCoord3fvARB (GLenum, const GLfloat *); GLAPI void APIENTRY glMultiTexCoord3iARB (GLenum, GLint, GLint, GLint); GLAPI void APIENTRY glMultiTexCoord3ivARB (GLenum, const GLint *); GLAPI void APIENTRY glMultiTexCoord3sARB (GLenum, GLshort, GLshort, GLshort); GLAPI void APIENTRY glMultiTexCoord3svARB (GLenum, const GLshort *); GLAPI void APIENTRY glMultiTexCoord4dARB (GLenum, GLdouble, GLdouble, GLdouble, GLdouble); GLAPI void APIENTRY glMultiTexCoord4dvARB (GLenum, const GLdouble *); GLAPI void APIENTRY glMultiTexCoord4fARB (GLenum, GLfloat, GLfloat, GLfloat, GLfloat); GLAPI void APIENTRY glMultiTexCoord4fvARB (GLenum, const GLfloat *); GLAPI void APIENTRY glMultiTexCoord4iARB (GLenum, GLint, GLint, GLint, GLint); GLAPI void APIENTRY glMultiTexCoord4ivARB (GLenum, const GLint *); GLAPI void APIENTRY glMultiTexCoord4sARB (GLenum, GLshort, GLshort, GLshort, GLshort); GLAPI void APIENTRY glMultiTexCoord4svARB (GLenum, const GLshort *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLACTIVETEXTUREARBPROC) (GLenum texture); typedef void (APIENTRYP PFNGLCLIENTACTIVETEXTUREARBPROC) (GLenum texture); typedef void (APIENTRYP PFNGLMULTITEXCOORD1DARBPROC) (GLenum target, GLdouble s); typedef void (APIENTRYP PFNGLMULTITEXCOORD1DVARBPROC) (GLenum target, const GLdouble *v); typedef void (APIENTRYP PFNGLMULTITEXCOORD1FARBPROC) (GLenum target, GLfloat s); typedef void (APIENTRYP PFNGLMULTITEXCOORD1FVARBPROC) (GLenum target, const GLfloat *v); typedef void (APIENTRYP PFNGLMULTITEXCOORD1IARBPROC) (GLenum target, GLint s); typedef void (APIENTRYP PFNGLMULTITEXCOORD1IVARBPROC) (GLenum target, const GLint *v); typedef void (APIENTRYP PFNGLMULTITEXCOORD1SARBPROC) (GLenum target, GLshort s); typedef void (APIENTRYP PFNGLMULTITEXCOORD1SVARBPROC) (GLenum target, const GLshort *v); typedef void (APIENTRYP PFNGLMULTITEXCOORD2DARBPROC) (GLenum target, GLdouble s, GLdouble t); typedef void (APIENTRYP PFNGLMULTITEXCOORD2DVARBPROC) (GLenum target, const GLdouble *v); typedef void (APIENTRYP PFNGLMULTITEXCOORD2FARBPROC) (GLenum target, GLfloat s, GLfloat t); typedef void (APIENTRYP PFNGLMULTITEXCOORD2FVARBPROC) (GLenum target, const GLfloat *v); typedef void (APIENTRYP PFNGLMULTITEXCOORD2IARBPROC) (GLenum target, GLint s, GLint t); typedef void (APIENTRYP PFNGLMULTITEXCOORD2IVARBPROC) (GLenum target, const GLint *v); typedef void (APIENTRYP PFNGLMULTITEXCOORD2SARBPROC) (GLenum target, GLshort s, GLshort t); typedef void (APIENTRYP PFNGLMULTITEXCOORD2SVARBPROC) (GLenum target, const GLshort *v); typedef void (APIENTRYP PFNGLMULTITEXCOORD3DARBPROC) (GLenum target, GLdouble s, GLdouble t, GLdouble r); typedef void (APIENTRYP PFNGLMULTITEXCOORD3DVARBPROC) (GLenum target, const GLdouble *v); typedef void (APIENTRYP PFNGLMULTITEXCOORD3FARBPROC) (GLenum target, GLfloat s, GLfloat t, GLfloat r); typedef void (APIENTRYP PFNGLMULTITEXCOORD3FVARBPROC) (GLenum target, const GLfloat *v); typedef void (APIENTRYP PFNGLMULTITEXCOORD3IARBPROC) (GLenum target, GLint s, GLint t, GLint r); typedef void (APIENTRYP PFNGLMULTITEXCOORD3IVARBPROC) (GLenum target, const GLint *v); typedef void (APIENTRYP PFNGLMULTITEXCOORD3SARBPROC) (GLenum target, GLshort s, GLshort t, GLshort r); typedef void (APIENTRYP PFNGLMULTITEXCOORD3SVARBPROC) (GLenum target, const GLshort *v); typedef void (APIENTRYP PFNGLMULTITEXCOORD4DARBPROC) (GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q); typedef void (APIENTRYP PFNGLMULTITEXCOORD4DVARBPROC) (GLenum target, const GLdouble *v); typedef void (APIENTRYP PFNGLMULTITEXCOORD4FARBPROC) (GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q); typedef void (APIENTRYP PFNGLMULTITEXCOORD4FVARBPROC) (GLenum target, const GLfloat *v); typedef void (APIENTRYP PFNGLMULTITEXCOORD4IARBPROC) (GLenum target, GLint s, GLint t, GLint r, GLint q); typedef void (APIENTRYP PFNGLMULTITEXCOORD4IVARBPROC) (GLenum target, const GLint *v); typedef void (APIENTRYP PFNGLMULTITEXCOORD4SARBPROC) (GLenum target, GLshort s, GLshort t, GLshort r, GLshort q); typedef void (APIENTRYP PFNGLMULTITEXCOORD4SVARBPROC) (GLenum target, const GLshort *v); #endif #ifndef GL_ARB_transpose_matrix #define GL_ARB_transpose_matrix 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glLoadTransposeMatrixfARB (const GLfloat *); GLAPI void APIENTRY glLoadTransposeMatrixdARB (const GLdouble *); GLAPI void APIENTRY glMultTransposeMatrixfARB (const GLfloat *); GLAPI void APIENTRY glMultTransposeMatrixdARB (const GLdouble *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXFARBPROC) (const GLfloat *m); typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXDARBPROC) (const GLdouble *m); typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXFARBPROC) (const GLfloat *m); typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXDARBPROC) (const GLdouble *m); #endif #ifndef GL_ARB_multisample #define GL_ARB_multisample 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glSampleCoverageARB (GLclampf, GLboolean); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLSAMPLECOVERAGEARBPROC) (GLclampf value, GLboolean invert); #endif #ifndef GL_ARB_texture_env_add #define GL_ARB_texture_env_add 1 #endif #ifndef GL_ARB_texture_cube_map #define GL_ARB_texture_cube_map 1 #endif #ifndef GL_ARB_texture_compression #define GL_ARB_texture_compression 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glCompressedTexImage3DARB (GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLsizei, const GLvoid *); GLAPI void APIENTRY glCompressedTexImage2DARB (GLenum, GLint, GLenum, GLsizei, GLsizei, GLint, GLsizei, const GLvoid *); GLAPI void APIENTRY glCompressedTexImage1DARB (GLenum, GLint, GLenum, GLsizei, GLint, GLsizei, const GLvoid *); GLAPI void APIENTRY glCompressedTexSubImage3DARB (GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid *); GLAPI void APIENTRY glCompressedTexSubImage2DARB (GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid *); GLAPI void APIENTRY glCompressedTexSubImage1DARB (GLenum, GLint, GLint, GLsizei, GLenum, GLsizei, const GLvoid *); GLAPI void APIENTRY glGetCompressedTexImageARB (GLenum, GLint, GLvoid *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE3DARBPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid *data); typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE2DARBPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *data); typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE1DARBPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const GLvoid *data); typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE3DARBPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid *data); typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE2DARBPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *data); typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE1DARBPROC) (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const GLvoid *data); typedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXIMAGEARBPROC) (GLenum target, GLint level, GLvoid *img); #endif #ifndef GL_ARB_texture_border_clamp #define GL_ARB_texture_border_clamp 1 #endif #ifndef GL_ARB_point_parameters #define GL_ARB_point_parameters 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glPointParameterfARB (GLenum, GLfloat); GLAPI void APIENTRY glPointParameterfvARB (GLenum, const GLfloat *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLPOINTPARAMETERFARBPROC) (GLenum pname, GLfloat param); typedef void (APIENTRYP PFNGLPOINTPARAMETERFVARBPROC) (GLenum pname, const GLfloat *params); #endif #ifndef GL_ARB_vertex_blend #define GL_ARB_vertex_blend 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glWeightbvARB (GLint, const GLbyte *); GLAPI void APIENTRY glWeightsvARB (GLint, const GLshort *); GLAPI void APIENTRY glWeightivARB (GLint, const GLint *); GLAPI void APIENTRY glWeightfvARB (GLint, const GLfloat *); GLAPI void APIENTRY glWeightdvARB (GLint, const GLdouble *); GLAPI void APIENTRY glWeightubvARB (GLint, const GLubyte *); GLAPI void APIENTRY glWeightusvARB (GLint, const GLushort *); GLAPI void APIENTRY glWeightuivARB (GLint, const GLuint *); GLAPI void APIENTRY glWeightPointerARB (GLint, GLenum, GLsizei, const GLvoid *); GLAPI void APIENTRY glVertexBlendARB (GLint); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLWEIGHTBVARBPROC) (GLint size, const GLbyte *weights); typedef void (APIENTRYP PFNGLWEIGHTSVARBPROC) (GLint size, const GLshort *weights); typedef void (APIENTRYP PFNGLWEIGHTIVARBPROC) (GLint size, const GLint *weights); typedef void (APIENTRYP PFNGLWEIGHTFVARBPROC) (GLint size, const GLfloat *weights); typedef void (APIENTRYP PFNGLWEIGHTDVARBPROC) (GLint size, const GLdouble *weights); typedef void (APIENTRYP PFNGLWEIGHTUBVARBPROC) (GLint size, const GLubyte *weights); typedef void (APIENTRYP PFNGLWEIGHTUSVARBPROC) (GLint size, const GLushort *weights); typedef void (APIENTRYP PFNGLWEIGHTUIVARBPROC) (GLint size, const GLuint *weights); typedef void (APIENTRYP PFNGLWEIGHTPOINTERARBPROC) (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer); typedef void (APIENTRYP PFNGLVERTEXBLENDARBPROC) (GLint count); #endif #ifndef GL_ARB_matrix_palette #define GL_ARB_matrix_palette 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glCurrentPaletteMatrixARB (GLint); GLAPI void APIENTRY glMatrixIndexubvARB (GLint, const GLubyte *); GLAPI void APIENTRY glMatrixIndexusvARB (GLint, const GLushort *); GLAPI void APIENTRY glMatrixIndexuivARB (GLint, const GLuint *); GLAPI void APIENTRY glMatrixIndexPointerARB (GLint, GLenum, GLsizei, const GLvoid *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLCURRENTPALETTEMATRIXARBPROC) (GLint index); typedef void (APIENTRYP PFNGLMATRIXINDEXUBVARBPROC) (GLint size, const GLubyte *indices); typedef void (APIENTRYP PFNGLMATRIXINDEXUSVARBPROC) (GLint size, const GLushort *indices); typedef void (APIENTRYP PFNGLMATRIXINDEXUIVARBPROC) (GLint size, const GLuint *indices); typedef void (APIENTRYP PFNGLMATRIXINDEXPOINTERARBPROC) (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer); #endif #ifndef GL_ARB_texture_env_combine #define GL_ARB_texture_env_combine 1 #endif #ifndef GL_ARB_texture_env_crossbar #define GL_ARB_texture_env_crossbar 1 #endif #ifndef GL_ARB_texture_env_dot3 #define GL_ARB_texture_env_dot3 1 #endif #ifndef GL_ARB_texture_mirrored_repeat #define GL_ARB_texture_mirrored_repeat 1 #endif #ifndef GL_ARB_depth_texture #define GL_ARB_depth_texture 1 #endif #ifndef GL_ARB_shadow #define GL_ARB_shadow 1 #endif #ifndef GL_ARB_shadow_ambient #define GL_ARB_shadow_ambient 1 #endif #ifndef GL_ARB_window_pos #define GL_ARB_window_pos 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glWindowPos2dARB (GLdouble, GLdouble); GLAPI void APIENTRY glWindowPos2dvARB (const GLdouble *); GLAPI void APIENTRY glWindowPos2fARB (GLfloat, GLfloat); GLAPI void APIENTRY glWindowPos2fvARB (const GLfloat *); GLAPI void APIENTRY glWindowPos2iARB (GLint, GLint); GLAPI void APIENTRY glWindowPos2ivARB (const GLint *); GLAPI void APIENTRY glWindowPos2sARB (GLshort, GLshort); GLAPI void APIENTRY glWindowPos2svARB (const GLshort *); GLAPI void APIENTRY glWindowPos3dARB (GLdouble, GLdouble, GLdouble); GLAPI void APIENTRY glWindowPos3dvARB (const GLdouble *); GLAPI void APIENTRY glWindowPos3fARB (GLfloat, GLfloat, GLfloat); GLAPI void APIENTRY glWindowPos3fvARB (const GLfloat *); GLAPI void APIENTRY glWindowPos3iARB (GLint, GLint, GLint); GLAPI void APIENTRY glWindowPos3ivARB (const GLint *); GLAPI void APIENTRY glWindowPos3sARB (GLshort, GLshort, GLshort); GLAPI void APIENTRY glWindowPos3svARB (const GLshort *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLWINDOWPOS2DARBPROC) (GLdouble x, GLdouble y); typedef void (APIENTRYP PFNGLWINDOWPOS2DVARBPROC) (const GLdouble *v); typedef void (APIENTRYP PFNGLWINDOWPOS2FARBPROC) (GLfloat x, GLfloat y); typedef void (APIENTRYP PFNGLWINDOWPOS2FVARBPROC) (const GLfloat *v); typedef void (APIENTRYP PFNGLWINDOWPOS2IARBPROC) (GLint x, GLint y); typedef void (APIENTRYP PFNGLWINDOWPOS2IVARBPROC) (const GLint *v); typedef void (APIENTRYP PFNGLWINDOWPOS2SARBPROC) (GLshort x, GLshort y); typedef void (APIENTRYP PFNGLWINDOWPOS2SVARBPROC) (const GLshort *v); typedef void (APIENTRYP PFNGLWINDOWPOS3DARBPROC) (GLdouble x, GLdouble y, GLdouble z); typedef void (APIENTRYP PFNGLWINDOWPOS3DVARBPROC) (const GLdouble *v); typedef void (APIENTRYP PFNGLWINDOWPOS3FARBPROC) (GLfloat x, GLfloat y, GLfloat z); typedef void (APIENTRYP PFNGLWINDOWPOS3FVARBPROC) (const GLfloat *v); typedef void (APIENTRYP PFNGLWINDOWPOS3IARBPROC) (GLint x, GLint y, GLint z); typedef void (APIENTRYP PFNGLWINDOWPOS3IVARBPROC) (const GLint *v); typedef void (APIENTRYP PFNGLWINDOWPOS3SARBPROC) (GLshort x, GLshort y, GLshort z); typedef void (APIENTRYP PFNGLWINDOWPOS3SVARBPROC) (const GLshort *v); #endif #ifndef GL_ARB_vertex_program #define GL_ARB_vertex_program 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glVertexAttrib1dARB (GLuint, GLdouble); GLAPI void APIENTRY glVertexAttrib1dvARB (GLuint, const GLdouble *); GLAPI void APIENTRY glVertexAttrib1fARB (GLuint, GLfloat); GLAPI void APIENTRY glVertexAttrib1fvARB (GLuint, const GLfloat *); GLAPI void APIENTRY glVertexAttrib1sARB (GLuint, GLshort); GLAPI void APIENTRY glVertexAttrib1svARB (GLuint, const GLshort *); GLAPI void APIENTRY glVertexAttrib2dARB (GLuint, GLdouble, GLdouble); GLAPI void APIENTRY glVertexAttrib2dvARB (GLuint, const GLdouble *); GLAPI void APIENTRY glVertexAttrib2fARB (GLuint, GLfloat, GLfloat); GLAPI void APIENTRY glVertexAttrib2fvARB (GLuint, const GLfloat *); GLAPI void APIENTRY glVertexAttrib2sARB (GLuint, GLshort, GLshort); GLAPI void APIENTRY glVertexAttrib2svARB (GLuint, const GLshort *); GLAPI void APIENTRY glVertexAttrib3dARB (GLuint, GLdouble, GLdouble, GLdouble); GLAPI void APIENTRY glVertexAttrib3dvARB (GLuint, const GLdouble *); GLAPI void APIENTRY glVertexAttrib3fARB (GLuint, GLfloat, GLfloat, GLfloat); GLAPI void APIENTRY glVertexAttrib3fvARB (GLuint, const GLfloat *); GLAPI void APIENTRY glVertexAttrib3sARB (GLuint, GLshort, GLshort, GLshort); GLAPI void APIENTRY glVertexAttrib3svARB (GLuint, const GLshort *); GLAPI void APIENTRY glVertexAttrib4NbvARB (GLuint, const GLbyte *); GLAPI void APIENTRY glVertexAttrib4NivARB (GLuint, const GLint *); GLAPI void APIENTRY glVertexAttrib4NsvARB (GLuint, const GLshort *); GLAPI void APIENTRY glVertexAttrib4NubARB (GLuint, GLubyte, GLubyte, GLubyte, GLubyte); GLAPI void APIENTRY glVertexAttrib4NubvARB (GLuint, const GLubyte *); GLAPI void APIENTRY glVertexAttrib4NuivARB (GLuint, const GLuint *); GLAPI void APIENTRY glVertexAttrib4NusvARB (GLuint, const GLushort *); GLAPI void APIENTRY glVertexAttrib4bvARB (GLuint, const GLbyte *); GLAPI void APIENTRY glVertexAttrib4dARB (GLuint, GLdouble, GLdouble, GLdouble, GLdouble); GLAPI void APIENTRY glVertexAttrib4dvARB (GLuint, const GLdouble *); GLAPI void APIENTRY glVertexAttrib4fARB (GLuint, GLfloat, GLfloat, GLfloat, GLfloat); GLAPI void APIENTRY glVertexAttrib4fvARB (GLuint, const GLfloat *); GLAPI void APIENTRY glVertexAttrib4ivARB (GLuint, const GLint *); GLAPI void APIENTRY glVertexAttrib4sARB (GLuint, GLshort, GLshort, GLshort, GLshort); GLAPI void APIENTRY glVertexAttrib4svARB (GLuint, const GLshort *); GLAPI void APIENTRY glVertexAttrib4ubvARB (GLuint, const GLubyte *); GLAPI void APIENTRY glVertexAttrib4uivARB (GLuint, const GLuint *); GLAPI void APIENTRY glVertexAttrib4usvARB (GLuint, const GLushort *); GLAPI void APIENTRY glVertexAttribPointerARB (GLuint, GLint, GLenum, GLboolean, GLsizei, const GLvoid *); GLAPI void APIENTRY glEnableVertexAttribArrayARB (GLuint); GLAPI void APIENTRY glDisableVertexAttribArrayARB (GLuint); GLAPI void APIENTRY glProgramStringARB (GLenum, GLenum, GLsizei, const GLvoid *); GLAPI void APIENTRY glBindProgramARB (GLenum, GLuint); GLAPI void APIENTRY glDeleteProgramsARB (GLsizei, const GLuint *); GLAPI void APIENTRY glGenProgramsARB (GLsizei, GLuint *); GLAPI void APIENTRY glProgramEnvParameter4dARB (GLenum, GLuint, GLdouble, GLdouble, GLdouble, GLdouble); GLAPI void APIENTRY glProgramEnvParameter4dvARB (GLenum, GLuint, const GLdouble *); GLAPI void APIENTRY glProgramEnvParameter4fARB (GLenum, GLuint, GLfloat, GLfloat, GLfloat, GLfloat); GLAPI void APIENTRY glProgramEnvParameter4fvARB (GLenum, GLuint, const GLfloat *); GLAPI void APIENTRY glProgramLocalParameter4dARB (GLenum, GLuint, GLdouble, GLdouble, GLdouble, GLdouble); GLAPI void APIENTRY glProgramLocalParameter4dvARB (GLenum, GLuint, const GLdouble *); GLAPI void APIENTRY glProgramLocalParameter4fARB (GLenum, GLuint, GLfloat, GLfloat, GLfloat, GLfloat); GLAPI void APIENTRY glProgramLocalParameter4fvARB (GLenum, GLuint, const GLfloat *); GLAPI void APIENTRY glGetProgramEnvParameterdvARB (GLenum, GLuint, GLdouble *); GLAPI void APIENTRY glGetProgramEnvParameterfvARB (GLenum, GLuint, GLfloat *); GLAPI void APIENTRY glGetProgramLocalParameterdvARB (GLenum, GLuint, GLdouble *); GLAPI void APIENTRY glGetProgramLocalParameterfvARB (GLenum, GLuint, GLfloat *); GLAPI void APIENTRY glGetProgramivARB (GLenum, GLenum, GLint *); GLAPI void APIENTRY glGetProgramStringARB (GLenum, GLenum, GLvoid *); GLAPI void APIENTRY glGetVertexAttribdvARB (GLuint, GLenum, GLdouble *); GLAPI void APIENTRY glGetVertexAttribfvARB (GLuint, GLenum, GLfloat *); GLAPI void APIENTRY glGetVertexAttribivARB (GLuint, GLenum, GLint *); GLAPI void APIENTRY glGetVertexAttribPointervARB (GLuint, GLenum, GLvoid* *); GLAPI GLboolean APIENTRY glIsProgramARB (GLuint); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLVERTEXATTRIB1DARBPROC) (GLuint index, GLdouble x); typedef void (APIENTRYP PFNGLVERTEXATTRIB1DVARBPROC) (GLuint index, const GLdouble *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB1FARBPROC) (GLuint index, GLfloat x); typedef void (APIENTRYP PFNGLVERTEXATTRIB1FVARBPROC) (GLuint index, const GLfloat *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB1SARBPROC) (GLuint index, GLshort x); typedef void (APIENTRYP PFNGLVERTEXATTRIB1SVARBPROC) (GLuint index, const GLshort *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB2DARBPROC) (GLuint index, GLdouble x, GLdouble y); typedef void (APIENTRYP PFNGLVERTEXATTRIB2DVARBPROC) (GLuint index, const GLdouble *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB2FARBPROC) (GLuint index, GLfloat x, GLfloat y); typedef void (APIENTRYP PFNGLVERTEXATTRIB2FVARBPROC) (GLuint index, const GLfloat *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB2SARBPROC) (GLuint index, GLshort x, GLshort y); typedef void (APIENTRYP PFNGLVERTEXATTRIB2SVARBPROC) (GLuint index, const GLshort *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB3DARBPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z); typedef void (APIENTRYP PFNGLVERTEXATTRIB3DVARBPROC) (GLuint index, const GLdouble *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB3FARBPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z); typedef void (APIENTRYP PFNGLVERTEXATTRIB3FVARBPROC) (GLuint index, const GLfloat *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB3SARBPROC) (GLuint index, GLshort x, GLshort y, GLshort z); typedef void (APIENTRYP PFNGLVERTEXATTRIB3SVARBPROC) (GLuint index, const GLshort *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB4NBVARBPROC) (GLuint index, const GLbyte *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB4NIVARBPROC) (GLuint index, const GLint *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB4NSVARBPROC) (GLuint index, const GLshort *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBARBPROC) (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w); typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBVARBPROC) (GLuint index, const GLubyte *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUIVARBPROC) (GLuint index, const GLuint *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUSVARBPROC) (GLuint index, const GLushort *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB4BVARBPROC) (GLuint index, const GLbyte *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB4DARBPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); typedef void (APIENTRYP PFNGLVERTEXATTRIB4DVARBPROC) (GLuint index, const GLdouble *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB4FARBPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); typedef void (APIENTRYP PFNGLVERTEXATTRIB4FVARBPROC) (GLuint index, const GLfloat *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB4IVARBPROC) (GLuint index, const GLint *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB4SARBPROC) (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w); typedef void (APIENTRYP PFNGLVERTEXATTRIB4SVARBPROC) (GLuint index, const GLshort *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB4UBVARBPROC) (GLuint index, const GLubyte *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB4UIVARBPROC) (GLuint index, const GLuint *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB4USVARBPROC) (GLuint index, const GLushort *v); typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERARBPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *pointer); typedef void (APIENTRYP PFNGLENABLEVERTEXATTRIBARRAYARBPROC) (GLuint index); typedef void (APIENTRYP PFNGLDISABLEVERTEXATTRIBARRAYARBPROC) (GLuint index); typedef void (APIENTRYP PFNGLPROGRAMSTRINGARBPROC) (GLenum target, GLenum format, GLsizei len, const GLvoid *string); typedef void (APIENTRYP PFNGLBINDPROGRAMARBPROC) (GLenum target, GLuint program); typedef void (APIENTRYP PFNGLDELETEPROGRAMSARBPROC) (GLsizei n, const GLuint *programs); typedef void (APIENTRYP PFNGLGENPROGRAMSARBPROC) (GLsizei n, GLuint *programs); typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETER4DARBPROC) (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETER4DVARBPROC) (GLenum target, GLuint index, const GLdouble *params); typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETER4FARBPROC) (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETER4FVARBPROC) (GLenum target, GLuint index, const GLfloat *params); typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETER4DARBPROC) (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETER4DVARBPROC) (GLenum target, GLuint index, const GLdouble *params); typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETER4FARBPROC) (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETER4FVARBPROC) (GLenum target, GLuint index, const GLfloat *params); typedef void (APIENTRYP PFNGLGETPROGRAMENVPARAMETERDVARBPROC) (GLenum target, GLuint index, GLdouble *params); typedef void (APIENTRYP PFNGLGETPROGRAMENVPARAMETERFVARBPROC) (GLenum target, GLuint index, GLfloat *params); typedef void (APIENTRYP PFNGLGETPROGRAMLOCALPARAMETERDVARBPROC) (GLenum target, GLuint index, GLdouble *params); typedef void (APIENTRYP PFNGLGETPROGRAMLOCALPARAMETERFVARBPROC) (GLenum target, GLuint index, GLfloat *params); typedef void (APIENTRYP PFNGLGETPROGRAMIVARBPROC) (GLenum target, GLenum pname, GLint *params); typedef void (APIENTRYP PFNGLGETPROGRAMSTRINGARBPROC) (GLenum target, GLenum pname, GLvoid *string); typedef void (APIENTRYP PFNGLGETVERTEXATTRIBDVARBPROC) (GLuint index, GLenum pname, GLdouble *params); typedef void (APIENTRYP PFNGLGETVERTEXATTRIBFVARBPROC) (GLuint index, GLenum pname, GLfloat *params); typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVARBPROC) (GLuint index, GLenum pname, GLint *params); typedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVARBPROC) (GLuint index, GLenum pname, GLvoid* *pointer); typedef GLboolean (APIENTRYP PFNGLISPROGRAMARBPROC) (GLuint program); #endif #ifndef GL_ARB_fragment_program #define GL_ARB_fragment_program 1 /* All ARB_fragment_program entry points are shared with ARB_vertex_program. */ #endif #ifndef GL_ARB_vertex_buffer_object #define GL_ARB_vertex_buffer_object 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glBindBufferARB (GLenum, GLuint); GLAPI void APIENTRY glDeleteBuffersARB (GLsizei, const GLuint *); GLAPI void APIENTRY glGenBuffersARB (GLsizei, GLuint *); GLAPI GLboolean APIENTRY glIsBufferARB (GLuint); GLAPI void APIENTRY glBufferDataARB (GLenum, GLsizeiptrARB, const GLvoid *, GLenum); GLAPI void APIENTRY glBufferSubDataARB (GLenum, GLintptrARB, GLsizeiptrARB, const GLvoid *); GLAPI void APIENTRY glGetBufferSubDataARB (GLenum, GLintptrARB, GLsizeiptrARB, GLvoid *); GLAPI GLvoid* APIENTRY glMapBufferARB (GLenum, GLenum); GLAPI GLboolean APIENTRY glUnmapBufferARB (GLenum); GLAPI void APIENTRY glGetBufferParameterivARB (GLenum, GLenum, GLint *); GLAPI void APIENTRY glGetBufferPointervARB (GLenum, GLenum, GLvoid* *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLBINDBUFFERARBPROC) (GLenum target, GLuint buffer); typedef void (APIENTRYP PFNGLDELETEBUFFERSARBPROC) (GLsizei n, const GLuint *buffers); typedef void (APIENTRYP PFNGLGENBUFFERSARBPROC) (GLsizei n, GLuint *buffers); typedef GLboolean (APIENTRYP PFNGLISBUFFERARBPROC) (GLuint buffer); typedef void (APIENTRYP PFNGLBUFFERDATAARBPROC) (GLenum target, GLsizeiptrARB size, const GLvoid *data, GLenum usage); typedef void (APIENTRYP PFNGLBUFFERSUBDATAARBPROC) (GLenum target, GLintptrARB offset, GLsizeiptrARB size, const GLvoid *data); typedef void (APIENTRYP PFNGLGETBUFFERSUBDATAARBPROC) (GLenum target, GLintptrARB offset, GLsizeiptrARB size, GLvoid *data); typedef GLvoid* (APIENTRYP PFNGLMAPBUFFERARBPROC) (GLenum target, GLenum access); typedef GLboolean (APIENTRYP PFNGLUNMAPBUFFERARBPROC) (GLenum target); typedef void (APIENTRYP PFNGLGETBUFFERPARAMETERIVARBPROC) (GLenum target, GLenum pname, GLint *params); typedef void (APIENTRYP PFNGLGETBUFFERPOINTERVARBPROC) (GLenum target, GLenum pname, GLvoid* *params); #endif #ifndef GL_ARB_occlusion_query #define GL_ARB_occlusion_query 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glGenQueriesARB (GLsizei, GLuint *); GLAPI void APIENTRY glDeleteQueriesARB (GLsizei, const GLuint *); GLAPI GLboolean APIENTRY glIsQueryARB (GLuint); GLAPI void APIENTRY glBeginQueryARB (GLenum, GLuint); GLAPI void APIENTRY glEndQueryARB (GLenum); GLAPI void APIENTRY glGetQueryivARB (GLenum, GLenum, GLint *); GLAPI void APIENTRY glGetQueryObjectivARB (GLuint, GLenum, GLint *); GLAPI void APIENTRY glGetQueryObjectuivARB (GLuint, GLenum, GLuint *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLGENQUERIESARBPROC) (GLsizei n, GLuint *ids); typedef void (APIENTRYP PFNGLDELETEQUERIESARBPROC) (GLsizei n, const GLuint *ids); typedef GLboolean (APIENTRYP PFNGLISQUERYARBPROC) (GLuint id); typedef void (APIENTRYP PFNGLBEGINQUERYARBPROC) (GLenum target, GLuint id); typedef void (APIENTRYP PFNGLENDQUERYARBPROC) (GLenum target); typedef void (APIENTRYP PFNGLGETQUERYIVARBPROC) (GLenum target, GLenum pname, GLint *params); typedef void (APIENTRYP PFNGLGETQUERYOBJECTIVARBPROC) (GLuint id, GLenum pname, GLint *params); typedef void (APIENTRYP PFNGLGETQUERYOBJECTUIVARBPROC) (GLuint id, GLenum pname, GLuint *params); #endif #ifndef GL_ARB_shader_objects #define GL_ARB_shader_objects 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glDeleteObjectARB (GLhandleARB); GLAPI GLhandleARB APIENTRY glGetHandleARB (GLenum); GLAPI void APIENTRY glDetachObjectARB (GLhandleARB, GLhandleARB); GLAPI GLhandleARB APIENTRY glCreateShaderObjectARB (GLenum); GLAPI void APIENTRY glShaderSourceARB (GLhandleARB, GLsizei, const GLcharARB* *, const GLint *); GLAPI void APIENTRY glCompileShaderARB (GLhandleARB); GLAPI GLhandleARB APIENTRY glCreateProgramObjectARB (void); GLAPI void APIENTRY glAttachObjectARB (GLhandleARB, GLhandleARB); GLAPI void APIENTRY glLinkProgramARB (GLhandleARB); GLAPI void APIENTRY glUseProgramObjectARB (GLhandleARB); GLAPI void APIENTRY glValidateProgramARB (GLhandleARB); GLAPI void APIENTRY glUniform1fARB (GLint, GLfloat); GLAPI void APIENTRY glUniform2fARB (GLint, GLfloat, GLfloat); GLAPI void APIENTRY glUniform3fARB (GLint, GLfloat, GLfloat, GLfloat); GLAPI void APIENTRY glUniform4fARB (GLint, GLfloat, GLfloat, GLfloat, GLfloat); GLAPI void APIENTRY glUniform1iARB (GLint, GLint); GLAPI void APIENTRY glUniform2iARB (GLint, GLint, GLint); GLAPI void APIENTRY glUniform3iARB (GLint, GLint, GLint, GLint); GLAPI void APIENTRY glUniform4iARB (GLint, GLint, GLint, GLint, GLint); GLAPI void APIENTRY glUniform1fvARB (GLint, GLsizei, const GLfloat *); GLAPI void APIENTRY glUniform2fvARB (GLint, GLsizei, const GLfloat *); GLAPI void APIENTRY glUniform3fvARB (GLint, GLsizei, const GLfloat *); GLAPI void APIENTRY glUniform4fvARB (GLint, GLsizei, const GLfloat *); GLAPI void APIENTRY glUniform1ivARB (GLint, GLsizei, const GLint *); GLAPI void APIENTRY glUniform2ivARB (GLint, GLsizei, const GLint *); GLAPI void APIENTRY glUniform3ivARB (GLint, GLsizei, const GLint *); GLAPI void APIENTRY glUniform4ivARB (GLint, GLsizei, const GLint *); GLAPI void APIENTRY glUniformMatrix2fvARB (GLint, GLsizei, GLboolean, const GLfloat *); GLAPI void APIENTRY glUniformMatrix3fvARB (GLint, GLsizei, GLboolean, const GLfloat *); GLAPI void APIENTRY glUniformMatrix4fvARB (GLint, GLsizei, GLboolean, const GLfloat *); GLAPI void APIENTRY glGetObjectParameterfvARB (GLhandleARB, GLenum, GLfloat *); GLAPI void APIENTRY glGetObjectParameterivARB (GLhandleARB, GLenum, GLint *); GLAPI void APIENTRY glGetInfoLogARB (GLhandleARB, GLsizei, GLsizei *, GLcharARB *); GLAPI void APIENTRY glGetAttachedObjectsARB (GLhandleARB, GLsizei, GLsizei *, GLhandleARB *); GLAPI GLint APIENTRY glGetUniformLocationARB (GLhandleARB, const GLcharARB *); GLAPI void APIENTRY glGetActiveUniformARB (GLhandleARB, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLcharARB *); GLAPI void APIENTRY glGetUniformfvARB (GLhandleARB, GLint, GLfloat *); GLAPI void APIENTRY glGetUniformivARB (GLhandleARB, GLint, GLint *); GLAPI void APIENTRY glGetShaderSourceARB (GLhandleARB, GLsizei, GLsizei *, GLcharARB *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLDELETEOBJECTARBPROC) (GLhandleARB obj); typedef GLhandleARB (APIENTRYP PFNGLGETHANDLEARBPROC) (GLenum pname); typedef void (APIENTRYP PFNGLDETACHOBJECTARBPROC) (GLhandleARB containerObj, GLhandleARB attachedObj); typedef GLhandleARB (APIENTRYP PFNGLCREATESHADEROBJECTARBPROC) (GLenum shaderType); typedef void (APIENTRYP PFNGLSHADERSOURCEARBPROC) (GLhandleARB shaderObj, GLsizei count, const GLcharARB* *string, const GLint *length); typedef void (APIENTRYP PFNGLCOMPILESHADERARBPROC) (GLhandleARB shaderObj); typedef GLhandleARB (APIENTRYP PFNGLCREATEPROGRAMOBJECTARBPROC) (void); typedef void (APIENTRYP PFNGLATTACHOBJECTARBPROC) (GLhandleARB containerObj, GLhandleARB obj); typedef void (APIENTRYP PFNGLLINKPROGRAMARBPROC) (GLhandleARB programObj); typedef void (APIENTRYP PFNGLUSEPROGRAMOBJECTARBPROC) (GLhandleARB programObj); typedef void (APIENTRYP PFNGLVALIDATEPROGRAMARBPROC) (GLhandleARB programObj); typedef void (APIENTRYP PFNGLUNIFORM1FARBPROC) (GLint location, GLfloat v0); typedef void (APIENTRYP PFNGLUNIFORM2FARBPROC) (GLint location, GLfloat v0, GLfloat v1); typedef void (APIENTRYP PFNGLUNIFORM3FARBPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2); typedef void (APIENTRYP PFNGLUNIFORM4FARBPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); typedef void (APIENTRYP PFNGLUNIFORM1IARBPROC) (GLint location, GLint v0); typedef void (APIENTRYP PFNGLUNIFORM2IARBPROC) (GLint location, GLint v0, GLint v1); typedef void (APIENTRYP PFNGLUNIFORM3IARBPROC) (GLint location, GLint v0, GLint v1, GLint v2); typedef void (APIENTRYP PFNGLUNIFORM4IARBPROC) (GLint location, GLint v0, GLint v1, GLint v2, GLint v3); typedef void (APIENTRYP PFNGLUNIFORM1FVARBPROC) (GLint location, GLsizei count, const GLfloat *value); typedef void (APIENTRYP PFNGLUNIFORM2FVARBPROC) (GLint location, GLsizei count, const GLfloat *value); typedef void (APIENTRYP PFNGLUNIFORM3FVARBPROC) (GLint location, GLsizei count, const GLfloat *value); typedef void (APIENTRYP PFNGLUNIFORM4FVARBPROC) (GLint location, GLsizei count, const GLfloat *value); typedef void (APIENTRYP PFNGLUNIFORM1IVARBPROC) (GLint location, GLsizei count, const GLint *value); typedef void (APIENTRYP PFNGLUNIFORM2IVARBPROC) (GLint location, GLsizei count, const GLint *value); typedef void (APIENTRYP PFNGLUNIFORM3IVARBPROC) (GLint location, GLsizei count, const GLint *value); typedef void (APIENTRYP PFNGLUNIFORM4IVARBPROC) (GLint location, GLsizei count, const GLint *value); typedef void (APIENTRYP PFNGLUNIFORMMATRIX2FVARBPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); typedef void (APIENTRYP PFNGLUNIFORMMATRIX3FVARBPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); typedef void (APIENTRYP PFNGLUNIFORMMATRIX4FVARBPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); typedef void (APIENTRYP PFNGLGETOBJECTPARAMETERFVARBPROC) (GLhandleARB obj, GLenum pname, GLfloat *params); typedef void (APIENTRYP PFNGLGETOBJECTPARAMETERIVARBPROC) (GLhandleARB obj, GLenum pname, GLint *params); typedef void (APIENTRYP PFNGLGETINFOLOGARBPROC) (GLhandleARB obj, GLsizei maxLength, GLsizei *length, GLcharARB *infoLog); typedef void (APIENTRYP PFNGLGETATTACHEDOBJECTSARBPROC) (GLhandleARB containerObj, GLsizei maxCount, GLsizei *count, GLhandleARB *obj); typedef GLint (APIENTRYP PFNGLGETUNIFORMLOCATIONARBPROC) (GLhandleARB programObj, const GLcharARB *name); typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMARBPROC) (GLhandleARB programObj, GLuint index, GLsizei maxLength, GLsizei *length, GLint *size, GLenum *type, GLcharARB *name); typedef void (APIENTRYP PFNGLGETUNIFORMFVARBPROC) (GLhandleARB programObj, GLint location, GLfloat *params); typedef void (APIENTRYP PFNGLGETUNIFORMIVARBPROC) (GLhandleARB programObj, GLint location, GLint *params); typedef void (APIENTRYP PFNGLGETSHADERSOURCEARBPROC) (GLhandleARB obj, GLsizei maxLength, GLsizei *length, GLcharARB *source); #endif #ifndef GL_ARB_vertex_shader #define GL_ARB_vertex_shader 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glBindAttribLocationARB (GLhandleARB, GLuint, const GLcharARB *); GLAPI void APIENTRY glGetActiveAttribARB (GLhandleARB, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLcharARB *); GLAPI GLint APIENTRY glGetAttribLocationARB (GLhandleARB, const GLcharARB *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLBINDATTRIBLOCATIONARBPROC) (GLhandleARB programObj, GLuint index, const GLcharARB *name); typedef void (APIENTRYP PFNGLGETACTIVEATTRIBARBPROC) (GLhandleARB programObj, GLuint index, GLsizei maxLength, GLsizei *length, GLint *size, GLenum *type, GLcharARB *name); typedef GLint (APIENTRYP PFNGLGETATTRIBLOCATIONARBPROC) (GLhandleARB programObj, const GLcharARB *name); #endif #ifndef GL_ARB_fragment_shader #define GL_ARB_fragment_shader 1 #endif #ifndef GL_ARB_shading_language_100 #define GL_ARB_shading_language_100 1 #endif #ifndef GL_ARB_texture_non_power_of_two #define GL_ARB_texture_non_power_of_two 1 #endif #ifndef GL_ARB_point_sprite #define GL_ARB_point_sprite 1 #endif #ifndef GL_ARB_fragment_program_shadow #define GL_ARB_fragment_program_shadow 1 #endif #ifndef GL_ARB_draw_buffers #define GL_ARB_draw_buffers 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glDrawBuffersARB (GLsizei, const GLenum *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLDRAWBUFFERSARBPROC) (GLsizei n, const GLenum *bufs); #endif #ifndef GL_ARB_texture_rectangle #define GL_ARB_texture_rectangle 1 #endif #ifndef GL_ARB_color_buffer_float #define GL_ARB_color_buffer_float 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glClampColorARB (GLenum, GLenum); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLCLAMPCOLORARBPROC) (GLenum target, GLenum clamp); #endif #ifndef GL_ARB_half_float_pixel #define GL_ARB_half_float_pixel 1 #endif #ifndef GL_ARB_texture_float #define GL_ARB_texture_float 1 #endif #ifndef GL_ARB_pixel_buffer_object #define GL_ARB_pixel_buffer_object 1 #endif #ifndef GL_EXT_abgr #define GL_EXT_abgr 1 #endif #ifndef GL_EXT_blend_color #define GL_EXT_blend_color 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glBlendColorEXT (GLclampf, GLclampf, GLclampf, GLclampf); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLBLENDCOLOREXTPROC) (GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha); #endif #ifndef GL_EXT_polygon_offset #define GL_EXT_polygon_offset 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glPolygonOffsetEXT (GLfloat, GLfloat); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLPOLYGONOFFSETEXTPROC) (GLfloat factor, GLfloat bias); #endif #ifndef GL_EXT_texture #define GL_EXT_texture 1 #endif #ifndef GL_EXT_texture3D #define GL_EXT_texture3D 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glTexImage3DEXT (GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid *); GLAPI void APIENTRY glTexSubImage3DEXT (GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLTEXIMAGE3DEXTPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *pixels); typedef void (APIENTRYP PFNGLTEXSUBIMAGE3DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid *pixels); #endif #ifndef GL_SGIS_texture_filter4 #define GL_SGIS_texture_filter4 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glGetTexFilterFuncSGIS (GLenum, GLenum, GLfloat *); GLAPI void APIENTRY glTexFilterFuncSGIS (GLenum, GLenum, GLsizei, const GLfloat *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLGETTEXFILTERFUNCSGISPROC) (GLenum target, GLenum filter, GLfloat *weights); typedef void (APIENTRYP PFNGLTEXFILTERFUNCSGISPROC) (GLenum target, GLenum filter, GLsizei n, const GLfloat *weights); #endif #ifndef GL_EXT_subtexture #define GL_EXT_subtexture 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glTexSubImage1DEXT (GLenum, GLint, GLint, GLsizei, GLenum, GLenum, const GLvoid *); GLAPI void APIENTRY glTexSubImage2DEXT (GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLTEXSUBIMAGE1DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const GLvoid *pixels); typedef void (APIENTRYP PFNGLTEXSUBIMAGE2DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels); #endif #ifndef GL_EXT_copy_texture #define GL_EXT_copy_texture 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glCopyTexImage1DEXT (GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLint); GLAPI void APIENTRY glCopyTexImage2DEXT (GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLsizei, GLint); GLAPI void APIENTRY glCopyTexSubImage1DEXT (GLenum, GLint, GLint, GLint, GLint, GLsizei); GLAPI void APIENTRY glCopyTexSubImage2DEXT (GLenum, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei); GLAPI void APIENTRY glCopyTexSubImage3DEXT (GLenum, GLint, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLCOPYTEXIMAGE1DEXTPROC) (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border); typedef void (APIENTRYP PFNGLCOPYTEXIMAGE2DEXTPROC) (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE1DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE2DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE3DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); #endif #ifndef GL_EXT_histogram #define GL_EXT_histogram 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glGetHistogramEXT (GLenum, GLboolean, GLenum, GLenum, GLvoid *); GLAPI void APIENTRY glGetHistogramParameterfvEXT (GLenum, GLenum, GLfloat *); GLAPI void APIENTRY glGetHistogramParameterivEXT (GLenum, GLenum, GLint *); GLAPI void APIENTRY glGetMinmaxEXT (GLenum, GLboolean, GLenum, GLenum, GLvoid *); GLAPI void APIENTRY glGetMinmaxParameterfvEXT (GLenum, GLenum, GLfloat *); GLAPI void APIENTRY glGetMinmaxParameterivEXT (GLenum, GLenum, GLint *); GLAPI void APIENTRY glHistogramEXT (GLenum, GLsizei, GLenum, GLboolean); GLAPI void APIENTRY glMinmaxEXT (GLenum, GLenum, GLboolean); GLAPI void APIENTRY glResetHistogramEXT (GLenum); GLAPI void APIENTRY glResetMinmaxEXT (GLenum); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLGETHISTOGRAMEXTPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLvoid *values); typedef void (APIENTRYP PFNGLGETHISTOGRAMPARAMETERFVEXTPROC) (GLenum target, GLenum pname, GLfloat *params); typedef void (APIENTRYP PFNGLGETHISTOGRAMPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params); typedef void (APIENTRYP PFNGLGETMINMAXEXTPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLvoid *values); typedef void (APIENTRYP PFNGLGETMINMAXPARAMETERFVEXTPROC) (GLenum target, GLenum pname, GLfloat *params); typedef void (APIENTRYP PFNGLGETMINMAXPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params); typedef void (APIENTRYP PFNGLHISTOGRAMEXTPROC) (GLenum target, GLsizei width, GLenum internalformat, GLboolean sink); typedef void (APIENTRYP PFNGLMINMAXEXTPROC) (GLenum target, GLenum internalformat, GLboolean sink); typedef void (APIENTRYP PFNGLRESETHISTOGRAMEXTPROC) (GLenum target); typedef void (APIENTRYP PFNGLRESETMINMAXEXTPROC) (GLenum target); #endif #ifndef GL_EXT_convolution #define GL_EXT_convolution 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glConvolutionFilter1DEXT (GLenum, GLenum, GLsizei, GLenum, GLenum, const GLvoid *); GLAPI void APIENTRY glConvolutionFilter2DEXT (GLenum, GLenum, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *); GLAPI void APIENTRY glConvolutionParameterfEXT (GLenum, GLenum, GLfloat); GLAPI void APIENTRY glConvolutionParameterfvEXT (GLenum, GLenum, const GLfloat *); GLAPI void APIENTRY glConvolutionParameteriEXT (GLenum, GLenum, GLint); GLAPI void APIENTRY glConvolutionParameterivEXT (GLenum, GLenum, const GLint *); GLAPI void APIENTRY glCopyConvolutionFilter1DEXT (GLenum, GLenum, GLint, GLint, GLsizei); GLAPI void APIENTRY glCopyConvolutionFilter2DEXT (GLenum, GLenum, GLint, GLint, GLsizei, GLsizei); GLAPI void APIENTRY glGetConvolutionFilterEXT (GLenum, GLenum, GLenum, GLvoid *); GLAPI void APIENTRY glGetConvolutionParameterfvEXT (GLenum, GLenum, GLfloat *); GLAPI void APIENTRY glGetConvolutionParameterivEXT (GLenum, GLenum, GLint *); GLAPI void APIENTRY glGetSeparableFilterEXT (GLenum, GLenum, GLenum, GLvoid *, GLvoid *, GLvoid *); GLAPI void APIENTRY glSeparableFilter2DEXT (GLenum, GLenum, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *, const GLvoid *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLCONVOLUTIONFILTER1DEXTPROC) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *image); typedef void (APIENTRYP PFNGLCONVOLUTIONFILTER2DEXTPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *image); typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERFEXTPROC) (GLenum target, GLenum pname, GLfloat params); typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERFVEXTPROC) (GLenum target, GLenum pname, const GLfloat *params); typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERIEXTPROC) (GLenum target, GLenum pname, GLint params); typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERIVEXTPROC) (GLenum target, GLenum pname, const GLint *params); typedef void (APIENTRYP PFNGLCOPYCONVOLUTIONFILTER1DEXTPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width); typedef void (APIENTRYP PFNGLCOPYCONVOLUTIONFILTER2DEXTPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height); typedef void (APIENTRYP PFNGLGETCONVOLUTIONFILTEREXTPROC) (GLenum target, GLenum format, GLenum type, GLvoid *image); typedef void (APIENTRYP PFNGLGETCONVOLUTIONPARAMETERFVEXTPROC) (GLenum target, GLenum pname, GLfloat *params); typedef void (APIENTRYP PFNGLGETCONVOLUTIONPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params); typedef void (APIENTRYP PFNGLGETSEPARABLEFILTEREXTPROC) (GLenum target, GLenum format, GLenum type, GLvoid *row, GLvoid *column, GLvoid *span); typedef void (APIENTRYP PFNGLSEPARABLEFILTER2DEXTPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *row, const GLvoid *column); #endif #ifndef GL_EXT_color_matrix #define GL_EXT_color_matrix 1 #endif #ifndef GL_SGI_color_table #define GL_SGI_color_table 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glColorTableSGI (GLenum, GLenum, GLsizei, GLenum, GLenum, const GLvoid *); GLAPI void APIENTRY glColorTableParameterfvSGI (GLenum, GLenum, const GLfloat *); GLAPI void APIENTRY glColorTableParameterivSGI (GLenum, GLenum, const GLint *); GLAPI void APIENTRY glCopyColorTableSGI (GLenum, GLenum, GLint, GLint, GLsizei); GLAPI void APIENTRY glGetColorTableSGI (GLenum, GLenum, GLenum, GLvoid *); GLAPI void APIENTRY glGetColorTableParameterfvSGI (GLenum, GLenum, GLfloat *); GLAPI void APIENTRY glGetColorTableParameterivSGI (GLenum, GLenum, GLint *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLCOLORTABLESGIPROC) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *table); typedef void (APIENTRYP PFNGLCOLORTABLEPARAMETERFVSGIPROC) (GLenum target, GLenum pname, const GLfloat *params); typedef void (APIENTRYP PFNGLCOLORTABLEPARAMETERIVSGIPROC) (GLenum target, GLenum pname, const GLint *params); typedef void (APIENTRYP PFNGLCOPYCOLORTABLESGIPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width); typedef void (APIENTRYP PFNGLGETCOLORTABLESGIPROC) (GLenum target, GLenum format, GLenum type, GLvoid *table); typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERFVSGIPROC) (GLenum target, GLenum pname, GLfloat *params); typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERIVSGIPROC) (GLenum target, GLenum pname, GLint *params); #endif #ifndef GL_SGIX_pixel_texture #define GL_SGIX_pixel_texture 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glPixelTexGenSGIX (GLenum); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLPIXELTEXGENSGIXPROC) (GLenum mode); #endif #ifndef GL_SGIS_pixel_texture #define GL_SGIS_pixel_texture 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glPixelTexGenParameteriSGIS (GLenum, GLint); GLAPI void APIENTRY glPixelTexGenParameterivSGIS (GLenum, const GLint *); GLAPI void APIENTRY glPixelTexGenParameterfSGIS (GLenum, GLfloat); GLAPI void APIENTRY glPixelTexGenParameterfvSGIS (GLenum, const GLfloat *); GLAPI void APIENTRY glGetPixelTexGenParameterivSGIS (GLenum, GLint *); GLAPI void APIENTRY glGetPixelTexGenParameterfvSGIS (GLenum, GLfloat *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLPIXELTEXGENPARAMETERISGISPROC) (GLenum pname, GLint param); typedef void (APIENTRYP PFNGLPIXELTEXGENPARAMETERIVSGISPROC) (GLenum pname, const GLint *params); typedef void (APIENTRYP PFNGLPIXELTEXGENPARAMETERFSGISPROC) (GLenum pname, GLfloat param); typedef void (APIENTRYP PFNGLPIXELTEXGENPARAMETERFVSGISPROC) (GLenum pname, const GLfloat *params); typedef void (APIENTRYP PFNGLGETPIXELTEXGENPARAMETERIVSGISPROC) (GLenum pname, GLint *params); typedef void (APIENTRYP PFNGLGETPIXELTEXGENPARAMETERFVSGISPROC) (GLenum pname, GLfloat *params); #endif #ifndef GL_SGIS_texture4D #define GL_SGIS_texture4D 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glTexImage4DSGIS (GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid *); GLAPI void APIENTRY glTexSubImage4DSGIS (GLenum, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLTEXIMAGE4DSGISPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLsizei size4d, GLint border, GLenum format, GLenum type, const GLvoid *pixels); typedef void (APIENTRYP PFNGLTEXSUBIMAGE4DSGISPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint woffset, GLsizei width, GLsizei height, GLsizei depth, GLsizei size4d, GLenum format, GLenum type, const GLvoid *pixels); #endif #ifndef GL_SGI_texture_color_table #define GL_SGI_texture_color_table 1 #endif #ifndef GL_EXT_cmyka #define GL_EXT_cmyka 1 #endif #ifndef GL_EXT_texture_object #define GL_EXT_texture_object 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI GLboolean APIENTRY glAreTexturesResidentEXT (GLsizei, const GLuint *, GLboolean *); GLAPI void APIENTRY glBindTextureEXT (GLenum, GLuint); GLAPI void APIENTRY glDeleteTexturesEXT (GLsizei, const GLuint *); GLAPI void APIENTRY glGenTexturesEXT (GLsizei, GLuint *); GLAPI GLboolean APIENTRY glIsTextureEXT (GLuint); GLAPI void APIENTRY glPrioritizeTexturesEXT (GLsizei, const GLuint *, const GLclampf *); #endif /* GL_GLEXT_PROTOTYPES */ typedef GLboolean (APIENTRYP PFNGLARETEXTURESRESIDENTEXTPROC) (GLsizei n, const GLuint *textures, GLboolean *residences); typedef void (APIENTRYP PFNGLBINDTEXTUREEXTPROC) (GLenum target, GLuint texture); typedef void (APIENTRYP PFNGLDELETETEXTURESEXTPROC) (GLsizei n, const GLuint *textures); typedef void (APIENTRYP PFNGLGENTEXTURESEXTPROC) (GLsizei n, GLuint *textures); typedef GLboolean (APIENTRYP PFNGLISTEXTUREEXTPROC) (GLuint texture); typedef void (APIENTRYP PFNGLPRIORITIZETEXTURESEXTPROC) (GLsizei n, const GLuint *textures, const GLclampf *priorities); #endif #ifndef GL_SGIS_detail_texture #define GL_SGIS_detail_texture 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glDetailTexFuncSGIS (GLenum, GLsizei, const GLfloat *); GLAPI void APIENTRY glGetDetailTexFuncSGIS (GLenum, GLfloat *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLDETAILTEXFUNCSGISPROC) (GLenum target, GLsizei n, const GLfloat *points); typedef void (APIENTRYP PFNGLGETDETAILTEXFUNCSGISPROC) (GLenum target, GLfloat *points); #endif #ifndef GL_SGIS_sharpen_texture #define GL_SGIS_sharpen_texture 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glSharpenTexFuncSGIS (GLenum, GLsizei, const GLfloat *); GLAPI void APIENTRY glGetSharpenTexFuncSGIS (GLenum, GLfloat *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLSHARPENTEXFUNCSGISPROC) (GLenum target, GLsizei n, const GLfloat *points); typedef void (APIENTRYP PFNGLGETSHARPENTEXFUNCSGISPROC) (GLenum target, GLfloat *points); #endif #ifndef GL_EXT_packed_pixels #define GL_EXT_packed_pixels 1 #endif #ifndef GL_SGIS_texture_lod #define GL_SGIS_texture_lod 1 #endif #ifndef GL_SGIS_multisample #define GL_SGIS_multisample 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glSampleMaskSGIS (GLclampf, GLboolean); GLAPI void APIENTRY glSamplePatternSGIS (GLenum); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLSAMPLEMASKSGISPROC) (GLclampf value, GLboolean invert); typedef void (APIENTRYP PFNGLSAMPLEPATTERNSGISPROC) (GLenum pattern); #endif #ifndef GL_EXT_rescale_normal #define GL_EXT_rescale_normal 1 #endif #ifndef GL_EXT_vertex_array #define GL_EXT_vertex_array 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glArrayElementEXT (GLint); GLAPI void APIENTRY glColorPointerEXT (GLint, GLenum, GLsizei, GLsizei, const GLvoid *); GLAPI void APIENTRY glDrawArraysEXT (GLenum, GLint, GLsizei); GLAPI void APIENTRY glEdgeFlagPointerEXT (GLsizei, GLsizei, const GLboolean *); GLAPI void APIENTRY glGetPointervEXT (GLenum, GLvoid* *); GLAPI void APIENTRY glIndexPointerEXT (GLenum, GLsizei, GLsizei, const GLvoid *); GLAPI void APIENTRY glNormalPointerEXT (GLenum, GLsizei, GLsizei, const GLvoid *); GLAPI void APIENTRY glTexCoordPointerEXT (GLint, GLenum, GLsizei, GLsizei, const GLvoid *); GLAPI void APIENTRY glVertexPointerEXT (GLint, GLenum, GLsizei, GLsizei, const GLvoid *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLARRAYELEMENTEXTPROC) (GLint i); typedef void (APIENTRYP PFNGLCOLORPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer); typedef void (APIENTRYP PFNGLDRAWARRAYSEXTPROC) (GLenum mode, GLint first, GLsizei count); typedef void (APIENTRYP PFNGLEDGEFLAGPOINTEREXTPROC) (GLsizei stride, GLsizei count, const GLboolean *pointer); typedef void (APIENTRYP PFNGLGETPOINTERVEXTPROC) (GLenum pname, GLvoid* *params); typedef void (APIENTRYP PFNGLINDEXPOINTEREXTPROC) (GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer); typedef void (APIENTRYP PFNGLNORMALPOINTEREXTPROC) (GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer); typedef void (APIENTRYP PFNGLTEXCOORDPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer); typedef void (APIENTRYP PFNGLVERTEXPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer); #endif #ifndef GL_EXT_misc_attribute #define GL_EXT_misc_attribute 1 #endif #ifndef GL_SGIS_generate_mipmap #define GL_SGIS_generate_mipmap 1 #endif #ifndef GL_SGIX_clipmap #define GL_SGIX_clipmap 1 #endif #ifndef GL_SGIX_shadow #define GL_SGIX_shadow 1 #endif #ifndef GL_SGIS_texture_edge_clamp #define GL_SGIS_texture_edge_clamp 1 #endif #ifndef GL_SGIS_texture_border_clamp #define GL_SGIS_texture_border_clamp 1 #endif #ifndef GL_EXT_blend_minmax #define GL_EXT_blend_minmax 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glBlendEquationEXT (GLenum); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLBLENDEQUATIONEXTPROC) (GLenum mode); #endif #ifndef GL_EXT_blend_subtract #define GL_EXT_blend_subtract 1 #endif #ifndef GL_EXT_blend_logic_op #define GL_EXT_blend_logic_op 1 #endif #ifndef GL_SGIX_interlace #define GL_SGIX_interlace 1 #endif #ifndef GL_SGIX_pixel_tiles #define GL_SGIX_pixel_tiles 1 #endif #ifndef GL_SGIX_texture_select #define GL_SGIX_texture_select 1 #endif #ifndef GL_SGIX_sprite #define GL_SGIX_sprite 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glSpriteParameterfSGIX (GLenum, GLfloat); GLAPI void APIENTRY glSpriteParameterfvSGIX (GLenum, const GLfloat *); GLAPI void APIENTRY glSpriteParameteriSGIX (GLenum, GLint); GLAPI void APIENTRY glSpriteParameterivSGIX (GLenum, const GLint *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLSPRITEPARAMETERFSGIXPROC) (GLenum pname, GLfloat param); typedef void (APIENTRYP PFNGLSPRITEPARAMETERFVSGIXPROC) (GLenum pname, const GLfloat *params); typedef void (APIENTRYP PFNGLSPRITEPARAMETERISGIXPROC) (GLenum pname, GLint param); typedef void (APIENTRYP PFNGLSPRITEPARAMETERIVSGIXPROC) (GLenum pname, const GLint *params); #endif #ifndef GL_SGIX_texture_multi_buffer #define GL_SGIX_texture_multi_buffer 1 #endif #ifndef GL_EXT_point_parameters #define GL_EXT_point_parameters 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glPointParameterfEXT (GLenum, GLfloat); GLAPI void APIENTRY glPointParameterfvEXT (GLenum, const GLfloat *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLPOINTPARAMETERFEXTPROC) (GLenum pname, GLfloat param); typedef void (APIENTRYP PFNGLPOINTPARAMETERFVEXTPROC) (GLenum pname, const GLfloat *params); #endif #ifndef GL_SGIS_point_parameters #define GL_SGIS_point_parameters 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glPointParameterfSGIS (GLenum, GLfloat); GLAPI void APIENTRY glPointParameterfvSGIS (GLenum, const GLfloat *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLPOINTPARAMETERFSGISPROC) (GLenum pname, GLfloat param); typedef void (APIENTRYP PFNGLPOINTPARAMETERFVSGISPROC) (GLenum pname, const GLfloat *params); #endif #ifndef GL_SGIX_instruments #define GL_SGIX_instruments 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI GLint APIENTRY glGetInstrumentsSGIX (void); GLAPI void APIENTRY glInstrumentsBufferSGIX (GLsizei, GLint *); GLAPI GLint APIENTRY glPollInstrumentsSGIX (GLint *); GLAPI void APIENTRY glReadInstrumentsSGIX (GLint); GLAPI void APIENTRY glStartInstrumentsSGIX (void); GLAPI void APIENTRY glStopInstrumentsSGIX (GLint); #endif /* GL_GLEXT_PROTOTYPES */ typedef GLint (APIENTRYP PFNGLGETINSTRUMENTSSGIXPROC) (void); typedef void (APIENTRYP PFNGLINSTRUMENTSBUFFERSGIXPROC) (GLsizei size, GLint *buffer); typedef GLint (APIENTRYP PFNGLPOLLINSTRUMENTSSGIXPROC) (GLint *marker_p); typedef void (APIENTRYP PFNGLREADINSTRUMENTSSGIXPROC) (GLint marker); typedef void (APIENTRYP PFNGLSTARTINSTRUMENTSSGIXPROC) (void); typedef void (APIENTRYP PFNGLSTOPINSTRUMENTSSGIXPROC) (GLint marker); #endif #ifndef GL_SGIX_texture_scale_bias #define GL_SGIX_texture_scale_bias 1 #endif #ifndef GL_SGIX_framezoom #define GL_SGIX_framezoom 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glFrameZoomSGIX (GLint); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLFRAMEZOOMSGIXPROC) (GLint factor); #endif #ifndef GL_SGIX_tag_sample_buffer #define GL_SGIX_tag_sample_buffer 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glTagSampleBufferSGIX (void); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLTAGSAMPLEBUFFERSGIXPROC) (void); #endif #ifndef GL_SGIX_polynomial_ffd #define GL_SGIX_polynomial_ffd 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glDeformationMap3dSGIX (GLenum, GLdouble, GLdouble, GLint, GLint, GLdouble, GLdouble, GLint, GLint, GLdouble, GLdouble, GLint, GLint, const GLdouble *); GLAPI void APIENTRY glDeformationMap3fSGIX (GLenum, GLfloat, GLfloat, GLint, GLint, GLfloat, GLfloat, GLint, GLint, GLfloat, GLfloat, GLint, GLint, const GLfloat *); GLAPI void APIENTRY glDeformSGIX (GLbitfield); GLAPI void APIENTRY glLoadIdentityDeformationMapSGIX (GLbitfield); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLDEFORMATIONMAP3DSGIXPROC) (GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, GLdouble w1, GLdouble w2, GLint wstride, GLint worder, const GLdouble *points); typedef void (APIENTRYP PFNGLDEFORMATIONMAP3FSGIXPROC) (GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, GLfloat w1, GLfloat w2, GLint wstride, GLint worder, const GLfloat *points); typedef void (APIENTRYP PFNGLDEFORMSGIXPROC) (GLbitfield mask); typedef void (APIENTRYP PFNGLLOADIDENTITYDEFORMATIONMAPSGIXPROC) (GLbitfield mask); #endif #ifndef GL_SGIX_reference_plane #define GL_SGIX_reference_plane 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glReferencePlaneSGIX (const GLdouble *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLREFERENCEPLANESGIXPROC) (const GLdouble *equation); #endif #ifndef GL_SGIX_flush_raster #define GL_SGIX_flush_raster 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glFlushRasterSGIX (void); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLFLUSHRASTERSGIXPROC) (void); #endif #ifndef GL_SGIX_depth_texture #define GL_SGIX_depth_texture 1 #endif #ifndef GL_SGIS_fog_function #define GL_SGIS_fog_function 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glFogFuncSGIS (GLsizei, const GLfloat *); GLAPI void APIENTRY glGetFogFuncSGIS (GLfloat *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLFOGFUNCSGISPROC) (GLsizei n, const GLfloat *points); typedef void (APIENTRYP PFNGLGETFOGFUNCSGISPROC) (GLfloat *points); #endif #ifndef GL_SGIX_fog_offset #define GL_SGIX_fog_offset 1 #endif #ifndef GL_HP_image_transform #define GL_HP_image_transform 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glImageTransformParameteriHP (GLenum, GLenum, GLint); GLAPI void APIENTRY glImageTransformParameterfHP (GLenum, GLenum, GLfloat); GLAPI void APIENTRY glImageTransformParameterivHP (GLenum, GLenum, const GLint *); GLAPI void APIENTRY glImageTransformParameterfvHP (GLenum, GLenum, const GLfloat *); GLAPI void APIENTRY glGetImageTransformParameterivHP (GLenum, GLenum, GLint *); GLAPI void APIENTRY glGetImageTransformParameterfvHP (GLenum, GLenum, GLfloat *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLIMAGETRANSFORMPARAMETERIHPPROC) (GLenum target, GLenum pname, GLint param); typedef void (APIENTRYP PFNGLIMAGETRANSFORMPARAMETERFHPPROC) (GLenum target, GLenum pname, GLfloat param); typedef void (APIENTRYP PFNGLIMAGETRANSFORMPARAMETERIVHPPROC) (GLenum target, GLenum pname, const GLint *params); typedef void (APIENTRYP PFNGLIMAGETRANSFORMPARAMETERFVHPPROC) (GLenum target, GLenum pname, const GLfloat *params); typedef void (APIENTRYP PFNGLGETIMAGETRANSFORMPARAMETERIVHPPROC) (GLenum target, GLenum pname, GLint *params); typedef void (APIENTRYP PFNGLGETIMAGETRANSFORMPARAMETERFVHPPROC) (GLenum target, GLenum pname, GLfloat *params); #endif #ifndef GL_HP_convolution_border_modes #define GL_HP_convolution_border_modes 1 #endif #ifndef GL_SGIX_texture_add_env #define GL_SGIX_texture_add_env 1 #endif #ifndef GL_EXT_color_subtable #define GL_EXT_color_subtable 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glColorSubTableEXT (GLenum, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *); GLAPI void APIENTRY glCopyColorSubTableEXT (GLenum, GLsizei, GLint, GLint, GLsizei); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLCOLORSUBTABLEEXTPROC) (GLenum target, GLsizei start, GLsizei count, GLenum format, GLenum type, const GLvoid *data); typedef void (APIENTRYP PFNGLCOPYCOLORSUBTABLEEXTPROC) (GLenum target, GLsizei start, GLint x, GLint y, GLsizei width); #endif #ifndef GL_PGI_vertex_hints #define GL_PGI_vertex_hints 1 #endif #ifndef GL_PGI_misc_hints #define GL_PGI_misc_hints 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glHintPGI (GLenum, GLint); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLHINTPGIPROC) (GLenum target, GLint mode); #endif #ifndef GL_EXT_paletted_texture #define GL_EXT_paletted_texture 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glColorTableEXT (GLenum, GLenum, GLsizei, GLenum, GLenum, const GLvoid *); GLAPI void APIENTRY glGetColorTableEXT (GLenum, GLenum, GLenum, GLvoid *); GLAPI void APIENTRY glGetColorTableParameterivEXT (GLenum, GLenum, GLint *); GLAPI void APIENTRY glGetColorTableParameterfvEXT (GLenum, GLenum, GLfloat *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLCOLORTABLEEXTPROC) (GLenum target, GLenum internalFormat, GLsizei width, GLenum format, GLenum type, const GLvoid *table); typedef void (APIENTRYP PFNGLGETCOLORTABLEEXTPROC) (GLenum target, GLenum format, GLenum type, GLvoid *data); typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params); typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERFVEXTPROC) (GLenum target, GLenum pname, GLfloat *params); #endif #ifndef GL_EXT_clip_volume_hint #define GL_EXT_clip_volume_hint 1 #endif #ifndef GL_SGIX_list_priority #define GL_SGIX_list_priority 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glGetListParameterfvSGIX (GLuint, GLenum, GLfloat *); GLAPI void APIENTRY glGetListParameterivSGIX (GLuint, GLenum, GLint *); GLAPI void APIENTRY glListParameterfSGIX (GLuint, GLenum, GLfloat); GLAPI void APIENTRY glListParameterfvSGIX (GLuint, GLenum, const GLfloat *); GLAPI void APIENTRY glListParameteriSGIX (GLuint, GLenum, GLint); GLAPI void APIENTRY glListParameterivSGIX (GLuint, GLenum, const GLint *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLGETLISTPARAMETERFVSGIXPROC) (GLuint list, GLenum pname, GLfloat *params); typedef void (APIENTRYP PFNGLGETLISTPARAMETERIVSGIXPROC) (GLuint list, GLenum pname, GLint *params); typedef void (APIENTRYP PFNGLLISTPARAMETERFSGIXPROC) (GLuint list, GLenum pname, GLfloat param); typedef void (APIENTRYP PFNGLLISTPARAMETERFVSGIXPROC) (GLuint list, GLenum pname, const GLfloat *params); typedef void (APIENTRYP PFNGLLISTPARAMETERISGIXPROC) (GLuint list, GLenum pname, GLint param); typedef void (APIENTRYP PFNGLLISTPARAMETERIVSGIXPROC) (GLuint list, GLenum pname, const GLint *params); #endif #ifndef GL_SGIX_ir_instrument1 #define GL_SGIX_ir_instrument1 1 #endif #ifndef GL_SGIX_calligraphic_fragment #define GL_SGIX_calligraphic_fragment 1 #endif #ifndef GL_SGIX_texture_lod_bias #define GL_SGIX_texture_lod_bias 1 #endif #ifndef GL_SGIX_shadow_ambient #define GL_SGIX_shadow_ambient 1 #endif #ifndef GL_EXT_index_texture #define GL_EXT_index_texture 1 #endif #ifndef GL_EXT_index_material #define GL_EXT_index_material 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glIndexMaterialEXT (GLenum, GLenum); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLINDEXMATERIALEXTPROC) (GLenum face, GLenum mode); #endif #ifndef GL_EXT_index_func #define GL_EXT_index_func 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glIndexFuncEXT (GLenum, GLclampf); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLINDEXFUNCEXTPROC) (GLenum func, GLclampf ref); #endif #ifndef GL_EXT_index_array_formats #define GL_EXT_index_array_formats 1 #endif #ifndef GL_EXT_compiled_vertex_array #define GL_EXT_compiled_vertex_array 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glLockArraysEXT (GLint, GLsizei); GLAPI void APIENTRY glUnlockArraysEXT (void); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLLOCKARRAYSEXTPROC) (GLint first, GLsizei count); typedef void (APIENTRYP PFNGLUNLOCKARRAYSEXTPROC) (void); #endif #ifndef GL_EXT_cull_vertex #define GL_EXT_cull_vertex 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glCullParameterdvEXT (GLenum, GLdouble *); GLAPI void APIENTRY glCullParameterfvEXT (GLenum, GLfloat *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLCULLPARAMETERDVEXTPROC) (GLenum pname, GLdouble *params); typedef void (APIENTRYP PFNGLCULLPARAMETERFVEXTPROC) (GLenum pname, GLfloat *params); #endif #ifndef GL_SGIX_ycrcb #define GL_SGIX_ycrcb 1 #endif #ifndef GL_SGIX_fragment_lighting #define GL_SGIX_fragment_lighting 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glFragmentColorMaterialSGIX (GLenum, GLenum); GLAPI void APIENTRY glFragmentLightfSGIX (GLenum, GLenum, GLfloat); GLAPI void APIENTRY glFragmentLightfvSGIX (GLenum, GLenum, const GLfloat *); GLAPI void APIENTRY glFragmentLightiSGIX (GLenum, GLenum, GLint); GLAPI void APIENTRY glFragmentLightivSGIX (GLenum, GLenum, const GLint *); GLAPI void APIENTRY glFragmentLightModelfSGIX (GLenum, GLfloat); GLAPI void APIENTRY glFragmentLightModelfvSGIX (GLenum, const GLfloat *); GLAPI void APIENTRY glFragmentLightModeliSGIX (GLenum, GLint); GLAPI void APIENTRY glFragmentLightModelivSGIX (GLenum, const GLint *); GLAPI void APIENTRY glFragmentMaterialfSGIX (GLenum, GLenum, GLfloat); GLAPI void APIENTRY glFragmentMaterialfvSGIX (GLenum, GLenum, const GLfloat *); GLAPI void APIENTRY glFragmentMaterialiSGIX (GLenum, GLenum, GLint); GLAPI void APIENTRY glFragmentMaterialivSGIX (GLenum, GLenum, const GLint *); GLAPI void APIENTRY glGetFragmentLightfvSGIX (GLenum, GLenum, GLfloat *); GLAPI void APIENTRY glGetFragmentLightivSGIX (GLenum, GLenum, GLint *); GLAPI void APIENTRY glGetFragmentMaterialfvSGIX (GLenum, GLenum, GLfloat *); GLAPI void APIENTRY glGetFragmentMaterialivSGIX (GLenum, GLenum, GLint *); GLAPI void APIENTRY glLightEnviSGIX (GLenum, GLint); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLFRAGMENTCOLORMATERIALSGIXPROC) (GLenum face, GLenum mode); typedef void (APIENTRYP PFNGLFRAGMENTLIGHTFSGIXPROC) (GLenum light, GLenum pname, GLfloat param); typedef void (APIENTRYP PFNGLFRAGMENTLIGHTFVSGIXPROC) (GLenum light, GLenum pname, const GLfloat *params); typedef void (APIENTRYP PFNGLFRAGMENTLIGHTISGIXPROC) (GLenum light, GLenum pname, GLint param); typedef void (APIENTRYP PFNGLFRAGMENTLIGHTIVSGIXPROC) (GLenum light, GLenum pname, const GLint *params); typedef void (APIENTRYP PFNGLFRAGMENTLIGHTMODELFSGIXPROC) (GLenum pname, GLfloat param); typedef void (APIENTRYP PFNGLFRAGMENTLIGHTMODELFVSGIXPROC) (GLenum pname, const GLfloat *params); typedef void (APIENTRYP PFNGLFRAGMENTLIGHTMODELISGIXPROC) (GLenum pname, GLint param); typedef void (APIENTRYP PFNGLFRAGMENTLIGHTMODELIVSGIXPROC) (GLenum pname, const GLint *params); typedef void (APIENTRYP PFNGLFRAGMENTMATERIALFSGIXPROC) (GLenum face, GLenum pname, GLfloat param); typedef void (APIENTRYP PFNGLFRAGMENTMATERIALFVSGIXPROC) (GLenum face, GLenum pname, const GLfloat *params); typedef void (APIENTRYP PFNGLFRAGMENTMATERIALISGIXPROC) (GLenum face, GLenum pname, GLint param); typedef void (APIENTRYP PFNGLFRAGMENTMATERIALIVSGIXPROC) (GLenum face, GLenum pname, const GLint *params); typedef void (APIENTRYP PFNGLGETFRAGMENTLIGHTFVSGIXPROC) (GLenum light, GLenum pname, GLfloat *params); typedef void (APIENTRYP PFNGLGETFRAGMENTLIGHTIVSGIXPROC) (GLenum light, GLenum pname, GLint *params); typedef void (APIENTRYP PFNGLGETFRAGMENTMATERIALFVSGIXPROC) (GLenum face, GLenum pname, GLfloat *params); typedef void (APIENTRYP PFNGLGETFRAGMENTMATERIALIVSGIXPROC) (GLenum face, GLenum pname, GLint *params); typedef void (APIENTRYP PFNGLLIGHTENVISGIXPROC) (GLenum pname, GLint param); #endif #ifndef GL_IBM_rasterpos_clip #define GL_IBM_rasterpos_clip 1 #endif #ifndef GL_HP_texture_lighting #define GL_HP_texture_lighting 1 #endif #ifndef GL_EXT_draw_range_elements #define GL_EXT_draw_range_elements 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glDrawRangeElementsEXT (GLenum, GLuint, GLuint, GLsizei, GLenum, const GLvoid *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTSEXTPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid *indices); #endif #ifndef GL_WIN_phong_shading #define GL_WIN_phong_shading 1 #endif #ifndef GL_WIN_specular_fog #define GL_WIN_specular_fog 1 #endif #ifndef GL_EXT_light_texture #define GL_EXT_light_texture 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glApplyTextureEXT (GLenum); GLAPI void APIENTRY glTextureLightEXT (GLenum); GLAPI void APIENTRY glTextureMaterialEXT (GLenum, GLenum); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLAPPLYTEXTUREEXTPROC) (GLenum mode); typedef void (APIENTRYP PFNGLTEXTURELIGHTEXTPROC) (GLenum pname); typedef void (APIENTRYP PFNGLTEXTUREMATERIALEXTPROC) (GLenum face, GLenum mode); #endif #ifndef GL_SGIX_blend_alpha_minmax #define GL_SGIX_blend_alpha_minmax 1 #endif #ifndef GL_EXT_bgra #define GL_EXT_bgra 1 #endif #ifndef GL_SGIX_async #define GL_SGIX_async 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glAsyncMarkerSGIX (GLuint); GLAPI GLint APIENTRY glFinishAsyncSGIX (GLuint *); GLAPI GLint APIENTRY glPollAsyncSGIX (GLuint *); GLAPI GLuint APIENTRY glGenAsyncMarkersSGIX (GLsizei); GLAPI void APIENTRY glDeleteAsyncMarkersSGIX (GLuint, GLsizei); GLAPI GLboolean APIENTRY glIsAsyncMarkerSGIX (GLuint); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLASYNCMARKERSGIXPROC) (GLuint marker); typedef GLint (APIENTRYP PFNGLFINISHASYNCSGIXPROC) (GLuint *markerp); typedef GLint (APIENTRYP PFNGLPOLLASYNCSGIXPROC) (GLuint *markerp); typedef GLuint (APIENTRYP PFNGLGENASYNCMARKERSSGIXPROC) (GLsizei range); typedef void (APIENTRYP PFNGLDELETEASYNCMARKERSSGIXPROC) (GLuint marker, GLsizei range); typedef GLboolean (APIENTRYP PFNGLISASYNCMARKERSGIXPROC) (GLuint marker); #endif #ifndef GL_SGIX_async_pixel #define GL_SGIX_async_pixel 1 #endif #ifndef GL_SGIX_async_histogram #define GL_SGIX_async_histogram 1 #endif #ifndef GL_INTEL_parallel_arrays #define GL_INTEL_parallel_arrays 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glVertexPointervINTEL (GLint, GLenum, const GLvoid* *); GLAPI void APIENTRY glNormalPointervINTEL (GLenum, const GLvoid* *); GLAPI void APIENTRY glColorPointervINTEL (GLint, GLenum, const GLvoid* *); GLAPI void APIENTRY glTexCoordPointervINTEL (GLint, GLenum, const GLvoid* *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLVERTEXPOINTERVINTELPROC) (GLint size, GLenum type, const GLvoid* *pointer); typedef void (APIENTRYP PFNGLNORMALPOINTERVINTELPROC) (GLenum type, const GLvoid* *pointer); typedef void (APIENTRYP PFNGLCOLORPOINTERVINTELPROC) (GLint size, GLenum type, const GLvoid* *pointer); typedef void (APIENTRYP PFNGLTEXCOORDPOINTERVINTELPROC) (GLint size, GLenum type, const GLvoid* *pointer); #endif #ifndef GL_HP_occlusion_test #define GL_HP_occlusion_test 1 #endif #ifndef GL_EXT_pixel_transform #define GL_EXT_pixel_transform 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glPixelTransformParameteriEXT (GLenum, GLenum, GLint); GLAPI void APIENTRY glPixelTransformParameterfEXT (GLenum, GLenum, GLfloat); GLAPI void APIENTRY glPixelTransformParameterivEXT (GLenum, GLenum, const GLint *); GLAPI void APIENTRY glPixelTransformParameterfvEXT (GLenum, GLenum, const GLfloat *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLPIXELTRANSFORMPARAMETERIEXTPROC) (GLenum target, GLenum pname, GLint param); typedef void (APIENTRYP PFNGLPIXELTRANSFORMPARAMETERFEXTPROC) (GLenum target, GLenum pname, GLfloat param); typedef void (APIENTRYP PFNGLPIXELTRANSFORMPARAMETERIVEXTPROC) (GLenum target, GLenum pname, const GLint *params); typedef void (APIENTRYP PFNGLPIXELTRANSFORMPARAMETERFVEXTPROC) (GLenum target, GLenum pname, const GLfloat *params); #endif #ifndef GL_EXT_pixel_transform_color_table #define GL_EXT_pixel_transform_color_table 1 #endif #ifndef GL_EXT_shared_texture_palette #define GL_EXT_shared_texture_palette 1 #endif #ifndef GL_EXT_separate_specular_color #define GL_EXT_separate_specular_color 1 #endif #ifndef GL_EXT_secondary_color #define GL_EXT_secondary_color 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glSecondaryColor3bEXT (GLbyte, GLbyte, GLbyte); GLAPI void APIENTRY glSecondaryColor3bvEXT (const GLbyte *); GLAPI void APIENTRY glSecondaryColor3dEXT (GLdouble, GLdouble, GLdouble); GLAPI void APIENTRY glSecondaryColor3dvEXT (const GLdouble *); GLAPI void APIENTRY glSecondaryColor3fEXT (GLfloat, GLfloat, GLfloat); GLAPI void APIENTRY glSecondaryColor3fvEXT (const GLfloat *); GLAPI void APIENTRY glSecondaryColor3iEXT (GLint, GLint, GLint); GLAPI void APIENTRY glSecondaryColor3ivEXT (const GLint *); GLAPI void APIENTRY glSecondaryColor3sEXT (GLshort, GLshort, GLshort); GLAPI void APIENTRY glSecondaryColor3svEXT (const GLshort *); GLAPI void APIENTRY glSecondaryColor3ubEXT (GLubyte, GLubyte, GLubyte); GLAPI void APIENTRY glSecondaryColor3ubvEXT (const GLubyte *); GLAPI void APIENTRY glSecondaryColor3uiEXT (GLuint, GLuint, GLuint); GLAPI void APIENTRY glSecondaryColor3uivEXT (const GLuint *); GLAPI void APIENTRY glSecondaryColor3usEXT (GLushort, GLushort, GLushort); GLAPI void APIENTRY glSecondaryColor3usvEXT (const GLushort *); GLAPI void APIENTRY glSecondaryColorPointerEXT (GLint, GLenum, GLsizei, const GLvoid *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BEXTPROC) (GLbyte red, GLbyte green, GLbyte blue); typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BVEXTPROC) (const GLbyte *v); typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DEXTPROC) (GLdouble red, GLdouble green, GLdouble blue); typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DVEXTPROC) (const GLdouble *v); typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FEXTPROC) (GLfloat red, GLfloat green, GLfloat blue); typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FVEXTPROC) (const GLfloat *v); typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IEXTPROC) (GLint red, GLint green, GLint blue); typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IVEXTPROC) (const GLint *v); typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SEXTPROC) (GLshort red, GLshort green, GLshort blue); typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SVEXTPROC) (const GLshort *v); typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBEXTPROC) (GLubyte red, GLubyte green, GLubyte blue); typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBVEXTPROC) (const GLubyte *v); typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIEXTPROC) (GLuint red, GLuint green, GLuint blue); typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIVEXTPROC) (const GLuint *v); typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USEXTPROC) (GLushort red, GLushort green, GLushort blue); typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USVEXTPROC) (const GLushort *v); typedef void (APIENTRYP PFNGLSECONDARYCOLORPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer); #endif #ifndef GL_EXT_texture_perturb_normal #define GL_EXT_texture_perturb_normal 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glTextureNormalEXT (GLenum); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLTEXTURENORMALEXTPROC) (GLenum mode); #endif #ifndef GL_EXT_multi_draw_arrays #define GL_EXT_multi_draw_arrays 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glMultiDrawArraysEXT (GLenum, GLint *, GLsizei *, GLsizei); GLAPI void APIENTRY glMultiDrawElementsEXT (GLenum, const GLsizei *, GLenum, const GLvoid* *, GLsizei); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSEXTPROC) (GLenum mode, GLint *first, GLsizei *count, GLsizei primcount); typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSEXTPROC) (GLenum mode, const GLsizei *count, GLenum type, const GLvoid* *indices, GLsizei primcount); #endif #ifndef GL_EXT_fog_coord #define GL_EXT_fog_coord 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glFogCoordfEXT (GLfloat); GLAPI void APIENTRY glFogCoordfvEXT (const GLfloat *); GLAPI void APIENTRY glFogCoorddEXT (GLdouble); GLAPI void APIENTRY glFogCoorddvEXT (const GLdouble *); GLAPI void APIENTRY glFogCoordPointerEXT (GLenum, GLsizei, const GLvoid *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLFOGCOORDFEXTPROC) (GLfloat coord); typedef void (APIENTRYP PFNGLFOGCOORDFVEXTPROC) (const GLfloat *coord); typedef void (APIENTRYP PFNGLFOGCOORDDEXTPROC) (GLdouble coord); typedef void (APIENTRYP PFNGLFOGCOORDDVEXTPROC) (const GLdouble *coord); typedef void (APIENTRYP PFNGLFOGCOORDPOINTEREXTPROC) (GLenum type, GLsizei stride, const GLvoid *pointer); #endif #ifndef GL_REND_screen_coordinates #define GL_REND_screen_coordinates 1 #endif #ifndef GL_EXT_coordinate_frame #define GL_EXT_coordinate_frame 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glTangent3bEXT (GLbyte, GLbyte, GLbyte); GLAPI void APIENTRY glTangent3bvEXT (const GLbyte *); GLAPI void APIENTRY glTangent3dEXT (GLdouble, GLdouble, GLdouble); GLAPI void APIENTRY glTangent3dvEXT (const GLdouble *); GLAPI void APIENTRY glTangent3fEXT (GLfloat, GLfloat, GLfloat); GLAPI void APIENTRY glTangent3fvEXT (const GLfloat *); GLAPI void APIENTRY glTangent3iEXT (GLint, GLint, GLint); GLAPI void APIENTRY glTangent3ivEXT (const GLint *); GLAPI void APIENTRY glTangent3sEXT (GLshort, GLshort, GLshort); GLAPI void APIENTRY glTangent3svEXT (const GLshort *); GLAPI void APIENTRY glBinormal3bEXT (GLbyte, GLbyte, GLbyte); GLAPI void APIENTRY glBinormal3bvEXT (const GLbyte *); GLAPI void APIENTRY glBinormal3dEXT (GLdouble, GLdouble, GLdouble); GLAPI void APIENTRY glBinormal3dvEXT (const GLdouble *); GLAPI void APIENTRY glBinormal3fEXT (GLfloat, GLfloat, GLfloat); GLAPI void APIENTRY glBinormal3fvEXT (const GLfloat *); GLAPI void APIENTRY glBinormal3iEXT (GLint, GLint, GLint); GLAPI void APIENTRY glBinormal3ivEXT (const GLint *); GLAPI void APIENTRY glBinormal3sEXT (GLshort, GLshort, GLshort); GLAPI void APIENTRY glBinormal3svEXT (const GLshort *); GLAPI void APIENTRY glTangentPointerEXT (GLenum, GLsizei, const GLvoid *); GLAPI void APIENTRY glBinormalPointerEXT (GLenum, GLsizei, const GLvoid *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLTANGENT3BEXTPROC) (GLbyte tx, GLbyte ty, GLbyte tz); typedef void (APIENTRYP PFNGLTANGENT3BVEXTPROC) (const GLbyte *v); typedef void (APIENTRYP PFNGLTANGENT3DEXTPROC) (GLdouble tx, GLdouble ty, GLdouble tz); typedef void (APIENTRYP PFNGLTANGENT3DVEXTPROC) (const GLdouble *v); typedef void (APIENTRYP PFNGLTANGENT3FEXTPROC) (GLfloat tx, GLfloat ty, GLfloat tz); typedef void (APIENTRYP PFNGLTANGENT3FVEXTPROC) (const GLfloat *v); typedef void (APIENTRYP PFNGLTANGENT3IEXTPROC) (GLint tx, GLint ty, GLint tz); typedef void (APIENTRYP PFNGLTANGENT3IVEXTPROC) (const GLint *v); typedef void (APIENTRYP PFNGLTANGENT3SEXTPROC) (GLshort tx, GLshort ty, GLshort tz); typedef void (APIENTRYP PFNGLTANGENT3SVEXTPROC) (const GLshort *v); typedef void (APIENTRYP PFNGLBINORMAL3BEXTPROC) (GLbyte bx, GLbyte by, GLbyte bz); typedef void (APIENTRYP PFNGLBINORMAL3BVEXTPROC) (const GLbyte *v); typedef void (APIENTRYP PFNGLBINORMAL3DEXTPROC) (GLdouble bx, GLdouble by, GLdouble bz); typedef void (APIENTRYP PFNGLBINORMAL3DVEXTPROC) (const GLdouble *v); typedef void (APIENTRYP PFNGLBINORMAL3FEXTPROC) (GLfloat bx, GLfloat by, GLfloat bz); typedef void (APIENTRYP PFNGLBINORMAL3FVEXTPROC) (const GLfloat *v); typedef void (APIENTRYP PFNGLBINORMAL3IEXTPROC) (GLint bx, GLint by, GLint bz); typedef void (APIENTRYP PFNGLBINORMAL3IVEXTPROC) (const GLint *v); typedef void (APIENTRYP PFNGLBINORMAL3SEXTPROC) (GLshort bx, GLshort by, GLshort bz); typedef void (APIENTRYP PFNGLBINORMAL3SVEXTPROC) (const GLshort *v); typedef void (APIENTRYP PFNGLTANGENTPOINTEREXTPROC) (GLenum type, GLsizei stride, const GLvoid *pointer); typedef void (APIENTRYP PFNGLBINORMALPOINTEREXTPROC) (GLenum type, GLsizei stride, const GLvoid *pointer); #endif #ifndef GL_EXT_texture_env_combine #define GL_EXT_texture_env_combine 1 #endif #ifndef GL_APPLE_specular_vector #define GL_APPLE_specular_vector 1 #endif #ifndef GL_APPLE_transform_hint #define GL_APPLE_transform_hint 1 #endif #ifndef GL_SGIX_fog_scale #define GL_SGIX_fog_scale 1 #endif #ifndef GL_SUNX_constant_data #define GL_SUNX_constant_data 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glFinishTextureSUNX (void); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLFINISHTEXTURESUNXPROC) (void); #endif #ifndef GL_SUN_global_alpha #define GL_SUN_global_alpha 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glGlobalAlphaFactorbSUN (GLbyte); GLAPI void APIENTRY glGlobalAlphaFactorsSUN (GLshort); GLAPI void APIENTRY glGlobalAlphaFactoriSUN (GLint); GLAPI void APIENTRY glGlobalAlphaFactorfSUN (GLfloat); GLAPI void APIENTRY glGlobalAlphaFactordSUN (GLdouble); GLAPI void APIENTRY glGlobalAlphaFactorubSUN (GLubyte); GLAPI void APIENTRY glGlobalAlphaFactorusSUN (GLushort); GLAPI void APIENTRY glGlobalAlphaFactoruiSUN (GLuint); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORBSUNPROC) (GLbyte factor); typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORSSUNPROC) (GLshort factor); typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORISUNPROC) (GLint factor); typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORFSUNPROC) (GLfloat factor); typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORDSUNPROC) (GLdouble factor); typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORUBSUNPROC) (GLubyte factor); typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORUSSUNPROC) (GLushort factor); typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORUISUNPROC) (GLuint factor); #endif #ifndef GL_SUN_triangle_list #define GL_SUN_triangle_list 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glReplacementCodeuiSUN (GLuint); GLAPI void APIENTRY glReplacementCodeusSUN (GLushort); GLAPI void APIENTRY glReplacementCodeubSUN (GLubyte); GLAPI void APIENTRY glReplacementCodeuivSUN (const GLuint *); GLAPI void APIENTRY glReplacementCodeusvSUN (const GLushort *); GLAPI void APIENTRY glReplacementCodeubvSUN (const GLubyte *); GLAPI void APIENTRY glReplacementCodePointerSUN (GLenum, GLsizei, const GLvoid* *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLREPLACEMENTCODEUISUNPROC) (GLuint code); typedef void (APIENTRYP PFNGLREPLACEMENTCODEUSSUNPROC) (GLushort code); typedef void (APIENTRYP PFNGLREPLACEMENTCODEUBSUNPROC) (GLubyte code); typedef void (APIENTRYP PFNGLREPLACEMENTCODEUIVSUNPROC) (const GLuint *code); typedef void (APIENTRYP PFNGLREPLACEMENTCODEUSVSUNPROC) (const GLushort *code); typedef void (APIENTRYP PFNGLREPLACEMENTCODEUBVSUNPROC) (const GLubyte *code); typedef void (APIENTRYP PFNGLREPLACEMENTCODEPOINTERSUNPROC) (GLenum type, GLsizei stride, const GLvoid* *pointer); #endif #ifndef GL_SUN_vertex #define GL_SUN_vertex 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glColor4ubVertex2fSUN (GLubyte, GLubyte, GLubyte, GLubyte, GLfloat, GLfloat); GLAPI void APIENTRY glColor4ubVertex2fvSUN (const GLubyte *, const GLfloat *); GLAPI void APIENTRY glColor4ubVertex3fSUN (GLubyte, GLubyte, GLubyte, GLubyte, GLfloat, GLfloat, GLfloat); GLAPI void APIENTRY glColor4ubVertex3fvSUN (const GLubyte *, const GLfloat *); GLAPI void APIENTRY glColor3fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat); GLAPI void APIENTRY glColor3fVertex3fvSUN (const GLfloat *, const GLfloat *); GLAPI void APIENTRY glNormal3fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat); GLAPI void APIENTRY glNormal3fVertex3fvSUN (const GLfloat *, const GLfloat *); GLAPI void APIENTRY glColor4fNormal3fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat); GLAPI void APIENTRY glColor4fNormal3fVertex3fvSUN (const GLfloat *, const GLfloat *, const GLfloat *); GLAPI void APIENTRY glTexCoord2fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat); GLAPI void APIENTRY glTexCoord2fVertex3fvSUN (const GLfloat *, const GLfloat *); GLAPI void APIENTRY glTexCoord4fVertex4fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat); GLAPI void APIENTRY glTexCoord4fVertex4fvSUN (const GLfloat *, const GLfloat *); GLAPI void APIENTRY glTexCoord2fColor4ubVertex3fSUN (GLfloat, GLfloat, GLubyte, GLubyte, GLubyte, GLubyte, GLfloat, GLfloat, GLfloat); GLAPI void APIENTRY glTexCoord2fColor4ubVertex3fvSUN (const GLfloat *, const GLubyte *, const GLfloat *); GLAPI void APIENTRY glTexCoord2fColor3fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat); GLAPI void APIENTRY glTexCoord2fColor3fVertex3fvSUN (const GLfloat *, const GLfloat *, const GLfloat *); GLAPI void APIENTRY glTexCoord2fNormal3fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat); GLAPI void APIENTRY glTexCoord2fNormal3fVertex3fvSUN (const GLfloat *, const GLfloat *, const GLfloat *); GLAPI void APIENTRY glTexCoord2fColor4fNormal3fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat); GLAPI void APIENTRY glTexCoord2fColor4fNormal3fVertex3fvSUN (const GLfloat *, const GLfloat *, const GLfloat *, const GLfloat *); GLAPI void APIENTRY glTexCoord4fColor4fNormal3fVertex4fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat); GLAPI void APIENTRY glTexCoord4fColor4fNormal3fVertex4fvSUN (const GLfloat *, const GLfloat *, const GLfloat *, const GLfloat *); GLAPI void APIENTRY glReplacementCodeuiVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat); GLAPI void APIENTRY glReplacementCodeuiVertex3fvSUN (const GLuint *, const GLfloat *); GLAPI void APIENTRY glReplacementCodeuiColor4ubVertex3fSUN (GLuint, GLubyte, GLubyte, GLubyte, GLubyte, GLfloat, GLfloat, GLfloat); GLAPI void APIENTRY glReplacementCodeuiColor4ubVertex3fvSUN (const GLuint *, const GLubyte *, const GLfloat *); GLAPI void APIENTRY glReplacementCodeuiColor3fVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat); GLAPI void APIENTRY glReplacementCodeuiColor3fVertex3fvSUN (const GLuint *, const GLfloat *, const GLfloat *); GLAPI void APIENTRY glReplacementCodeuiNormal3fVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat); GLAPI void APIENTRY glReplacementCodeuiNormal3fVertex3fvSUN (const GLuint *, const GLfloat *, const GLfloat *); GLAPI void APIENTRY glReplacementCodeuiColor4fNormal3fVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat); GLAPI void APIENTRY glReplacementCodeuiColor4fNormal3fVertex3fvSUN (const GLuint *, const GLfloat *, const GLfloat *, const GLfloat *); GLAPI void APIENTRY glReplacementCodeuiTexCoord2fVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat); GLAPI void APIENTRY glReplacementCodeuiTexCoord2fVertex3fvSUN (const GLuint *, const GLfloat *, const GLfloat *); GLAPI void APIENTRY glReplacementCodeuiTexCoord2fNormal3fVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat); GLAPI void APIENTRY glReplacementCodeuiTexCoord2fNormal3fVertex3fvSUN (const GLuint *, const GLfloat *, const GLfloat *, const GLfloat *); GLAPI void APIENTRY glReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat); GLAPI void APIENTRY glReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fvSUN (const GLuint *, const GLfloat *, const GLfloat *, const GLfloat *, const GLfloat *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLCOLOR4UBVERTEX2FSUNPROC) (GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y); typedef void (APIENTRYP PFNGLCOLOR4UBVERTEX2FVSUNPROC) (const GLubyte *c, const GLfloat *v); typedef void (APIENTRYP PFNGLCOLOR4UBVERTEX3FSUNPROC) (GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z); typedef void (APIENTRYP PFNGLCOLOR4UBVERTEX3FVSUNPROC) (const GLubyte *c, const GLfloat *v); typedef void (APIENTRYP PFNGLCOLOR3FVERTEX3FSUNPROC) (GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z); typedef void (APIENTRYP PFNGLCOLOR3FVERTEX3FVSUNPROC) (const GLfloat *c, const GLfloat *v); typedef void (APIENTRYP PFNGLNORMAL3FVERTEX3FSUNPROC) (GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); typedef void (APIENTRYP PFNGLNORMAL3FVERTEX3FVSUNPROC) (const GLfloat *n, const GLfloat *v); typedef void (APIENTRYP PFNGLCOLOR4FNORMAL3FVERTEX3FSUNPROC) (GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); typedef void (APIENTRYP PFNGLCOLOR4FNORMAL3FVERTEX3FVSUNPROC) (const GLfloat *c, const GLfloat *n, const GLfloat *v); typedef void (APIENTRYP PFNGLTEXCOORD2FVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLfloat x, GLfloat y, GLfloat z); typedef void (APIENTRYP PFNGLTEXCOORD2FVERTEX3FVSUNPROC) (const GLfloat *tc, const GLfloat *v); typedef void (APIENTRYP PFNGLTEXCOORD4FVERTEX4FSUNPROC) (GLfloat s, GLfloat t, GLfloat p, GLfloat q, GLfloat x, GLfloat y, GLfloat z, GLfloat w); typedef void (APIENTRYP PFNGLTEXCOORD4FVERTEX4FVSUNPROC) (const GLfloat *tc, const GLfloat *v); typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR4UBVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z); typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR4UBVERTEX3FVSUNPROC) (const GLfloat *tc, const GLubyte *c, const GLfloat *v); typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR3FVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z); typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR3FVERTEX3FVSUNPROC) (const GLfloat *tc, const GLfloat *c, const GLfloat *v); typedef void (APIENTRYP PFNGLTEXCOORD2FNORMAL3FVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); typedef void (APIENTRYP PFNGLTEXCOORD2FNORMAL3FVERTEX3FVSUNPROC) (const GLfloat *tc, const GLfloat *n, const GLfloat *v); typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR4FNORMAL3FVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR4FNORMAL3FVERTEX3FVSUNPROC) (const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v); typedef void (APIENTRYP PFNGLTEXCOORD4FCOLOR4FNORMAL3FVERTEX4FSUNPROC) (GLfloat s, GLfloat t, GLfloat p, GLfloat q, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z, GLfloat w); typedef void (APIENTRYP PFNGLTEXCOORD4FCOLOR4FNORMAL3FVERTEX4FVSUNPROC) (const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v); typedef void (APIENTRYP PFNGLREPLACEMENTCODEUIVERTEX3FSUNPROC) (GLuint rc, GLfloat x, GLfloat y, GLfloat z); typedef void (APIENTRYP PFNGLREPLACEMENTCODEUIVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *v); typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR4UBVERTEX3FSUNPROC) (GLuint rc, GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z); typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR4UBVERTEX3FVSUNPROC) (const GLuint *rc, const GLubyte *c, const GLfloat *v); typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR3FVERTEX3FSUNPROC) (GLuint rc, GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z); typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *c, const GLfloat *v); typedef void (APIENTRYP PFNGLREPLACEMENTCODEUINORMAL3FVERTEX3FSUNPROC) (GLuint rc, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); typedef void (APIENTRYP PFNGLREPLACEMENTCODEUINORMAL3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *n, const GLfloat *v); typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR4FNORMAL3FVERTEX3FSUNPROC) (GLuint rc, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR4FNORMAL3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *c, const GLfloat *n, const GLfloat *v); typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FVERTEX3FSUNPROC) (GLuint rc, GLfloat s, GLfloat t, GLfloat x, GLfloat y, GLfloat z); typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *tc, const GLfloat *v); typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FNORMAL3FVERTEX3FSUNPROC) (GLuint rc, GLfloat s, GLfloat t, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FNORMAL3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *tc, const GLfloat *n, const GLfloat *v); typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FCOLOR4FNORMAL3FVERTEX3FSUNPROC) (GLuint rc, GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FCOLOR4FNORMAL3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v); #endif #ifndef GL_EXT_blend_func_separate #define GL_EXT_blend_func_separate 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glBlendFuncSeparateEXT (GLenum, GLenum, GLenum, GLenum); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEEXTPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); #endif #ifndef GL_INGR_blend_func_separate #define GL_INGR_blend_func_separate 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glBlendFuncSeparateINGR (GLenum, GLenum, GLenum, GLenum); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEINGRPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); #endif #ifndef GL_INGR_color_clamp #define GL_INGR_color_clamp 1 #endif #ifndef GL_INGR_interlace_read #define GL_INGR_interlace_read 1 #endif #ifndef GL_EXT_stencil_wrap #define GL_EXT_stencil_wrap 1 #endif #ifndef GL_EXT_422_pixels #define GL_EXT_422_pixels 1 #endif #ifndef GL_NV_texgen_reflection #define GL_NV_texgen_reflection 1 #endif #ifndef GL_SUN_convolution_border_modes #define GL_SUN_convolution_border_modes 1 #endif #ifndef GL_EXT_texture_env_add #define GL_EXT_texture_env_add 1 #endif #ifndef GL_EXT_texture_lod_bias #define GL_EXT_texture_lod_bias 1 #endif #ifndef GL_EXT_texture_filter_anisotropic #define GL_EXT_texture_filter_anisotropic 1 #endif #ifndef GL_EXT_vertex_weighting #define GL_EXT_vertex_weighting 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glVertexWeightfEXT (GLfloat); GLAPI void APIENTRY glVertexWeightfvEXT (const GLfloat *); GLAPI void APIENTRY glVertexWeightPointerEXT (GLsizei, GLenum, GLsizei, const GLvoid *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLVERTEXWEIGHTFEXTPROC) (GLfloat weight); typedef void (APIENTRYP PFNGLVERTEXWEIGHTFVEXTPROC) (const GLfloat *weight); typedef void (APIENTRYP PFNGLVERTEXWEIGHTPOINTEREXTPROC) (GLsizei size, GLenum type, GLsizei stride, const GLvoid *pointer); #endif #ifndef GL_NV_light_max_exponent #define GL_NV_light_max_exponent 1 #endif #ifndef GL_NV_vertex_array_range #define GL_NV_vertex_array_range 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glFlushVertexArrayRangeNV (void); GLAPI void APIENTRY glVertexArrayRangeNV (GLsizei, const GLvoid *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLFLUSHVERTEXARRAYRANGENVPROC) (void); typedef void (APIENTRYP PFNGLVERTEXARRAYRANGENVPROC) (GLsizei length, const GLvoid *pointer); #endif #ifndef GL_NV_register_combiners #define GL_NV_register_combiners 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glCombinerParameterfvNV (GLenum, const GLfloat *); GLAPI void APIENTRY glCombinerParameterfNV (GLenum, GLfloat); GLAPI void APIENTRY glCombinerParameterivNV (GLenum, const GLint *); GLAPI void APIENTRY glCombinerParameteriNV (GLenum, GLint); GLAPI void APIENTRY glCombinerInputNV (GLenum, GLenum, GLenum, GLenum, GLenum, GLenum); GLAPI void APIENTRY glCombinerOutputNV (GLenum, GLenum, GLenum, GLenum, GLenum, GLenum, GLenum, GLboolean, GLboolean, GLboolean); GLAPI void APIENTRY glFinalCombinerInputNV (GLenum, GLenum, GLenum, GLenum); GLAPI void APIENTRY glGetCombinerInputParameterfvNV (GLenum, GLenum, GLenum, GLenum, GLfloat *); GLAPI void APIENTRY glGetCombinerInputParameterivNV (GLenum, GLenum, GLenum, GLenum, GLint *); GLAPI void APIENTRY glGetCombinerOutputParameterfvNV (GLenum, GLenum, GLenum, GLfloat *); GLAPI void APIENTRY glGetCombinerOutputParameterivNV (GLenum, GLenum, GLenum, GLint *); GLAPI void APIENTRY glGetFinalCombinerInputParameterfvNV (GLenum, GLenum, GLfloat *); GLAPI void APIENTRY glGetFinalCombinerInputParameterivNV (GLenum, GLenum, GLint *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLCOMBINERPARAMETERFVNVPROC) (GLenum pname, const GLfloat *params); typedef void (APIENTRYP PFNGLCOMBINERPARAMETERFNVPROC) (GLenum pname, GLfloat param); typedef void (APIENTRYP PFNGLCOMBINERPARAMETERIVNVPROC) (GLenum pname, const GLint *params); typedef void (APIENTRYP PFNGLCOMBINERPARAMETERINVPROC) (GLenum pname, GLint param); typedef void (APIENTRYP PFNGLCOMBINERINPUTNVPROC) (GLenum stage, GLenum portion, GLenum variable, GLenum input, GLenum mapping, GLenum componentUsage); typedef void (APIENTRYP PFNGLCOMBINEROUTPUTNVPROC) (GLenum stage, GLenum portion, GLenum abOutput, GLenum cdOutput, GLenum sumOutput, GLenum scale, GLenum bias, GLboolean abDotProduct, GLboolean cdDotProduct, GLboolean muxSum); typedef void (APIENTRYP PFNGLFINALCOMBINERINPUTNVPROC) (GLenum variable, GLenum input, GLenum mapping, GLenum componentUsage); typedef void (APIENTRYP PFNGLGETCOMBINERINPUTPARAMETERFVNVPROC) (GLenum stage, GLenum portion, GLenum variable, GLenum pname, GLfloat *params); typedef void (APIENTRYP PFNGLGETCOMBINERINPUTPARAMETERIVNVPROC) (GLenum stage, GLenum portion, GLenum variable, GLenum pname, GLint *params); typedef void (APIENTRYP PFNGLGETCOMBINEROUTPUTPARAMETERFVNVPROC) (GLenum stage, GLenum portion, GLenum pname, GLfloat *params); typedef void (APIENTRYP PFNGLGETCOMBINEROUTPUTPARAMETERIVNVPROC) (GLenum stage, GLenum portion, GLenum pname, GLint *params); typedef void (APIENTRYP PFNGLGETFINALCOMBINERINPUTPARAMETERFVNVPROC) (GLenum variable, GLenum pname, GLfloat *params); typedef void (APIENTRYP PFNGLGETFINALCOMBINERINPUTPARAMETERIVNVPROC) (GLenum variable, GLenum pname, GLint *params); #endif #ifndef GL_NV_fog_distance #define GL_NV_fog_distance 1 #endif #ifndef GL_NV_texgen_emboss #define GL_NV_texgen_emboss 1 #endif #ifndef GL_NV_blend_square #define GL_NV_blend_square 1 #endif #ifndef GL_NV_texture_env_combine4 #define GL_NV_texture_env_combine4 1 #endif #ifndef GL_MESA_resize_buffers #define GL_MESA_resize_buffers 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glResizeBuffersMESA (void); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLRESIZEBUFFERSMESAPROC) (void); #endif #ifndef GL_MESA_window_pos #define GL_MESA_window_pos 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glWindowPos2dMESA (GLdouble, GLdouble); GLAPI void APIENTRY glWindowPos2dvMESA (const GLdouble *); GLAPI void APIENTRY glWindowPos2fMESA (GLfloat, GLfloat); GLAPI void APIENTRY glWindowPos2fvMESA (const GLfloat *); GLAPI void APIENTRY glWindowPos2iMESA (GLint, GLint); GLAPI void APIENTRY glWindowPos2ivMESA (const GLint *); GLAPI void APIENTRY glWindowPos2sMESA (GLshort, GLshort); GLAPI void APIENTRY glWindowPos2svMESA (const GLshort *); GLAPI void APIENTRY glWindowPos3dMESA (GLdouble, GLdouble, GLdouble); GLAPI void APIENTRY glWindowPos3dvMESA (const GLdouble *); GLAPI void APIENTRY glWindowPos3fMESA (GLfloat, GLfloat, GLfloat); GLAPI void APIENTRY glWindowPos3fvMESA (const GLfloat *); GLAPI void APIENTRY glWindowPos3iMESA (GLint, GLint, GLint); GLAPI void APIENTRY glWindowPos3ivMESA (const GLint *); GLAPI void APIENTRY glWindowPos3sMESA (GLshort, GLshort, GLshort); GLAPI void APIENTRY glWindowPos3svMESA (const GLshort *); GLAPI void APIENTRY glWindowPos4dMESA (GLdouble, GLdouble, GLdouble, GLdouble); GLAPI void APIENTRY glWindowPos4dvMESA (const GLdouble *); GLAPI void APIENTRY glWindowPos4fMESA (GLfloat, GLfloat, GLfloat, GLfloat); GLAPI void APIENTRY glWindowPos4fvMESA (const GLfloat *); GLAPI void APIENTRY glWindowPos4iMESA (GLint, GLint, GLint, GLint); GLAPI void APIENTRY glWindowPos4ivMESA (const GLint *); GLAPI void APIENTRY glWindowPos4sMESA (GLshort, GLshort, GLshort, GLshort); GLAPI void APIENTRY glWindowPos4svMESA (const GLshort *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLWINDOWPOS2DMESAPROC) (GLdouble x, GLdouble y); typedef void (APIENTRYP PFNGLWINDOWPOS2DVMESAPROC) (const GLdouble *v); typedef void (APIENTRYP PFNGLWINDOWPOS2FMESAPROC) (GLfloat x, GLfloat y); typedef void (APIENTRYP PFNGLWINDOWPOS2FVMESAPROC) (const GLfloat *v); typedef void (APIENTRYP PFNGLWINDOWPOS2IMESAPROC) (GLint x, GLint y); typedef void (APIENTRYP PFNGLWINDOWPOS2IVMESAPROC) (const GLint *v); typedef void (APIENTRYP PFNGLWINDOWPOS2SMESAPROC) (GLshort x, GLshort y); typedef void (APIENTRYP PFNGLWINDOWPOS2SVMESAPROC) (const GLshort *v); typedef void (APIENTRYP PFNGLWINDOWPOS3DMESAPROC) (GLdouble x, GLdouble y, GLdouble z); typedef void (APIENTRYP PFNGLWINDOWPOS3DVMESAPROC) (const GLdouble *v); typedef void (APIENTRYP PFNGLWINDOWPOS3FMESAPROC) (GLfloat x, GLfloat y, GLfloat z); typedef void (APIENTRYP PFNGLWINDOWPOS3FVMESAPROC) (const GLfloat *v); typedef void (APIENTRYP PFNGLWINDOWPOS3IMESAPROC) (GLint x, GLint y, GLint z); typedef void (APIENTRYP PFNGLWINDOWPOS3IVMESAPROC) (const GLint *v); typedef void (APIENTRYP PFNGLWINDOWPOS3SMESAPROC) (GLshort x, GLshort y, GLshort z); typedef void (APIENTRYP PFNGLWINDOWPOS3SVMESAPROC) (const GLshort *v); typedef void (APIENTRYP PFNGLWINDOWPOS4DMESAPROC) (GLdouble x, GLdouble y, GLdouble z, GLdouble w); typedef void (APIENTRYP PFNGLWINDOWPOS4DVMESAPROC) (const GLdouble *v); typedef void (APIENTRYP PFNGLWINDOWPOS4FMESAPROC) (GLfloat x, GLfloat y, GLfloat z, GLfloat w); typedef void (APIENTRYP PFNGLWINDOWPOS4FVMESAPROC) (const GLfloat *v); typedef void (APIENTRYP PFNGLWINDOWPOS4IMESAPROC) (GLint x, GLint y, GLint z, GLint w); typedef void (APIENTRYP PFNGLWINDOWPOS4IVMESAPROC) (const GLint *v); typedef void (APIENTRYP PFNGLWINDOWPOS4SMESAPROC) (GLshort x, GLshort y, GLshort z, GLshort w); typedef void (APIENTRYP PFNGLWINDOWPOS4SVMESAPROC) (const GLshort *v); #endif #ifndef GL_IBM_cull_vertex #define GL_IBM_cull_vertex 1 #endif #ifndef GL_IBM_multimode_draw_arrays #define GL_IBM_multimode_draw_arrays 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glMultiModeDrawArraysIBM (const GLenum *, const GLint *, const GLsizei *, GLsizei, GLint); GLAPI void APIENTRY glMultiModeDrawElementsIBM (const GLenum *, const GLsizei *, GLenum, const GLvoid* const *, GLsizei, GLint); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLMULTIMODEDRAWARRAYSIBMPROC) (const GLenum *mode, const GLint *first, const GLsizei *count, GLsizei primcount, GLint modestride); typedef void (APIENTRYP PFNGLMULTIMODEDRAWELEMENTSIBMPROC) (const GLenum *mode, const GLsizei *count, GLenum type, const GLvoid* const *indices, GLsizei primcount, GLint modestride); #endif #ifndef GL_IBM_vertex_array_lists #define GL_IBM_vertex_array_lists 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glColorPointerListIBM (GLint, GLenum, GLint, const GLvoid* *, GLint); GLAPI void APIENTRY glSecondaryColorPointerListIBM (GLint, GLenum, GLint, const GLvoid* *, GLint); GLAPI void APIENTRY glEdgeFlagPointerListIBM (GLint, const GLboolean* *, GLint); GLAPI void APIENTRY glFogCoordPointerListIBM (GLenum, GLint, const GLvoid* *, GLint); GLAPI void APIENTRY glIndexPointerListIBM (GLenum, GLint, const GLvoid* *, GLint); GLAPI void APIENTRY glNormalPointerListIBM (GLenum, GLint, const GLvoid* *, GLint); GLAPI void APIENTRY glTexCoordPointerListIBM (GLint, GLenum, GLint, const GLvoid* *, GLint); GLAPI void APIENTRY glVertexPointerListIBM (GLint, GLenum, GLint, const GLvoid* *, GLint); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLCOLORPOINTERLISTIBMPROC) (GLint size, GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride); typedef void (APIENTRYP PFNGLSECONDARYCOLORPOINTERLISTIBMPROC) (GLint size, GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride); typedef void (APIENTRYP PFNGLEDGEFLAGPOINTERLISTIBMPROC) (GLint stride, const GLboolean* *pointer, GLint ptrstride); typedef void (APIENTRYP PFNGLFOGCOORDPOINTERLISTIBMPROC) (GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride); typedef void (APIENTRYP PFNGLINDEXPOINTERLISTIBMPROC) (GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride); typedef void (APIENTRYP PFNGLNORMALPOINTERLISTIBMPROC) (GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride); typedef void (APIENTRYP PFNGLTEXCOORDPOINTERLISTIBMPROC) (GLint size, GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride); typedef void (APIENTRYP PFNGLVERTEXPOINTERLISTIBMPROC) (GLint size, GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride); #endif #ifndef GL_SGIX_subsample #define GL_SGIX_subsample 1 #endif #ifndef GL_SGIX_ycrcba #define GL_SGIX_ycrcba 1 #endif #ifndef GL_SGIX_ycrcb_subsample #define GL_SGIX_ycrcb_subsample 1 #endif #ifndef GL_SGIX_depth_pass_instrument #define GL_SGIX_depth_pass_instrument 1 #endif #ifndef GL_3DFX_texture_compression_FXT1 #define GL_3DFX_texture_compression_FXT1 1 #endif #ifndef GL_3DFX_multisample #define GL_3DFX_multisample 1 #endif #ifndef GL_3DFX_tbuffer #define GL_3DFX_tbuffer 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glTbufferMask3DFX (GLuint); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLTBUFFERMASK3DFXPROC) (GLuint mask); #endif #ifndef GL_EXT_multisample #define GL_EXT_multisample 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glSampleMaskEXT (GLclampf, GLboolean); GLAPI void APIENTRY glSamplePatternEXT (GLenum); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLSAMPLEMASKEXTPROC) (GLclampf value, GLboolean invert); typedef void (APIENTRYP PFNGLSAMPLEPATTERNEXTPROC) (GLenum pattern); #endif #ifndef GL_SGIX_vertex_preclip #define GL_SGIX_vertex_preclip 1 #endif #ifndef GL_SGIX_convolution_accuracy #define GL_SGIX_convolution_accuracy 1 #endif #ifndef GL_SGIX_resample #define GL_SGIX_resample 1 #endif #ifndef GL_SGIS_point_line_texgen #define GL_SGIS_point_line_texgen 1 #endif #ifndef GL_SGIS_texture_color_mask #define GL_SGIS_texture_color_mask 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glTextureColorMaskSGIS (GLboolean, GLboolean, GLboolean, GLboolean); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLTEXTURECOLORMASKSGISPROC) (GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha); #endif #ifndef GL_SGIX_igloo_interface #define GL_SGIX_igloo_interface 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glIglooInterfaceSGIX (GLenum, const GLvoid *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLIGLOOINTERFACESGIXPROC) (GLenum pname, const GLvoid *params); #endif #ifndef GL_EXT_texture_env_dot3 #define GL_EXT_texture_env_dot3 1 #endif #ifndef GL_ATI_texture_mirror_once #define GL_ATI_texture_mirror_once 1 #endif #ifndef GL_NV_fence #define GL_NV_fence 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glDeleteFencesNV (GLsizei, const GLuint *); GLAPI void APIENTRY glGenFencesNV (GLsizei, GLuint *); GLAPI GLboolean APIENTRY glIsFenceNV (GLuint); GLAPI GLboolean APIENTRY glTestFenceNV (GLuint); GLAPI void APIENTRY glGetFenceivNV (GLuint, GLenum, GLint *); GLAPI void APIENTRY glFinishFenceNV (GLuint); GLAPI void APIENTRY glSetFenceNV (GLuint, GLenum); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLDELETEFENCESNVPROC) (GLsizei n, const GLuint *fences); typedef void (APIENTRYP PFNGLGENFENCESNVPROC) (GLsizei n, GLuint *fences); typedef GLboolean (APIENTRYP PFNGLISFENCENVPROC) (GLuint fence); typedef GLboolean (APIENTRYP PFNGLTESTFENCENVPROC) (GLuint fence); typedef void (APIENTRYP PFNGLGETFENCEIVNVPROC) (GLuint fence, GLenum pname, GLint *params); typedef void (APIENTRYP PFNGLFINISHFENCENVPROC) (GLuint fence); typedef void (APIENTRYP PFNGLSETFENCENVPROC) (GLuint fence, GLenum condition); #endif #ifndef GL_NV_evaluators #define GL_NV_evaluators 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glMapControlPointsNV (GLenum, GLuint, GLenum, GLsizei, GLsizei, GLint, GLint, GLboolean, const GLvoid *); GLAPI void APIENTRY glMapParameterivNV (GLenum, GLenum, const GLint *); GLAPI void APIENTRY glMapParameterfvNV (GLenum, GLenum, const GLfloat *); GLAPI void APIENTRY glGetMapControlPointsNV (GLenum, GLuint, GLenum, GLsizei, GLsizei, GLboolean, GLvoid *); GLAPI void APIENTRY glGetMapParameterivNV (GLenum, GLenum, GLint *); GLAPI void APIENTRY glGetMapParameterfvNV (GLenum, GLenum, GLfloat *); GLAPI void APIENTRY glGetMapAttribParameterivNV (GLenum, GLuint, GLenum, GLint *); GLAPI void APIENTRY glGetMapAttribParameterfvNV (GLenum, GLuint, GLenum, GLfloat *); GLAPI void APIENTRY glEvalMapsNV (GLenum, GLenum); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLMAPCONTROLPOINTSNVPROC) (GLenum target, GLuint index, GLenum type, GLsizei ustride, GLsizei vstride, GLint uorder, GLint vorder, GLboolean packed, const GLvoid *points); typedef void (APIENTRYP PFNGLMAPPARAMETERIVNVPROC) (GLenum target, GLenum pname, const GLint *params); typedef void (APIENTRYP PFNGLMAPPARAMETERFVNVPROC) (GLenum target, GLenum pname, const GLfloat *params); typedef void (APIENTRYP PFNGLGETMAPCONTROLPOINTSNVPROC) (GLenum target, GLuint index, GLenum type, GLsizei ustride, GLsizei vstride, GLboolean packed, GLvoid *points); typedef void (APIENTRYP PFNGLGETMAPPARAMETERIVNVPROC) (GLenum target, GLenum pname, GLint *params); typedef void (APIENTRYP PFNGLGETMAPPARAMETERFVNVPROC) (GLenum target, GLenum pname, GLfloat *params); typedef void (APIENTRYP PFNGLGETMAPATTRIBPARAMETERIVNVPROC) (GLenum target, GLuint index, GLenum pname, GLint *params); typedef void (APIENTRYP PFNGLGETMAPATTRIBPARAMETERFVNVPROC) (GLenum target, GLuint index, GLenum pname, GLfloat *params); typedef void (APIENTRYP PFNGLEVALMAPSNVPROC) (GLenum target, GLenum mode); #endif #ifndef GL_NV_packed_depth_stencil #define GL_NV_packed_depth_stencil 1 #endif #ifndef GL_NV_register_combiners2 #define GL_NV_register_combiners2 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glCombinerStageParameterfvNV (GLenum, GLenum, const GLfloat *); GLAPI void APIENTRY glGetCombinerStageParameterfvNV (GLenum, GLenum, GLfloat *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLCOMBINERSTAGEPARAMETERFVNVPROC) (GLenum stage, GLenum pname, const GLfloat *params); typedef void (APIENTRYP PFNGLGETCOMBINERSTAGEPARAMETERFVNVPROC) (GLenum stage, GLenum pname, GLfloat *params); #endif #ifndef GL_NV_texture_compression_vtc #define GL_NV_texture_compression_vtc 1 #endif #ifndef GL_NV_texture_rectangle #define GL_NV_texture_rectangle 1 #endif #ifndef GL_NV_texture_shader #define GL_NV_texture_shader 1 #endif #ifndef GL_NV_texture_shader2 #define GL_NV_texture_shader2 1 #endif #ifndef GL_NV_vertex_array_range2 #define GL_NV_vertex_array_range2 1 #endif #ifndef GL_NV_vertex_program #define GL_NV_vertex_program 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI GLboolean APIENTRY glAreProgramsResidentNV (GLsizei, const GLuint *, GLboolean *); GLAPI void APIENTRY glBindProgramNV (GLenum, GLuint); GLAPI void APIENTRY glDeleteProgramsNV (GLsizei, const GLuint *); GLAPI void APIENTRY glExecuteProgramNV (GLenum, GLuint, const GLfloat *); GLAPI void APIENTRY glGenProgramsNV (GLsizei, GLuint *); GLAPI void APIENTRY glGetProgramParameterdvNV (GLenum, GLuint, GLenum, GLdouble *); GLAPI void APIENTRY glGetProgramParameterfvNV (GLenum, GLuint, GLenum, GLfloat *); GLAPI void APIENTRY glGetProgramivNV (GLuint, GLenum, GLint *); GLAPI void APIENTRY glGetProgramStringNV (GLuint, GLenum, GLubyte *); GLAPI void APIENTRY glGetTrackMatrixivNV (GLenum, GLuint, GLenum, GLint *); GLAPI void APIENTRY glGetVertexAttribdvNV (GLuint, GLenum, GLdouble *); GLAPI void APIENTRY glGetVertexAttribfvNV (GLuint, GLenum, GLfloat *); GLAPI void APIENTRY glGetVertexAttribivNV (GLuint, GLenum, GLint *); GLAPI void APIENTRY glGetVertexAttribPointervNV (GLuint, GLenum, GLvoid* *); GLAPI GLboolean APIENTRY glIsProgramNV (GLuint); GLAPI void APIENTRY glLoadProgramNV (GLenum, GLuint, GLsizei, const GLubyte *); GLAPI void APIENTRY glProgramParameter4dNV (GLenum, GLuint, GLdouble, GLdouble, GLdouble, GLdouble); GLAPI void APIENTRY glProgramParameter4dvNV (GLenum, GLuint, const GLdouble *); GLAPI void APIENTRY glProgramParameter4fNV (GLenum, GLuint, GLfloat, GLfloat, GLfloat, GLfloat); GLAPI void APIENTRY glProgramParameter4fvNV (GLenum, GLuint, const GLfloat *); GLAPI void APIENTRY glProgramParameters4dvNV (GLenum, GLuint, GLuint, const GLdouble *); GLAPI void APIENTRY glProgramParameters4fvNV (GLenum, GLuint, GLuint, const GLfloat *); GLAPI void APIENTRY glRequestResidentProgramsNV (GLsizei, const GLuint *); GLAPI void APIENTRY glTrackMatrixNV (GLenum, GLuint, GLenum, GLenum); GLAPI void APIENTRY glVertexAttribPointerNV (GLuint, GLint, GLenum, GLsizei, const GLvoid *); GLAPI void APIENTRY glVertexAttrib1dNV (GLuint, GLdouble); GLAPI void APIENTRY glVertexAttrib1dvNV (GLuint, const GLdouble *); GLAPI void APIENTRY glVertexAttrib1fNV (GLuint, GLfloat); GLAPI void APIENTRY glVertexAttrib1fvNV (GLuint, const GLfloat *); GLAPI void APIENTRY glVertexAttrib1sNV (GLuint, GLshort); GLAPI void APIENTRY glVertexAttrib1svNV (GLuint, const GLshort *); GLAPI void APIENTRY glVertexAttrib2dNV (GLuint, GLdouble, GLdouble); GLAPI void APIENTRY glVertexAttrib2dvNV (GLuint, const GLdouble *); GLAPI void APIENTRY glVertexAttrib2fNV (GLuint, GLfloat, GLfloat); GLAPI void APIENTRY glVertexAttrib2fvNV (GLuint, const GLfloat *); GLAPI void APIENTRY glVertexAttrib2sNV (GLuint, GLshort, GLshort); GLAPI void APIENTRY glVertexAttrib2svNV (GLuint, const GLshort *); GLAPI void APIENTRY glVertexAttrib3dNV (GLuint, GLdouble, GLdouble, GLdouble); GLAPI void APIENTRY glVertexAttrib3dvNV (GLuint, const GLdouble *); GLAPI void APIENTRY glVertexAttrib3fNV (GLuint, GLfloat, GLfloat, GLfloat); GLAPI void APIENTRY glVertexAttrib3fvNV (GLuint, const GLfloat *); GLAPI void APIENTRY glVertexAttrib3sNV (GLuint, GLshort, GLshort, GLshort); GLAPI void APIENTRY glVertexAttrib3svNV (GLuint, const GLshort *); GLAPI void APIENTRY glVertexAttrib4dNV (GLuint, GLdouble, GLdouble, GLdouble, GLdouble); GLAPI void APIENTRY glVertexAttrib4dvNV (GLuint, const GLdouble *); GLAPI void APIENTRY glVertexAttrib4fNV (GLuint, GLfloat, GLfloat, GLfloat, GLfloat); GLAPI void APIENTRY glVertexAttrib4fvNV (GLuint, const GLfloat *); GLAPI void APIENTRY glVertexAttrib4sNV (GLuint, GLshort, GLshort, GLshort, GLshort); GLAPI void APIENTRY glVertexAttrib4svNV (GLuint, const GLshort *); GLAPI void APIENTRY glVertexAttrib4ubNV (GLuint, GLubyte, GLubyte, GLubyte, GLubyte); GLAPI void APIENTRY glVertexAttrib4ubvNV (GLuint, const GLubyte *); GLAPI void APIENTRY glVertexAttribs1dvNV (GLuint, GLsizei, const GLdouble *); GLAPI void APIENTRY glVertexAttribs1fvNV (GLuint, GLsizei, const GLfloat *); GLAPI void APIENTRY glVertexAttribs1svNV (GLuint, GLsizei, const GLshort *); GLAPI void APIENTRY glVertexAttribs2dvNV (GLuint, GLsizei, const GLdouble *); GLAPI void APIENTRY glVertexAttribs2fvNV (GLuint, GLsizei, const GLfloat *); GLAPI void APIENTRY glVertexAttribs2svNV (GLuint, GLsizei, const GLshort *); GLAPI void APIENTRY glVertexAttribs3dvNV (GLuint, GLsizei, const GLdouble *); GLAPI void APIENTRY glVertexAttribs3fvNV (GLuint, GLsizei, const GLfloat *); GLAPI void APIENTRY glVertexAttribs3svNV (GLuint, GLsizei, const GLshort *); GLAPI void APIENTRY glVertexAttribs4dvNV (GLuint, GLsizei, const GLdouble *); GLAPI void APIENTRY glVertexAttribs4fvNV (GLuint, GLsizei, const GLfloat *); GLAPI void APIENTRY glVertexAttribs4svNV (GLuint, GLsizei, const GLshort *); GLAPI void APIENTRY glVertexAttribs4ubvNV (GLuint, GLsizei, const GLubyte *); #endif /* GL_GLEXT_PROTOTYPES */ typedef GLboolean (APIENTRYP PFNGLAREPROGRAMSRESIDENTNVPROC) (GLsizei n, const GLuint *programs, GLboolean *residences); typedef void (APIENTRYP PFNGLBINDPROGRAMNVPROC) (GLenum target, GLuint id); typedef void (APIENTRYP PFNGLDELETEPROGRAMSNVPROC) (GLsizei n, const GLuint *programs); typedef void (APIENTRYP PFNGLEXECUTEPROGRAMNVPROC) (GLenum target, GLuint id, const GLfloat *params); typedef void (APIENTRYP PFNGLGENPROGRAMSNVPROC) (GLsizei n, GLuint *programs); typedef void (APIENTRYP PFNGLGETPROGRAMPARAMETERDVNVPROC) (GLenum target, GLuint index, GLenum pname, GLdouble *params); typedef void (APIENTRYP PFNGLGETPROGRAMPARAMETERFVNVPROC) (GLenum target, GLuint index, GLenum pname, GLfloat *params); typedef void (APIENTRYP PFNGLGETPROGRAMIVNVPROC) (GLuint id, GLenum pname, GLint *params); typedef void (APIENTRYP PFNGLGETPROGRAMSTRINGNVPROC) (GLuint id, GLenum pname, GLubyte *program); typedef void (APIENTRYP PFNGLGETTRACKMATRIXIVNVPROC) (GLenum target, GLuint address, GLenum pname, GLint *params); typedef void (APIENTRYP PFNGLGETVERTEXATTRIBDVNVPROC) (GLuint index, GLenum pname, GLdouble *params); typedef void (APIENTRYP PFNGLGETVERTEXATTRIBFVNVPROC) (GLuint index, GLenum pname, GLfloat *params); typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVNVPROC) (GLuint index, GLenum pname, GLint *params); typedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVNVPROC) (GLuint index, GLenum pname, GLvoid* *pointer); typedef GLboolean (APIENTRYP PFNGLISPROGRAMNVPROC) (GLuint id); typedef void (APIENTRYP PFNGLLOADPROGRAMNVPROC) (GLenum target, GLuint id, GLsizei len, const GLubyte *program); typedef void (APIENTRYP PFNGLPROGRAMPARAMETER4DNVPROC) (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); typedef void (APIENTRYP PFNGLPROGRAMPARAMETER4DVNVPROC) (GLenum target, GLuint index, const GLdouble *v); typedef void (APIENTRYP PFNGLPROGRAMPARAMETER4FNVPROC) (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); typedef void (APIENTRYP PFNGLPROGRAMPARAMETER4FVNVPROC) (GLenum target, GLuint index, const GLfloat *v); typedef void (APIENTRYP PFNGLPROGRAMPARAMETERS4DVNVPROC) (GLenum target, GLuint index, GLuint count, const GLdouble *v); typedef void (APIENTRYP PFNGLPROGRAMPARAMETERS4FVNVPROC) (GLenum target, GLuint index, GLuint count, const GLfloat *v); typedef void (APIENTRYP PFNGLREQUESTRESIDENTPROGRAMSNVPROC) (GLsizei n, const GLuint *programs); typedef void (APIENTRYP PFNGLTRACKMATRIXNVPROC) (GLenum target, GLuint address, GLenum matrix, GLenum transform); typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERNVPROC) (GLuint index, GLint fsize, GLenum type, GLsizei stride, const GLvoid *pointer); typedef void (APIENTRYP PFNGLVERTEXATTRIB1DNVPROC) (GLuint index, GLdouble x); typedef void (APIENTRYP PFNGLVERTEXATTRIB1DVNVPROC) (GLuint index, const GLdouble *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB1FNVPROC) (GLuint index, GLfloat x); typedef void (APIENTRYP PFNGLVERTEXATTRIB1FVNVPROC) (GLuint index, const GLfloat *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB1SNVPROC) (GLuint index, GLshort x); typedef void (APIENTRYP PFNGLVERTEXATTRIB1SVNVPROC) (GLuint index, const GLshort *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB2DNVPROC) (GLuint index, GLdouble x, GLdouble y); typedef void (APIENTRYP PFNGLVERTEXATTRIB2DVNVPROC) (GLuint index, const GLdouble *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB2FNVPROC) (GLuint index, GLfloat x, GLfloat y); typedef void (APIENTRYP PFNGLVERTEXATTRIB2FVNVPROC) (GLuint index, const GLfloat *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB2SNVPROC) (GLuint index, GLshort x, GLshort y); typedef void (APIENTRYP PFNGLVERTEXATTRIB2SVNVPROC) (GLuint index, const GLshort *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB3DNVPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z); typedef void (APIENTRYP PFNGLVERTEXATTRIB3DVNVPROC) (GLuint index, const GLdouble *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB3FNVPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z); typedef void (APIENTRYP PFNGLVERTEXATTRIB3FVNVPROC) (GLuint index, const GLfloat *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB3SNVPROC) (GLuint index, GLshort x, GLshort y, GLshort z); typedef void (APIENTRYP PFNGLVERTEXATTRIB3SVNVPROC) (GLuint index, const GLshort *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB4DNVPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); typedef void (APIENTRYP PFNGLVERTEXATTRIB4DVNVPROC) (GLuint index, const GLdouble *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB4FNVPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); typedef void (APIENTRYP PFNGLVERTEXATTRIB4FVNVPROC) (GLuint index, const GLfloat *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB4SNVPROC) (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w); typedef void (APIENTRYP PFNGLVERTEXATTRIB4SVNVPROC) (GLuint index, const GLshort *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB4UBNVPROC) (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w); typedef void (APIENTRYP PFNGLVERTEXATTRIB4UBVNVPROC) (GLuint index, const GLubyte *v); typedef void (APIENTRYP PFNGLVERTEXATTRIBS1DVNVPROC) (GLuint index, GLsizei count, const GLdouble *v); typedef void (APIENTRYP PFNGLVERTEXATTRIBS1FVNVPROC) (GLuint index, GLsizei count, const GLfloat *v); typedef void (APIENTRYP PFNGLVERTEXATTRIBS1SVNVPROC) (GLuint index, GLsizei count, const GLshort *v); typedef void (APIENTRYP PFNGLVERTEXATTRIBS2DVNVPROC) (GLuint index, GLsizei count, const GLdouble *v); typedef void (APIENTRYP PFNGLVERTEXATTRIBS2FVNVPROC) (GLuint index, GLsizei count, const GLfloat *v); typedef void (APIENTRYP PFNGLVERTEXATTRIBS2SVNVPROC) (GLuint index, GLsizei count, const GLshort *v); typedef void (APIENTRYP PFNGLVERTEXATTRIBS3DVNVPROC) (GLuint index, GLsizei count, const GLdouble *v); typedef void (APIENTRYP PFNGLVERTEXATTRIBS3FVNVPROC) (GLuint index, GLsizei count, const GLfloat *v); typedef void (APIENTRYP PFNGLVERTEXATTRIBS3SVNVPROC) (GLuint index, GLsizei count, const GLshort *v); typedef void (APIENTRYP PFNGLVERTEXATTRIBS4DVNVPROC) (GLuint index, GLsizei count, const GLdouble *v); typedef void (APIENTRYP PFNGLVERTEXATTRIBS4FVNVPROC) (GLuint index, GLsizei count, const GLfloat *v); typedef void (APIENTRYP PFNGLVERTEXATTRIBS4SVNVPROC) (GLuint index, GLsizei count, const GLshort *v); typedef void (APIENTRYP PFNGLVERTEXATTRIBS4UBVNVPROC) (GLuint index, GLsizei count, const GLubyte *v); #endif #ifndef GL_SGIX_texture_coordinate_clamp #define GL_SGIX_texture_coordinate_clamp 1 #endif #ifndef GL_SGIX_scalebias_hint #define GL_SGIX_scalebias_hint 1 #endif #ifndef GL_OML_interlace #define GL_OML_interlace 1 #endif #ifndef GL_OML_subsample #define GL_OML_subsample 1 #endif #ifndef GL_OML_resample #define GL_OML_resample 1 #endif #ifndef GL_NV_copy_depth_to_color #define GL_NV_copy_depth_to_color 1 #endif #ifndef GL_ATI_envmap_bumpmap #define GL_ATI_envmap_bumpmap 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glTexBumpParameterivATI (GLenum, const GLint *); GLAPI void APIENTRY glTexBumpParameterfvATI (GLenum, const GLfloat *); GLAPI void APIENTRY glGetTexBumpParameterivATI (GLenum, GLint *); GLAPI void APIENTRY glGetTexBumpParameterfvATI (GLenum, GLfloat *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLTEXBUMPPARAMETERIVATIPROC) (GLenum pname, const GLint *param); typedef void (APIENTRYP PFNGLTEXBUMPPARAMETERFVATIPROC) (GLenum pname, const GLfloat *param); typedef void (APIENTRYP PFNGLGETTEXBUMPPARAMETERIVATIPROC) (GLenum pname, GLint *param); typedef void (APIENTRYP PFNGLGETTEXBUMPPARAMETERFVATIPROC) (GLenum pname, GLfloat *param); #endif #ifndef GL_ATI_fragment_shader #define GL_ATI_fragment_shader 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI GLuint APIENTRY glGenFragmentShadersATI (GLuint); GLAPI void APIENTRY glBindFragmentShaderATI (GLuint); GLAPI void APIENTRY glDeleteFragmentShaderATI (GLuint); GLAPI void APIENTRY glBeginFragmentShaderATI (void); GLAPI void APIENTRY glEndFragmentShaderATI (void); GLAPI void APIENTRY glPassTexCoordATI (GLuint, GLuint, GLenum); GLAPI void APIENTRY glSampleMapATI (GLuint, GLuint, GLenum); GLAPI void APIENTRY glColorFragmentOp1ATI (GLenum, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint); GLAPI void APIENTRY glColorFragmentOp2ATI (GLenum, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint); GLAPI void APIENTRY glColorFragmentOp3ATI (GLenum, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint); GLAPI void APIENTRY glAlphaFragmentOp1ATI (GLenum, GLuint, GLuint, GLuint, GLuint, GLuint); GLAPI void APIENTRY glAlphaFragmentOp2ATI (GLenum, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint); GLAPI void APIENTRY glAlphaFragmentOp3ATI (GLenum, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint); GLAPI void APIENTRY glSetFragmentShaderConstantATI (GLuint, const GLfloat *); #endif /* GL_GLEXT_PROTOTYPES */ typedef GLuint (APIENTRYP PFNGLGENFRAGMENTSHADERSATIPROC) (GLuint range); typedef void (APIENTRYP PFNGLBINDFRAGMENTSHADERATIPROC) (GLuint id); typedef void (APIENTRYP PFNGLDELETEFRAGMENTSHADERATIPROC) (GLuint id); typedef void (APIENTRYP PFNGLBEGINFRAGMENTSHADERATIPROC) (void); typedef void (APIENTRYP PFNGLENDFRAGMENTSHADERATIPROC) (void); typedef void (APIENTRYP PFNGLPASSTEXCOORDATIPROC) (GLuint dst, GLuint coord, GLenum swizzle); typedef void (APIENTRYP PFNGLSAMPLEMAPATIPROC) (GLuint dst, GLuint interp, GLenum swizzle); typedef void (APIENTRYP PFNGLCOLORFRAGMENTOP1ATIPROC) (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod); typedef void (APIENTRYP PFNGLCOLORFRAGMENTOP2ATIPROC) (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod); typedef void (APIENTRYP PFNGLCOLORFRAGMENTOP3ATIPROC) (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod, GLuint arg3, GLuint arg3Rep, GLuint arg3Mod); typedef void (APIENTRYP PFNGLALPHAFRAGMENTOP1ATIPROC) (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod); typedef void (APIENTRYP PFNGLALPHAFRAGMENTOP2ATIPROC) (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod); typedef void (APIENTRYP PFNGLALPHAFRAGMENTOP3ATIPROC) (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod, GLuint arg3, GLuint arg3Rep, GLuint arg3Mod); typedef void (APIENTRYP PFNGLSETFRAGMENTSHADERCONSTANTATIPROC) (GLuint dst, const GLfloat *value); #endif #ifndef GL_ATI_pn_triangles #define GL_ATI_pn_triangles 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glPNTrianglesiATI (GLenum, GLint); GLAPI void APIENTRY glPNTrianglesfATI (GLenum, GLfloat); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLPNTRIANGLESIATIPROC) (GLenum pname, GLint param); typedef void (APIENTRYP PFNGLPNTRIANGLESFATIPROC) (GLenum pname, GLfloat param); #endif #ifndef GL_ATI_vertex_array_object #define GL_ATI_vertex_array_object 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI GLuint APIENTRY glNewObjectBufferATI (GLsizei, const GLvoid *, GLenum); GLAPI GLboolean APIENTRY glIsObjectBufferATI (GLuint); GLAPI void APIENTRY glUpdateObjectBufferATI (GLuint, GLuint, GLsizei, const GLvoid *, GLenum); GLAPI void APIENTRY glGetObjectBufferfvATI (GLuint, GLenum, GLfloat *); GLAPI void APIENTRY glGetObjectBufferivATI (GLuint, GLenum, GLint *); GLAPI void APIENTRY glFreeObjectBufferATI (GLuint); GLAPI void APIENTRY glArrayObjectATI (GLenum, GLint, GLenum, GLsizei, GLuint, GLuint); GLAPI void APIENTRY glGetArrayObjectfvATI (GLenum, GLenum, GLfloat *); GLAPI void APIENTRY glGetArrayObjectivATI (GLenum, GLenum, GLint *); GLAPI void APIENTRY glVariantArrayObjectATI (GLuint, GLenum, GLsizei, GLuint, GLuint); GLAPI void APIENTRY glGetVariantArrayObjectfvATI (GLuint, GLenum, GLfloat *); GLAPI void APIENTRY glGetVariantArrayObjectivATI (GLuint, GLenum, GLint *); #endif /* GL_GLEXT_PROTOTYPES */ typedef GLuint (APIENTRYP PFNGLNEWOBJECTBUFFERATIPROC) (GLsizei size, const GLvoid *pointer, GLenum usage); typedef GLboolean (APIENTRYP PFNGLISOBJECTBUFFERATIPROC) (GLuint buffer); typedef void (APIENTRYP PFNGLUPDATEOBJECTBUFFERATIPROC) (GLuint buffer, GLuint offset, GLsizei size, const GLvoid *pointer, GLenum preserve); typedef void (APIENTRYP PFNGLGETOBJECTBUFFERFVATIPROC) (GLuint buffer, GLenum pname, GLfloat *params); typedef void (APIENTRYP PFNGLGETOBJECTBUFFERIVATIPROC) (GLuint buffer, GLenum pname, GLint *params); typedef void (APIENTRYP PFNGLFREEOBJECTBUFFERATIPROC) (GLuint buffer); typedef void (APIENTRYP PFNGLARRAYOBJECTATIPROC) (GLenum array, GLint size, GLenum type, GLsizei stride, GLuint buffer, GLuint offset); typedef void (APIENTRYP PFNGLGETARRAYOBJECTFVATIPROC) (GLenum array, GLenum pname, GLfloat *params); typedef void (APIENTRYP PFNGLGETARRAYOBJECTIVATIPROC) (GLenum array, GLenum pname, GLint *params); typedef void (APIENTRYP PFNGLVARIANTARRAYOBJECTATIPROC) (GLuint id, GLenum type, GLsizei stride, GLuint buffer, GLuint offset); typedef void (APIENTRYP PFNGLGETVARIANTARRAYOBJECTFVATIPROC) (GLuint id, GLenum pname, GLfloat *params); typedef void (APIENTRYP PFNGLGETVARIANTARRAYOBJECTIVATIPROC) (GLuint id, GLenum pname, GLint *params); #endif #ifndef GL_EXT_vertex_shader #define GL_EXT_vertex_shader 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glBeginVertexShaderEXT (void); GLAPI void APIENTRY glEndVertexShaderEXT (void); GLAPI void APIENTRY glBindVertexShaderEXT (GLuint); GLAPI GLuint APIENTRY glGenVertexShadersEXT (GLuint); GLAPI void APIENTRY glDeleteVertexShaderEXT (GLuint); GLAPI void APIENTRY glShaderOp1EXT (GLenum, GLuint, GLuint); GLAPI void APIENTRY glShaderOp2EXT (GLenum, GLuint, GLuint, GLuint); GLAPI void APIENTRY glShaderOp3EXT (GLenum, GLuint, GLuint, GLuint, GLuint); GLAPI void APIENTRY glSwizzleEXT (GLuint, GLuint, GLenum, GLenum, GLenum, GLenum); GLAPI void APIENTRY glWriteMaskEXT (GLuint, GLuint, GLenum, GLenum, GLenum, GLenum); GLAPI void APIENTRY glInsertComponentEXT (GLuint, GLuint, GLuint); GLAPI void APIENTRY glExtractComponentEXT (GLuint, GLuint, GLuint); GLAPI GLuint APIENTRY glGenSymbolsEXT (GLenum, GLenum, GLenum, GLuint); GLAPI void APIENTRY glSetInvariantEXT (GLuint, GLenum, const GLvoid *); GLAPI void APIENTRY glSetLocalConstantEXT (GLuint, GLenum, const GLvoid *); GLAPI void APIENTRY glVariantbvEXT (GLuint, const GLbyte *); GLAPI void APIENTRY glVariantsvEXT (GLuint, const GLshort *); GLAPI void APIENTRY glVariantivEXT (GLuint, const GLint *); GLAPI void APIENTRY glVariantfvEXT (GLuint, const GLfloat *); GLAPI void APIENTRY glVariantdvEXT (GLuint, const GLdouble *); GLAPI void APIENTRY glVariantubvEXT (GLuint, const GLubyte *); GLAPI void APIENTRY glVariantusvEXT (GLuint, const GLushort *); GLAPI void APIENTRY glVariantuivEXT (GLuint, const GLuint *); GLAPI void APIENTRY glVariantPointerEXT (GLuint, GLenum, GLuint, const GLvoid *); GLAPI void APIENTRY glEnableVariantClientStateEXT (GLuint); GLAPI void APIENTRY glDisableVariantClientStateEXT (GLuint); GLAPI GLuint APIENTRY glBindLightParameterEXT (GLenum, GLenum); GLAPI GLuint APIENTRY glBindMaterialParameterEXT (GLenum, GLenum); GLAPI GLuint APIENTRY glBindTexGenParameterEXT (GLenum, GLenum, GLenum); GLAPI GLuint APIENTRY glBindTextureUnitParameterEXT (GLenum, GLenum); GLAPI GLuint APIENTRY glBindParameterEXT (GLenum); GLAPI GLboolean APIENTRY glIsVariantEnabledEXT (GLuint, GLenum); GLAPI void APIENTRY glGetVariantBooleanvEXT (GLuint, GLenum, GLboolean *); GLAPI void APIENTRY glGetVariantIntegervEXT (GLuint, GLenum, GLint *); GLAPI void APIENTRY glGetVariantFloatvEXT (GLuint, GLenum, GLfloat *); GLAPI void APIENTRY glGetVariantPointervEXT (GLuint, GLenum, GLvoid* *); GLAPI void APIENTRY glGetInvariantBooleanvEXT (GLuint, GLenum, GLboolean *); GLAPI void APIENTRY glGetInvariantIntegervEXT (GLuint, GLenum, GLint *); GLAPI void APIENTRY glGetInvariantFloatvEXT (GLuint, GLenum, GLfloat *); GLAPI void APIENTRY glGetLocalConstantBooleanvEXT (GLuint, GLenum, GLboolean *); GLAPI void APIENTRY glGetLocalConstantIntegervEXT (GLuint, GLenum, GLint *); GLAPI void APIENTRY glGetLocalConstantFloatvEXT (GLuint, GLenum, GLfloat *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLBEGINVERTEXSHADEREXTPROC) (void); typedef void (APIENTRYP PFNGLENDVERTEXSHADEREXTPROC) (void); typedef void (APIENTRYP PFNGLBINDVERTEXSHADEREXTPROC) (GLuint id); typedef GLuint (APIENTRYP PFNGLGENVERTEXSHADERSEXTPROC) (GLuint range); typedef void (APIENTRYP PFNGLDELETEVERTEXSHADEREXTPROC) (GLuint id); typedef void (APIENTRYP PFNGLSHADEROP1EXTPROC) (GLenum op, GLuint res, GLuint arg1); typedef void (APIENTRYP PFNGLSHADEROP2EXTPROC) (GLenum op, GLuint res, GLuint arg1, GLuint arg2); typedef void (APIENTRYP PFNGLSHADEROP3EXTPROC) (GLenum op, GLuint res, GLuint arg1, GLuint arg2, GLuint arg3); typedef void (APIENTRYP PFNGLSWIZZLEEXTPROC) (GLuint res, GLuint in, GLenum outX, GLenum outY, GLenum outZ, GLenum outW); typedef void (APIENTRYP PFNGLWRITEMASKEXTPROC) (GLuint res, GLuint in, GLenum outX, GLenum outY, GLenum outZ, GLenum outW); typedef void (APIENTRYP PFNGLINSERTCOMPONENTEXTPROC) (GLuint res, GLuint src, GLuint num); typedef void (APIENTRYP PFNGLEXTRACTCOMPONENTEXTPROC) (GLuint res, GLuint src, GLuint num); typedef GLuint (APIENTRYP PFNGLGENSYMBOLSEXTPROC) (GLenum datatype, GLenum storagetype, GLenum range, GLuint components); typedef void (APIENTRYP PFNGLSETINVARIANTEXTPROC) (GLuint id, GLenum type, const GLvoid *addr); typedef void (APIENTRYP PFNGLSETLOCALCONSTANTEXTPROC) (GLuint id, GLenum type, const GLvoid *addr); typedef void (APIENTRYP PFNGLVARIANTBVEXTPROC) (GLuint id, const GLbyte *addr); typedef void (APIENTRYP PFNGLVARIANTSVEXTPROC) (GLuint id, const GLshort *addr); typedef void (APIENTRYP PFNGLVARIANTIVEXTPROC) (GLuint id, const GLint *addr); typedef void (APIENTRYP PFNGLVARIANTFVEXTPROC) (GLuint id, const GLfloat *addr); typedef void (APIENTRYP PFNGLVARIANTDVEXTPROC) (GLuint id, const GLdouble *addr); typedef void (APIENTRYP PFNGLVARIANTUBVEXTPROC) (GLuint id, const GLubyte *addr); typedef void (APIENTRYP PFNGLVARIANTUSVEXTPROC) (GLuint id, const GLushort *addr); typedef void (APIENTRYP PFNGLVARIANTUIVEXTPROC) (GLuint id, const GLuint *addr); typedef void (APIENTRYP PFNGLVARIANTPOINTEREXTPROC) (GLuint id, GLenum type, GLuint stride, const GLvoid *addr); typedef void (APIENTRYP PFNGLENABLEVARIANTCLIENTSTATEEXTPROC) (GLuint id); typedef void (APIENTRYP PFNGLDISABLEVARIANTCLIENTSTATEEXTPROC) (GLuint id); typedef GLuint (APIENTRYP PFNGLBINDLIGHTPARAMETEREXTPROC) (GLenum light, GLenum value); typedef GLuint (APIENTRYP PFNGLBINDMATERIALPARAMETEREXTPROC) (GLenum face, GLenum value); typedef GLuint (APIENTRYP PFNGLBINDTEXGENPARAMETEREXTPROC) (GLenum unit, GLenum coord, GLenum value); typedef GLuint (APIENTRYP PFNGLBINDTEXTUREUNITPARAMETEREXTPROC) (GLenum unit, GLenum value); typedef GLuint (APIENTRYP PFNGLBINDPARAMETEREXTPROC) (GLenum value); typedef GLboolean (APIENTRYP PFNGLISVARIANTENABLEDEXTPROC) (GLuint id, GLenum cap); typedef void (APIENTRYP PFNGLGETVARIANTBOOLEANVEXTPROC) (GLuint id, GLenum value, GLboolean *data); typedef void (APIENTRYP PFNGLGETVARIANTINTEGERVEXTPROC) (GLuint id, GLenum value, GLint *data); typedef void (APIENTRYP PFNGLGETVARIANTFLOATVEXTPROC) (GLuint id, GLenum value, GLfloat *data); typedef void (APIENTRYP PFNGLGETVARIANTPOINTERVEXTPROC) (GLuint id, GLenum value, GLvoid* *data); typedef void (APIENTRYP PFNGLGETINVARIANTBOOLEANVEXTPROC) (GLuint id, GLenum value, GLboolean *data); typedef void (APIENTRYP PFNGLGETINVARIANTINTEGERVEXTPROC) (GLuint id, GLenum value, GLint *data); typedef void (APIENTRYP PFNGLGETINVARIANTFLOATVEXTPROC) (GLuint id, GLenum value, GLfloat *data); typedef void (APIENTRYP PFNGLGETLOCALCONSTANTBOOLEANVEXTPROC) (GLuint id, GLenum value, GLboolean *data); typedef void (APIENTRYP PFNGLGETLOCALCONSTANTINTEGERVEXTPROC) (GLuint id, GLenum value, GLint *data); typedef void (APIENTRYP PFNGLGETLOCALCONSTANTFLOATVEXTPROC) (GLuint id, GLenum value, GLfloat *data); #endif #ifndef GL_ATI_vertex_streams #define GL_ATI_vertex_streams 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glVertexStream1sATI (GLenum, GLshort); GLAPI void APIENTRY glVertexStream1svATI (GLenum, const GLshort *); GLAPI void APIENTRY glVertexStream1iATI (GLenum, GLint); GLAPI void APIENTRY glVertexStream1ivATI (GLenum, const GLint *); GLAPI void APIENTRY glVertexStream1fATI (GLenum, GLfloat); GLAPI void APIENTRY glVertexStream1fvATI (GLenum, const GLfloat *); GLAPI void APIENTRY glVertexStream1dATI (GLenum, GLdouble); GLAPI void APIENTRY glVertexStream1dvATI (GLenum, const GLdouble *); GLAPI void APIENTRY glVertexStream2sATI (GLenum, GLshort, GLshort); GLAPI void APIENTRY glVertexStream2svATI (GLenum, const GLshort *); GLAPI void APIENTRY glVertexStream2iATI (GLenum, GLint, GLint); GLAPI void APIENTRY glVertexStream2ivATI (GLenum, const GLint *); GLAPI void APIENTRY glVertexStream2fATI (GLenum, GLfloat, GLfloat); GLAPI void APIENTRY glVertexStream2fvATI (GLenum, const GLfloat *); GLAPI void APIENTRY glVertexStream2dATI (GLenum, GLdouble, GLdouble); GLAPI void APIENTRY glVertexStream2dvATI (GLenum, const GLdouble *); GLAPI void APIENTRY glVertexStream3sATI (GLenum, GLshort, GLshort, GLshort); GLAPI void APIENTRY glVertexStream3svATI (GLenum, const GLshort *); GLAPI void APIENTRY glVertexStream3iATI (GLenum, GLint, GLint, GLint); GLAPI void APIENTRY glVertexStream3ivATI (GLenum, const GLint *); GLAPI void APIENTRY glVertexStream3fATI (GLenum, GLfloat, GLfloat, GLfloat); GLAPI void APIENTRY glVertexStream3fvATI (GLenum, const GLfloat *); GLAPI void APIENTRY glVertexStream3dATI (GLenum, GLdouble, GLdouble, GLdouble); GLAPI void APIENTRY glVertexStream3dvATI (GLenum, const GLdouble *); GLAPI void APIENTRY glVertexStream4sATI (GLenum, GLshort, GLshort, GLshort, GLshort); GLAPI void APIENTRY glVertexStream4svATI (GLenum, const GLshort *); GLAPI void APIENTRY glVertexStream4iATI (GLenum, GLint, GLint, GLint, GLint); GLAPI void APIENTRY glVertexStream4ivATI (GLenum, const GLint *); GLAPI void APIENTRY glVertexStream4fATI (GLenum, GLfloat, GLfloat, GLfloat, GLfloat); GLAPI void APIENTRY glVertexStream4fvATI (GLenum, const GLfloat *); GLAPI void APIENTRY glVertexStream4dATI (GLenum, GLdouble, GLdouble, GLdouble, GLdouble); GLAPI void APIENTRY glVertexStream4dvATI (GLenum, const GLdouble *); GLAPI void APIENTRY glNormalStream3bATI (GLenum, GLbyte, GLbyte, GLbyte); GLAPI void APIENTRY glNormalStream3bvATI (GLenum, const GLbyte *); GLAPI void APIENTRY glNormalStream3sATI (GLenum, GLshort, GLshort, GLshort); GLAPI void APIENTRY glNormalStream3svATI (GLenum, const GLshort *); GLAPI void APIENTRY glNormalStream3iATI (GLenum, GLint, GLint, GLint); GLAPI void APIENTRY glNormalStream3ivATI (GLenum, const GLint *); GLAPI void APIENTRY glNormalStream3fATI (GLenum, GLfloat, GLfloat, GLfloat); GLAPI void APIENTRY glNormalStream3fvATI (GLenum, const GLfloat *); GLAPI void APIENTRY glNormalStream3dATI (GLenum, GLdouble, GLdouble, GLdouble); GLAPI void APIENTRY glNormalStream3dvATI (GLenum, const GLdouble *); GLAPI void APIENTRY glClientActiveVertexStreamATI (GLenum); GLAPI void APIENTRY glVertexBlendEnviATI (GLenum, GLint); GLAPI void APIENTRY glVertexBlendEnvfATI (GLenum, GLfloat); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLVERTEXSTREAM1SATIPROC) (GLenum stream, GLshort x); typedef void (APIENTRYP PFNGLVERTEXSTREAM1SVATIPROC) (GLenum stream, const GLshort *coords); typedef void (APIENTRYP PFNGLVERTEXSTREAM1IATIPROC) (GLenum stream, GLint x); typedef void (APIENTRYP PFNGLVERTEXSTREAM1IVATIPROC) (GLenum stream, const GLint *coords); typedef void (APIENTRYP PFNGLVERTEXSTREAM1FATIPROC) (GLenum stream, GLfloat x); typedef void (APIENTRYP PFNGLVERTEXSTREAM1FVATIPROC) (GLenum stream, const GLfloat *coords); typedef void (APIENTRYP PFNGLVERTEXSTREAM1DATIPROC) (GLenum stream, GLdouble x); typedef void (APIENTRYP PFNGLVERTEXSTREAM1DVATIPROC) (GLenum stream, const GLdouble *coords); typedef void (APIENTRYP PFNGLVERTEXSTREAM2SATIPROC) (GLenum stream, GLshort x, GLshort y); typedef void (APIENTRYP PFNGLVERTEXSTREAM2SVATIPROC) (GLenum stream, const GLshort *coords); typedef void (APIENTRYP PFNGLVERTEXSTREAM2IATIPROC) (GLenum stream, GLint x, GLint y); typedef void (APIENTRYP PFNGLVERTEXSTREAM2IVATIPROC) (GLenum stream, const GLint *coords); typedef void (APIENTRYP PFNGLVERTEXSTREAM2FATIPROC) (GLenum stream, GLfloat x, GLfloat y); typedef void (APIENTRYP PFNGLVERTEXSTREAM2FVATIPROC) (GLenum stream, const GLfloat *coords); typedef void (APIENTRYP PFNGLVERTEXSTREAM2DATIPROC) (GLenum stream, GLdouble x, GLdouble y); typedef void (APIENTRYP PFNGLVERTEXSTREAM2DVATIPROC) (GLenum stream, const GLdouble *coords); typedef void (APIENTRYP PFNGLVERTEXSTREAM3SATIPROC) (GLenum stream, GLshort x, GLshort y, GLshort z); typedef void (APIENTRYP PFNGLVERTEXSTREAM3SVATIPROC) (GLenum stream, const GLshort *coords); typedef void (APIENTRYP PFNGLVERTEXSTREAM3IATIPROC) (GLenum stream, GLint x, GLint y, GLint z); typedef void (APIENTRYP PFNGLVERTEXSTREAM3IVATIPROC) (GLenum stream, const GLint *coords); typedef void (APIENTRYP PFNGLVERTEXSTREAM3FATIPROC) (GLenum stream, GLfloat x, GLfloat y, GLfloat z); typedef void (APIENTRYP PFNGLVERTEXSTREAM3FVATIPROC) (GLenum stream, const GLfloat *coords); typedef void (APIENTRYP PFNGLVERTEXSTREAM3DATIPROC) (GLenum stream, GLdouble x, GLdouble y, GLdouble z); typedef void (APIENTRYP PFNGLVERTEXSTREAM3DVATIPROC) (GLenum stream, const GLdouble *coords); typedef void (APIENTRYP PFNGLVERTEXSTREAM4SATIPROC) (GLenum stream, GLshort x, GLshort y, GLshort z, GLshort w); typedef void (APIENTRYP PFNGLVERTEXSTREAM4SVATIPROC) (GLenum stream, const GLshort *coords); typedef void (APIENTRYP PFNGLVERTEXSTREAM4IATIPROC) (GLenum stream, GLint x, GLint y, GLint z, GLint w); typedef void (APIENTRYP PFNGLVERTEXSTREAM4IVATIPROC) (GLenum stream, const GLint *coords); typedef void (APIENTRYP PFNGLVERTEXSTREAM4FATIPROC) (GLenum stream, GLfloat x, GLfloat y, GLfloat z, GLfloat w); typedef void (APIENTRYP PFNGLVERTEXSTREAM4FVATIPROC) (GLenum stream, const GLfloat *coords); typedef void (APIENTRYP PFNGLVERTEXSTREAM4DATIPROC) (GLenum stream, GLdouble x, GLdouble y, GLdouble z, GLdouble w); typedef void (APIENTRYP PFNGLVERTEXSTREAM4DVATIPROC) (GLenum stream, const GLdouble *coords); typedef void (APIENTRYP PFNGLNORMALSTREAM3BATIPROC) (GLenum stream, GLbyte nx, GLbyte ny, GLbyte nz); typedef void (APIENTRYP PFNGLNORMALSTREAM3BVATIPROC) (GLenum stream, const GLbyte *coords); typedef void (APIENTRYP PFNGLNORMALSTREAM3SATIPROC) (GLenum stream, GLshort nx, GLshort ny, GLshort nz); typedef void (APIENTRYP PFNGLNORMALSTREAM3SVATIPROC) (GLenum stream, const GLshort *coords); typedef void (APIENTRYP PFNGLNORMALSTREAM3IATIPROC) (GLenum stream, GLint nx, GLint ny, GLint nz); typedef void (APIENTRYP PFNGLNORMALSTREAM3IVATIPROC) (GLenum stream, const GLint *coords); typedef void (APIENTRYP PFNGLNORMALSTREAM3FATIPROC) (GLenum stream, GLfloat nx, GLfloat ny, GLfloat nz); typedef void (APIENTRYP PFNGLNORMALSTREAM3FVATIPROC) (GLenum stream, const GLfloat *coords); typedef void (APIENTRYP PFNGLNORMALSTREAM3DATIPROC) (GLenum stream, GLdouble nx, GLdouble ny, GLdouble nz); typedef void (APIENTRYP PFNGLNORMALSTREAM3DVATIPROC) (GLenum stream, const GLdouble *coords); typedef void (APIENTRYP PFNGLCLIENTACTIVEVERTEXSTREAMATIPROC) (GLenum stream); typedef void (APIENTRYP PFNGLVERTEXBLENDENVIATIPROC) (GLenum pname, GLint param); typedef void (APIENTRYP PFNGLVERTEXBLENDENVFATIPROC) (GLenum pname, GLfloat param); #endif #ifndef GL_ATI_element_array #define GL_ATI_element_array 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glElementPointerATI (GLenum, const GLvoid *); GLAPI void APIENTRY glDrawElementArrayATI (GLenum, GLsizei); GLAPI void APIENTRY glDrawRangeElementArrayATI (GLenum, GLuint, GLuint, GLsizei); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLELEMENTPOINTERATIPROC) (GLenum type, const GLvoid *pointer); typedef void (APIENTRYP PFNGLDRAWELEMENTARRAYATIPROC) (GLenum mode, GLsizei count); typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTARRAYATIPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count); #endif #ifndef GL_SUN_mesh_array #define GL_SUN_mesh_array 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glDrawMeshArraysSUN (GLenum, GLint, GLsizei, GLsizei); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLDRAWMESHARRAYSSUNPROC) (GLenum mode, GLint first, GLsizei count, GLsizei width); #endif #ifndef GL_SUN_slice_accum #define GL_SUN_slice_accum 1 #endif #ifndef GL_NV_multisample_filter_hint #define GL_NV_multisample_filter_hint 1 #endif #ifndef GL_NV_depth_clamp #define GL_NV_depth_clamp 1 #endif #ifndef GL_NV_occlusion_query #define GL_NV_occlusion_query 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glGenOcclusionQueriesNV (GLsizei, GLuint *); GLAPI void APIENTRY glDeleteOcclusionQueriesNV (GLsizei, const GLuint *); GLAPI GLboolean APIENTRY glIsOcclusionQueryNV (GLuint); GLAPI void APIENTRY glBeginOcclusionQueryNV (GLuint); GLAPI void APIENTRY glEndOcclusionQueryNV (void); GLAPI void APIENTRY glGetOcclusionQueryivNV (GLuint, GLenum, GLint *); GLAPI void APIENTRY glGetOcclusionQueryuivNV (GLuint, GLenum, GLuint *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLGENOCCLUSIONQUERIESNVPROC) (GLsizei n, GLuint *ids); typedef void (APIENTRYP PFNGLDELETEOCCLUSIONQUERIESNVPROC) (GLsizei n, const GLuint *ids); typedef GLboolean (APIENTRYP PFNGLISOCCLUSIONQUERYNVPROC) (GLuint id); typedef void (APIENTRYP PFNGLBEGINOCCLUSIONQUERYNVPROC) (GLuint id); typedef void (APIENTRYP PFNGLENDOCCLUSIONQUERYNVPROC) (void); typedef void (APIENTRYP PFNGLGETOCCLUSIONQUERYIVNVPROC) (GLuint id, GLenum pname, GLint *params); typedef void (APIENTRYP PFNGLGETOCCLUSIONQUERYUIVNVPROC) (GLuint id, GLenum pname, GLuint *params); #endif #ifndef GL_NV_point_sprite #define GL_NV_point_sprite 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glPointParameteriNV (GLenum, GLint); GLAPI void APIENTRY glPointParameterivNV (GLenum, const GLint *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLPOINTPARAMETERINVPROC) (GLenum pname, GLint param); typedef void (APIENTRYP PFNGLPOINTPARAMETERIVNVPROC) (GLenum pname, const GLint *params); #endif #ifndef GL_NV_texture_shader3 #define GL_NV_texture_shader3 1 #endif #ifndef GL_NV_vertex_program1_1 #define GL_NV_vertex_program1_1 1 #endif #ifndef GL_EXT_shadow_funcs #define GL_EXT_shadow_funcs 1 #endif #ifndef GL_EXT_stencil_two_side #define GL_EXT_stencil_two_side 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glActiveStencilFaceEXT (GLenum); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLACTIVESTENCILFACEEXTPROC) (GLenum face); #endif #ifndef GL_ATI_text_fragment_shader #define GL_ATI_text_fragment_shader 1 #endif #ifndef GL_APPLE_client_storage #define GL_APPLE_client_storage 1 #endif #ifndef GL_APPLE_element_array #define GL_APPLE_element_array 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glElementPointerAPPLE (GLenum, const GLvoid *); GLAPI void APIENTRY glDrawElementArrayAPPLE (GLenum, GLint, GLsizei); GLAPI void APIENTRY glDrawRangeElementArrayAPPLE (GLenum, GLuint, GLuint, GLint, GLsizei); GLAPI void APIENTRY glMultiDrawElementArrayAPPLE (GLenum, const GLint *, const GLsizei *, GLsizei); GLAPI void APIENTRY glMultiDrawRangeElementArrayAPPLE (GLenum, GLuint, GLuint, const GLint *, const GLsizei *, GLsizei); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLELEMENTPOINTERAPPLEPROC) (GLenum type, const GLvoid *pointer); typedef void (APIENTRYP PFNGLDRAWELEMENTARRAYAPPLEPROC) (GLenum mode, GLint first, GLsizei count); typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTARRAYAPPLEPROC) (GLenum mode, GLuint start, GLuint end, GLint first, GLsizei count); typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTARRAYAPPLEPROC) (GLenum mode, const GLint *first, const GLsizei *count, GLsizei primcount); typedef void (APIENTRYP PFNGLMULTIDRAWRANGEELEMENTARRAYAPPLEPROC) (GLenum mode, GLuint start, GLuint end, const GLint *first, const GLsizei *count, GLsizei primcount); #endif #ifndef GL_APPLE_fence #define GL_APPLE_fence 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glGenFencesAPPLE (GLsizei, GLuint *); GLAPI void APIENTRY glDeleteFencesAPPLE (GLsizei, const GLuint *); GLAPI void APIENTRY glSetFenceAPPLE (GLuint); GLAPI GLboolean APIENTRY glIsFenceAPPLE (GLuint); GLAPI GLboolean APIENTRY glTestFenceAPPLE (GLuint); GLAPI void APIENTRY glFinishFenceAPPLE (GLuint); GLAPI GLboolean APIENTRY glTestObjectAPPLE (GLenum, GLuint); GLAPI void APIENTRY glFinishObjectAPPLE (GLenum, GLint); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLGENFENCESAPPLEPROC) (GLsizei n, GLuint *fences); typedef void (APIENTRYP PFNGLDELETEFENCESAPPLEPROC) (GLsizei n, const GLuint *fences); typedef void (APIENTRYP PFNGLSETFENCEAPPLEPROC) (GLuint fence); typedef GLboolean (APIENTRYP PFNGLISFENCEAPPLEPROC) (GLuint fence); typedef GLboolean (APIENTRYP PFNGLTESTFENCEAPPLEPROC) (GLuint fence); typedef void (APIENTRYP PFNGLFINISHFENCEAPPLEPROC) (GLuint fence); typedef GLboolean (APIENTRYP PFNGLTESTOBJECTAPPLEPROC) (GLenum object, GLuint name); typedef void (APIENTRYP PFNGLFINISHOBJECTAPPLEPROC) (GLenum object, GLint name); #endif #ifndef GL_APPLE_vertex_array_object #define GL_APPLE_vertex_array_object 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glBindVertexArrayAPPLE (GLuint); GLAPI void APIENTRY glDeleteVertexArraysAPPLE (GLsizei, const GLuint *); GLAPI void APIENTRY glGenVertexArraysAPPLE (GLsizei, const GLuint *); GLAPI GLboolean APIENTRY glIsVertexArrayAPPLE (GLuint); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLBINDVERTEXARRAYAPPLEPROC) (GLuint array); typedef void (APIENTRYP PFNGLDELETEVERTEXARRAYSAPPLEPROC) (GLsizei n, const GLuint *arrays); typedef void (APIENTRYP PFNGLGENVERTEXARRAYSAPPLEPROC) (GLsizei n, const GLuint *arrays); typedef GLboolean (APIENTRYP PFNGLISVERTEXARRAYAPPLEPROC) (GLuint array); #endif #ifndef GL_APPLE_vertex_array_range #define GL_APPLE_vertex_array_range 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glVertexArrayRangeAPPLE (GLsizei, GLvoid *); GLAPI void APIENTRY glFlushVertexArrayRangeAPPLE (GLsizei, GLvoid *); GLAPI void APIENTRY glVertexArrayParameteriAPPLE (GLenum, GLint); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLVERTEXARRAYRANGEAPPLEPROC) (GLsizei length, GLvoid *pointer); typedef void (APIENTRYP PFNGLFLUSHVERTEXARRAYRANGEAPPLEPROC) (GLsizei length, GLvoid *pointer); typedef void (APIENTRYP PFNGLVERTEXARRAYPARAMETERIAPPLEPROC) (GLenum pname, GLint param); #endif #ifndef GL_APPLE_ycbcr_422 #define GL_APPLE_ycbcr_422 1 #endif #ifndef GL_S3_s3tc #define GL_S3_s3tc 1 #endif #ifndef GL_ATI_draw_buffers #define GL_ATI_draw_buffers 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glDrawBuffersATI (GLsizei, const GLenum *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLDRAWBUFFERSATIPROC) (GLsizei n, const GLenum *bufs); #endif #ifndef GL_ATI_pixel_format_float #define GL_ATI_pixel_format_float 1 /* This is really a WGL extension, but defines some associated GL enums. * ATI does not export "GL_ATI_pixel_format_float" in the GL_EXTENSIONS string. */ #endif #ifndef GL_ATI_texture_env_combine3 #define GL_ATI_texture_env_combine3 1 #endif #ifndef GL_ATI_texture_float #define GL_ATI_texture_float 1 #endif #ifndef GL_NV_float_buffer #define GL_NV_float_buffer 1 #endif #ifndef GL_NV_fragment_program #define GL_NV_fragment_program 1 /* Some NV_fragment_program entry points are shared with ARB_vertex_program. */ #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glProgramNamedParameter4fNV (GLuint, GLsizei, const GLubyte *, GLfloat, GLfloat, GLfloat, GLfloat); GLAPI void APIENTRY glProgramNamedParameter4dNV (GLuint, GLsizei, const GLubyte *, GLdouble, GLdouble, GLdouble, GLdouble); GLAPI void APIENTRY glProgramNamedParameter4fvNV (GLuint, GLsizei, const GLubyte *, const GLfloat *); GLAPI void APIENTRY glProgramNamedParameter4dvNV (GLuint, GLsizei, const GLubyte *, const GLdouble *); GLAPI void APIENTRY glGetProgramNamedParameterfvNV (GLuint, GLsizei, const GLubyte *, GLfloat *); GLAPI void APIENTRY glGetProgramNamedParameterdvNV (GLuint, GLsizei, const GLubyte *, GLdouble *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLPROGRAMNAMEDPARAMETER4FNVPROC) (GLuint id, GLsizei len, const GLubyte *name, GLfloat x, GLfloat y, GLfloat z, GLfloat w); typedef void (APIENTRYP PFNGLPROGRAMNAMEDPARAMETER4DNVPROC) (GLuint id, GLsizei len, const GLubyte *name, GLdouble x, GLdouble y, GLdouble z, GLdouble w); typedef void (APIENTRYP PFNGLPROGRAMNAMEDPARAMETER4FVNVPROC) (GLuint id, GLsizei len, const GLubyte *name, const GLfloat *v); typedef void (APIENTRYP PFNGLPROGRAMNAMEDPARAMETER4DVNVPROC) (GLuint id, GLsizei len, const GLubyte *name, const GLdouble *v); typedef void (APIENTRYP PFNGLGETPROGRAMNAMEDPARAMETERFVNVPROC) (GLuint id, GLsizei len, const GLubyte *name, GLfloat *params); typedef void (APIENTRYP PFNGLGETPROGRAMNAMEDPARAMETERDVNVPROC) (GLuint id, GLsizei len, const GLubyte *name, GLdouble *params); #endif #ifndef GL_NV_half_float #define GL_NV_half_float 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glVertex2hNV (GLhalfNV, GLhalfNV); GLAPI void APIENTRY glVertex2hvNV (const GLhalfNV *); GLAPI void APIENTRY glVertex3hNV (GLhalfNV, GLhalfNV, GLhalfNV); GLAPI void APIENTRY glVertex3hvNV (const GLhalfNV *); GLAPI void APIENTRY glVertex4hNV (GLhalfNV, GLhalfNV, GLhalfNV, GLhalfNV); GLAPI void APIENTRY glVertex4hvNV (const GLhalfNV *); GLAPI void APIENTRY glNormal3hNV (GLhalfNV, GLhalfNV, GLhalfNV); GLAPI void APIENTRY glNormal3hvNV (const GLhalfNV *); GLAPI void APIENTRY glColor3hNV (GLhalfNV, GLhalfNV, GLhalfNV); GLAPI void APIENTRY glColor3hvNV (const GLhalfNV *); GLAPI void APIENTRY glColor4hNV (GLhalfNV, GLhalfNV, GLhalfNV, GLhalfNV); GLAPI void APIENTRY glColor4hvNV (const GLhalfNV *); GLAPI void APIENTRY glTexCoord1hNV (GLhalfNV); GLAPI void APIENTRY glTexCoord1hvNV (const GLhalfNV *); GLAPI void APIENTRY glTexCoord2hNV (GLhalfNV, GLhalfNV); GLAPI void APIENTRY glTexCoord2hvNV (const GLhalfNV *); GLAPI void APIENTRY glTexCoord3hNV (GLhalfNV, GLhalfNV, GLhalfNV); GLAPI void APIENTRY glTexCoord3hvNV (const GLhalfNV *); GLAPI void APIENTRY glTexCoord4hNV (GLhalfNV, GLhalfNV, GLhalfNV, GLhalfNV); GLAPI void APIENTRY glTexCoord4hvNV (const GLhalfNV *); GLAPI void APIENTRY glMultiTexCoord1hNV (GLenum, GLhalfNV); GLAPI void APIENTRY glMultiTexCoord1hvNV (GLenum, const GLhalfNV *); GLAPI void APIENTRY glMultiTexCoord2hNV (GLenum, GLhalfNV, GLhalfNV); GLAPI void APIENTRY glMultiTexCoord2hvNV (GLenum, const GLhalfNV *); GLAPI void APIENTRY glMultiTexCoord3hNV (GLenum, GLhalfNV, GLhalfNV, GLhalfNV); GLAPI void APIENTRY glMultiTexCoord3hvNV (GLenum, const GLhalfNV *); GLAPI void APIENTRY glMultiTexCoord4hNV (GLenum, GLhalfNV, GLhalfNV, GLhalfNV, GLhalfNV); GLAPI void APIENTRY glMultiTexCoord4hvNV (GLenum, const GLhalfNV *); GLAPI void APIENTRY glFogCoordhNV (GLhalfNV); GLAPI void APIENTRY glFogCoordhvNV (const GLhalfNV *); GLAPI void APIENTRY glSecondaryColor3hNV (GLhalfNV, GLhalfNV, GLhalfNV); GLAPI void APIENTRY glSecondaryColor3hvNV (const GLhalfNV *); GLAPI void APIENTRY glVertexWeighthNV (GLhalfNV); GLAPI void APIENTRY glVertexWeighthvNV (const GLhalfNV *); GLAPI void APIENTRY glVertexAttrib1hNV (GLuint, GLhalfNV); GLAPI void APIENTRY glVertexAttrib1hvNV (GLuint, const GLhalfNV *); GLAPI void APIENTRY glVertexAttrib2hNV (GLuint, GLhalfNV, GLhalfNV); GLAPI void APIENTRY glVertexAttrib2hvNV (GLuint, const GLhalfNV *); GLAPI void APIENTRY glVertexAttrib3hNV (GLuint, GLhalfNV, GLhalfNV, GLhalfNV); GLAPI void APIENTRY glVertexAttrib3hvNV (GLuint, const GLhalfNV *); GLAPI void APIENTRY glVertexAttrib4hNV (GLuint, GLhalfNV, GLhalfNV, GLhalfNV, GLhalfNV); GLAPI void APIENTRY glVertexAttrib4hvNV (GLuint, const GLhalfNV *); GLAPI void APIENTRY glVertexAttribs1hvNV (GLuint, GLsizei, const GLhalfNV *); GLAPI void APIENTRY glVertexAttribs2hvNV (GLuint, GLsizei, const GLhalfNV *); GLAPI void APIENTRY glVertexAttribs3hvNV (GLuint, GLsizei, const GLhalfNV *); GLAPI void APIENTRY glVertexAttribs4hvNV (GLuint, GLsizei, const GLhalfNV *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLVERTEX2HNVPROC) (GLhalfNV x, GLhalfNV y); typedef void (APIENTRYP PFNGLVERTEX2HVNVPROC) (const GLhalfNV *v); typedef void (APIENTRYP PFNGLVERTEX3HNVPROC) (GLhalfNV x, GLhalfNV y, GLhalfNV z); typedef void (APIENTRYP PFNGLVERTEX3HVNVPROC) (const GLhalfNV *v); typedef void (APIENTRYP PFNGLVERTEX4HNVPROC) (GLhalfNV x, GLhalfNV y, GLhalfNV z, GLhalfNV w); typedef void (APIENTRYP PFNGLVERTEX4HVNVPROC) (const GLhalfNV *v); typedef void (APIENTRYP PFNGLNORMAL3HNVPROC) (GLhalfNV nx, GLhalfNV ny, GLhalfNV nz); typedef void (APIENTRYP PFNGLNORMAL3HVNVPROC) (const GLhalfNV *v); typedef void (APIENTRYP PFNGLCOLOR3HNVPROC) (GLhalfNV red, GLhalfNV green, GLhalfNV blue); typedef void (APIENTRYP PFNGLCOLOR3HVNVPROC) (const GLhalfNV *v); typedef void (APIENTRYP PFNGLCOLOR4HNVPROC) (GLhalfNV red, GLhalfNV green, GLhalfNV blue, GLhalfNV alpha); typedef void (APIENTRYP PFNGLCOLOR4HVNVPROC) (const GLhalfNV *v); typedef void (APIENTRYP PFNGLTEXCOORD1HNVPROC) (GLhalfNV s); typedef void (APIENTRYP PFNGLTEXCOORD1HVNVPROC) (const GLhalfNV *v); typedef void (APIENTRYP PFNGLTEXCOORD2HNVPROC) (GLhalfNV s, GLhalfNV t); typedef void (APIENTRYP PFNGLTEXCOORD2HVNVPROC) (const GLhalfNV *v); typedef void (APIENTRYP PFNGLTEXCOORD3HNVPROC) (GLhalfNV s, GLhalfNV t, GLhalfNV r); typedef void (APIENTRYP PFNGLTEXCOORD3HVNVPROC) (const GLhalfNV *v); typedef void (APIENTRYP PFNGLTEXCOORD4HNVPROC) (GLhalfNV s, GLhalfNV t, GLhalfNV r, GLhalfNV q); typedef void (APIENTRYP PFNGLTEXCOORD4HVNVPROC) (const GLhalfNV *v); typedef void (APIENTRYP PFNGLMULTITEXCOORD1HNVPROC) (GLenum target, GLhalfNV s); typedef void (APIENTRYP PFNGLMULTITEXCOORD1HVNVPROC) (GLenum target, const GLhalfNV *v); typedef void (APIENTRYP PFNGLMULTITEXCOORD2HNVPROC) (GLenum target, GLhalfNV s, GLhalfNV t); typedef void (APIENTRYP PFNGLMULTITEXCOORD2HVNVPROC) (GLenum target, const GLhalfNV *v); typedef void (APIENTRYP PFNGLMULTITEXCOORD3HNVPROC) (GLenum target, GLhalfNV s, GLhalfNV t, GLhalfNV r); typedef void (APIENTRYP PFNGLMULTITEXCOORD3HVNVPROC) (GLenum target, const GLhalfNV *v); typedef void (APIENTRYP PFNGLMULTITEXCOORD4HNVPROC) (GLenum target, GLhalfNV s, GLhalfNV t, GLhalfNV r, GLhalfNV q); typedef void (APIENTRYP PFNGLMULTITEXCOORD4HVNVPROC) (GLenum target, const GLhalfNV *v); typedef void (APIENTRYP PFNGLFOGCOORDHNVPROC) (GLhalfNV fog); typedef void (APIENTRYP PFNGLFOGCOORDHVNVPROC) (const GLhalfNV *fog); typedef void (APIENTRYP PFNGLSECONDARYCOLOR3HNVPROC) (GLhalfNV red, GLhalfNV green, GLhalfNV blue); typedef void (APIENTRYP PFNGLSECONDARYCOLOR3HVNVPROC) (const GLhalfNV *v); typedef void (APIENTRYP PFNGLVERTEXWEIGHTHNVPROC) (GLhalfNV weight); typedef void (APIENTRYP PFNGLVERTEXWEIGHTHVNVPROC) (const GLhalfNV *weight); typedef void (APIENTRYP PFNGLVERTEXATTRIB1HNVPROC) (GLuint index, GLhalfNV x); typedef void (APIENTRYP PFNGLVERTEXATTRIB1HVNVPROC) (GLuint index, const GLhalfNV *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB2HNVPROC) (GLuint index, GLhalfNV x, GLhalfNV y); typedef void (APIENTRYP PFNGLVERTEXATTRIB2HVNVPROC) (GLuint index, const GLhalfNV *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB3HNVPROC) (GLuint index, GLhalfNV x, GLhalfNV y, GLhalfNV z); typedef void (APIENTRYP PFNGLVERTEXATTRIB3HVNVPROC) (GLuint index, const GLhalfNV *v); typedef void (APIENTRYP PFNGLVERTEXATTRIB4HNVPROC) (GLuint index, GLhalfNV x, GLhalfNV y, GLhalfNV z, GLhalfNV w); typedef void (APIENTRYP PFNGLVERTEXATTRIB4HVNVPROC) (GLuint index, const GLhalfNV *v); typedef void (APIENTRYP PFNGLVERTEXATTRIBS1HVNVPROC) (GLuint index, GLsizei n, const GLhalfNV *v); typedef void (APIENTRYP PFNGLVERTEXATTRIBS2HVNVPROC) (GLuint index, GLsizei n, const GLhalfNV *v); typedef void (APIENTRYP PFNGLVERTEXATTRIBS3HVNVPROC) (GLuint index, GLsizei n, const GLhalfNV *v); typedef void (APIENTRYP PFNGLVERTEXATTRIBS4HVNVPROC) (GLuint index, GLsizei n, const GLhalfNV *v); #endif #ifndef GL_NV_pixel_data_range #define GL_NV_pixel_data_range 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glPixelDataRangeNV (GLenum, GLsizei, GLvoid *); GLAPI void APIENTRY glFlushPixelDataRangeNV (GLenum); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLPIXELDATARANGENVPROC) (GLenum target, GLsizei length, GLvoid *pointer); typedef void (APIENTRYP PFNGLFLUSHPIXELDATARANGENVPROC) (GLenum target); #endif #ifndef GL_NV_primitive_restart #define GL_NV_primitive_restart 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glPrimitiveRestartNV (void); GLAPI void APIENTRY glPrimitiveRestartIndexNV (GLuint); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLPRIMITIVERESTARTNVPROC) (void); typedef void (APIENTRYP PFNGLPRIMITIVERESTARTINDEXNVPROC) (GLuint index); #endif #ifndef GL_NV_texture_expand_normal #define GL_NV_texture_expand_normal 1 #endif #ifndef GL_NV_vertex_program2 #define GL_NV_vertex_program2 1 #endif #ifndef GL_ATI_map_object_buffer #define GL_ATI_map_object_buffer 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI GLvoid* APIENTRY glMapObjectBufferATI (GLuint); GLAPI void APIENTRY glUnmapObjectBufferATI (GLuint); #endif /* GL_GLEXT_PROTOTYPES */ typedef GLvoid* (APIENTRYP PFNGLMAPOBJECTBUFFERATIPROC) (GLuint buffer); typedef void (APIENTRYP PFNGLUNMAPOBJECTBUFFERATIPROC) (GLuint buffer); #endif #ifndef GL_ATI_separate_stencil #define GL_ATI_separate_stencil 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glStencilOpSeparateATI (GLenum, GLenum, GLenum, GLenum); GLAPI void APIENTRY glStencilFuncSeparateATI (GLenum, GLenum, GLint, GLuint); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLSTENCILOPSEPARATEATIPROC) (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass); typedef void (APIENTRYP PFNGLSTENCILFUNCSEPARATEATIPROC) (GLenum frontfunc, GLenum backfunc, GLint ref, GLuint mask); #endif #ifndef GL_ATI_vertex_attrib_array_object #define GL_ATI_vertex_attrib_array_object 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glVertexAttribArrayObjectATI (GLuint, GLint, GLenum, GLboolean, GLsizei, GLuint, GLuint); GLAPI void APIENTRY glGetVertexAttribArrayObjectfvATI (GLuint, GLenum, GLfloat *); GLAPI void APIENTRY glGetVertexAttribArrayObjectivATI (GLuint, GLenum, GLint *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLVERTEXATTRIBARRAYOBJECTATIPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, GLuint buffer, GLuint offset); typedef void (APIENTRYP PFNGLGETVERTEXATTRIBARRAYOBJECTFVATIPROC) (GLuint index, GLenum pname, GLfloat *params); typedef void (APIENTRYP PFNGLGETVERTEXATTRIBARRAYOBJECTIVATIPROC) (GLuint index, GLenum pname, GLint *params); #endif #ifndef GL_OES_read_format #define GL_OES_read_format 1 #endif #ifndef GL_EXT_depth_bounds_test #define GL_EXT_depth_bounds_test 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glDepthBoundsEXT (GLclampd, GLclampd); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLDEPTHBOUNDSEXTPROC) (GLclampd zmin, GLclampd zmax); #endif #ifndef GL_EXT_texture_mirror_clamp #define GL_EXT_texture_mirror_clamp 1 #endif #ifndef GL_EXT_blend_equation_separate #define GL_EXT_blend_equation_separate 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glBlendEquationSeparateEXT (GLenum, GLenum); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEEXTPROC) (GLenum modeRGB, GLenum modeAlpha); #endif #ifndef GL_MESA_pack_invert #define GL_MESA_pack_invert 1 #endif #ifndef GL_MESA_ycbcr_texture #define GL_MESA_ycbcr_texture 1 #endif #ifndef GL_EXT_pixel_buffer_object #define GL_EXT_pixel_buffer_object 1 #endif #ifndef GL_NV_fragment_program_option #define GL_NV_fragment_program_option 1 #endif #ifndef GL_NV_fragment_program2 #define GL_NV_fragment_program2 1 #endif #ifndef GL_NV_vertex_program2_option #define GL_NV_vertex_program2_option 1 #endif #ifndef GL_NV_vertex_program3 #define GL_NV_vertex_program3 1 #endif #ifndef GL_EXT_framebuffer_object #define GL_EXT_framebuffer_object 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI GLboolean APIENTRY glIsRenderbufferEXT (GLuint); GLAPI void APIENTRY glBindRenderbufferEXT (GLenum, GLuint); GLAPI void APIENTRY glDeleteRenderbuffersEXT (GLsizei, const GLuint *); GLAPI void APIENTRY glGenRenderbuffersEXT (GLsizei, GLuint *); GLAPI void APIENTRY glRenderbufferStorageEXT (GLenum, GLenum, GLsizei, GLsizei); GLAPI void APIENTRY glGetRenderbufferParameterivEXT (GLenum, GLenum, GLint *); GLAPI GLboolean APIENTRY glIsFramebufferEXT (GLuint); GLAPI void APIENTRY glBindFramebufferEXT (GLenum, GLuint); GLAPI void APIENTRY glDeleteFramebuffersEXT (GLsizei, const GLuint *); GLAPI void APIENTRY glGenFramebuffersEXT (GLsizei, GLuint *); GLAPI GLenum APIENTRY glCheckFramebufferStatusEXT (GLenum); GLAPI void APIENTRY glFramebufferTexture1DEXT (GLenum, GLenum, GLenum, GLuint, GLint); GLAPI void APIENTRY glFramebufferTexture2DEXT (GLenum, GLenum, GLenum, GLuint, GLint); GLAPI void APIENTRY glFramebufferTexture3DEXT (GLenum, GLenum, GLenum, GLuint, GLint, GLint); GLAPI void APIENTRY glFramebufferRenderbufferEXT (GLenum, GLenum, GLenum, GLuint); GLAPI void APIENTRY glGetFramebufferAttachmentParameterivEXT (GLenum, GLenum, GLenum, GLint *); GLAPI void APIENTRY glGenerateMipmapEXT (GLenum); #endif /* GL_GLEXT_PROTOTYPES */ typedef GLboolean (APIENTRYP PFNGLISRENDERBUFFEREXTPROC) (GLuint renderbuffer); typedef void (APIENTRYP PFNGLBINDRENDERBUFFEREXTPROC) (GLenum target, GLuint renderbuffer); typedef void (APIENTRYP PFNGLDELETERENDERBUFFERSEXTPROC) (GLsizei n, const GLuint *renderbuffers); typedef void (APIENTRYP PFNGLGENRENDERBUFFERSEXTPROC) (GLsizei n, GLuint *renderbuffers); typedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEEXTPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height); typedef void (APIENTRYP PFNGLGETRENDERBUFFERPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params); typedef GLboolean (APIENTRYP PFNGLISFRAMEBUFFEREXTPROC) (GLuint framebuffer); typedef void (APIENTRYP PFNGLBINDFRAMEBUFFEREXTPROC) (GLenum target, GLuint framebuffer); typedef void (APIENTRYP PFNGLDELETEFRAMEBUFFERSEXTPROC) (GLsizei n, const GLuint *framebuffers); typedef void (APIENTRYP PFNGLGENFRAMEBUFFERSEXTPROC) (GLsizei n, GLuint *framebuffers); typedef GLenum (APIENTRYP PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC) (GLenum target); typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE1DEXTPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE2DEXTPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE3DEXTPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset); typedef void (APIENTRYP PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC) (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); typedef void (APIENTRYP PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVEXTPROC) (GLenum target, GLenum attachment, GLenum pname, GLint *params); typedef void (APIENTRYP PFNGLGENERATEMIPMAPEXTPROC) (GLenum target); #endif #ifndef GL_GREMEDY_string_marker #define GL_GREMEDY_string_marker 1 #ifdef GL_GLEXT_PROTOTYPES GLAPI void APIENTRY glStringMarkerGREMEDY (GLsizei, const GLvoid *); #endif /* GL_GLEXT_PROTOTYPES */ typedef void (APIENTRYP PFNGLSTRINGMARKERGREMEDYPROC) (GLsizei len, const GLvoid *string); #endif #ifdef __cplusplus } #endif #endif #endif /* NO_SDL_GLEXT */ /*@}*/ ================================================ FILE: other/sdl/include/SDL_platform.h ================================================ /* SDL - Simple DirectMedia Layer Copyright (C) 1997-2009 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org */ /** @file SDL_platform.h * Try to get a standard set of platform defines */ #ifndef _SDL_platform_h #define _SDL_platform_h #if defined(_AIX) #undef __AIX__ #define __AIX__ 1 #endif #if defined(__BEOS__) #undef __BEOS__ #define __BEOS__ 1 #endif #if defined(__HAIKU__) #undef __HAIKU__ #define __HAIKU__ 1 #endif #if defined(bsdi) || defined(__bsdi) || defined(__bsdi__) #undef __BSDI__ #define __BSDI__ 1 #endif #if defined(_arch_dreamcast) #undef __DREAMCAST__ #define __DREAMCAST__ 1 #endif #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) #undef __FREEBSD__ #define __FREEBSD__ 1 #endif #if defined(__HAIKU__) #undef __HAIKU__ #define __HAIKU__ 1 #endif #if defined(hpux) || defined(__hpux) || defined(__hpux__) #undef __HPUX__ #define __HPUX__ 1 #endif #if defined(sgi) || defined(__sgi) || defined(__sgi__) || defined(_SGI_SOURCE) #undef __IRIX__ #define __IRIX__ 1 #endif #if defined(linux) || defined(__linux) || defined(__linux__) #undef __LINUX__ #define __LINUX__ 1 #endif #if defined(__APPLE__) #undef __MACOSX__ #define __MACOSX__ 1 #elif defined(macintosh) #undef __MACOS__ #define __MACOS__ 1 #endif #if defined(__NetBSD__) #undef __NETBSD__ #define __NETBSD__ 1 #endif #if defined(__OpenBSD__) #undef __OPENBSD__ #define __OPENBSD__ 1 #endif #if defined(__OS2__) #undef __OS2__ #define __OS2__ 1 #endif #if defined(osf) || defined(__osf) || defined(__osf__) || defined(_OSF_SOURCE) #undef __OSF__ #define __OSF__ 1 #endif #if defined(__QNXNTO__) #undef __QNXNTO__ #define __QNXNTO__ 1 #endif #if defined(riscos) || defined(__riscos) || defined(__riscos__) #undef __RISCOS__ #define __RISCOS__ 1 #endif #if defined(__SVR4) #undef __SOLARIS__ #define __SOLARIS__ 1 #endif #if defined(WIN32) || defined(_WIN32) #undef __WIN32__ #define __WIN32__ 1 #endif #endif /* _SDL_platform_h */ ================================================ FILE: other/sdl/include/SDL_quit.h ================================================ /* SDL - Simple DirectMedia Layer Copyright (C) 1997-2009 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org */ /** @file SDL_quit.h * Include file for SDL quit event handling */ #ifndef _SDL_quit_h #define _SDL_quit_h #include "SDL_stdinc.h" #include "SDL_error.h" /** @file SDL_quit.h * An SDL_QUITEVENT is generated when the user tries to close the application * window. If it is ignored or filtered out, the window will remain open. * If it is not ignored or filtered, it is queued normally and the window * is allowed to close. When the window is closed, screen updates will * complete, but have no effect. * * SDL_Init() installs signal handlers for SIGINT (keyboard interrupt) * and SIGTERM (system termination request), if handlers do not already * exist, that generate SDL_QUITEVENT events as well. There is no way * to determine the cause of an SDL_QUITEVENT, but setting a signal * handler in your application will override the default generation of * quit events for that signal. */ /** @file SDL_quit.h * There are no functions directly affecting the quit event */ #define SDL_QuitRequested() \ (SDL_PumpEvents(), SDL_PeepEvents(NULL,0,SDL_PEEKEVENT,SDL_QUITMASK)) #endif /* _SDL_quit_h */ ================================================ FILE: other/sdl/include/SDL_rwops.h ================================================ /* SDL - Simple DirectMedia Layer Copyright (C) 1997-2009 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org */ /** @file SDL_rwops.h * This file provides a general interface for SDL to read and write * data sources. It can easily be extended to files, memory, etc. */ #ifndef _SDL_rwops_h #define _SDL_rwops_h #include "SDL_stdinc.h" #include "SDL_error.h" #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif /** This is the read/write operation structure -- very basic */ typedef struct SDL_RWops { /** Seek to 'offset' relative to whence, one of stdio's whence values: * SEEK_SET, SEEK_CUR, SEEK_END * Returns the final offset in the data source. */ int (SDLCALL *seek)(struct SDL_RWops *context, int offset, int whence); /** Read up to 'maxnum' objects each of size 'size' from the data * source to the area pointed at by 'ptr'. * Returns the number of objects read, or -1 if the read failed. */ int (SDLCALL *read)(struct SDL_RWops *context, void *ptr, int size, int maxnum); /** Write exactly 'num' objects each of size 'objsize' from the area * pointed at by 'ptr' to data source. * Returns 'num', or -1 if the write failed. */ int (SDLCALL *write)(struct SDL_RWops *context, const void *ptr, int size, int num); /** Close and free an allocated SDL_FSops structure */ int (SDLCALL *close)(struct SDL_RWops *context); Uint32 type; union { #if defined(__WIN32__) && !defined(__SYMBIAN32__) struct { int append; void *h; struct { void *data; int size; int left; } buffer; } win32io; #endif #ifdef HAVE_STDIO_H struct { int autoclose; FILE *fp; } stdio; #endif struct { Uint8 *base; Uint8 *here; Uint8 *stop; } mem; struct { void *data1; } unknown; } hidden; } SDL_RWops; /** @name Functions to create SDL_RWops structures from various data sources */ /*@{*/ extern DECLSPEC SDL_RWops * SDLCALL SDL_RWFromFile(const char *file, const char *mode); #ifdef HAVE_STDIO_H extern DECLSPEC SDL_RWops * SDLCALL SDL_RWFromFP(FILE *fp, int autoclose); #endif extern DECLSPEC SDL_RWops * SDLCALL SDL_RWFromMem(void *mem, int size); extern DECLSPEC SDL_RWops * SDLCALL SDL_RWFromConstMem(const void *mem, int size); extern DECLSPEC SDL_RWops * SDLCALL SDL_AllocRW(void); extern DECLSPEC void SDLCALL SDL_FreeRW(SDL_RWops *area); /*@}*/ /** @name Seek Reference Points */ /*@{*/ #define RW_SEEK_SET 0 /**< Seek from the beginning of data */ #define RW_SEEK_CUR 1 /**< Seek relative to current read point */ #define RW_SEEK_END 2 /**< Seek relative to the end of data */ /*@}*/ /** @name Macros to easily read and write from an SDL_RWops structure */ /*@{*/ #define SDL_RWseek(ctx, offset, whence) (ctx)->seek(ctx, offset, whence) #define SDL_RWtell(ctx) (ctx)->seek(ctx, 0, RW_SEEK_CUR) #define SDL_RWread(ctx, ptr, size, n) (ctx)->read(ctx, ptr, size, n) #define SDL_RWwrite(ctx, ptr, size, n) (ctx)->write(ctx, ptr, size, n) #define SDL_RWclose(ctx) (ctx)->close(ctx) /*@}*/ /** @name Read an item of the specified endianness and return in native format */ /*@{*/ extern DECLSPEC Uint16 SDLCALL SDL_ReadLE16(SDL_RWops *src); extern DECLSPEC Uint16 SDLCALL SDL_ReadBE16(SDL_RWops *src); extern DECLSPEC Uint32 SDLCALL SDL_ReadLE32(SDL_RWops *src); extern DECLSPEC Uint32 SDLCALL SDL_ReadBE32(SDL_RWops *src); extern DECLSPEC Uint64 SDLCALL SDL_ReadLE64(SDL_RWops *src); extern DECLSPEC Uint64 SDLCALL SDL_ReadBE64(SDL_RWops *src); /*@}*/ /** @name Write an item of native format to the specified endianness */ /*@{*/ extern DECLSPEC int SDLCALL SDL_WriteLE16(SDL_RWops *dst, Uint16 value); extern DECLSPEC int SDLCALL SDL_WriteBE16(SDL_RWops *dst, Uint16 value); extern DECLSPEC int SDLCALL SDL_WriteLE32(SDL_RWops *dst, Uint32 value); extern DECLSPEC int SDLCALL SDL_WriteBE32(SDL_RWops *dst, Uint32 value); extern DECLSPEC int SDLCALL SDL_WriteLE64(SDL_RWops *dst, Uint64 value); extern DECLSPEC int SDLCALL SDL_WriteBE64(SDL_RWops *dst, Uint64 value); /*@}*/ /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* _SDL_rwops_h */ ================================================ FILE: other/sdl/include/SDL_stdinc.h ================================================ /* SDL - Simple DirectMedia Layer Copyright (C) 1997-2009 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org */ /** @file SDL_stdinc.h * This is a general header that includes C language support */ #ifndef _SDL_stdinc_h #define _SDL_stdinc_h #include "SDL_config.h" #ifdef HAVE_SYS_TYPES_H #include <sys/types.h> #endif #ifdef HAVE_STDIO_H #include <stdio.h> #endif #if defined(STDC_HEADERS) # include <stdlib.h> # include <stddef.h> # include <stdarg.h> #else # if defined(HAVE_STDLIB_H) # include <stdlib.h> # elif defined(HAVE_MALLOC_H) # include <malloc.h> # endif # if defined(HAVE_STDDEF_H) # include <stddef.h> # endif # if defined(HAVE_STDARG_H) # include <stdarg.h> # endif #endif #ifdef HAVE_STRING_H # if !defined(STDC_HEADERS) && defined(HAVE_MEMORY_H) # include <memory.h> # endif # include <string.h> #endif #ifdef HAVE_STRINGS_H # include <strings.h> #endif #if defined(HAVE_INTTYPES_H) # include <inttypes.h> #elif defined(HAVE_STDINT_H) # include <stdint.h> #endif #ifdef HAVE_CTYPE_H # include <ctype.h> #endif #if defined(HAVE_ICONV) && defined(HAVE_ICONV_H) # include <iconv.h> #endif /** The number of elements in an array */ #define SDL_arraysize(array) (sizeof(array)/sizeof(array[0])) #define SDL_TABLESIZE(table) SDL_arraysize(table) /* Use proper C++ casts when compiled as C++ to be compatible with the option -Wold-style-cast of GCC (and -Werror=old-style-cast in GCC 4.2 and above. */ #ifdef __cplusplus #define SDL_reinterpret_cast(type, expression) reinterpret_cast<type>(expression) #define SDL_static_cast(type, expression) static_cast<type>(expression) #else #define SDL_reinterpret_cast(type, expression) ((type)(expression)) #define SDL_static_cast(type, expression) ((type)(expression)) #endif /** @name Basic data types */ /*@{*/ typedef enum { SDL_FALSE = 0, SDL_TRUE = 1 } SDL_bool; typedef int8_t Sint8; typedef uint8_t Uint8; typedef int16_t Sint16; typedef uint16_t Uint16; typedef int32_t Sint32; typedef uint32_t Uint32; #ifdef SDL_HAS_64BIT_TYPE typedef int64_t Sint64; #ifndef SYMBIAN32_GCCE typedef uint64_t Uint64; #endif #else /* This is really just a hack to prevent the compiler from complaining */ typedef struct { Uint32 hi; Uint32 lo; } Uint64, Sint64; #endif /*@}*/ /** @name Make sure the types really have the right sizes */ /*@{*/ #define SDL_COMPILE_TIME_ASSERT(name, x) \ typedef int SDL_dummy_ ## name[(x) * 2 - 1] SDL_COMPILE_TIME_ASSERT(uint8, sizeof(Uint8) == 1); SDL_COMPILE_TIME_ASSERT(sint8, sizeof(Sint8) == 1); SDL_COMPILE_TIME_ASSERT(uint16, sizeof(Uint16) == 2); SDL_COMPILE_TIME_ASSERT(sint16, sizeof(Sint16) == 2); SDL_COMPILE_TIME_ASSERT(uint32, sizeof(Uint32) == 4); SDL_COMPILE_TIME_ASSERT(sint32, sizeof(Sint32) == 4); SDL_COMPILE_TIME_ASSERT(uint64, sizeof(Uint64) == 8); SDL_COMPILE_TIME_ASSERT(sint64, sizeof(Sint64) == 8); /*@}*/ /** @name Enum Size Check * Check to make sure enums are the size of ints, for structure packing. * For both Watcom C/C++ and Borland C/C++ the compiler option that makes * enums having the size of an int must be enabled. * This is "-b" for Borland C/C++ and "-ei" for Watcom C/C++ (v11). */ /* Enable enums always int in CodeWarrior (for MPW use "-enum int") */ #ifdef __MWERKS__ #pragma enumsalwaysint on #endif typedef enum { DUMMY_ENUM_VALUE } SDL_DUMMY_ENUM; #ifndef __NDS__ SDL_COMPILE_TIME_ASSERT(enum, sizeof(SDL_DUMMY_ENUM) == sizeof(int)); #endif /*@}*/ #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif #ifdef HAVE_MALLOC #define SDL_malloc malloc #else extern DECLSPEC void * SDLCALL SDL_malloc(size_t size); #endif #ifdef HAVE_CALLOC #define SDL_calloc calloc #else extern DECLSPEC void * SDLCALL SDL_calloc(size_t nmemb, size_t size); #endif #ifdef HAVE_REALLOC #define SDL_realloc realloc #else extern DECLSPEC void * SDLCALL SDL_realloc(void *mem, size_t size); #endif #ifdef HAVE_FREE #define SDL_free free #else extern DECLSPEC void SDLCALL SDL_free(void *mem); #endif #if defined(HAVE_ALLOCA) && !defined(alloca) # if defined(HAVE_ALLOCA_H) # include <alloca.h> # elif defined(__GNUC__) # define alloca __builtin_alloca # elif defined(_MSC_VER) # include <malloc.h> # define alloca _alloca # elif defined(__WATCOMC__) # include <malloc.h> # elif defined(__BORLANDC__) # include <malloc.h> # elif defined(__DMC__) # include <stdlib.h> # elif defined(__AIX__) #pragma alloca # elif defined(__MRC__) void *alloca (unsigned); # else char *alloca (); # endif #endif #ifdef HAVE_ALLOCA #define SDL_stack_alloc(type, count) (type*)alloca(sizeof(type)*(count)) #define SDL_stack_free(data) #else #define SDL_stack_alloc(type, count) (type*)SDL_malloc(sizeof(type)*(count)) #define SDL_stack_free(data) SDL_free(data) #endif #ifdef HAVE_GETENV #define SDL_getenv getenv #else extern DECLSPEC char * SDLCALL SDL_getenv(const char *name); #endif #ifdef HAVE_PUTENV #define SDL_putenv putenv #else extern DECLSPEC int SDLCALL SDL_putenv(const char *variable); #endif #ifdef HAVE_QSORT #define SDL_qsort qsort #else extern DECLSPEC void SDLCALL SDL_qsort(void *base, size_t nmemb, size_t size, int (*compare)(const void *, const void *)); #endif #ifdef HAVE_ABS #define SDL_abs abs #else #define SDL_abs(X) ((X) < 0 ? -(X) : (X)) #endif #define SDL_min(x, y) (((x) < (y)) ? (x) : (y)) #define SDL_max(x, y) (((x) > (y)) ? (x) : (y)) #ifdef HAVE_CTYPE_H #define SDL_isdigit(X) isdigit(X) #define SDL_isspace(X) isspace(X) #define SDL_toupper(X) toupper(X) #define SDL_tolower(X) tolower(X) #else #define SDL_isdigit(X) (((X) >= '0') && ((X) <= '9')) #define SDL_isspace(X) (((X) == ' ') || ((X) == '\t') || ((X) == '\r') || ((X) == '\n')) #define SDL_toupper(X) (((X) >= 'a') && ((X) <= 'z') ? ('A'+((X)-'a')) : (X)) #define SDL_tolower(X) (((X) >= 'A') && ((X) <= 'Z') ? ('a'+((X)-'A')) : (X)) #endif #ifdef HAVE_MEMSET #define SDL_memset memset #else extern DECLSPEC void * SDLCALL SDL_memset(void *dst, int c, size_t len); #endif #if defined(__GNUC__) && defined(i386) #define SDL_memset4(dst, val, len) \ do { \ int u0, u1, u2; \ __asm__ __volatile__ ( \ "cld\n\t" \ "rep ; stosl\n\t" \ : "=&D" (u0), "=&a" (u1), "=&c" (u2) \ : "0" (dst), "1" (val), "2" (SDL_static_cast(Uint32, len)) \ : "memory" ); \ } while(0) #endif #ifndef SDL_memset4 #define SDL_memset4(dst, val, len) \ do { \ unsigned _count = (len); \ unsigned _n = (_count + 3) / 4; \ Uint32 *_p = SDL_static_cast(Uint32 *, dst); \ Uint32 _val = (val); \ if (len == 0) break; \ switch (_count % 4) { \ case 0: do { *_p++ = _val; \ case 3: *_p++ = _val; \ case 2: *_p++ = _val; \ case 1: *_p++ = _val; \ } while ( --_n ); \ } \ } while(0) #endif /* We can count on memcpy existing on Mac OS X and being well-tuned. */ #if defined(__MACH__) && defined(__APPLE__) #define SDL_memcpy(dst, src, len) memcpy(dst, src, len) #elif defined(__GNUC__) && defined(i386) #define SDL_memcpy(dst, src, len) \ do { \ int u0, u1, u2; \ __asm__ __volatile__ ( \ "cld\n\t" \ "rep ; movsl\n\t" \ "testb $2,%b4\n\t" \ "je 1f\n\t" \ "movsw\n" \ "1:\ttestb $1,%b4\n\t" \ "je 2f\n\t" \ "movsb\n" \ "2:" \ : "=&c" (u0), "=&D" (u1), "=&S" (u2) \ : "0" (SDL_static_cast(unsigned, len)/4), "q" (len), "1" (dst),"2" (src) \ : "memory" ); \ } while(0) #endif #ifndef SDL_memcpy #ifdef HAVE_MEMCPY #define SDL_memcpy memcpy #elif defined(HAVE_BCOPY) #define SDL_memcpy(d, s, n) bcopy((s), (d), (n)) #else extern DECLSPEC void * SDLCALL SDL_memcpy(void *dst, const void *src, size_t len); #endif #endif /* We can count on memcpy existing on Mac OS X and being well-tuned. */ #if defined(__MACH__) && defined(__APPLE__) #define SDL_memcpy4(dst, src, len) memcpy(dst, src, (len)*4) #elif defined(__GNUC__) && defined(i386) #define SDL_memcpy4(dst, src, len) \ do { \ int ecx, edi, esi; \ __asm__ __volatile__ ( \ "cld\n\t" \ "rep ; movsl" \ : "=&c" (ecx), "=&D" (edi), "=&S" (esi) \ : "0" (SDL_static_cast(unsigned, len)), "1" (dst), "2" (src) \ : "memory" ); \ } while(0) #endif #ifndef SDL_memcpy4 #define SDL_memcpy4(dst, src, len) SDL_memcpy(dst, src, (len) << 2) #endif #if defined(__GNUC__) && defined(i386) #define SDL_revcpy(dst, src, len) \ do { \ int u0, u1, u2; \ char *dstp = SDL_static_cast(char *, dst); \ char *srcp = SDL_static_cast(char *, src); \ int n = (len); \ if ( n >= 4 ) { \ __asm__ __volatile__ ( \ "std\n\t" \ "rep ; movsl\n\t" \ "cld\n\t" \ : "=&c" (u0), "=&D" (u1), "=&S" (u2) \ : "0" (n >> 2), \ "1" (dstp+(n-4)), "2" (srcp+(n-4)) \ : "memory" ); \ } \ switch (n & 3) { \ case 3: dstp[2] = srcp[2]; \ case 2: dstp[1] = srcp[1]; \ case 1: dstp[0] = srcp[0]; \ break; \ default: \ break; \ } \ } while(0) #endif #ifndef SDL_revcpy extern DECLSPEC void * SDLCALL SDL_revcpy(void *dst, const void *src, size_t len); #endif #ifdef HAVE_MEMMOVE #define SDL_memmove memmove #elif defined(HAVE_BCOPY) #define SDL_memmove(d, s, n) bcopy((s), (d), (n)) #else #define SDL_memmove(dst, src, len) \ do { \ if ( dst < src ) { \ SDL_memcpy(dst, src, len); \ } else { \ SDL_revcpy(dst, src, len); \ } \ } while(0) #endif #ifdef HAVE_MEMCMP #define SDL_memcmp memcmp #else extern DECLSPEC int SDLCALL SDL_memcmp(const void *s1, const void *s2, size_t len); #endif #ifdef HAVE_STRLEN #define SDL_strlen strlen #else extern DECLSPEC size_t SDLCALL SDL_strlen(const char *string); #endif #ifdef HAVE_STRLCPY #define SDL_strlcpy strlcpy #else extern DECLSPEC size_t SDLCALL SDL_strlcpy(char *dst, const char *src, size_t maxlen); #endif #ifdef HAVE_STRLCAT #define SDL_strlcat strlcat #else extern DECLSPEC size_t SDLCALL SDL_strlcat(char *dst, const char *src, size_t maxlen); #endif #ifdef HAVE_STRDUP #define SDL_strdup strdup #else extern DECLSPEC char * SDLCALL SDL_strdup(const char *string); #endif #ifdef HAVE__STRREV #define SDL_strrev _strrev #else extern DECLSPEC char * SDLCALL SDL_strrev(char *string); #endif #ifdef HAVE__STRUPR #define SDL_strupr _strupr #else extern DECLSPEC char * SDLCALL SDL_strupr(char *string); #endif #ifdef HAVE__STRLWR #define SDL_strlwr _strlwr #else extern DECLSPEC char * SDLCALL SDL_strlwr(char *string); #endif #ifdef HAVE_STRCHR #define SDL_strchr strchr #elif defined(HAVE_INDEX) #define SDL_strchr index #else extern DECLSPEC char * SDLCALL SDL_strchr(const char *string, int c); #endif #ifdef HAVE_STRRCHR #define SDL_strrchr strrchr #elif defined(HAVE_RINDEX) #define SDL_strrchr rindex #else extern DECLSPEC char * SDLCALL SDL_strrchr(const char *string, int c); #endif #ifdef HAVE_STRSTR #define SDL_strstr strstr #else extern DECLSPEC char * SDLCALL SDL_strstr(const char *haystack, const char *needle); #endif #ifdef HAVE_ITOA #define SDL_itoa itoa #else #define SDL_itoa(value, string, radix) SDL_ltoa((long)value, string, radix) #endif #ifdef HAVE__LTOA #define SDL_ltoa _ltoa #else extern DECLSPEC char * SDLCALL SDL_ltoa(long value, char *string, int radix); #endif #ifdef HAVE__UITOA #define SDL_uitoa _uitoa #else #define SDL_uitoa(value, string, radix) SDL_ultoa((long)value, string, radix) #endif #ifdef HAVE__ULTOA #define SDL_ultoa _ultoa #else extern DECLSPEC char * SDLCALL SDL_ultoa(unsigned long value, char *string, int radix); #endif #ifdef HAVE_STRTOL #define SDL_strtol strtol #else extern DECLSPEC long SDLCALL SDL_strtol(const char *string, char **endp, int base); #endif #ifdef HAVE_STRTOUL #define SDL_strtoul strtoul #else extern DECLSPEC unsigned long SDLCALL SDL_strtoul(const char *string, char **endp, int base); #endif #ifdef SDL_HAS_64BIT_TYPE #ifdef HAVE__I64TOA #define SDL_lltoa _i64toa #else extern DECLSPEC char* SDLCALL SDL_lltoa(Sint64 value, char *string, int radix); #endif #ifdef HAVE__UI64TOA #define SDL_ulltoa _ui64toa #else extern DECLSPEC char* SDLCALL SDL_ulltoa(Uint64 value, char *string, int radix); #endif #ifdef HAVE_STRTOLL #define SDL_strtoll strtoll #else extern DECLSPEC Sint64 SDLCALL SDL_strtoll(const char *string, char **endp, int base); #endif #ifdef HAVE_STRTOULL #define SDL_strtoull strtoull #else extern DECLSPEC Uint64 SDLCALL SDL_strtoull(const char *string, char **endp, int base); #endif #endif /* SDL_HAS_64BIT_TYPE */ #ifdef HAVE_STRTOD #define SDL_strtod strtod #else extern DECLSPEC double SDLCALL SDL_strtod(const char *string, char **endp); #endif #ifdef HAVE_ATOI #define SDL_atoi atoi #else #define SDL_atoi(X) SDL_strtol(X, NULL, 0) #endif #ifdef HAVE_ATOF #define SDL_atof atof #else #define SDL_atof(X) SDL_strtod(X, NULL) #endif #ifdef HAVE_STRCMP #define SDL_strcmp strcmp #else extern DECLSPEC int SDLCALL SDL_strcmp(const char *str1, const char *str2); #endif #ifdef HAVE_STRNCMP #define SDL_strncmp strncmp #else extern DECLSPEC int SDLCALL SDL_strncmp(const char *str1, const char *str2, size_t maxlen); #endif #ifdef HAVE_STRCASECMP #define SDL_strcasecmp strcasecmp #elif defined(HAVE__STRICMP) #define SDL_strcasecmp _stricmp #else extern DECLSPEC int SDLCALL SDL_strcasecmp(const char *str1, const char *str2); #endif #ifdef HAVE_STRNCASECMP #define SDL_strncasecmp strncasecmp #elif defined(HAVE__STRNICMP) #define SDL_strncasecmp _strnicmp #else extern DECLSPEC int SDLCALL SDL_strncasecmp(const char *str1, const char *str2, size_t maxlen); #endif #ifdef HAVE_SSCANF #define SDL_sscanf sscanf #else extern DECLSPEC int SDLCALL SDL_sscanf(const char *text, const char *fmt, ...); #endif #ifdef HAVE_SNPRINTF #define SDL_snprintf snprintf #else extern DECLSPEC int SDLCALL SDL_snprintf(char *text, size_t maxlen, const char *fmt, ...); #endif #ifdef HAVE_VSNPRINTF #define SDL_vsnprintf vsnprintf #else extern DECLSPEC int SDLCALL SDL_vsnprintf(char *text, size_t maxlen, const char *fmt, va_list ap); #endif /** @name SDL_ICONV Error Codes * The SDL implementation of iconv() returns these error codes */ /*@{*/ #define SDL_ICONV_ERROR (size_t)-1 #define SDL_ICONV_E2BIG (size_t)-2 #define SDL_ICONV_EILSEQ (size_t)-3 #define SDL_ICONV_EINVAL (size_t)-4 /*@}*/ #if defined(HAVE_ICONV) && defined(HAVE_ICONV_H) #define SDL_iconv_t iconv_t #define SDL_iconv_open iconv_open #define SDL_iconv_close iconv_close #else typedef struct _SDL_iconv_t *SDL_iconv_t; extern DECLSPEC SDL_iconv_t SDLCALL SDL_iconv_open(const char *tocode, const char *fromcode); extern DECLSPEC int SDLCALL SDL_iconv_close(SDL_iconv_t cd); #endif extern DECLSPEC size_t SDLCALL SDL_iconv(SDL_iconv_t cd, const char **inbuf, size_t *inbytesleft, char **outbuf, size_t *outbytesleft); /** This function converts a string between encodings in one pass, returning a * string that must be freed with SDL_free() or NULL on error. */ extern DECLSPEC char * SDLCALL SDL_iconv_string(const char *tocode, const char *fromcode, const char *inbuf, size_t inbytesleft); #define SDL_iconv_utf8_locale(S) SDL_iconv_string("", "UTF-8", S, SDL_strlen(S)+1) #define SDL_iconv_utf8_ucs2(S) (Uint16 *)SDL_iconv_string("UCS-2", "UTF-8", S, SDL_strlen(S)+1) #define SDL_iconv_utf8_ucs4(S) (Uint32 *)SDL_iconv_string("UCS-4", "UTF-8", S, SDL_strlen(S)+1) /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* _SDL_stdinc_h */ ================================================ FILE: other/sdl/include/SDL_syswm.h ================================================ /* SDL - Simple DirectMedia Layer Copyright (C) 1997-2009 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org */ /** @file SDL_syswm.h * Include file for SDL custom system window manager hooks */ #ifndef _SDL_syswm_h #define _SDL_syswm_h #include "SDL_stdinc.h" #include "SDL_error.h" #include "SDL_version.h" #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif /** @file SDL_syswm.h * Your application has access to a special type of event 'SDL_SYSWMEVENT', * which contains window-manager specific information and arrives whenever * an unhandled window event occurs. This event is ignored by default, but * you can enable it with SDL_EventState() */ #ifdef SDL_PROTOTYPES_ONLY struct SDL_SysWMinfo; typedef struct SDL_SysWMinfo SDL_SysWMinfo; #else /* This is the structure for custom window manager events */ #if defined(SDL_VIDEO_DRIVER_X11) #if defined(__APPLE__) && defined(__MACH__) /* conflicts with Quickdraw.h */ #define Cursor X11Cursor #endif #include <X11/Xlib.h> #include <X11/Xatom.h> #if defined(__APPLE__) && defined(__MACH__) /* matches the re-define above */ #undef Cursor #endif /** These are the various supported subsystems under UNIX */ typedef enum { SDL_SYSWM_X11 } SDL_SYSWM_TYPE; /** The UNIX custom event structure */ struct SDL_SysWMmsg { SDL_version version; SDL_SYSWM_TYPE subsystem; union { XEvent xevent; } event; }; /** The UNIX custom window manager information structure. * When this structure is returned, it holds information about which * low level system it is using, and will be one of SDL_SYSWM_TYPE. */ typedef struct SDL_SysWMinfo { SDL_version version; SDL_SYSWM_TYPE subsystem; union { struct { Display *display; /**< The X11 display */ Window window; /**< The X11 display window */ /** These locking functions should be called around * any X11 functions using the display variable, * but not the gfxdisplay variable. * They lock the event thread, so should not be * called around event functions or from event filters. */ /*@{*/ void (*lock_func)(void); void (*unlock_func)(void); /*@}*/ /** @name Introduced in SDL 1.0.2 */ /*@{*/ Window fswindow; /**< The X11 fullscreen window */ Window wmwindow; /**< The X11 managed input window */ /*@}*/ /** @name Introduced in SDL 1.2.12 */ /*@{*/ Display *gfxdisplay; /**< The X11 display to which rendering is done */ /*@}*/ } x11; } info; } SDL_SysWMinfo; #elif defined(SDL_VIDEO_DRIVER_NANOX) #include <microwin/nano-X.h> /** The generic custom event structure */ struct SDL_SysWMmsg { SDL_version version; int data; }; /** The windows custom window manager information structure */ typedef struct SDL_SysWMinfo { SDL_version version ; GR_WINDOW_ID window ; /* The display window */ } SDL_SysWMinfo; #elif defined(SDL_VIDEO_DRIVER_WINDIB) || defined(SDL_VIDEO_DRIVER_DDRAW) || defined(SDL_VIDEO_DRIVER_GAPI) #define WIN32_LEAN_AND_MEAN #include <windows.h> /** The windows custom event structure */ struct SDL_SysWMmsg { SDL_version version; HWND hwnd; /**< The window for the message */ UINT msg; /**< The type of message */ WPARAM wParam; /**< WORD message parameter */ LPARAM lParam; /**< LONG message parameter */ }; /** The windows custom window manager information structure */ typedef struct SDL_SysWMinfo { SDL_version version; HWND window; /**< The Win32 display window */ HGLRC hglrc; /**< The OpenGL context, if any */ } SDL_SysWMinfo; #elif defined(SDL_VIDEO_DRIVER_RISCOS) /** RISC OS custom event structure */ struct SDL_SysWMmsg { SDL_version version; int eventCode; /**< The window for the message */ int pollBlock[64]; }; /** The RISC OS custom window manager information structure */ typedef struct SDL_SysWMinfo { SDL_version version; int wimpVersion; /**< Wimp version running under */ int taskHandle; /**< The RISC OS task handle */ int window; /**< The RISC OS display window */ } SDL_SysWMinfo; #elif defined(SDL_VIDEO_DRIVER_PHOTON) #include <sys/neutrino.h> #include <Ph.h> /** The QNX custom event structure */ struct SDL_SysWMmsg { SDL_version version; int data; }; /** The QNX custom window manager information structure */ typedef struct SDL_SysWMinfo { SDL_version version; int data; } SDL_SysWMinfo; #else /** The generic custom event structure */ struct SDL_SysWMmsg { SDL_version version; int data; }; /** The generic custom window manager information structure */ typedef struct SDL_SysWMinfo { SDL_version version; int data; } SDL_SysWMinfo; #endif /* video driver type */ #endif /* SDL_PROTOTYPES_ONLY */ /* Function prototypes */ /** * This function gives you custom hooks into the window manager information. * It fills the structure pointed to by 'info' with custom information and * returns 1 if the function is implemented. If it's not implemented, or * the version member of the 'info' structure is invalid, it returns 0. * * You typically use this function like this: * @code * SDL_SysWMInfo info; * SDL_VERSION(&info.version); * if ( SDL_GetWMInfo(&info) ) { ... } * @endcode */ extern DECLSPEC int SDLCALL SDL_GetWMInfo(SDL_SysWMinfo *info); /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* _SDL_syswm_h */ ================================================ FILE: other/sdl/include/SDL_thread.h ================================================ /* SDL - Simple DirectMedia Layer Copyright (C) 1997-2009 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org */ #ifndef _SDL_thread_h #define _SDL_thread_h /** @file SDL_thread.h * Header for the SDL thread management routines * * @note These are independent of the other SDL routines. */ #include "SDL_stdinc.h" #include "SDL_error.h" /* Thread synchronization primitives */ #include "SDL_mutex.h" #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif /** The SDL thread structure, defined in SDL_thread.c */ struct SDL_Thread; typedef struct SDL_Thread SDL_Thread; /** Create a thread */ #if ((defined(__WIN32__) && !defined(HAVE_LIBC)) || defined(__OS2__)) && !defined(__SYMBIAN32__) /** * We compile SDL into a DLL on OS/2. This means, that it's the DLL which * creates a new thread for the calling process with the SDL_CreateThread() * API. There is a problem with this, that only the RTL of the SDL.DLL will * be initialized for those threads, and not the RTL of the calling application! * To solve this, we make a little hack here. * We'll always use the caller's _beginthread() and _endthread() APIs to * start a new thread. This way, if it's the SDL.DLL which uses this API, * then the RTL of SDL.DLL will be used to create the new thread, and if it's * the application, then the RTL of the application will be used. * So, in short: * Always use the _beginthread() and _endthread() of the calling runtime library! */ #define SDL_PASSED_BEGINTHREAD_ENDTHREAD #ifndef _WIN32_WCE #include <process.h> /* This has _beginthread() and _endthread() defined! */ #endif #ifdef __OS2__ typedef int (*pfnSDL_CurrentBeginThread)(void (*func)(void *), void *, unsigned, void *arg); typedef void (*pfnSDL_CurrentEndThread)(void); #elif __GNUC__ typedef unsigned long (__cdecl *pfnSDL_CurrentBeginThread) (void *, unsigned, unsigned (__stdcall *func)(void *), void *arg, unsigned, unsigned *threadID); typedef void (__cdecl *pfnSDL_CurrentEndThread)(unsigned code); #else typedef uintptr_t (__cdecl *pfnSDL_CurrentBeginThread) (void *, unsigned, unsigned (__stdcall *func)(void *), void *arg, unsigned, unsigned *threadID); typedef void (__cdecl *pfnSDL_CurrentEndThread)(unsigned code); #endif extern DECLSPEC SDL_Thread * SDLCALL SDL_CreateThread(int (SDLCALL *fn)(void *), void *data, pfnSDL_CurrentBeginThread pfnBeginThread, pfnSDL_CurrentEndThread pfnEndThread); #ifdef __OS2__ #define SDL_CreateThread(fn, data) SDL_CreateThread(fn, data, _beginthread, _endthread) #elif defined(_WIN32_WCE) #define SDL_CreateThread(fn, data) SDL_CreateThread(fn, data, NULL, NULL) #else #define SDL_CreateThread(fn, data) SDL_CreateThread(fn, data, _beginthreadex, _endthreadex) #endif #else extern DECLSPEC SDL_Thread * SDLCALL SDL_CreateThread(int (SDLCALL *fn)(void *), void *data); #endif /** Get the 32-bit thread identifier for the current thread */ extern DECLSPEC Uint32 SDLCALL SDL_ThreadID(void); /** Get the 32-bit thread identifier for the specified thread, * equivalent to SDL_ThreadID() if the specified thread is NULL. */ extern DECLSPEC Uint32 SDLCALL SDL_GetThreadID(SDL_Thread *thread); /** Wait for a thread to finish. * The return code for the thread function is placed in the area * pointed to by 'status', if 'status' is not NULL. */ extern DECLSPEC void SDLCALL SDL_WaitThread(SDL_Thread *thread, int *status); /** Forcefully kill a thread without worrying about its state */ extern DECLSPEC void SDLCALL SDL_KillThread(SDL_Thread *thread); /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* _SDL_thread_h */ ================================================ FILE: other/sdl/include/SDL_timer.h ================================================ /* SDL - Simple DirectMedia Layer Copyright (C) 1997-2009 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org */ #ifndef _SDL_timer_h #define _SDL_timer_h /** @file SDL_timer.h * Header for the SDL time management routines */ #include "SDL_stdinc.h" #include "SDL_error.h" #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif /** This is the OS scheduler timeslice, in milliseconds */ #define SDL_TIMESLICE 10 /** This is the maximum resolution of the SDL timer on all platforms */ #define TIMER_RESOLUTION 10 /**< Experimentally determined */ /** * Get the number of milliseconds since the SDL library initialization. * Note that this value wraps if the program runs for more than ~49 days. */ extern DECLSPEC Uint32 SDLCALL SDL_GetTicks(void); /** Wait a specified number of milliseconds before returning */ extern DECLSPEC void SDLCALL SDL_Delay(Uint32 ms); /** Function prototype for the timer callback function */ typedef Uint32 (SDLCALL *SDL_TimerCallback)(Uint32 interval); /** * Set a callback to run after the specified number of milliseconds has * elapsed. The callback function is passed the current timer interval * and returns the next timer interval. If the returned value is the * same as the one passed in, the periodic alarm continues, otherwise a * new alarm is scheduled. If the callback returns 0, the periodic alarm * is cancelled. * * To cancel a currently running timer, call SDL_SetTimer(0, NULL); * * The timer callback function may run in a different thread than your * main code, and so shouldn't call any functions from within itself. * * The maximum resolution of this timer is 10 ms, which means that if * you request a 16 ms timer, your callback will run approximately 20 ms * later on an unloaded system. If you wanted to set a flag signaling * a frame update at 30 frames per second (every 33 ms), you might set a * timer for 30 ms: * @code SDL_SetTimer((33/10)*10, flag_update); @endcode * * If you use this function, you need to pass SDL_INIT_TIMER to SDL_Init(). * * Under UNIX, you should not use raise or use SIGALRM and this function * in the same program, as it is implemented using setitimer(). You also * should not use this function in multi-threaded applications as signals * to multi-threaded apps have undefined behavior in some implementations. * * This function returns 0 if successful, or -1 if there was an error. */ extern DECLSPEC int SDLCALL SDL_SetTimer(Uint32 interval, SDL_TimerCallback callback); /** @name New timer API * New timer API, supports multiple timers * Written by Stephane Peter <megastep@lokigames.com> */ /*@{*/ /** * Function prototype for the new timer callback function. * The callback function is passed the current timer interval and returns * the next timer interval. If the returned value is the same as the one * passed in, the periodic alarm continues, otherwise a new alarm is * scheduled. If the callback returns 0, the periodic alarm is cancelled. */ typedef Uint32 (SDLCALL *SDL_NewTimerCallback)(Uint32 interval, void *param); /** Definition of the timer ID type */ typedef struct _SDL_TimerID *SDL_TimerID; /** Add a new timer to the pool of timers already running. * Returns a timer ID, or NULL when an error occurs. */ extern DECLSPEC SDL_TimerID SDLCALL SDL_AddTimer(Uint32 interval, SDL_NewTimerCallback callback, void *param); /** * Remove one of the multiple timers knowing its ID. * Returns a boolean value indicating success. */ extern DECLSPEC SDL_bool SDLCALL SDL_RemoveTimer(SDL_TimerID t); /*@}*/ /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* _SDL_timer_h */ ================================================ FILE: other/sdl/include/SDL_types.h ================================================ /* SDL - Simple DirectMedia Layer Copyright (C) 1997-2009 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org */ /** @file SDL_types.h * @deprecated Use SDL_stdinc.h instead. */ /* DEPRECATED */ #include "SDL_stdinc.h" ================================================ FILE: other/sdl/include/SDL_version.h ================================================ /* SDL - Simple DirectMedia Layer Copyright (C) 1997-2009 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org */ /** @file SDL_version.h * This header defines the current SDL version */ #ifndef _SDL_version_h #define _SDL_version_h #include "SDL_stdinc.h" #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif /** @name Version Number * Printable format: "%d.%d.%d", MAJOR, MINOR, PATCHLEVEL */ /*@{*/ #define SDL_MAJOR_VERSION 1 #define SDL_MINOR_VERSION 2 #define SDL_PATCHLEVEL 14 /*@}*/ typedef struct SDL_version { Uint8 major; Uint8 minor; Uint8 patch; } SDL_version; /** * This macro can be used to fill a version structure with the compile-time * version of the SDL library. */ #define SDL_VERSION(X) \ { \ (X)->major = SDL_MAJOR_VERSION; \ (X)->minor = SDL_MINOR_VERSION; \ (X)->patch = SDL_PATCHLEVEL; \ } /** This macro turns the version numbers into a numeric value: * (1,2,3) -> (1203) * This assumes that there will never be more than 100 patchlevels */ #define SDL_VERSIONNUM(X, Y, Z) \ ((X)*1000 + (Y)*100 + (Z)) /** This is the version number macro for the current SDL version */ #define SDL_COMPILEDVERSION \ SDL_VERSIONNUM(SDL_MAJOR_VERSION, SDL_MINOR_VERSION, SDL_PATCHLEVEL) /** This macro will evaluate to true if compiled with SDL at least X.Y.Z */ #define SDL_VERSION_ATLEAST(X, Y, Z) \ (SDL_COMPILEDVERSION >= SDL_VERSIONNUM(X, Y, Z)) /** This function gets the version of the dynamically linked SDL library. * it should NOT be used to fill a version structure, instead you should * use the SDL_Version() macro. */ extern DECLSPEC const SDL_version * SDLCALL SDL_Linked_Version(void); /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* _SDL_version_h */ ================================================ FILE: other/sdl/include/SDL_video.h ================================================ /* SDL - Simple DirectMedia Layer Copyright (C) 1997-2009 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org */ /** @file SDL_video.h * Header file for access to the SDL raw framebuffer window */ #ifndef _SDL_video_h #define _SDL_video_h #include "SDL_stdinc.h" #include "SDL_error.h" #include "SDL_rwops.h" #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif /** @name Transparency definitions * These define alpha as the opacity of a surface */ /*@{*/ #define SDL_ALPHA_OPAQUE 255 #define SDL_ALPHA_TRANSPARENT 0 /*@}*/ /** @name Useful data types */ /*@{*/ typedef struct SDL_Rect { Sint16 x, y; Uint16 w, h; } SDL_Rect; typedef struct SDL_Color { Uint8 r; Uint8 g; Uint8 b; Uint8 unused; } SDL_Color; #define SDL_Colour SDL_Color typedef struct SDL_Palette { int ncolors; SDL_Color *colors; } SDL_Palette; /*@}*/ /** Everything in the pixel format structure is read-only */ typedef struct SDL_PixelFormat { SDL_Palette *palette; Uint8 BitsPerPixel; Uint8 BytesPerPixel; Uint8 Rloss; Uint8 Gloss; Uint8 Bloss; Uint8 Aloss; Uint8 Rshift; Uint8 Gshift; Uint8 Bshift; Uint8 Ashift; Uint32 Rmask; Uint32 Gmask; Uint32 Bmask; Uint32 Amask; /** RGB color key information */ Uint32 colorkey; /** Alpha value information (per-surface alpha) */ Uint8 alpha; } SDL_PixelFormat; /** This structure should be treated as read-only, except for 'pixels', * which, if not NULL, contains the raw pixel data for the surface. */ typedef struct SDL_Surface { Uint32 flags; /**< Read-only */ SDL_PixelFormat *format; /**< Read-only */ int w, h; /**< Read-only */ Uint16 pitch; /**< Read-only */ void *pixels; /**< Read-write */ int offset; /**< Private */ /** Hardware-specific surface info */ struct private_hwdata *hwdata; /** clipping information */ SDL_Rect clip_rect; /**< Read-only */ Uint32 unused1; /**< for binary compatibility */ /** Allow recursive locks */ Uint32 locked; /**< Private */ /** info for fast blit mapping to other surfaces */ struct SDL_BlitMap *map; /**< Private */ /** format version, bumped at every change to invalidate blit maps */ unsigned int format_version; /**< Private */ /** Reference count -- used when freeing surface */ int refcount; /**< Read-mostly */ } SDL_Surface; /** @name SDL_Surface Flags * These are the currently supported flags for the SDL_surface */ /*@{*/ /** Available for SDL_CreateRGBSurface() or SDL_SetVideoMode() */ /*@{*/ #define SDL_SWSURFACE 0x00000000 /**< Surface is in system memory */ #define SDL_HWSURFACE 0x00000001 /**< Surface is in video memory */ #define SDL_ASYNCBLIT 0x00000004 /**< Use asynchronous blits if possible */ /*@}*/ /** Available for SDL_SetVideoMode() */ /*@{*/ #define SDL_ANYFORMAT 0x10000000 /**< Allow any video depth/pixel-format */ #define SDL_HWPALETTE 0x20000000 /**< Surface has exclusive palette */ #define SDL_DOUBLEBUF 0x40000000 /**< Set up double-buffered video mode */ #define SDL_FULLSCREEN 0x80000000 /**< Surface is a full screen display */ #define SDL_OPENGL 0x00000002 /**< Create an OpenGL rendering context */ #define SDL_OPENGLBLIT 0x0000000A /**< Create an OpenGL rendering context and use it for blitting */ #define SDL_RESIZABLE 0x00000010 /**< This video mode may be resized */ #define SDL_NOFRAME 0x00000020 /**< No window caption or edge frame */ /*@}*/ /** Used internally (read-only) */ /*@{*/ #define SDL_HWACCEL 0x00000100 /**< Blit uses hardware acceleration */ #define SDL_SRCCOLORKEY 0x00001000 /**< Blit uses a source color key */ #define SDL_RLEACCELOK 0x00002000 /**< Private flag */ #define SDL_RLEACCEL 0x00004000 /**< Surface is RLE encoded */ #define SDL_SRCALPHA 0x00010000 /**< Blit uses source alpha blending */ #define SDL_PREALLOC 0x01000000 /**< Surface uses preallocated memory */ /*@}*/ /*@}*/ /** Evaluates to true if the surface needs to be locked before access */ #define SDL_MUSTLOCK(surface) \ (surface->offset || \ ((surface->flags & (SDL_HWSURFACE|SDL_ASYNCBLIT|SDL_RLEACCEL)) != 0)) /** typedef for private surface blitting functions */ typedef int (*SDL_blit)(struct SDL_Surface *src, SDL_Rect *srcrect, struct SDL_Surface *dst, SDL_Rect *dstrect); /** Useful for determining the video hardware capabilities */ typedef struct SDL_VideoInfo { Uint32 hw_available :1; /**< Flag: Can you create hardware surfaces? */ Uint32 wm_available :1; /**< Flag: Can you talk to a window manager? */ Uint32 UnusedBits1 :6; Uint32 UnusedBits2 :1; Uint32 blit_hw :1; /**< Flag: Accelerated blits HW --> HW */ Uint32 blit_hw_CC :1; /**< Flag: Accelerated blits with Colorkey */ Uint32 blit_hw_A :1; /**< Flag: Accelerated blits with Alpha */ Uint32 blit_sw :1; /**< Flag: Accelerated blits SW --> HW */ Uint32 blit_sw_CC :1; /**< Flag: Accelerated blits with Colorkey */ Uint32 blit_sw_A :1; /**< Flag: Accelerated blits with Alpha */ Uint32 blit_fill :1; /**< Flag: Accelerated color fill */ Uint32 UnusedBits3 :16; Uint32 video_mem; /**< The total amount of video memory (in K) */ SDL_PixelFormat *vfmt; /**< Value: The format of the video surface */ int current_w; /**< Value: The current video mode width */ int current_h; /**< Value: The current video mode height */ } SDL_VideoInfo; /** @name Overlay Formats * The most common video overlay formats. * For an explanation of these pixel formats, see: * http://www.webartz.com/fourcc/indexyuv.htm * * For information on the relationship between color spaces, see: * http://www.neuro.sfc.keio.ac.jp/~aly/polygon/info/color-space-faq.html */ /*@{*/ #define SDL_YV12_OVERLAY 0x32315659 /**< Planar mode: Y + V + U (3 planes) */ #define SDL_IYUV_OVERLAY 0x56555949 /**< Planar mode: Y + U + V (3 planes) */ #define SDL_YUY2_OVERLAY 0x32595559 /**< Packed mode: Y0+U0+Y1+V0 (1 plane) */ #define SDL_UYVY_OVERLAY 0x59565955 /**< Packed mode: U0+Y0+V0+Y1 (1 plane) */ #define SDL_YVYU_OVERLAY 0x55595659 /**< Packed mode: Y0+V0+Y1+U0 (1 plane) */ /*@}*/ /** The YUV hardware video overlay */ typedef struct SDL_Overlay { Uint32 format; /**< Read-only */ int w, h; /**< Read-only */ int planes; /**< Read-only */ Uint16 *pitches; /**< Read-only */ Uint8 **pixels; /**< Read-write */ /** @name Hardware-specific surface info */ /*@{*/ struct private_yuvhwfuncs *hwfuncs; struct private_yuvhwdata *hwdata; /*@{*/ /** @name Special flags */ /*@{*/ Uint32 hw_overlay :1; /**< Flag: This overlay hardware accelerated? */ Uint32 UnusedBits :31; /*@}*/ } SDL_Overlay; /** Public enumeration for setting the OpenGL window attributes. */ typedef enum { SDL_GL_RED_SIZE, SDL_GL_GREEN_SIZE, SDL_GL_BLUE_SIZE, SDL_GL_ALPHA_SIZE, SDL_GL_BUFFER_SIZE, SDL_GL_DOUBLEBUFFER, SDL_GL_DEPTH_SIZE, SDL_GL_STENCIL_SIZE, SDL_GL_ACCUM_RED_SIZE, SDL_GL_ACCUM_GREEN_SIZE, SDL_GL_ACCUM_BLUE_SIZE, SDL_GL_ACCUM_ALPHA_SIZE, SDL_GL_STEREO, SDL_GL_MULTISAMPLEBUFFERS, SDL_GL_MULTISAMPLESAMPLES, SDL_GL_ACCELERATED_VISUAL, SDL_GL_SWAP_CONTROL } SDL_GLattr; /** @name flags for SDL_SetPalette() */ /*@{*/ #define SDL_LOGPAL 0x01 #define SDL_PHYSPAL 0x02 /*@}*/ /* Function prototypes */ /** * @name Video Init and Quit * These functions are used internally, and should not be used unless you * have a specific need to specify the video driver you want to use. * You should normally use SDL_Init() or SDL_InitSubSystem(). */ /*@{*/ /** * Initializes the video subsystem. Sets up a connection * to the window manager, etc, and determines the current video mode and * pixel format, but does not initialize a window or graphics mode. * Note that event handling is activated by this routine. * * If you use both sound and video in your application, you need to call * SDL_Init() before opening the sound device, otherwise under Win32 DirectX, * you won't be able to set full-screen display modes. */ extern DECLSPEC int SDLCALL SDL_VideoInit(const char *driver_name, Uint32 flags); extern DECLSPEC void SDLCALL SDL_VideoQuit(void); /*@}*/ /** * This function fills the given character buffer with the name of the * video driver, and returns a pointer to it if the video driver has * been initialized. It returns NULL if no driver has been initialized. */ extern DECLSPEC char * SDLCALL SDL_VideoDriverName(char *namebuf, int maxlen); /** * This function returns a pointer to the current display surface. * If SDL is doing format conversion on the display surface, this * function returns the publicly visible surface, not the real video * surface. */ extern DECLSPEC SDL_Surface * SDLCALL SDL_GetVideoSurface(void); /** * This function returns a read-only pointer to information about the * video hardware. If this is called before SDL_SetVideoMode(), the 'vfmt' * member of the returned structure will contain the pixel format of the * "best" video mode. */ extern DECLSPEC const SDL_VideoInfo * SDLCALL SDL_GetVideoInfo(void); /** * Check to see if a particular video mode is supported. * It returns 0 if the requested mode is not supported under any bit depth, * or returns the bits-per-pixel of the closest available mode with the * given width and height. If this bits-per-pixel is different from the * one used when setting the video mode, SDL_SetVideoMode() will succeed, * but will emulate the requested bits-per-pixel with a shadow surface. * * The arguments to SDL_VideoModeOK() are the same ones you would pass to * SDL_SetVideoMode() */ extern DECLSPEC int SDLCALL SDL_VideoModeOK(int width, int height, int bpp, Uint32 flags); /** * Return a pointer to an array of available screen dimensions for the * given format and video flags, sorted largest to smallest. Returns * NULL if there are no dimensions available for a particular format, * or (SDL_Rect **)-1 if any dimension is okay for the given format. * * If 'format' is NULL, the mode list will be for the format given * by SDL_GetVideoInfo()->vfmt */ extern DECLSPEC SDL_Rect ** SDLCALL SDL_ListModes(SDL_PixelFormat *format, Uint32 flags); /** * Set up a video mode with the specified width, height and bits-per-pixel. * * If 'bpp' is 0, it is treated as the current display bits per pixel. * * If SDL_ANYFORMAT is set in 'flags', the SDL library will try to set the * requested bits-per-pixel, but will return whatever video pixel format is * available. The default is to emulate the requested pixel format if it * is not natively available. * * If SDL_HWSURFACE is set in 'flags', the video surface will be placed in * video memory, if possible, and you may have to call SDL_LockSurface() * in order to access the raw framebuffer. Otherwise, the video surface * will be created in system memory. * * If SDL_ASYNCBLIT is set in 'flags', SDL will try to perform rectangle * updates asynchronously, but you must always lock before accessing pixels. * SDL will wait for updates to complete before returning from the lock. * * If SDL_HWPALETTE is set in 'flags', the SDL library will guarantee * that the colors set by SDL_SetColors() will be the colors you get. * Otherwise, in 8-bit mode, SDL_SetColors() may not be able to set all * of the colors exactly the way they are requested, and you should look * at the video surface structure to determine the actual palette. * If SDL cannot guarantee that the colors you request can be set, * i.e. if the colormap is shared, then the video surface may be created * under emulation in system memory, overriding the SDL_HWSURFACE flag. * * If SDL_FULLSCREEN is set in 'flags', the SDL library will try to set * a fullscreen video mode. The default is to create a windowed mode * if the current graphics system has a window manager. * If the SDL library is able to set a fullscreen video mode, this flag * will be set in the surface that is returned. * * If SDL_DOUBLEBUF is set in 'flags', the SDL library will try to set up * two surfaces in video memory and swap between them when you call * SDL_Flip(). This is usually slower than the normal single-buffering * scheme, but prevents "tearing" artifacts caused by modifying video * memory while the monitor is refreshing. It should only be used by * applications that redraw the entire screen on every update. * * If SDL_RESIZABLE is set in 'flags', the SDL library will allow the * window manager, if any, to resize the window at runtime. When this * occurs, SDL will send a SDL_VIDEORESIZE event to you application, * and you must respond to the event by re-calling SDL_SetVideoMode() * with the requested size (or another size that suits the application). * * If SDL_NOFRAME is set in 'flags', the SDL library will create a window * without any title bar or frame decoration. Fullscreen video modes have * this flag set automatically. * * This function returns the video framebuffer surface, or NULL if it fails. * * If you rely on functionality provided by certain video flags, check the * flags of the returned surface to make sure that functionality is available. * SDL will fall back to reduced functionality if the exact flags you wanted * are not available. */ extern DECLSPEC SDL_Surface * SDLCALL SDL_SetVideoMode (int width, int height, int bpp, Uint32 flags); /** @name SDL_Update Functions * These functions should not be called while 'screen' is locked. */ /*@{*/ /** * Makes sure the given list of rectangles is updated on the given screen. */ extern DECLSPEC void SDLCALL SDL_UpdateRects (SDL_Surface *screen, int numrects, SDL_Rect *rects); /** * If 'x', 'y', 'w' and 'h' are all 0, SDL_UpdateRect will update the entire * screen. */ extern DECLSPEC void SDLCALL SDL_UpdateRect (SDL_Surface *screen, Sint32 x, Sint32 y, Uint32 w, Uint32 h); /*@}*/ /** * On hardware that supports double-buffering, this function sets up a flip * and returns. The hardware will wait for vertical retrace, and then swap * video buffers before the next video surface blit or lock will return. * On hardware that doesn not support double-buffering, this is equivalent * to calling SDL_UpdateRect(screen, 0, 0, 0, 0); * The SDL_DOUBLEBUF flag must have been passed to SDL_SetVideoMode() when * setting the video mode for this function to perform hardware flipping. * This function returns 0 if successful, or -1 if there was an error. */ extern DECLSPEC int SDLCALL SDL_Flip(SDL_Surface *screen); /** * Set the gamma correction for each of the color channels. * The gamma values range (approximately) between 0.1 and 10.0 * * If this function isn't supported directly by the hardware, it will * be emulated using gamma ramps, if available. If successful, this * function returns 0, otherwise it returns -1. */ extern DECLSPEC int SDLCALL SDL_SetGamma(float red, float green, float blue); /** * Set the gamma translation table for the red, green, and blue channels * of the video hardware. Each table is an array of 256 16-bit quantities, * representing a mapping between the input and output for that channel. * The input is the index into the array, and the output is the 16-bit * gamma value at that index, scaled to the output color precision. * * You may pass NULL for any of the channels to leave it unchanged. * If the call succeeds, it will return 0. If the display driver or * hardware does not support gamma translation, or otherwise fails, * this function will return -1. */ extern DECLSPEC int SDLCALL SDL_SetGammaRamp(const Uint16 *red, const Uint16 *green, const Uint16 *blue); /** * Retrieve the current values of the gamma translation tables. * * You must pass in valid pointers to arrays of 256 16-bit quantities. * Any of the pointers may be NULL to ignore that channel. * If the call succeeds, it will return 0. If the display driver or * hardware does not support gamma translation, or otherwise fails, * this function will return -1. */ extern DECLSPEC int SDLCALL SDL_GetGammaRamp(Uint16 *red, Uint16 *green, Uint16 *blue); /** * Sets a portion of the colormap for the given 8-bit surface. If 'surface' * is not a palettized surface, this function does nothing, returning 0. * If all of the colors were set as passed to SDL_SetColors(), it will * return 1. If not all the color entries were set exactly as given, * it will return 0, and you should look at the surface palette to * determine the actual color palette. * * When 'surface' is the surface associated with the current display, the * display colormap will be updated with the requested colors. If * SDL_HWPALETTE was set in SDL_SetVideoMode() flags, SDL_SetColors() * will always return 1, and the palette is guaranteed to be set the way * you desire, even if the window colormap has to be warped or run under * emulation. */ extern DECLSPEC int SDLCALL SDL_SetColors(SDL_Surface *surface, SDL_Color *colors, int firstcolor, int ncolors); /** * Sets a portion of the colormap for a given 8-bit surface. * 'flags' is one or both of: * SDL_LOGPAL -- set logical palette, which controls how blits are mapped * to/from the surface, * SDL_PHYSPAL -- set physical palette, which controls how pixels look on * the screen * Only screens have physical palettes. Separate change of physical/logical * palettes is only possible if the screen has SDL_HWPALETTE set. * * The return value is 1 if all colours could be set as requested, and 0 * otherwise. * * SDL_SetColors() is equivalent to calling this function with * flags = (SDL_LOGPAL|SDL_PHYSPAL). */ extern DECLSPEC int SDLCALL SDL_SetPalette(SDL_Surface *surface, int flags, SDL_Color *colors, int firstcolor, int ncolors); /** * Maps an RGB triple to an opaque pixel value for a given pixel format */ extern DECLSPEC Uint32 SDLCALL SDL_MapRGB (const SDL_PixelFormat * const format, const Uint8 r, const Uint8 g, const Uint8 b); /** * Maps an RGBA quadruple to a pixel value for a given pixel format */ extern DECLSPEC Uint32 SDLCALL SDL_MapRGBA (const SDL_PixelFormat * const format, const Uint8 r, const Uint8 g, const Uint8 b, const Uint8 a); /** * Maps a pixel value into the RGB components for a given pixel format */ extern DECLSPEC void SDLCALL SDL_GetRGB(Uint32 pixel, const SDL_PixelFormat * const fmt, Uint8 *r, Uint8 *g, Uint8 *b); /** * Maps a pixel value into the RGBA components for a given pixel format */ extern DECLSPEC void SDLCALL SDL_GetRGBA(Uint32 pixel, const SDL_PixelFormat * const fmt, Uint8 *r, Uint8 *g, Uint8 *b, Uint8 *a); /** @sa SDL_CreateRGBSurface */ #define SDL_AllocSurface SDL_CreateRGBSurface /** * Allocate and free an RGB surface (must be called after SDL_SetVideoMode) * If the depth is 4 or 8 bits, an empty palette is allocated for the surface. * If the depth is greater than 8 bits, the pixel format is set using the * flags '[RGB]mask'. * If the function runs out of memory, it will return NULL. * * The 'flags' tell what kind of surface to create. * SDL_SWSURFACE means that the surface should be created in system memory. * SDL_HWSURFACE means that the surface should be created in video memory, * with the same format as the display surface. This is useful for surfaces * that will not change much, to take advantage of hardware acceleration * when being blitted to the display surface. * SDL_ASYNCBLIT means that SDL will try to perform asynchronous blits with * this surface, but you must always lock it before accessing the pixels. * SDL will wait for current blits to finish before returning from the lock. * SDL_SRCCOLORKEY indicates that the surface will be used for colorkey blits. * If the hardware supports acceleration of colorkey blits between * two surfaces in video memory, SDL will try to place the surface in * video memory. If this isn't possible or if there is no hardware * acceleration available, the surface will be placed in system memory. * SDL_SRCALPHA means that the surface will be used for alpha blits and * if the hardware supports hardware acceleration of alpha blits between * two surfaces in video memory, to place the surface in video memory * if possible, otherwise it will be placed in system memory. * If the surface is created in video memory, blits will be _much_ faster, * but the surface format must be identical to the video surface format, * and the only way to access the pixels member of the surface is to use * the SDL_LockSurface() and SDL_UnlockSurface() calls. * If the requested surface actually resides in video memory, SDL_HWSURFACE * will be set in the flags member of the returned surface. If for some * reason the surface could not be placed in video memory, it will not have * the SDL_HWSURFACE flag set, and will be created in system memory instead. */ extern DECLSPEC SDL_Surface * SDLCALL SDL_CreateRGBSurface (Uint32 flags, int width, int height, int depth, Uint32 Rmask, Uint32 Gmask, Uint32 Bmask, Uint32 Amask); /** @sa SDL_CreateRGBSurface */ extern DECLSPEC SDL_Surface * SDLCALL SDL_CreateRGBSurfaceFrom(void *pixels, int width, int height, int depth, int pitch, Uint32 Rmask, Uint32 Gmask, Uint32 Bmask, Uint32 Amask); extern DECLSPEC void SDLCALL SDL_FreeSurface(SDL_Surface *surface); /** * SDL_LockSurface() sets up a surface for directly accessing the pixels. * Between calls to SDL_LockSurface()/SDL_UnlockSurface(), you can write * to and read from 'surface->pixels', using the pixel format stored in * 'surface->format'. Once you are done accessing the surface, you should * use SDL_UnlockSurface() to release it. * * Not all surfaces require locking. If SDL_MUSTLOCK(surface) evaluates * to 0, then you can read and write to the surface at any time, and the * pixel format of the surface will not change. In particular, if the * SDL_HWSURFACE flag is not given when calling SDL_SetVideoMode(), you * will not need to lock the display surface before accessing it. * * No operating system or library calls should be made between lock/unlock * pairs, as critical system locks may be held during this time. * * SDL_LockSurface() returns 0, or -1 if the surface couldn't be locked. */ extern DECLSPEC int SDLCALL SDL_LockSurface(SDL_Surface *surface); extern DECLSPEC void SDLCALL SDL_UnlockSurface(SDL_Surface *surface); /** * Load a surface from a seekable SDL data source (memory or file.) * If 'freesrc' is non-zero, the source will be closed after being read. * Returns the new surface, or NULL if there was an error. * The new surface should be freed with SDL_FreeSurface(). */ extern DECLSPEC SDL_Surface * SDLCALL SDL_LoadBMP_RW(SDL_RWops *src, int freesrc); /** Convenience macro -- load a surface from a file */ #define SDL_LoadBMP(file) SDL_LoadBMP_RW(SDL_RWFromFile(file, "rb"), 1) /** * Save a surface to a seekable SDL data source (memory or file.) * If 'freedst' is non-zero, the source will be closed after being written. * Returns 0 if successful or -1 if there was an error. */ extern DECLSPEC int SDLCALL SDL_SaveBMP_RW (SDL_Surface *surface, SDL_RWops *dst, int freedst); /** Convenience macro -- save a surface to a file */ #define SDL_SaveBMP(surface, file) \ SDL_SaveBMP_RW(surface, SDL_RWFromFile(file, "wb"), 1) /** * Sets the color key (transparent pixel) in a blittable surface. * If 'flag' is SDL_SRCCOLORKEY (optionally OR'd with SDL_RLEACCEL), * 'key' will be the transparent pixel in the source image of a blit. * SDL_RLEACCEL requests RLE acceleration for the surface if present, * and removes RLE acceleration if absent. * If 'flag' is 0, this function clears any current color key. * This function returns 0, or -1 if there was an error. */ extern DECLSPEC int SDLCALL SDL_SetColorKey (SDL_Surface *surface, Uint32 flag, Uint32 key); /** * This function sets the alpha value for the entire surface, as opposed to * using the alpha component of each pixel. This value measures the range * of transparency of the surface, 0 being completely transparent to 255 * being completely opaque. An 'alpha' value of 255 causes blits to be * opaque, the source pixels copied to the destination (the default). Note * that per-surface alpha can be combined with colorkey transparency. * * If 'flag' is 0, alpha blending is disabled for the surface. * If 'flag' is SDL_SRCALPHA, alpha blending is enabled for the surface. * OR:ing the flag with SDL_RLEACCEL requests RLE acceleration for the * surface; if SDL_RLEACCEL is not specified, the RLE accel will be removed. * * The 'alpha' parameter is ignored for surfaces that have an alpha channel. */ extern DECLSPEC int SDLCALL SDL_SetAlpha(SDL_Surface *surface, Uint32 flag, Uint8 alpha); /** * Sets the clipping rectangle for the destination surface in a blit. * * If the clip rectangle is NULL, clipping will be disabled. * If the clip rectangle doesn't intersect the surface, the function will * return SDL_FALSE and blits will be completely clipped. Otherwise the * function returns SDL_TRUE and blits to the surface will be clipped to * the intersection of the surface area and the clipping rectangle. * * Note that blits are automatically clipped to the edges of the source * and destination surfaces. */ extern DECLSPEC SDL_bool SDLCALL SDL_SetClipRect(SDL_Surface *surface, const SDL_Rect *rect); /** * Gets the clipping rectangle for the destination surface in a blit. * 'rect' must be a pointer to a valid rectangle which will be filled * with the correct values. */ extern DECLSPEC void SDLCALL SDL_GetClipRect(SDL_Surface *surface, SDL_Rect *rect); /** * Creates a new surface of the specified format, and then copies and maps * the given surface to it so the blit of the converted surface will be as * fast as possible. If this function fails, it returns NULL. * * The 'flags' parameter is passed to SDL_CreateRGBSurface() and has those * semantics. You can also pass SDL_RLEACCEL in the flags parameter and * SDL will try to RLE accelerate colorkey and alpha blits in the resulting * surface. * * This function is used internally by SDL_DisplayFormat(). */ extern DECLSPEC SDL_Surface * SDLCALL SDL_ConvertSurface (SDL_Surface *src, SDL_PixelFormat *fmt, Uint32 flags); /** * This performs a fast blit from the source surface to the destination * surface. It assumes that the source and destination rectangles are * the same size. If either 'srcrect' or 'dstrect' are NULL, the entire * surface (src or dst) is copied. The final blit rectangles are saved * in 'srcrect' and 'dstrect' after all clipping is performed. * If the blit is successful, it returns 0, otherwise it returns -1. * * The blit function should not be called on a locked surface. * * The blit semantics for surfaces with and without alpha and colorkey * are defined as follows: * * RGBA->RGB: * SDL_SRCALPHA set: * alpha-blend (using alpha-channel). * SDL_SRCCOLORKEY ignored. * SDL_SRCALPHA not set: * copy RGB. * if SDL_SRCCOLORKEY set, only copy the pixels matching the * RGB values of the source colour key, ignoring alpha in the * comparison. * * RGB->RGBA: * SDL_SRCALPHA set: * alpha-blend (using the source per-surface alpha value); * set destination alpha to opaque. * SDL_SRCALPHA not set: * copy RGB, set destination alpha to source per-surface alpha value. * both: * if SDL_SRCCOLORKEY set, only copy the pixels matching the * source colour key. * * RGBA->RGBA: * SDL_SRCALPHA set: * alpha-blend (using the source alpha channel) the RGB values; * leave destination alpha untouched. [Note: is this correct?] * SDL_SRCCOLORKEY ignored. * SDL_SRCALPHA not set: * copy all of RGBA to the destination. * if SDL_SRCCOLORKEY set, only copy the pixels matching the * RGB values of the source colour key, ignoring alpha in the * comparison. * * RGB->RGB: * SDL_SRCALPHA set: * alpha-blend (using the source per-surface alpha value). * SDL_SRCALPHA not set: * copy RGB. * both: * if SDL_SRCCOLORKEY set, only copy the pixels matching the * source colour key. * * If either of the surfaces were in video memory, and the blit returns -2, * the video memory was lost, so it should be reloaded with artwork and * re-blitted: * @code * while ( SDL_BlitSurface(image, imgrect, screen, dstrect) == -2 ) { * while ( SDL_LockSurface(image) < 0 ) * Sleep(10); * -- Write image pixels to image->pixels -- * SDL_UnlockSurface(image); * } * @endcode * * This happens under DirectX 5.0 when the system switches away from your * fullscreen application. The lock will also fail until you have access * to the video memory again. * * You should call SDL_BlitSurface() unless you know exactly how SDL * blitting works internally and how to use the other blit functions. */ #define SDL_BlitSurface SDL_UpperBlit /** This is the public blit function, SDL_BlitSurface(), and it performs * rectangle validation and clipping before passing it to SDL_LowerBlit() */ extern DECLSPEC int SDLCALL SDL_UpperBlit (SDL_Surface *src, SDL_Rect *srcrect, SDL_Surface *dst, SDL_Rect *dstrect); /** This is a semi-private blit function and it performs low-level surface * blitting only. */ extern DECLSPEC int SDLCALL SDL_LowerBlit (SDL_Surface *src, SDL_Rect *srcrect, SDL_Surface *dst, SDL_Rect *dstrect); /** * This function performs a fast fill of the given rectangle with 'color' * The given rectangle is clipped to the destination surface clip area * and the final fill rectangle is saved in the passed in pointer. * If 'dstrect' is NULL, the whole surface will be filled with 'color' * The color should be a pixel of the format used by the surface, and * can be generated by the SDL_MapRGB() function. * This function returns 0 on success, or -1 on error. */ extern DECLSPEC int SDLCALL SDL_FillRect (SDL_Surface *dst, SDL_Rect *dstrect, Uint32 color); /** * This function takes a surface and copies it to a new surface of the * pixel format and colors of the video framebuffer, suitable for fast * blitting onto the display surface. It calls SDL_ConvertSurface() * * If you want to take advantage of hardware colorkey or alpha blit * acceleration, you should set the colorkey and alpha value before * calling this function. * * If the conversion fails or runs out of memory, it returns NULL */ extern DECLSPEC SDL_Surface * SDLCALL SDL_DisplayFormat(SDL_Surface *surface); /** * This function takes a surface and copies it to a new surface of the * pixel format and colors of the video framebuffer (if possible), * suitable for fast alpha blitting onto the display surface. * The new surface will always have an alpha channel. * * If you want to take advantage of hardware colorkey or alpha blit * acceleration, you should set the colorkey and alpha value before * calling this function. * * If the conversion fails or runs out of memory, it returns NULL */ extern DECLSPEC SDL_Surface * SDLCALL SDL_DisplayFormatAlpha(SDL_Surface *surface); /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** @name YUV video surface overlay functions */ /*@{*/ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** This function creates a video output overlay * Calling the returned surface an overlay is something of a misnomer because * the contents of the display surface underneath the area where the overlay * is shown is undefined - it may be overwritten with the converted YUV data. */ extern DECLSPEC SDL_Overlay * SDLCALL SDL_CreateYUVOverlay(int width, int height, Uint32 format, SDL_Surface *display); /** Lock an overlay for direct access, and unlock it when you are done */ extern DECLSPEC int SDLCALL SDL_LockYUVOverlay(SDL_Overlay *overlay); extern DECLSPEC void SDLCALL SDL_UnlockYUVOverlay(SDL_Overlay *overlay); /** Blit a video overlay to the display surface. * The contents of the video surface underneath the blit destination are * not defined. * The width and height of the destination rectangle may be different from * that of the overlay, but currently only 2x scaling is supported. */ extern DECLSPEC int SDLCALL SDL_DisplayYUVOverlay(SDL_Overlay *overlay, SDL_Rect *dstrect); /** Free a video overlay */ extern DECLSPEC void SDLCALL SDL_FreeYUVOverlay(SDL_Overlay *overlay); /*@}*/ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** @name OpenGL support functions. */ /*@{*/ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Dynamically load an OpenGL library, or the default one if path is NULL * * If you do this, you need to retrieve all of the GL functions used in * your program from the dynamic library using SDL_GL_GetProcAddress(). */ extern DECLSPEC int SDLCALL SDL_GL_LoadLibrary(const char *path); /** * Get the address of a GL function */ extern DECLSPEC void * SDLCALL SDL_GL_GetProcAddress(const char* proc); /** * Set an attribute of the OpenGL subsystem before intialization. */ extern DECLSPEC int SDLCALL SDL_GL_SetAttribute(SDL_GLattr attr, int value); /** * Get an attribute of the OpenGL subsystem from the windowing * interface, such as glX. This is of course different from getting * the values from SDL's internal OpenGL subsystem, which only * stores the values you request before initialization. * * Developers should track the values they pass into SDL_GL_SetAttribute * themselves if they want to retrieve these values. */ extern DECLSPEC int SDLCALL SDL_GL_GetAttribute(SDL_GLattr attr, int* value); /** * Swap the OpenGL buffers, if double-buffering is supported. */ extern DECLSPEC void SDLCALL SDL_GL_SwapBuffers(void); /** @name OpenGL Internal Functions * Internal functions that should not be called unless you have read * and understood the source code for these functions. */ /*@{*/ extern DECLSPEC void SDLCALL SDL_GL_UpdateRects(int numrects, SDL_Rect* rects); extern DECLSPEC void SDLCALL SDL_GL_Lock(void); extern DECLSPEC void SDLCALL SDL_GL_Unlock(void); /*@}*/ /*@}*/ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** @name Window Manager Functions */ /** These functions allow interaction with the window manager, if any. */ /*@{*/ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Sets the title and icon text of the display window (UTF-8 encoded) */ extern DECLSPEC void SDLCALL SDL_WM_SetCaption(const char *title, const char *icon); /** * Gets the title and icon text of the display window (UTF-8 encoded) */ extern DECLSPEC void SDLCALL SDL_WM_GetCaption(char **title, char **icon); /** * Sets the icon for the display window. * This function must be called before the first call to SDL_SetVideoMode(). * It takes an icon surface, and a mask in MSB format. * If 'mask' is NULL, the entire icon surface will be used as the icon. */ extern DECLSPEC void SDLCALL SDL_WM_SetIcon(SDL_Surface *icon, Uint8 *mask); /** * This function iconifies the window, and returns 1 if it succeeded. * If the function succeeds, it generates an SDL_APPACTIVE loss event. * This function is a noop and returns 0 in non-windowed environments. */ extern DECLSPEC int SDLCALL SDL_WM_IconifyWindow(void); /** * Toggle fullscreen mode without changing the contents of the screen. * If the display surface does not require locking before accessing * the pixel information, then the memory pointers will not change. * * If this function was able to toggle fullscreen mode (change from * running in a window to fullscreen, or vice-versa), it will return 1. * If it is not implemented, or fails, it returns 0. * * The next call to SDL_SetVideoMode() will set the mode fullscreen * attribute based on the flags parameter - if SDL_FULLSCREEN is not * set, then the display will be windowed by default where supported. * * This is currently only implemented in the X11 video driver. */ extern DECLSPEC int SDLCALL SDL_WM_ToggleFullScreen(SDL_Surface *surface); typedef enum { SDL_GRAB_QUERY = -1, SDL_GRAB_OFF = 0, SDL_GRAB_ON = 1, SDL_GRAB_FULLSCREEN /**< Used internally */ } SDL_GrabMode; /** * This function allows you to set and query the input grab state of * the application. It returns the new input grab state. * * Grabbing means that the mouse is confined to the application window, * and nearly all keyboard input is passed directly to the application, * and not interpreted by a window manager, if any. */ extern DECLSPEC SDL_GrabMode SDLCALL SDL_WM_GrabInput(SDL_GrabMode mode); /*@}*/ /** @internal Not in public API at the moment - do not use! */ extern DECLSPEC int SDLCALL SDL_SoftStretch(SDL_Surface *src, SDL_Rect *srcrect, SDL_Surface *dst, SDL_Rect *dstrect); /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* _SDL_video_h */ ================================================ FILE: other/sdl/include/begin_code.h ================================================ /* SDL - Simple DirectMedia Layer Copyright (C) 1997-2009 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Sam Lantinga slouken@libsdl.org */ /** * @file begin_code.h * This file sets things up for C dynamic library function definitions, * static inlined functions, and structures aligned at 4-byte alignment. * If you don't like ugly C preprocessor code, don't look at this file. :) */ /** * @file begin_code.h * This shouldn't be nested -- included it around code only. */ #ifdef _begin_code_h #error Nested inclusion of begin_code.h #endif #define _begin_code_h /** * @def DECLSPEC * Some compilers use a special export keyword */ #ifndef DECLSPEC # if defined(__BEOS__) || defined(__HAIKU__) # if defined(__GNUC__) # define DECLSPEC __declspec(dllexport) # else # define DECLSPEC __declspec(export) # endif # elif defined(__WIN32__) # ifdef __BORLANDC__ # ifdef BUILD_SDL # define DECLSPEC # else # define DECLSPEC __declspec(dllimport) # endif # else # define DECLSPEC __declspec(dllexport) # endif # elif defined(__OS2__) # ifdef __WATCOMC__ # ifdef BUILD_SDL # define DECLSPEC __declspec(dllexport) # else # define DECLSPEC # endif # elif defined (__GNUC__) && __GNUC__ < 4 # /* Added support for GCC-EMX <v4.x */ # /* this is needed for XFree86/OS2 developement */ # /* F. Ambacher(anakor@snafu.de) 05.2008 */ # ifdef BUILD_SDL # define DECLSPEC __declspec(dllexport) # else # define DECLSPEC # endif # else # define DECLSPEC # endif # else # if defined(__GNUC__) && __GNUC__ >= 4 # define DECLSPEC __attribute__ ((visibility("default"))) # else # define DECLSPEC # endif # endif #endif /** * @def SDLCALL * By default SDL uses the C calling convention */ #ifndef SDLCALL # if defined(__WIN32__) && !defined(__GNUC__) # define SDLCALL __cdecl # elif defined(__OS2__) # if defined (__GNUC__) && __GNUC__ < 4 # /* Added support for GCC-EMX <v4.x */ # /* this is needed for XFree86/OS2 developement */ # /* F. Ambacher(anakor@snafu.de) 05.2008 */ # define SDLCALL _cdecl # else # /* On other compilers on OS/2, we use the _System calling convention */ # /* to be compatible with every compiler */ # define SDLCALL _System # endif # else # define SDLCALL # endif #endif /* SDLCALL */ #ifdef __SYMBIAN32__ #ifndef EKA2 #undef DECLSPEC #define DECLSPEC #elif !defined(__WINS__) #undef DECLSPEC #define DECLSPEC __declspec(dllexport) #endif /* !EKA2 */ #endif /* __SYMBIAN32__ */ /** * @file begin_code.h * Force structure packing at 4 byte alignment. * This is necessary if the header is included in code which has structure * packing set to an alternate value, say for loading structures from disk. * The packing is reset to the previous value in close_code.h */ #if defined(_MSC_VER) || defined(__MWERKS__) || defined(__BORLANDC__) #ifdef _MSC_VER #pragma warning(disable: 4103) #endif #ifdef __BORLANDC__ #pragma nopackwarning #endif #pragma pack(push,4) #elif (defined(__MWERKS__) && defined(__MACOS__)) #pragma options align=mac68k4byte #pragma enumsalwaysint on #endif /* Compiler needs structure packing set */ /** * @def SDL_INLINE_OKAY * Set up compiler-specific options for inlining functions */ #ifndef SDL_INLINE_OKAY #ifdef __GNUC__ #define SDL_INLINE_OKAY #else /* Add any special compiler-specific cases here */ #if defined(_MSC_VER) || defined(__BORLANDC__) || \ defined(__DMC__) || defined(__SC__) || \ defined(__WATCOMC__) || defined(__LCC__) || \ defined(__DECC) || defined(__EABI__) #ifndef __inline__ #define __inline__ __inline #endif #define SDL_INLINE_OKAY #else #if !defined(__MRC__) && !defined(_SGI_SOURCE) #ifndef __inline__ #define __inline__ inline #endif #define SDL_INLINE_OKAY #endif /* Not a funky compiler */ #endif /* Visual C++ */ #endif /* GNU C */ #endif /* SDL_INLINE_OKAY */ /** * @def __inline__ * If inlining isn't supported, remove "__inline__", turning static * inlined functions into static functions (resulting in code bloat * in all files which include the offending header files) */ #ifndef SDL_INLINE_OKAY #define __inline__ #endif /** * @def NULL * Apparently this is needed by several Windows compilers */ #if !defined(__MACH__) #ifndef NULL #ifdef __cplusplus #define NULL 0 #else #define NULL ((void *)0) #endif #endif /* NULL */ #endif /* ! Mac OS X - breaks precompiled headers */ ================================================ FILE: other/sdl/include/close_code.h ================================================ /* SDL - Simple DirectMedia Layer Copyright (C) 1997-2009 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Sam Lantinga slouken@libsdl.org */ /** * @file close_code.h * This file reverses the effects of begin_code.h and should be included * after you finish any function and structure declarations in your headers */ #undef _begin_code_h /** * @file close_code.h * Reset structure packing at previous byte alignment */ #if defined(_MSC_VER) || defined(__MWERKS__) || defined(__WATCOMC__) || defined(__BORLANDC__) #ifdef __BORLANDC__ #pragma nopackwarning #endif #if (defined(__MWERKS__) && defined(__MACOS__)) #pragma options align=reset #pragma enumsalwaysint reset #else #pragma pack(pop) #endif #endif /* Compiler needs structure packing set */ ================================================ FILE: other/sdl/sdl.lua ================================================ SDL = { basepath = PathDir(ModuleFilename()), OptFind = function (name, required) local check = function(option, settings) option.value = false option.use_sdlconfig = false option.use_winlib = 0 option.use_osxframework = false option.lib_path = nil if ExecuteSilent("sdl-config") > 0 and ExecuteSilent("sdl-config --cflags") == 0 then option.value = true option.use_sdlconfig = true end if platform == "win32" then option.value = true option.use_winlib = 32 elseif platform == "win64" then option.value = true option.use_winlib = 64 end if platform == "macosx" then option.value = true option.use_osxframework = true option.use_sdlconfig = false end end local apply = function(option, settings) if option.use_sdlconfig == true then settings.cc.flags:Add("`sdl-config --cflags`") settings.link.flags:Add("`sdl-config --libs`") end if option.use_osxframework == true then client_settings.link.frameworks:Add("SDL") client_settings.cc.includes:Add("/Library/Frameworks/SDL.framework/Headers") end if option.use_winlib > 0 then settings.cc.includes:Add(SDL.basepath .. "/include") if option.use_winlib == 32 then settings.link.libpath:Add(SDL.basepath .. "/lib32") else settings.link.libpath:Add(SDL.basepath .. "/lib64") end settings.link.libs:Add("SDL") settings.link.libs:Add("SDLmain") end end local save = function(option, output) output:option(option, "value") output:option(option, "use_sdlconfig") output:option(option, "use_winlib") output:option(option, "use_osxframework") end local display = function(option) if option.value == true then if option.use_sdlconfig == true then return "using sdl-config" end if option.use_winlib == 32 then return "using supplied win32 libraries" end if option.use_winlib == 64 then return "using supplied win64 libraries" end if option.use_osxframework == true then return "using osx framework" end return "using unknown method" else if option.required then return "not found (required)" else return "not found (optional)" end end end local o = MakeOption(name, 0, check, save, display) o.Apply = apply o.include_path = nil o.lib_path = nil o.required = required return o end } ================================================ FILE: other/sdl/sdlnotes.txt ================================================ NOTE. This is a really stripped down version of SDL only used to compile teeworlds for windows. For a complete release of SDL, please visit their site at http://www.libsdl.org. ================================================ FILE: readme.txt ================================================ Copyright (c) 2013 Magnus Auvinen This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Please visit http://www.teeworlds.com for up-to-date information about the game, including new versions, custom maps and much more. ================================================ FILE: scripts/SDL_keysym.h ================================================ /* SDL - Simple DirectMedia Layer Copyright (C) 1997-2006 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org */ #ifndef _SDL_keysym_h #define _SDL_keysym_h /* What we really want is a mapping of every raw key on the keyboard. To support international keyboards, we use the range 0xA1 - 0xFF as international virtual keycodes. We'll follow in the footsteps of X11... The names of the keys */ typedef enum { /* The keyboard syms have been cleverly chosen to map to ASCII */ SDLK_UNKNOWN = 0, SDLK_FIRST = 0, SDLK_BACKSPACE = 8, SDLK_TAB = 9, SDLK_CLEAR = 12, SDLK_RETURN = 13, SDLK_PAUSE = 19, SDLK_ESCAPE = 27, SDLK_SPACE = 32, SDLK_EXCLAIM = 33, SDLK_QUOTEDBL = 34, SDLK_HASH = 35, SDLK_DOLLAR = 36, SDLK_AMPERSAND = 38, SDLK_QUOTE = 39, SDLK_LEFTPAREN = 40, SDLK_RIGHTPAREN = 41, SDLK_ASTERISK = 42, SDLK_PLUS = 43, SDLK_COMMA = 44, SDLK_MINUS = 45, SDLK_PERIOD = 46, SDLK_SLASH = 47, SDLK_0 = 48, SDLK_1 = 49, SDLK_2 = 50, SDLK_3 = 51, SDLK_4 = 52, SDLK_5 = 53, SDLK_6 = 54, SDLK_7 = 55, SDLK_8 = 56, SDLK_9 = 57, SDLK_COLON = 58, SDLK_SEMICOLON = 59, SDLK_LESS = 60, SDLK_EQUALS = 61, SDLK_GREATER = 62, SDLK_QUESTION = 63, SDLK_AT = 64, /* Skip uppercase letters */ SDLK_LEFTBRACKET = 91, SDLK_BACKSLASH = 92, SDLK_RIGHTBRACKET = 93, SDLK_CARET = 94, SDLK_UNDERSCORE = 95, SDLK_BACKQUOTE = 96, SDLK_a = 97, SDLK_b = 98, SDLK_c = 99, SDLK_d = 100, SDLK_e = 101, SDLK_f = 102, SDLK_g = 103, SDLK_h = 104, SDLK_i = 105, SDLK_j = 106, SDLK_k = 107, SDLK_l = 108, SDLK_m = 109, SDLK_n = 110, SDLK_o = 111, SDLK_p = 112, SDLK_q = 113, SDLK_r = 114, SDLK_s = 115, SDLK_t = 116, SDLK_u = 117, SDLK_v = 118, SDLK_w = 119, SDLK_x = 120, SDLK_y = 121, SDLK_z = 122, SDLK_DELETE = 127, /* End of ASCII mapped keysyms */ /* International keyboard syms */ SDLK_WORLD_0 = 160, /* 0xA0 */ SDLK_WORLD_1 = 161, SDLK_WORLD_2 = 162, SDLK_WORLD_3 = 163, SDLK_WORLD_4 = 164, SDLK_WORLD_5 = 165, SDLK_WORLD_6 = 166, SDLK_WORLD_7 = 167, SDLK_WORLD_8 = 168, SDLK_WORLD_9 = 169, SDLK_WORLD_10 = 170, SDLK_WORLD_11 = 171, SDLK_WORLD_12 = 172, SDLK_WORLD_13 = 173, SDLK_WORLD_14 = 174, SDLK_WORLD_15 = 175, SDLK_WORLD_16 = 176, SDLK_WORLD_17 = 177, SDLK_WORLD_18 = 178, SDLK_WORLD_19 = 179, SDLK_WORLD_20 = 180, SDLK_WORLD_21 = 181, SDLK_WORLD_22 = 182, SDLK_WORLD_23 = 183, SDLK_WORLD_24 = 184, SDLK_WORLD_25 = 185, SDLK_WORLD_26 = 186, SDLK_WORLD_27 = 187, SDLK_WORLD_28 = 188, SDLK_WORLD_29 = 189, SDLK_WORLD_30 = 190, SDLK_WORLD_31 = 191, SDLK_WORLD_32 = 192, SDLK_WORLD_33 = 193, SDLK_WORLD_34 = 194, SDLK_WORLD_35 = 195, SDLK_WORLD_36 = 196, SDLK_WORLD_37 = 197, SDLK_WORLD_38 = 198, SDLK_WORLD_39 = 199, SDLK_WORLD_40 = 200, SDLK_WORLD_41 = 201, SDLK_WORLD_42 = 202, SDLK_WORLD_43 = 203, SDLK_WORLD_44 = 204, SDLK_WORLD_45 = 205, SDLK_WORLD_46 = 206, SDLK_WORLD_47 = 207, SDLK_WORLD_48 = 208, SDLK_WORLD_49 = 209, SDLK_WORLD_50 = 210, SDLK_WORLD_51 = 211, SDLK_WORLD_52 = 212, SDLK_WORLD_53 = 213, SDLK_WORLD_54 = 214, SDLK_WORLD_55 = 215, SDLK_WORLD_56 = 216, SDLK_WORLD_57 = 217, SDLK_WORLD_58 = 218, SDLK_WORLD_59 = 219, SDLK_WORLD_60 = 220, SDLK_WORLD_61 = 221, SDLK_WORLD_62 = 222, SDLK_WORLD_63 = 223, SDLK_WORLD_64 = 224, SDLK_WORLD_65 = 225, SDLK_WORLD_66 = 226, SDLK_WORLD_67 = 227, SDLK_WORLD_68 = 228, SDLK_WORLD_69 = 229, SDLK_WORLD_70 = 230, SDLK_WORLD_71 = 231, SDLK_WORLD_72 = 232, SDLK_WORLD_73 = 233, SDLK_WORLD_74 = 234, SDLK_WORLD_75 = 235, SDLK_WORLD_76 = 236, SDLK_WORLD_77 = 237, SDLK_WORLD_78 = 238, SDLK_WORLD_79 = 239, SDLK_WORLD_80 = 240, SDLK_WORLD_81 = 241, SDLK_WORLD_82 = 242, SDLK_WORLD_83 = 243, SDLK_WORLD_84 = 244, SDLK_WORLD_85 = 245, SDLK_WORLD_86 = 246, SDLK_WORLD_87 = 247, SDLK_WORLD_88 = 248, SDLK_WORLD_89 = 249, SDLK_WORLD_90 = 250, SDLK_WORLD_91 = 251, SDLK_WORLD_92 = 252, SDLK_WORLD_93 = 253, SDLK_WORLD_94 = 254, SDLK_WORLD_95 = 255, /* 0xFF */ /* Numeric keypad */ SDLK_KP0 = 256, SDLK_KP1 = 257, SDLK_KP2 = 258, SDLK_KP3 = 259, SDLK_KP4 = 260, SDLK_KP5 = 261, SDLK_KP6 = 262, SDLK_KP7 = 263, SDLK_KP8 = 264, SDLK_KP9 = 265, SDLK_KP_PERIOD = 266, SDLK_KP_DIVIDE = 267, SDLK_KP_MULTIPLY = 268, SDLK_KP_MINUS = 269, SDLK_KP_PLUS = 270, SDLK_KP_ENTER = 271, SDLK_KP_EQUALS = 272, /* Arrows + Home/End pad */ SDLK_UP = 273, SDLK_DOWN = 274, SDLK_RIGHT = 275, SDLK_LEFT = 276, SDLK_INSERT = 277, SDLK_HOME = 278, SDLK_END = 279, SDLK_PAGEUP = 280, SDLK_PAGEDOWN = 281, /* Function keys */ SDLK_F1 = 282, SDLK_F2 = 283, SDLK_F3 = 284, SDLK_F4 = 285, SDLK_F5 = 286, SDLK_F6 = 287, SDLK_F7 = 288, SDLK_F8 = 289, SDLK_F9 = 290, SDLK_F10 = 291, SDLK_F11 = 292, SDLK_F12 = 293, SDLK_F13 = 294, SDLK_F14 = 295, SDLK_F15 = 296, /* Key state modifier keys */ SDLK_NUMLOCK = 300, SDLK_CAPSLOCK = 301, SDLK_SCROLLOCK = 302, SDLK_RSHIFT = 303, SDLK_LSHIFT = 304, SDLK_RCTRL = 305, SDLK_LCTRL = 306, SDLK_RALT = 307, SDLK_LALT = 308, SDLK_RMETA = 309, SDLK_LMETA = 310, SDLK_LSUPER = 311, /* Left "Windows" key */ SDLK_RSUPER = 312, /* Right "Windows" key */ SDLK_MODE = 313, /* "Alt Gr" key */ SDLK_COMPOSE = 314, /* Multi-key compose key */ /* Miscellaneous function keys */ SDLK_HELP = 315, SDLK_PRINT = 316, SDLK_SYSREQ = 317, SDLK_BREAK = 318, SDLK_MENU = 319, SDLK_POWER = 320, /* Power Macintosh power key */ SDLK_EURO = 321, /* Some european keyboards */ SDLK_UNDO = 322, /* Atari keyboard has Undo */ /* Add any other keys here */ SDLK_LAST } SDLKey; /* Enumeration of valid key mods (possibly OR'd together) */ typedef enum { KMOD_NONE = 0x0000, KMOD_LSHIFT= 0x0001, KMOD_RSHIFT= 0x0002, KMOD_LCTRL = 0x0040, KMOD_RCTRL = 0x0080, KMOD_LALT = 0x0100, KMOD_RALT = 0x0200, KMOD_LMETA = 0x0400, KMOD_RMETA = 0x0800, KMOD_NUM = 0x1000, KMOD_CAPS = 0x2000, KMOD_MODE = 0x4000, KMOD_RESERVED = 0x8000 } SDLMod; #define KMOD_CTRL (KMOD_LCTRL|KMOD_RCTRL) #define KMOD_SHIFT (KMOD_LSHIFT|KMOD_RSHIFT) #define KMOD_ALT (KMOD_LALT|KMOD_RALT) #define KMOD_META (KMOD_LMETA|KMOD_RMETA) #endif /* _SDL_keysym_h */ ================================================ FILE: scripts/build.py ================================================ import imp, optparse, os, re, shutil, sys, zipfile os.chdir(os.path.dirname(os.path.realpath(sys.argv[0])) + "/..") import twlib arguments = optparse.OptionParser() arguments.add_option("-b", "--url-bam", default = "http://github.com/matricks/bam/archive/master.zip", help = "URL from which the bam source code will be downloaded") arguments.add_option("-t", "--url-teeworlds", default = "http://github.com/teeworlds/teeworlds/archive/master.zip", help = "URL from which the teeworlds source code will be downloaded") arguments.add_option("-r", "--release-type", default = "server_release client_release", help = "Parts of the game which should be builded (for example client_release, debug, server_release or a combination of any of them)") (options, arguments) = arguments.parse_args() bam = options.url_bam[7:].split("/") version_bam = re.search(r"\d\.\d\.\d", bam[len(bam)-1]) if version_bam: version_bam = version_bam.group(0) else: version_bam = "trunk" teeworlds = options.url_teeworlds[7:].split("/") version_teeworlds = re.search(r"\d\.\d\.\d", teeworlds[len(teeworlds)-1]) if version_teeworlds: version_teeworlds = version_teeworlds.group(0) else: version_teeworlds = "trunk" bam_execution_path = "" if version_bam < "0.3.0": bam_execution_path = "src%s" % os.sep name = "teeworlds" flag_clean = True flag_download = True flag_unpack = True flag_build_bam = True flag_build_teeworlds = True flag_make_release = True if os.name == "nt": platform = "win32" else: # get name osname = os.popen("uname").readline().strip().lower() if osname == "darwin": osname = "osx" # get arch machine = os.popen("uname -m").readline().strip().lower() arch = "unknown" if machine[0] == "i" and machine[2:] == "86": arch = "x86" elif machine == "x86_64": arch = "x86_64" elif "power" in machine.lower(): arch = "ppc" platform = osname + "_" + arch print("%s-%s-%s" % (name, version_teeworlds, platform)) root_dir = os.getcwd() + os.sep work_dir = root_dir + "scripts/work" def unzip(filename, where): try: z = zipfile.ZipFile(filename, "r") except: return False list = "\n" for name in z.namelist(): list += "%s\n" % name try: os.makedirs(where+"/"+os.path.dirname(name)) except: pass try: f = open(where+"/"+name, "wb") f.write(z.read(name)) f.close() except: pass z.close() directory = "[^/\n]*?/" part_1 = "(?<=\n)" part_2 = "[^/\n]+(?=\n)" regular_expression = r"%s%s" % (part_1, part_2) main_directory = re.search(regular_expression, list) while main_directory == None: part_1 += directory regular_expression = r"%s%s" % (part_1, part_2) main_directory = re.search(regular_expression, list) main_directory = re.search(r".*/", "./%s" % main_directory.group(0)) return main_directory.group(0) def bail(reason): print(reason) os.chdir(work_dir) sys.exit(-1) def clean(): print("*** cleaning ***") try: shutil.rmtree(work_dir) except: pass def file_exists(file): try: open(file).close() return True except: return False; def search_object(directory, object): directory = os.listdir(directory) for entry in directory: match = re.search(object, entry) if match != None: return entry # clean if flag_clean: clean() # make dir try: os.mkdir(work_dir) except: pass # change dir os.chdir(work_dir) # download if flag_download: print("*** downloading bam source package ***") src_package_bam = twlib.fetch_file(options.url_bam) if src_package_bam: if version_bam == 'trunk': version = re.search(r"-[^-]*?([^-]*?)\.[^.]*$", src_package_bam) if version: version_bam = version.group(1) else: bail("couldn't find bam source package and couldn't download it") print("*** downloading %s source package ***" % name) src_package_teeworlds = twlib.fetch_file(options.url_teeworlds) if src_package_teeworlds: if version_teeworlds == 'trunk': version = re.search(r"-[^-]*?([^-]*?)\.[^.]*$", src_package_teeworlds) if version: version_teeworlds = version.group(1) else: bail("couldn't find %s source package and couldn't download it" % name) # unpack if flag_unpack: print("*** unpacking source ***") if hasattr(locals(), 'src_package_bam') == False: src_package_bam = search_object(work_dir, r"bam.*?\.") if not src_package_bam: bail("couldn't find bam source package") src_dir_bam = unzip(src_package_bam, ".") if not src_dir_bam: bail("couldn't unpack bam source package") if hasattr(locals(), 'src_package_teeworlds') == False: src_package_teeworlds = search_object(work_dir, r"teeworlds.*?\.") if not src_package_bam: bail("couldn't find %s source package" % name) src_dir_teeworlds = unzip(src_package_teeworlds, ".") if not src_dir_teeworlds: bail("couldn't unpack %s source package" % name) # build bam if flag_build_bam: print("*** building bam ***") os.chdir("%s/%s" % (work_dir, src_dir_bam)) if os.name == "nt": if os.system("g++ -v >nul 2>&1") == 0: print("using gcc") os.system("make_win32_mingw.bat") else: print("using cl") os.system("make_win32_msvc.bat") if file_exists("%sbam.exe" % bam_execution_path) == False: bail("failed to build bam") else: os.system("sh make_unix.sh") if file_exists("%sbam" % bam_execution_path) == False: bail("failed to build bam") os.chdir(work_dir) # build the game if flag_build_teeworlds: print("*** building %s ***" % name) if hasattr(locals(), 'src_dir_bam') == False: src_dir_bam = search_object(work_dir, r"bam[^\.]*$") + os.sep if src_dir_bam: directory = src_dir_bam + bam_execution_path file = r"bam" if os.name == "nt": file += r"\.exe" if not search_object(directory, file): bail("couldn't find bam") else: bail("couldn't find bam") if hasattr(locals(), 'src_dir_teeworlds') == False: src_dir_teeworlds = search_object(work_dir, r"teeworlds[^\.]*$") if not src_dir_teeworlds: bail("couldn't find %s source" % name) command = 1 if os.name == "nt": if os.system("g++ -v >nul 2>&1") == 0: print("using gcc") os.chdir(src_dir_teeworlds) command = os.system('"%s\\%s%sbam" %s' % (work_dir, src_dir_bam, bam_execution_path, options.release_type)) else: print("using cl") file = open("build.bat", "wb") content = "@echo off\n" content += "@REM check if we already have the tools in the environment\n" content += "if exist \"%VCINSTALLDIR%\" (\ngoto compile\n)\n" content += "@REM Check for Visual Studio\n" content += "if exist \"%VS100COMNTOOLS%\" (\nset VSPATH=\"%VS100COMNTOOLS%\"\ngoto set_env\n)\n" content += "if exist \"%VS90COMNTOOLS%\" (\nset VSPATH=\"%VS90COMNTOOLS%\"\ngoto set_env\n)\n" content += "if exist \"%VS80COMNTOOLS%\" (\nset VSPATH=\"%VS80COMNTOOLS%\"\ngoto set_env\n)\n\n" content += "echo You need Microsoft Visual Studio 8, 9 or 10 installed\n" content += "exit\n" content += "@ setup the environment\n" content += ":set_env\n" content += "call %VSPATH%vsvars32.bat\n\n" content += ":compile\n" content += 'cd %s\n"%s\\%s%sbam" config\n"%s\\%s%sbam" %s' % (src_dir_teeworlds, work_dir, src_dir_bam, bam_execution_path, work_dir, src_dir_bam, bam_execution_path, options.release_type) file.write(content.encode()) file.close() command = os.system("build.bat") else: os.chdir(src_dir_teeworlds) command = os.system("%s/%s%sbam %s" % (work_dir, src_dir_bam, bam_execution_path, options.release_type)) if command != 0: bail("failed to build %s" % name) os.chdir(work_dir) # make release if flag_make_release: print("*** making release ***") if hasattr(locals(), 'src_dir_teeworlds') == False: src_dir_teeworlds = search_object(work_dir, r"teeworlds[^\.]*$") if not src_dir_teeworlds: bail("couldn't find %s source" % name) os.chdir(src_dir_teeworlds) command = '"%s/%s/scripts/make_release.py" %s %s' % (work_dir, src_dir_teeworlds, version_teeworlds, platform) if os.name != "nt": command = "python %s" % command if os.system(command) != 0: bail("failed to make a relase of %s" % name) final_output = "FAIL" for f in os.listdir("."): if version_teeworlds in f and platform in f and name in f and (".zip" in f or ".tar.gz" in f): final_output = f os.chdir(work_dir) shutil.copy("%s/%s" % (src_dir_teeworlds, final_output), "../"+final_output) os.chdir(root_dir) clean() print("*** all done ***") ================================================ FILE: scripts/check_header_guards.py ================================================ import os PATH = "../src/" def check_file(filename): file = open(filename) while 1: line = file.readline() if len(line) == 0: break if line[0] == "/" or line[0] == "*" or line[0] == "\r" or line[0] == "\n" or line[0] == "\t": continue if line[:7] == "#ifndef": hg = "#ifndef " + ("_".join(filename.split(PATH)[1].split("/"))[:-2]).upper() + "_H" if line[:-1] != hg: print "Wrong header guard in " + filename else: print "Missing header guard in " + filename break file.close() def check_dir(dir): list = os.listdir(dir) for file in list: if os.path.isdir(dir+file): if file != "external" and file != "generated": check_dir(dir+file+"/") elif file[-2:] == ".h" and file != "keynames.h": check_file(dir+file) check_dir(PATH) ================================================ FILE: scripts/cmd5.py ================================================ import hashlib, sys, re alphanum = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_".encode() def cstrip(lines): d = "".encode() for l in lines: l = re.sub("#.*".encode(), "".encode(), l) l = re.sub("//.*".encode(), "".encode(), l) d += l + " ".encode() d = re.sub("\/\*.*?\*/".encode(), "".encode(), d) # remove /* */ comments d = d.replace("\t".encode(), " ".encode()) # tab to space d = re.sub(" *".encode(), " ".encode(), d) # remove double spaces d = re.sub("".encode(), "".encode(), d) # remove /* */ comments d = d.strip() # this eats up cases like 'n {' i = 1 while i < len(d)-2: if d[i:i + 1] == " ".encode(): if not (d[i - 1:i] in alphanum and d[i+1:i + 2] in alphanum): d = d[:i] + d[i + 1:] i += 1 return d f = "".encode() for filename in sys.argv[1:]: f += cstrip([l.strip() for l in open(filename, "rb")]) hash = hashlib.md5(f).hexdigest().lower()[16:] #TODO 0.7: improve nethash creation print('#define GAME_NETVERSION_HASH "%s"' % hash) ================================================ FILE: scripts/compiler.py ================================================ #!/usr/bin/python import sys import struct import os option_ptrsize = struct.calcsize("P") option_intsize = struct.calcsize("l") option_floatsize = struct.calcsize("f") option_inttype = "long" option_floattype = "float" class node: def __init__(self): self.values = [] self.children = [] self.parent = 0 def name(self): if len(self.values): return self.values[0] return "" def debug_print(self, level): print (" "*level) + " ".join(self.values), if len(self.children): print "{" for c in self.children: c.debug_print(level+1) print (" "*level)+"}" else: print "" def debug_root(self): for c in self.children: c.debug_print(0) # TODO: should return list of items in the tree, def gather(self, str): def recurse(parts, path, node): if not len(parts): r = {} path = path + "." + node.values[0] r = [node] #print "found", path return r l = [] for c in node.children: if parts[0] == "*" or c.values[0] == parts[0]: if len(node.values): if len(path): l += recurse(parts[1:], path+"."+node.values[0], c) else: l += recurse(parts[1:], node.values[0], c) else: l += recurse(parts[1:], path, c) return l parts = str.split(".") return recurse(parts, "", self) def find_node(self, str): parts = str.split(".") node = self for part in parts: if len(part) == 0: continue if part == "parent": node = node.parent else: found = 0 for c in node.children: if part == c.values[0]: node = c found = 1 break if node == self: return return node def get_single(self, str): parts = str.split("@") index = -1 if len(parts) == 2: index = int(parts[1]) node = self if len(parts[0]): node = self.find_node(parts[0]) if not node: print "failed to get", str return Null if index == -1: return node.get_path()[1:] return node.values[index] def get_path(self): if self.parent == 0: return "" return self.parent.get_path() + "." + self.values[0] def get_single_name(self, str): return self.get_path()[1:] + "." + str class parser: lines = [] def parse_node(self, this_node): while len(self.lines): line = self.lines.pop(0) # grab line fields = line.strip().split() # TODO: improve this to handle strings with spaces if not len(fields): continue if fields[-1] == '{': new_node = node() new_node.parent = this_node new_node.values = fields[:-1] this_node.children += [new_node] self.parse_node(new_node) elif fields[-1] == '}': break else: new_node = node() new_node.parent = this_node new_node.values = fields this_node.children += [new_node] def parse_file(self, filename): self.lines = file(filename).readlines() n = node() self.parse_node(n) return n def parse_file(filename): return parser().parse_file(filename) class pointer: def __init__(self, index, target): self.index = index self.target = target class data_constructor: def __init__(self): self.data = "" self.trans = 0 self.pointers = [] self.targets = {} self.enums = {} def get_type(self, s): return self.trans.types[s] def allocate(self, size): index = len(self.data) self.data += "\0"*size return index def add_pointer(self, index, target): self.pointers += [pointer(index, target)] def add_enum(self, name, value): self.enums[name] = value def get_enum_value(self, name): if not name in self.enums: print "ERROR: couldn't find enum '%s'" % (name) return self.enums[name] def add_target(self, target, index): # TODO: warn about duplicates #print "add_target(target='%s' index=%d)" % (target, index) self.targets[target] = index def write(self, index, size, data): try: self.data = self.data[:index] + data + self.data[index+size:] except: print "write error:" print "\tself.data =", self.data print "\tdata =", data def patch_pointers(self): for p in self.pointers: if p.target in self.targets: i = self.targets[p.target] #print "ptr @ %d -> %s -> %d" % (p.index, p.target, i) data = struct.pack("P", i) self.write(p.index, len(data), data) else: print "ERROR: couldn't find target '%s' for pointer at %d" % (p.target, p.index) class type: def __init__(self): self.name = "" def size(self): pass class structure: def __init__(self): self.name = "" self.members = [] def size(self): s = 0 for m in self.members: s += m.size() return s def emit_header_code(self, out): print >>out, "struct", self.name print >>out, "{" for m in self.members: for l in m.get_code(): print >>out, "\t" + l print >>out, "};" print >>out, "" def emit_source_code(self, out): print >>out, "static void patch_ptr_%s(%s *self, char *base)" % (self.name, self.name) print >>out, "{" for m in self.members: for l in m.get_patch_code("self", "base"): print >>out, "\t" + l print >>out, "}" print >>out, "" def emit_data(self, cons, index, src_data): #print self.name+":" member_index = index for m in self.members: #print "\t" + m.name m.emit_data(cons, member_index, src_data) member_index += m.size() class variable: def __init__(self): self.expr = "" self.type = "" self.subtype = "" def get_code(self): return [] def get_patch_code(self, ptrname, basename): return [] def emit_data(self, cons, index, src_data): pass class variable_int(variable): def get_code(self): return ["%s %s;" % (option_inttype, self.name)] def size(self): return option_intsize def emit_data(self, cons, index, src_data): try: value = int(self.expr) except: value = int(src_data.get_single(self.expr)) #print "int", self.name, "=", value, "@", index data = struct.pack("l", value) cons.write(index, len(data), data) class variable_float(variable): def get_code(self): return ["%s %s;" % (option_floattype, self.name)] def size(self): return option_floatsize def emit_data(self, cons, index, src_data): try: value = float(self.expr) except: value = float(src_data.get_single(self.expr)) #print "int", self.name, "=", value, "@", index data = struct.pack("f", value) cons.write(index, len(data), data) class variable_string(variable): def get_code(self): return ["char *%s;" % (self.name)] def get_patch_code(self, ptrname, basename): return ["patch_ptr((char **)&(%s->%s), %s);" % (ptrname, self.name, basename)] def size(self): return option_ptrsize def emit_data(self, cons, index, src_data): string = src_data.get_single(self.expr) string = string.strip()[1:-1] # skip " and " string_index = cons.allocate(len(string)+1) cons.write(string_index, len(string), string) data = struct.pack("P", string_index) # TODO: solve this cons.write(index, len(data), data) class variable_ptr(variable): def get_code(self): return ["%s *%s;" % (self.subtype, self.name)] def get_patch_code(self, ptrname, basename): return ["patch_ptr((char**)&(%s->%s), %s);" % (ptrname, self.name, basename)] def size(self): return option_ptrsize def emit_data(self, cons, index, src_data): target = src_data.get_single(self.expr) cons.add_pointer(index, target) class variable_enum(variable): def get_code(self): return ["long *%s;" % (self.name)] def size(self): return option_intsize def emit_data(self, cons, index, src_data): target = src_data.get_single(self.expr) data = struct.pack("l", cons.get_enum_value(target)) cons.write(index, len(data), data) class variable_instance(variable): def get_code(self): return ["%s %s;" % (self.subtype, self.name)] def get_patch_code(self, ptrname, basename): return ["patch_ptr_%s(&(%s->%s), %s);" % (self.subtype, ptrname, self.name, basename)] def size(self): return self.translator.types[self.subtype].size() def emit_data(self, cons, index, src_data): target = src_data.find_node(self.expr) translator.types[self.subtype].emit_data(cons, index, target) #target = #cons.add_pointer(index, target) class variable_array(variable): def get_code(self): return ["long num_%s;" % self.name, "%s *%s;" % (self.subtype, self.name)] def get_patch_code(self, ptrname, baseptr): code = [] code += ["patch_ptr((char**)&(%s->%s), %s);" % (ptrname, self.name, baseptr)] code += ["for(int i = 0; i < %s->num_%s; i++)" % (ptrname, self.name)] code += ["\tpatch_ptr_%s(%s->%s+i, %s);" % (self.subtype, ptrname, self.name, baseptr)] return code def emit_data(self, cons, index, src_data): array_data = src_data.gather(self.expr) array_type = cons.get_type(self.subtype) size = array_type.size()*len(array_data) #print "packing array", self.name #print "\ttype =", array_type.name #print "\tsize =", array_type.size() array_index = cons.allocate(size) data = struct.pack("lP", len(array_data), array_index) # TODO: solve this cons.write(index, len(data), data) member_index = array_index for node in array_data: cons.add_target(node.get_path()[1:], member_index) array_type.emit_data(cons, member_index, node) member_index += array_type.size() #print "array", member_index def size(self): return option_ptrsize+option_intsize class const_arrayint: def __init__(self): self.name = "" self.values = [] def emit_header_code(self, out): print >>out, "enum" print >>out, "{" for i in xrange(0, len(self.values)): print >>out, "\t%s_%s = %d," % (self.name.upper(), self.values[i].upper(), i) print >>out, "\tNUM_%sS = %d" % (self.name.upper(), len(self.values)) print >>out, "};" print >>out, "" class translator: def __init__(self): self.types = {} self.structs = [] self.constants = [] self.data = 0 self.srcdata = 0 self.types["int"] = variable_int() self.types["float"] = variable_float() self.types["string"] = variable_string() self.types["ptr"] = variable_ptr() self.types["array"] = variable_array() def parse_variable(self, node): if len(node.values) != 4: print node.values raise "error parsing variable" type = node.values[0] subtype = "" if type == "int": v = variable_int() elif type == "enum": v = variable_enum() elif type == "float": v = variable_float() elif type == "string": v = variable_string() else: # complex type parts = type.split(":") if len(parts) != 2: raise "can't emit code for variable %s of type %s" % (self.name, self.type) elif parts[0] == "ptr": subtype = parts[1] v = variable_ptr() elif parts[0] == "instance": subtype = parts[1] v = variable_instance() elif parts[0] == "array": subtype = parts[1] v = variable_array() else: raise "can't emit code for variable %s of type %s" % (self.name, self.type) v.translator = self v.type = node.values[0] v.subtype = subtype v.name = node.values[1] assignment = node.values[2] v.expr = node.values[3] if assignment != "=": raise "error parsing variable. expected =" return v def parse_struct(self, node): if len(node.values) != 2: raise "error parsing struct" s = structure() s.name = node.values[1] for statement in node.children: s.members += [self.parse_variable(statement)] return s def parse_constant(self, node): if len(node.values) != 5: print node.values raise "error parsing constant" type = node.values[1] name = node.values[2] assignment = node.values[3] expression = node.values[4] if assignment != "=": print node.values raise "error parsing constant" ints = const_arrayint() ints.name = name items = self.srcdata.gather(expression) for c in items: ints.values += [c.name()] self.constants += [ints] def parse(self, script, srcdata): self.srcdata = srcdata for statement in script.children: if statement.values[0] == "struct": s = self.parse_struct(statement) self.structs += [s] self.types[s.name] = s elif statement.values[0] == "const": self.parse_constant(statement) else: raise "unknown statement:" + statement def emit_header_code(self, out): for c in self.constants: c.emit_header_code(out) for s in self.structs: s.emit_header_code(out) print >>out, "" print >>out, "struct data_container *load_data_from_file(const char *filename);" print >>out, "struct data_container *load_data_from_memory(unsigned char *filename);" print >>out, "" def emit_source_code(self, out, header_filename): print >>out, ''' #include "%s" #include <stdio.h> #include <stdlib.h> static void patch_ptr(char **ptr, char *base) { *ptr = base+(size_t)(*ptr); } ''' % header_filename for s in self.structs: s.emit_source_code(out) print >>out, ''' data_container *load_data_from_memory(unsigned char *mem) { if(mem[0] != sizeof(void*)) return 0; if(mem[1] != sizeof(long)) return 0; if(mem[2] != sizeof(float)) return 0; /* patch all pointers */ data_container *con = (data_container*)(mem + 4); patch_ptr_data_container(con, (char *)con); return con; } data_container *load_data_from_file(const char *filename) { unsigned char *data = 0; int size; /* open file */ FILE *f = fopen(filename, "rb"); /* get size */ fseek(f, 0, SEEK_END); size = ftell(f); fseek(f, 0, SEEK_SET); /* allocate, read data and close file */ data = (unsigned char *)malloc(size); fread(data, 1, size, f); fclose(f); return load_data_from_memory(data); } ''' def emit_data(self): for s in self.structs: if s.name == "data_container": #print "found data_container" cons = data_constructor() cons.trans = self i = cons.allocate(s.size()) s.emit_data(cons, i, self.srcdata) cons.patch_pointers() header = struct.pack("bbbb", option_ptrsize, option_intsize, option_floatsize, 0) return header + cons.data def create_translator(script, srcdata): t = translator() t.parse(script, srcdata) return t def validate(script, validator): def validate_values(values, check): if not len(check) or check[0] == "*": print "too many values" return p = check[0].split(":") type = p[0] name = p[1] # TODO: check type and stuff # recurse if len(values) > 1: if not len(check): print "unexpected value" validate_values(values[1:], check[1:]) else: if len(check) > 1 and check[1] != "*": print "to few values" if len(script.values): validate_values(script.values, validator.values) for child in script.children: tag = child.values[0] n = validator.find_node("tag:"+tag) if not n: found = 0 for vc in validator.children: if "ident:" in vc.values[0]: validate(child, vc) print vc.values[0] found = 1 break if not found: print "error:", tag, "not found" else: print "tag:"+tag validate(child, n) input_filename = sys.argv[1] script_filename = sys.argv[2] output_filename = 0 coutput_filename = 0 header_filename = 0 source_filename = 0 sheader_filename = 0 if sys.argv[3] == '-h': header_filename = sys.argv[4] elif sys.argv[3] == '-s': source_filename = sys.argv[4] sheader_filename = sys.argv[5] elif sys.argv[3] == '-d': output_filename = sys.argv[4] elif sys.argv[3] == '-c': coutput_filename = sys.argv[4] srcdata = parse_file(input_filename) script = parse_file(script_filename) translator = create_translator(script, srcdata) if header_filename: translator.emit_header_code(file(header_filename, "w")) if source_filename: translator.emit_source_code(file(source_filename, "w"), os.path.basename(sheader_filename)) if output_filename: rawdata = translator.emit_data() file(output_filename, "wb").write(rawdata) if coutput_filename: i = 0 rawdata = translator.emit_data() f = file(coutput_filename, "w") print >>f,"unsigned char internal_data[] = {" print >>f,str(ord(rawdata[0])), for d in rawdata[1:]: s = ","+str(ord(d)) print >>f,s, i += len(s)+1 if i >= 70: print >>f,"" i = 0 print >>f,"" print >>f,"};" print >>f,"" f.close() ================================================ FILE: scripts/copyright.py ================================================ import os, sys os.chdir(os.path.dirname(os.path.realpath(sys.argv[0])) + "/..") notice = [b"/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */\n", b"/* If you are missing that file, acquire a complete release at teeworlds.com. */\n"] exclude = ["src%sengine%sexternal" % (os.sep, os.sep), "src%sosxlaunch" % os.sep] updated_files = 0 def fix_copyright_notice(filename): global updated_files f = open(filename, "rb") lines = f.readlines() f.close() i = 0 length_lines = len(lines) if length_lines > 0: while i <= length_lines and (lines[i].decode("utf-8").lstrip()[:2] == "//" or lines[i].decode("utf-8").lstrip()[:2] == "/*" and lines[i].decode("utf-8").rstrip()[-2:] == "*/") and ("Magnus" in lines[i].decode("utf-8") or "magnus" in lines[i].decode("utf-8") or "Auvinen" in lines[i].decode("utf-8") or "auvinen" in lines[i].decode("utf-8") or "license" in lines[i].decode("utf-8") or "teeworlds" in lines[i].decode("utf-8")): i += 1 length_notice = len(notice) if i > 0: j = 0 while lines[j] == notice[j]: j += 1 if j == length_notice: return k = j j = 0 while j < length_notice -1 - k: lines = [notice[j]] + lines j += 1 while j < length_notice: lines[j] = notice[j] j += 1 if length_lines == 0 or i == 0: j = length_notice - 1 while j >= 0: lines = [notice[j]] + lines j -= 1 open(filename, "wb").writelines(lines) updated_files += 1 skip = False for root, dirs, files in os.walk("src"): for excluding in exclude: if root[:len(excluding)] == excluding: skip = True break if skip == True: skip = False continue for name in files: filename = os.path.join(root, name) if filename[-2:] != ".c" and filename[-4:] != ".cpp" and filename[-2:] != ".h": continue fix_copyright_notice(filename) output = "file" if updated_files != 1: output += "s" print("*** updated %d %s ***" % (updated_files, output)) ================================================ FILE: scripts/count_source.sh ================================================ svn blame `svn -R ls | grep ^src | grep -v external | grep -v /$ | grep -v \.txt` | python scripts/process_blame.py ================================================ FILE: scripts/dat2c.py ================================================ import sys data = file(sys.argv[1], "rb").read() i = 0 print "unsigned char", sys.argv[2], "[] = {" print str(ord(data[0])), for d in data[1:]: s = ","+str(ord(d)) print s, i += len(s)+1 if i >= 70: print "" i = 0 print "" print "};" ================================================ FILE: scripts/font_converter.py ================================================ from __future__ import with_statement import struct import sys import re def convert(input, output): with open(input, "r") as in_file: with open(output, "w") as out_file: def build_dic(parts): dic = {} for part in parts: key, value = part.split('=') try: dic[key] = int(value) except: dic[key] = value return dic def get_entry(line): while line[-1] == "\r" or line[-1] == "\n": line = line[0:-1] parts = [] quote = 0 part = "" for c in line: if c == "\"": quote = 1-quote elif c == " " and not quote: if part: parts.append(part) part = "" else: part += c if part: parts.append(part) type = parts[0] dic = build_dic(parts[1:]) return type, dic def write_int16(val): out_file.write(struct.pack('<h', val)) def write_info(dic): write_int16(dic["size"]) def write_common(dic): write_int16(dic["scaleW"]) write_int16(dic["scaleH"]) write_int16(dic["lineHeight"]) write_int16(dic["base"]) def write_page(dic): pass def write_chars(dic): pass def write_char(dic): write_int16(dic["x"]) write_int16(dic["y"]) write_int16(dic["width"]) write_int16(dic["height"]) write_int16(dic["xoffset"]) write_int16(dic["yoffset"]) write_int16(dic["xadvance"]) def write_default_char(): write_int16(0) write_int16(0) write_int16(0) write_int16(0) write_int16(0) write_int16(0) write_int16(0) def write_kernings(dic): pass def write_kerning(dic): write_int16(dic["amount"]) def write_default_kerning(): write_int16(0) chars = [] kernings = [] for i in range(256): chars.append(None) for i in range(256*256): kernings.append(None) def save_char(dic): if dic["id"] < 256: chars[dic["id"]] = dic def save_kerning(dic): kernings[dic["first"] + dic["second"]*256] = dic write_table = { "info": write_info, "common": write_common, "page": write_page, "chars": write_chars, "char": save_char, "kernings": write_kernings, "kerning": save_kerning } for line in in_file: type, dic = get_entry(line) write_table[type](dic) for i in range(256): if chars[i]: write_char(chars[i]) else: write_default_char() for i in range(256*256): if kernings[i]: write_kerning(kernings[i]) else: write_default_kerning() if len(sys.argv) >= 2: print "converting..." filenames = sys.argv[1:] for filename in filenames: input = filename output = re.sub("fnt$", "tfnt", input) print "input: %s, output: %s" % (input, output) convert(input, output) print "done!" else: print "font converter! converts .fnt files to teeworlds .tfnt" print "usage: font_converter <input>" ================================================ FILE: scripts/font_installer.sh ================================================ echo Generating .fnts... ../../font_generator/a.out python ../scripts/font_converter.py default*.fnt ================================================ FILE: scripts/gen_keys.py ================================================ import sys, os # genereate keys.h file f = file("src/engine/keys.h", "w") keynames = [] for i in range(0, 512): keynames += ["&%d"%i] print >>f, "#ifndef ENGINE_KEYS_H" print >>f, "#define ENGINE_KEYS_H" print >>f, '/* AUTO GENERATED! DO NOT EDIT MANUALLY! */' print >>f, "enum" print >>f, "{" highestid = 0 for line in open("scripts/SDL_keysym.h"): l = line.strip().split("=") if len(l) == 2 and "SDLK_" in line: key = l[0].strip().replace("SDLK_", "KEY_") value = int(l[1].split(",")[0].strip()) print >>f, "\t%s = %d,"%(key, value) keynames[value] = key.replace("KEY_", "").lower() if value > highestid: highestid =value print >>f, "\tKEY_MOUSE_1 = %d,"%(highestid+1); keynames[highestid+1] = "mouse1" print >>f, "\tKEY_MOUSE_2 = %d,"%(highestid+2); keynames[highestid+2] = "mouse2" print >>f, "\tKEY_MOUSE_3 = %d,"%(highestid+3); keynames[highestid+3] = "mouse3" print >>f, "\tKEY_MOUSE_4 = %d,"%(highestid+4); keynames[highestid+4] = "mouse4" print >>f, "\tKEY_MOUSE_5 = %d,"%(highestid+5); keynames[highestid+5] = "mouse5" print >>f, "\tKEY_MOUSE_6 = %d,"%(highestid+6); keynames[highestid+6] = "mouse6" print >>f, "\tKEY_MOUSE_7 = %d,"%(highestid+7); keynames[highestid+7] = "mouse7" print >>f, "\tKEY_MOUSE_8 = %d,"%(highestid+8); keynames[highestid+8] = "mouse8" print >>f, "\tKEY_MOUSE_WHEEL_UP = %d,"%(highestid+9); keynames[highestid+9] = "mousewheelup" print >>f, "\tKEY_MOUSE_WHEEL_DOWN = %d,"%(highestid+10); keynames[highestid+10] = "mousewheeldown" print >>f, "\tKEY_LAST," print >>f, "};" print >>f, "" print >>f, "#endif" # generate keynames.c file f = file("src/engine/client/keynames.h", "w") print >>f, '/* AUTO GENERATED! DO NOT EDIT MANUALLY! */' print >>f, '' print >>f, '#ifndef KEYS_INCLUDE' print >>f, '#error do not include this header!' print >>f, '#endif' print >>f, '' print >>f, "#include <string.h>" print >>f, "" print >>f, "const char g_aaKeyStrings[512][16] =" print >>f, "{" for n in keynames: print >>f, '\t"%s",'%n print >>f, "};" print >>f, "" f.close() ================================================ FILE: scripts/linecount.sh ================================================ #!/bin/sh wc `find . -iname *.cpp` `find . -iname *.h` `find . -iname *.c` ================================================ FILE: scripts/make_docs.sh ================================================ perl docs/tool/NaturalDocs -i src/game -i src/engine -xi src/engine/external -p docs/conf -o html docs/output ================================================ FILE: scripts/make_release.py ================================================ import shutil, optparse, os, re, sys, zipfile os.chdir(os.path.dirname(os.path.realpath(sys.argv[0])) + "/..") import twlib arguments = optparse.OptionParser(usage="usage: %prog VERSION PLATFORM [options]\n\nVERSION - Version number\nPLATFORM - Target platform (f.e. linux86, linux86_64, osx, src, win32)") arguments.add_option("-l", "--url-languages", default = "http://github.com/teeworlds/teeworlds-translation/archive/master.zip", help = "URL from which the teeworlds language files will be downloaded") arguments.add_option("-m", "--url-maps", default = "http://github.com/teeworlds/teeworlds-maps/archive/master.zip", help = "URL from which the teeworlds maps files will be downloaded") arguments.add_option("-s", "--source-dir", help = "Source directory which is used for building the package") (options, arguments) = arguments.parse_args() if len(sys.argv) != 3: print("wrong number of arguments") print(sys.argv[0], "VERSION PLATFORM") sys.exit(-1) if options.source_dir != None: if os.path.exists(options.source_dir) == False: print("Source directory " + options.source_dir + " doesn't exist") exit(1) os.chdir(options.source_dir) #valid_platforms = ["win32", "osx", "linux86", "linux86_64", "src"] name = "teeworlds" version = sys.argv[1] platform = sys.argv[2] exe_ext = "" use_zip = 0 use_gz = 1 use_dmg = 0 use_bundle = 0 include_data = True include_exe = True include_src = False #if not options.platform in valid_platforms: # print("not a valid platform") # print(valid_platforms) # sys.exit(-1) if platform == "src": include_exe = False include_src = True use_zip = 1 elif platform == 'win32': exe_ext = ".exe" use_zip = 1 use_gz = 0 elif platform == 'osx': use_dmg = 1 use_gz = 0 use_bundle = 1 def unzip(filename, where): try: z = zipfile.ZipFile(filename, "r") except: return False for name in z.namelist(): z.extract(name, where) z.close() return z.namelist()[0] def copydir(src, dst, excl=[]): for root, dirs, files in os.walk(src, topdown=True): if "/." in root or "\\." in root: continue for name in dirs: if name[0] != '.': os.mkdir(os.path.join(dst, root, name)) for name in files: if name[0] != '.': shutil.copy(os.path.join(root, name), os.path.join(dst, root, name)) def copyfiles(src, dst): dir = os.listdir(src) for files in dir: shutil.copy(os.path.join(src, files), os.path.join(dst, files)) def clean(): print("*** cleaning ***") try: shutil.rmtree(package_dir) shutil.rmtree(languages_dir) shutil.rmtree(maps_dir) os.remove(src_package_languages) os.remove(src_package_maps) except: pass package = "%s-%s-%s" %(name, version, platform) package_dir = package print("cleaning target") shutil.rmtree(package_dir, True) os.mkdir(package_dir) print("download and extract languages") src_package_languages = twlib.fetch_file(options.url_languages) if not src_package_languages: print("couldn't download languages") sys.exit(-1) languages_dir = unzip(src_package_languages, ".") if not languages_dir: print("couldn't unzip languages") sys.exit(-1) print("download and extract maps") src_package_maps = twlib.fetch_file(options.url_maps) if not src_package_maps: print("couldn't download maps") sys.exit(-1) maps_dir = unzip(src_package_maps, ".") if not maps_dir: print("couldn't unzip maps") sys.exit(-1) print("adding files") shutil.copy("readme.txt", package_dir) shutil.copy("license.txt", package_dir) shutil.copy("storage.cfg", package_dir) if include_data and not use_bundle: os.mkdir(os.path.join(package_dir, "data")) copydir("data", package_dir) copyfiles(languages_dir, package_dir+"/data/languages") copyfiles(maps_dir, package_dir+"/data/maps") if platform[:3] == "win": shutil.copy("other/config_directory.bat", package_dir) shutil.copy("SDL.dll", package_dir) shutil.copy("freetype.dll", package_dir) if include_exe and not use_bundle: shutil.copy(name+exe_ext, package_dir) shutil.copy(name+"_srv"+exe_ext, package_dir) if include_src: for p in ["src", "scripts", "datasrc", "other", "objs"]: os.mkdir(os.path.join(package_dir, p)) copydir(p, package_dir) shutil.copy("bam.lua", package_dir) shutil.copy("configure.lua", package_dir) if use_bundle: bins = [name, name+'_srv', 'serverlaunch'] platforms = ('x86', 'x86_64', 'ppc') for bin in bins: to_lipo = [] for p in platforms: fname = bin+'_'+p if os.path.isfile(fname): to_lipo.append(fname) if to_lipo: os.system("lipo -create -output "+bin+" "+" ".join(to_lipo)) # create Teeworlds appfolder clientbundle_content_dir = os.path.join(package_dir, "Teeworlds.app/Contents") clientbundle_bin_dir = os.path.join(clientbundle_content_dir, "MacOS") clientbundle_resource_dir = os.path.join(clientbundle_content_dir, "Resources") clientbundle_framework_dir = os.path.join(clientbundle_content_dir, "Frameworks") os.mkdir(os.path.join(package_dir, "Teeworlds.app")) os.mkdir(clientbundle_content_dir) os.mkdir(clientbundle_bin_dir) os.mkdir(clientbundle_resource_dir) os.mkdir(clientbundle_framework_dir) os.mkdir(os.path.join(clientbundle_resource_dir, "data")) copydir("data", clientbundle_resource_dir) os.chdir(languages_dir) copydir("data", "../"+clientbundle_resource_dir) os.chdir("..") shutil.copy("other/icons/Teeworlds.icns", clientbundle_resource_dir) shutil.copy(name+exe_ext, clientbundle_bin_dir) os.system("cp -R /Library/Frameworks/SDL.framework " + clientbundle_framework_dir) file(os.path.join(clientbundle_content_dir, "Info.plist"), "w").write(""" <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>CFBundleDevelopmentRegion</key> <string>English</string> <key>CFBundleExecutable</key> <string>teeworlds</string> <key>CFBundleIconFile</key> <string>Teeworlds</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundlePackageType</key> <string>APPL</string> <key>CFBundleSignature</key> <string>????</string> <key>CFBundleVersion</key> <string>%s</string> </dict> </plist> """ % (version)) file(os.path.join(clientbundle_content_dir, "PkgInfo"), "w").write("APPL????") # create Teeworlds Server appfolder serverbundle_content_dir = os.path.join(package_dir, "Teeworlds Server.app/Contents") serverbundle_bin_dir = os.path.join(serverbundle_content_dir, "MacOS") serverbundle_resource_dir = os.path.join(serverbundle_content_dir, "Resources") os.mkdir(os.path.join(package_dir, "Teeworlds Server.app")) os.mkdir(serverbundle_content_dir) os.mkdir(serverbundle_bin_dir) os.mkdir(serverbundle_resource_dir) os.mkdir(os.path.join(serverbundle_resource_dir, "data")) os.mkdir(os.path.join(serverbundle_resource_dir, "data/maps")) os.mkdir(os.path.join(serverbundle_resource_dir, "data/mapres")) copydir("data/maps", serverbundle_resource_dir) shutil.copy("other/icons/Teeworlds_srv.icns", serverbundle_resource_dir) shutil.copy(name+"_srv"+exe_ext, serverbundle_bin_dir) shutil.copy("serverlaunch"+exe_ext, serverbundle_bin_dir + "/"+name+"_server") file(os.path.join(serverbundle_content_dir, "Info.plist"), "w").write(""" <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>CFBundleDevelopmentRegion</key> <string>English</string> <key>CFBundleExecutable</key> <string>teeworlds_server</string> <key>CFBundleIconFile</key> <string>Teeworlds_srv</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundlePackageType</key> <string>APPL</string> <key>CFBundleSignature</key> <string>????</string> <key>CFBundleVersion</key> <string>%s</string> </dict> </plist> """ % (version)) file(os.path.join(serverbundle_content_dir, "PkgInfo"), "w").write("APPL????") if use_zip: print("making zip archive") zf = zipfile.ZipFile("%s.zip" % package, 'w', zipfile.ZIP_DEFLATED) for root, dirs, files in os.walk(package_dir, topdown=True): for name in files: n = os.path.join(root, name) zf.write(n, n) #zf.printdir() zf.close() if use_gz: print("making tar.gz archive") os.system("tar czf %s.tar.gz %s" % (package, package_dir)) if use_dmg: print("making disk image") os.system("rm -f %s.dmg %s_temp.dmg" % (package, package)) os.system("hdiutil create -srcfolder %s -volname Teeworlds -quiet %s_temp" % (package_dir, package)) os.system("hdiutil convert %s_temp.dmg -format UDBZ -o %s.dmg -quiet" % (package, package)) os.system("rm -f %s_temp.dmg" % package) clean() print("done") ================================================ FILE: scripts/make_src.py ================================================ import os, shutil, zipfile, sys if len(sys.argv) <= 1: print "%s VERSION [SVN TREE]" % sys.argv[0] sys.exit(-1) version = sys.argv[1] svn_tree = "tags/release-%s" % version if len(sys.argv) > 2: svn_tree = sys.argv[2] # make clean if 1: try: shutil.rmtree("srcwork") except: pass try: os.mkdir("srcwork") except: pass root_dir = os.getcwd() + "/srcwork" # change dir os.chdir(root_dir) # fix bam #if 1: # os.system("svn export http://stalverk80.se/svn/bam bam") # z = zipfile.ZipFile("../bam.zip", "w") # for root, dirs, files in os.walk("bam"): # for f in files: # z.write(root+"/"+ f) # z.close() if 1: os.system("svn export svn://svn.teeworlds.com/teeworlds/%s teeworlds" % svn_tree) os.chdir("teeworlds") os.system("python scripts/make_release.py %s src" % version) os.chdir(root_dir) for f in os.listdir("teeworlds"): if "teeworlds" in f and "src" in f and (".zip" in f or ".tar.gz" in f): shutil.copy("teeworlds/"+f, "../" + f) ================================================ FILE: scripts/mass_server.py ================================================ #from random import choice import random import os masterservers = ["localhost 8300"] maps = [ ["dm1", "dm2", "dm6"], ["dm1", "dm2", "dm6"], ["ctf1", "ctf2", "ctf3"], ] servernames = [ "%s playhouse", "%s own server", ] nicks = [] for l in file("scripts/nicks.txt"): nicks += l.replace(":port80c.se.quakenet.org 353 matricks_ = #pcw :", "").strip().split() inick = 0 def get_nick(): global inick, nicks inick = (inick+1)%len(nicks) return nicks[inick].replace("`", "\`") for s in xrange(0, 350): cmd = "./fake_server_d_d " cmd += '-n "%s" ' % (random.choice(servernames) % get_nick()) for m in masterservers: cmd += '-m %s '%m max = random.randint(2, 16) cmd += "-x %d " % max t = random.randint(0, 2) cmd += '-a "%s" ' % random.choice(maps[t]) cmd += '-g %d ' % random.randint(0, 100) cmd += '-t %d ' % t # dm, tdm, ctf cmd += "-f %d " % random.randint(0, 1) # password protected for p in xrange(0, random.randint(0, max)): cmd += '-p "%s" %d ' % (get_nick(), random.randint(0, 20)) print cmd os.popen2(cmd) ================================================ FILE: scripts/netobj.py ================================================ import sys, os line_count = 0 class variable: name = "unknown" def __init__(self, args, name): global line_count self.name = name self.line = line_count def emit_declaration(self): return ["\tint %s;" % self.name] def linedef(self): return "#line %d" % self.line def emit_secure(self, parent): return [] def emit_unpack(self): return ["msg.%s = msg_unpack_int();" % self.name] def emit_unpack_check(self): return [] def emit_pack(self): return ["\t\tmsg_pack_int(%s);" % self.name] class var_any(variable): def __init__(self, args, name): variable.__init__(self, args, name) class var_range(variable): def __init__(self, args, name): variable.__init__(self, args, name) self.min = args[0] self.max = args[1] def emit_unpack_check(self): return ["if(msg.%s < %s || msg.%s > %s) { msg_failed_on = \"%s\"; return 0; }" % (self.name, self.min, self.name, self.max, self.name)] def emit_secure(self, parent): return [self.linedef(), "obj->%s = netobj_clamp_int(\"%s.%s\", obj->%s, %s, %s);" % (self.name, parent.name, self.name, self.name, self.min, self.max)] class var_string(variable): def __init__(self, args, name): variable.__init__(self, args, name) class var_string(variable): def __init__(self, args, name): variable.__init__(self, args, name) def emit_declaration(self): return ["\tconst char *%s;" % self.name] def emit_unpack(self): return ["msg.%s = msg_unpack_string();" % self.name] def emit_pack(self): return ["\t\tmsg_pack_string(%s, -1);" % self.name] class object: def __init__(self, line): fields = line.split() self.name = fields[1] self.extends = None if len(fields) == 4 and fields[2] == "extends": self.extends = fields[3] self.enum_name = "NETOBJTYPE_%s" % self.name.upper() self.struct_name = "NETOBJ_%s" % self.name.upper() self.members = [] def parse(self, lines): global line_count for index in xrange(0, len(lines)): line_count += 1 line = lines[index] if not len(line): continue if line == "end": return lines[index+1:] else: # check for argument fields = line.split(")", 1) if len(fields) == 2: names = [line.strip() for line in fields[1].split(",")] l = fields[0].split("(", 1) type = l[0] args = [line.strip() for line in l[1].split(",")] else: l = fields[0].split(None, 1) type = l[0] args = [] names = [line.strip() for line in l[1].split(",")] for name in names: create_string = 'var_%s(%s, "%s")' % (type, args, name) new_member = eval(create_string) self.members += [new_member] raise BaseException("Parse error") def emit_declaration(self): lines = [] if self.extends: lines += ["struct %s : public NETOBJ_%s\n {" % (self.struct_name, self.extends.upper())] else: lines += ["struct %s\n {" % self.struct_name] for m in self.members: lines += m.emit_declaration() lines += ["};"] return lines def emit_secure(self): lines = [] for m in self.members: lines += m.emit_secure(self) return lines class message: def __init__(self, line): fields = line.split() self.name = fields[1] self.enum_name = "NETMSGTYPE_%s" % self.name.upper() self.struct_name = "NETMSG_%s" % self.name.upper() self.members = [] def parse(self, lines): global line_count for index in xrange(0, len(lines)): line_count += 1 line = lines[index] if not len(line): continue if line == "end": return lines[index+1:] else: # check for argument fields = line.split(")", 1) if len(fields) == 2: names = [line.strip() for line in fields[1].split(",")] l = fields[0].split("(", 1) type = l[0] args = [line.strip() for line in l[1].split(",")] else: l = fields[0].split(None, 1) type = l[0] args = [] names = [line.strip() for line in l[1].split(",")] for name in names: create_string = 'var_%s(%s, "%s")' % (type, args, name) new_member = eval(create_string) self.members += [new_member] raise BaseException("Parse error") def emit_declaration(self): lines = [] lines += ["struct %s\n {" % self.struct_name] for m in self.members: lines += m.emit_declaration() lines += ["\tvoid pack(int flags)"] lines += ["\t{"] lines += ["\t\tmsg_pack_start(%s, flags);" % self.enum_name] for m in self.members: lines += m.emit_pack() lines += ["\t\tmsg_pack_end();"] lines += ["\t}"] lines += ["};"] return lines def emit_unpack(self): lines = [] for m in self.members: lines += m.emit_unpack() for m in self.members: lines += m.emit_unpack_check() return lines def emit_pack(self): lines = [] for m in self.members: lines += m.emit_pack() return lines class event(object): def __init__(self, line): object.__init__(self, line) self.enum_name = "NETEVENTTYPE_%s" % self.name.upper() self.struct_name = "NETEVENT_%s" % self.name.upper() class raw_reader: def __init__(self): self.raw_lines = [] def parse(self, lines): global line_count for index in xrange(0, len(lines)): line_count += 1 line = lines[index] if not len(line): continue if line == "end": return lines[index+1:] else: self.raw_lines += [line] raise BaseException("Parse error") class proto: def __init__(self): self.objects = [] self.messages = [] self.source_raw = [] self.header_raw = [] def load(filename): # read the file global line_count line_count = 0 lines = [line.split("//", 2)[0].strip() for line in file(filename).readlines()] p = proto() while len(lines): line_count += 1 line = lines[0] if not len(line): del lines[0] continue fields = line.split(None, 1) del lines[0] if fields[0] == "object": new_obj = object(line) lines = new_obj.parse(lines) p.objects += [new_obj] elif fields[0] == "message": new_msg = message(line) lines = new_msg.parse(lines) p.messages += [new_msg] elif fields[0] == "event": new_obj = event(line) lines = new_obj.parse(lines) p.objects += [new_obj] elif fields[0] == "raw_source": raw = raw_reader() lines = raw.parse(lines) p.source_raw += raw.raw_lines elif fields[0] == "raw_header": raw = raw_reader() lines = raw.parse(lines) p.header_raw += raw.raw_lines else: print "error, strange line:", line return p def emit_header_file(f, p): for l in p.header_raw: print >>f, l if 1: # emit the enum table for objects print >>f, "enum {" print >>f, "\tNETOBJTYPE_INVALID=0," for obj in p.objects: print >>f, "\t%s," % obj.enum_name print >>f, "\tNUM_NETOBJTYPES" print >>f, "};" print >>f, "" if 1: # emit the enum table for messages print >>f, "enum {" print >>f, "\tNETMSGTYPE_INVALID=0," for msg in p.messages: print >>f, "\t%s," % msg.enum_name print >>f, "\tNUM_NETMSGTYPES" print >>f, "};" print >>f, "" print >>f, "int netobj_secure(int type, void *data, int size);" print >>f, "const char *netobj_get_name(int type);" print >>f, "int netobj_num_corrections();" print >>f, "const char *netobj_corrected_on();" print >>f, "" print >>f, "void *netmsg_secure_unpack(int type);" print >>f, "const char *netmsg_get_name(int type);" print >>f, "const char *netmsg_failed_on();" print >>f, "" for obj in p.objects: for l in obj.emit_declaration(): print >>f, l print >>f, "" for msg in p.messages: for l in msg.emit_declaration(): print >>f, l print >>f, "" def emit_source_file(f, p, protofilename): print >>f, "#line 1 \"%s\"" % os.path.abspath(protofilename).replace("\\", "\\\\") for l in p.source_raw: print >>f, l print >>f, "const char *msg_failed_on = \"\";" print >>f, "const char *obj_corrected_on = \"\";" print >>f, "static int num_corrections = 0;" print >>f, "int netobj_num_corrections() { return num_corrections; }" print >>f, "const char *netobj_corrected_on() { return obj_corrected_on; }" print >>f, "const char *netmsg_failed_on() { return msg_failed_on; }" print >>f, "" print >>f, "static int netobj_clamp_int(const char *error_msg, int v, int min, int max)" print >>f, "{" print >>f, "\tif(v<min) { obj_corrected_on = error_msg; num_corrections++; return min; }" print >>f, "\tif(v>max) { obj_corrected_on = error_msg; num_corrections++; return max; }" print >>f, "\treturn v;" print >>f, "}" print >>f, "" if 1: # names print >>f, "static const char *object_names[] = {" print >>f, "\t" + '"invalid",' for obj in p.objects: print >>f, '\t"%s",' % obj.name print >>f, '\t""' print >>f, "};" print >>f, "" if 1: # secure functions print >>f, "static int secure_object_invalid(void *data, int size) { return 0; }" for obj in p.objects: print >>f, "static int secure_%s(void *data, int size)" % obj.name print >>f, "{" print >>f, "\t%s *obj = (%s *)data;" % (obj.struct_name, obj.struct_name) print >>f, "\t(void)obj;" # to get rid of "unused variable" warning print >>f, "\tif(size != sizeof(%s)) return -1;" % obj.struct_name if obj.extends: print >>f, "\tif(secure_%s(data, sizeof(NETOBJ_%s)) != 0) return -1;" % (obj.extends, obj.extends.upper()) for l in obj.emit_secure(): print >>f, "\t" + l print >>f, "\treturn 0;"; print >>f, "}" print >>f, "" if 1: # secure function table print >>f, "typedef int(*SECUREFUNC)(void *data, int size);" print >>f, "static SECUREFUNC secure_funcs[] = {" print >>f, "\t" + 'secure_object_invalid,' for obj in p.objects: print >>f, "\tsecure_%s," % obj.name print >>f, "\t" + '0x0' print >>f, "};" print >>f, "" if 1: print >>f, "int netobj_secure(int type, void *data, int size)" print >>f, "{" print >>f, "\tif(type < 0 || type >= NUM_NETOBJTYPES) return -1;" print >>f, "\treturn secure_funcs[type](data, size);" print >>f, "};" print >>f, "" if 1: print >>f, "const char *netobj_get_name(int type)" print >>f, "{" print >>f, "\tif(type < 0 || type >= NUM_NETOBJTYPES) return \"(invalid)\";" print >>f, "\treturn object_names[type];" print >>f, "};" print >>f, "" if 1: # names print >>f, "static const char *message_names[] = {" print >>f, "\t" + '"invalid",' for msg in p.messages: print >>f, '\t"%s",' % msg.name print >>f, '\t""' print >>f, "};" print >>f, "" if 1: # secure functions print >>f, "static void *secure_unpack_invalid() { return 0; }" for msg in p.messages: print >>f, "static void *secure_unpack_%s()" % msg.name print >>f, "{" print >>f, "\tstatic %s msg;" % msg.struct_name for l in msg.emit_unpack(): print >>f, "\t" + l print >>f, "\treturn &msg;"; print >>f, "}" print >>f, "" if 1: # secure function table print >>f, "typedef void *(*SECUREUNPACKFUNC)();" print >>f, "static SECUREUNPACKFUNC secure_unpack_funcs[] = {" print >>f, "\t" + 'secure_unpack_invalid,' for msg in p.messages: print >>f, "\tsecure_unpack_%s," % msg.name print >>f, "\t" + '0x0' print >>f, "};" print >>f, "" if 1: print >>f, "void *netmsg_secure_unpack(int type)" print >>f, "{" print >>f, "\tvoid *msg;" print >>f, "\tmsg_failed_on = \"\";" print >>f, "\tif(type < 0 || type >= NUM_NETMSGTYPES) return 0;" print >>f, "\tmsg = secure_unpack_funcs[type]();" print >>f, "\tif(msg_unpack_error()) return 0;" print >>f, "\treturn msg;" print >>f, "};" print >>f, "" if 1: print >>f, "const char *netmsg_get_name(int type)" print >>f, "{" print >>f, "\tif(type < 0 || type >= NUM_NETMSGTYPES) return \"(invalid)\";" print >>f, "\treturn message_names[type];" print >>f, "};" print >>f, "" if sys.argv[1] == "header": p = load(sys.argv[2]) emit_header_file(file(sys.argv[3], "w"), p) elif sys.argv[1] == "source": p = load(sys.argv[2]) emit_source_file(file(sys.argv[3], "w"), p, sys.argv[2]) else: print "invalid command" sys.exit(-1) ================================================ FILE: scripts/nicks.txt ================================================ :port80c.se.quakenet.org 353 matricks_ = #pcw :SPQR|Snapshot em0k1d n1sse iTouch|HedaN Hyeen Mattzki i9`Nilzon matricks_ WCG|Johan format` |ceMan PREGE lololollalalal kishe|Pookie polisen Rambo-ohsite firre15 ais-nax Obbmaster diskoturk SR|KinG gone-andytheman [FG]AkO cfg-gunnar proshit|Benis raaEW bengan-- Loser^ zNEKS Fokka Ping28|kwnztahh Palo^ partyZAH NillePillopio discover J-N ios Cajanen Bsite`oZe haxxcoto Hell[v]SOVA rabies Lampard2k7 DeFuN Linkan bjorniss Soet-DgR-_-[A] BridgeMill|Mod1 :port80c.se.quakenet.org 353 matricks_ = #pcw :Mutt Hofvits [G][L][H][f] dahlgren Zervantes ben_dover fanfanfanfan ibersklan-ruyrl Grismusen Ploxzish Ejwin^mp Poontuus sintr0z hbfs___dSq Bombastic sasdd ErNoI TaizK UnLess Astan SwS-Garcia WyH|spliffstar lololololol Simixiz SD|barkeN MOOE keekz Centern Xzide^^ N43-HYPER LeaW`3D hotnils Lectra`MAEKTIG fnytt frtyschoooooooo insanity|DavidO dr-tom MIM wayu n9ef dinmammaamamam eppel Fess1g wardh hzapRingMeisteR kidneb xplayn Lajgarn flaxe HEJJADANNE :port80c.se.quakenet.org 353 matricks_ = #pcw :Big^F Bsite`layd hejehjhk hsd1rrruffe AroooooN lexx_ lucchi AriGold DeDDu maflip eMO-aboOoOo Ramos6 ruub bjuse Chawn r3t _ogg kAerhu AIE|malle KimIO-SWE LooOOLiiiZ333eN kullersten Poke_- DryNox KoSmurfen ExakTT Gs|T1AO vtine|MAAAUNS heroX Twind [wc3]-Chiwi[CL] chilirec|raimat SeeWaR erdussel TROPP- exay franky540 ActionBarbie mHz\ZTK`sleep RRP^Jaffa cookiemonstAH WarL|thiDe Oskar^ qK-iMaz Nacka VILLIG-Booyah Beltdjur SoX-cOUPE kund|playz BCS|Winter :port80c.se.quakenet.org 353 matricks_ = #pcw :Pajsarn svamp tfs\a TruqN babben hr-gil mapD|endoZz gnomie bostrom kA-WANGA kNNas Abxtract|pilshe vogga koolaid-krille DeVixx jwn rdl-- Kee FjuNe koolaid-iskn Pr0`Z10d3y snowsky vibes Nikjou vtine|zlivero OmGaAA mAJ|Britt hekla [0]apa kEy [F]Kaela bananskalFTW|da jeb` vampyren H0JT4R0LJ4 SheVa^ mAxXI Lectro FtN bajajajajajajja mZ`WIGGE dAMI^ moll3 GitfaN boisan [cs]-sNT Ex`Novag[jb] PPB|everest[wa] xiver- KulaN N43-xhady pluffenFOSHO wilho :port80c.se.quakenet.org 353 matricks_ = #pcw :Nilsson^Arvika nRe`SmitH Ice`Lie[jb] sukki elgenkek drt0FF TaZ- Caesarion Limonaatipoika robf[S] DNAtive broder lolipop jollsy Genander Ballo_Ong Musikant|musicu ToY|Machine nerf|dupl0x gopy` fn\EXESSION FreZZ joharn _Folz [D]KvasteN daeeawewasdfadf CamelRyttArn Xabian HinzeL qRoN _dARUUF CUC|MiniMe^Away hewnk ASTRA|ove xideR Krigarn^ nIw|PlixxaN nMe|| Plumpen S0DA|BorrE teddis daboomb Bongo` Unknownperson TTA`BAdh SefuTzu`AWAY QRLGRIM neraz :port80c.se.quakenet.org 353 matricks_ = #pcw :Xipho|Fudge Guggztah etojk Lindgrene [V]ZAIKON BmF^Off Wf`jeager\aw Havsmanet-ehn krisa hojhoj alfonz RoBBY faB|mHk Cheeser Admin1337 DoFFrR Caution- mZ`NoKaas HR|bramhultz`` mxyzptlk luder^myfish i`pikoL ZhenjkEe^^-777 Mansvalp sajje1996 v4de Redical`quexOFF n^sdadasJo eXITD`aw teknikvm-jaoel FLIPP-Shapen ALEJKO cliz^ acequeen Ferato Shudde sinsKal`ply frittlol Deadlier Farbrorspurk FizaH` \Azash sWingY fb\ekN xtreck addeadam KneKk azkiN rinxzor :port80c.se.quakenet.org 353 matricks_ = #pcw :ArneH asdn brunte GeN|HollywoodHu bL\ZuND UNNEBERZ Synthetic|Xorci portoni saxparty|imso Inti |RnE oFFily Sp|DiamaNt Rhombus Nebrek kelamies Thingg BFB|incedeNt TAZzen whinan J0nte p12|wiggie okaJ mZ`Raztad FABF R3|sNELL blaupunkt2 Norrland-WaHoO maccan Ben---- aimD aLTOR EVIG|Falken nilsso bamstAr aGona`scalper reign[m4]n inzejN|ZoneX imag1ne a^meda|EYIE conejito puhaaa clime dsp123 mario_o bRRRA litextra|wezy TG|SaTaN Mando Weiche- wezzan :port80c.se.quakenet.org 353 matricks_ = #pcw :Labe mp`serve soulK [V]Gudiikzt4r XampeD fs\dcube TrolleRovarN Emptyy SG-daskep0t Byssan Bernts1 SG|YAhoo KOKKA rL`SnowZen^ hIGHTECH__ aPPeLk4k4n otto^_ backs`wouL DeaGJIa mONGOLOJD|kree xekafutuwu uris vagrant ^a^cklet neaK-spiN nozter Arve S0oker GotticH pr0n^ traff`mElissA BC|Kebab2000 CipRi andor-- barbara- traff`lizze harserver3on3 RalleTruss EAES EKEMAN Cowafuckingdogk superlime LokY Hockey-Syvve Gigi qk-WyverN Larsito spendex eiviN und`feelme :port80c.se.quakenet.org 353 matricks_ = #pcw :aderblasu yHYSS Cmore WaskE lodiz NachiMux Bodde kiiM Claddy TTAgital soker2on2plz mixzxz TmY- KrabbateN HAKKAKDGK VarsKo^aW Fuzak GZ`Kirra^^ mhaji Full|Hytra saxy0z0z0z Akapulka|urban CaZzpeR DarkLink FALLE- AmoZ mADSEN inetpro asd1 [100fps]elgit0 loltih GOLIATH`JONKAN sn1tch_4qs ischi87 Wazee LLLgHOST Derotti flw mandis daskdkad BlixteN_OFF Mjada-Hickdead Eazy-game|pAjk DulleN Sp3karn aimstar^mWd voffsi asdas Keo-muAz Liviu^^ vLaNskyldig :port80c.se.quakenet.org 353 matricks_ = #pcw :sdfgdfg [4]bappo polackn [42]xeelol basseeee LuppaN eSport|RoxoR Heat2 Helgon`KEXITAN vaxxus|kY kaarel_ i-Link`Slobbo DazOFF Lectra`VolveR [51N19E]Mdr NFTS_aptand pd\cilleh wirram Ag- kn1^ROSA Nixt0n @Josi berrtill mikl ut|brbr LoLiz3N Ishootudie HaGa1 Tetrispro|Veloc Stilig firin Local`Bhz goodR N-Bot GangstA^Niise CLOCKK MaGeN churru` tB-SidW playm8|DjwaNdz PenisPasta sbd-phuntanN Sh4cky vED kimpann mylvis ville_12345678 MeLL^-Q sio\chaez :port80c.se.quakenet.org 353 matricks_ = #pcw :PLAYER|ZOMG KappeZ^ pennpenn FatzoooO Snark^ Laakko FreddaN zure fiSKen vaccA[cx] Beart FD|Phoenix latrviabaatvik saffu tveka`StiKo HubbaBubbaBoyz q5^n3imad RETARDED pLym|Muffe GYG|RagnarssoN rF|neddemIRC HydrOO ollee sliff Eaten_Alive bollih\away fisarn Fanboyz\qcube Oish Da5|Poppo brottare mHz\xAantic [blueprint|Sn] SneZ WarQ|TriZ^ webcore|R3D95 rubeiiin`1st elius j0mppe- Zwoltex hebbe lallala vAH_ cp^traxzzlol Kung-Fonz Sprattelvatten inzejn[M] :port80c.se.quakenet.org 353 matricks_ = #pcw :IR|psN backs`Fester Linus CreEckDeztrox _hillztaah IrLo bissen jonjonjon giant^da princip-xtinct smaakskcake [P]use ZerOSh00TS WarQ|Mathilda [P]nikkz sEasiun N43-PuNKy PuttEE Sp|SaLo^| zErios Klerburgare Silikon|Laxen e`zejN hejkanin Zien volvers promizer yewlar HeJ_hEj`aw jeakk rilleh x1ofdewm Swift^ Infinit3 RattiSorsa Ludvika|keken `m1r0n robbagg PillaD-Goss3N Apa`MAx |1g|LegoBilen Ainish [EN]Xanti aviad- puFFFin hejbabuirabakal Hodja WildHead :port80c.se.quakenet.org 353 matricks_ = #pcw :Lo2P VadeHs|FortFarN Bollhuvve ebayer BEckzOFF Gonzo9014 DarkmindTheGrea trwon nena_ skillbill TpN-Rille^OFF Apl- zune[N] matsinyyyy spyyr stkiih MOSSEN Mathiaz dot222222222 MUFFINN DIMMamxxx xtinct BANZAI|Unders siCKO^^ ALEXMAN GM95 PinkDeagle Chlebo WiNk0 NITR0 Mykos Immortal-King Brodda inzejN|TiGeR Jaaanpoo GZ`SneLF |Ahoehoe R4mzi sadasda FoSho zOOM^ HEHEO2 princip-HermiN^ SUPERFASTTEC yohanseN n23|folieN-_- muffins crakkiz tmd-vdF Ello^ :port80c.se.quakenet.org 353 matricks_ = #pcw :WOTS|christian |F|6|F|Volle Sp4rv3N Nibbler|LAN BVG|Anonim HENNING Local`sNl ifektO whipee\ vaxxus|gtv cL\\ninjaaraben r4jz_- vaxxus|nIc vaxxus|aVd Beastie^ Meier bjarne-_-12 Kalhygge|aBc inspet nuLLifY zlF BLAN|sUPERJAK biggy flon-sebbe fjurtis-otrolig Kalhygge|naXo Playgr0und Bamsar^Bwhl Kalhygge|meXA Kindow sylta pZi paraL^Deja BlasTmaN-tB deeh` [5b]CW|maxii AceDude_- LG^Panik GoA-Het^y|OFF sTr1nG^AFK zxn^off denbette^BNC ZoniX^Off LG^bruzken :port80c.se.quakenet.org 353 matricks_ = #pcw :Zip^BNC ANONZOFF c`FoOjegerOff Ordspil^afk zanoJ-off bakhoj^off VeLuX^BNC p-zkarp Error404 Nivius^^ DP^OFF|SILENTY VICKY SkytteNOFF nAz JC|RedeTeZ^BNC hooligan`away Splutt|BNC svennjeavlnOFF aNTWAn CB|knubbiz-`AWA bliztr NB|freq[N] kOllEH deML|StoLeN\OFF DOED|EnRIz erN^BNC^AW jompa Cha0tix^OFF Pinstrup-off wolves-munkaway skoogan airhead^OFF Jeffie D5|Lindahl^OFF onaqui skinK aNders|BNC KadaveR^ valtsu_ sledz[aw] Cryptztahh`off FleexOFF stycket :port80c.se.quakenet.org 353 matricks_ = #pcw :xGx_kmn^off WC anto_o GAndroo^aw schmaCk|icko lyngordon wUULF tX|Dzenan dERG0 chansurf HW|eriksson SG|Hornet xTz`ReXor^off_ syn4psE catsie skize Hezxy tomater HildaOFF nEXIN-tirre [NeutroN] ^sne WoA|dfish xTz`xNitroX^off exero koiz drastic`aVoid Checky_OFF Graxor LinusOFF_ nesc|Meibi` crezz eLiaZ unrea CharlieE eco`nejked tompA^ exp3rt Moejoe FloraCs|Aora Kalhygge|z1 iksO fake[n]ick FloraCsAora inzejN|Jonse ZoRoXo FD|tVEKA XMG\Gngs brrave^Borta :port80c.se.quakenet.org 353 matricks_ = #pcw :aLpi-AtroOFF mustafakrister PEWPEW MiRRE`OFFLiNE Mixxarna-WejK^ gP|Deex cAD-BNC1 tomh BnCinzejn henka snacjsar EnE|vilsN TixoNBnc shifty|ossi WSOP|fredada MortenSoccer kiimpan [E]Polle^ doke muuuie Androoz SIXO wtai|tryckveard [sc]-falle Tele\weRRe`OFF Martin_- annette-away iGwtRealT3cH gUsk smekarn Onttu xVera`kreeeeee Somppiaeae LasseMan [SS]BoZo inzejn[A] HR|WINESY ^^juh0^^ BYS`vojnik nejmzah Sh1ft-_- Thunder-str R22du sankan DDark MtM PlayN-ziNk^Aw :port80c.se.quakenet.org 353 matricks_ = #pcw :pd|firren GROSSER LIMEDNULKE HellkaN Mattan tzeron`g0ne Mr-Zorky HoD-Espen BAdhBNC ahlt ramoneur roxon_ dOFF`bth WcG|memphis Jules_ Hye Toot Justicia hajpad-Ante Fia`T8im e5g-Re\FILM hjort iNet\fjollabero Jeespoks SH|Thonk ztar`oFF Widow[away] mj\away CheatoN^BNC LAPPHOREoff dO`esn paal`aw Prayon emFFF zeLo FluBBa dalleBNC aTer waah|off kdo^ C_OFFE Dynis|AWAY miniwolbc BpN^away ReF^Zzz kyAx-OFF therazorsedge vT-viggolito CaLm[mC] Fredde^ acuBNC :port80c.se.quakenet.org 353 matricks_ = #pcw :Xipho|HollyWood _ArvedssoN^BNC Rayan Mastodonten kempa Blizo`bnc SnIpa Suspected`Bnc1 Neftus dO`RadeoN Madicken daniel123 D-Line|m00jsi osbnc2 AWskian quality`BNC2 inzite`chad CHiLLiPiLl^bnc swaftan QlintoN iTouch|LundiN vandalizm Qslig[FM] makke Tele\wHomp^bnc steamacc4sale Playbackvxo asiQ^BNC Cash-Flow deniiX ITFYTD olssonn nehyd [421]Bihaz- CrilleeOFF elicious`wE111A sndOFF`Ass_slac kusn Myscobnc shade`nu [1Ramlosa] j1m1bnc TPI-piggerN :port80c.se.quakenet.org 353 matricks_ = #pcw :gedis`AFK mX|Ximer3`BNC Rofel Std samhOFF tG`JeBuu roxz peace`zwa _jacce dRELL tetta bubbenBNC`[GA] __viktor ture frell newbcake k00HOOHO-- makkan Bihaz_- joacim _simon sajje1995 emf|zupppiyoyoy elixyr forfam|bOFF elitasson _sockan Gulle der-Andy RexorN NER|M0wz`aw n0pL_OFF AdamBNC kRIIL falCoOFF ajz antein splexan DNX Team-Unic_bnc2 Team-Unic_bnc1 Team-dH^Jacki3 |F|6|F|Penelo SCUMMY-OFF goL|GustiS^away koppar MartinsBNC xANIZ\bnc chilLboY :port80c.se.quakenet.org 353 matricks_ = #pcw :Erik2son powerbnc2 Nizer Qeamer tobiasmatss swsBNC `Tobb Pyret Gv\MortiOFF aTschi xamber123 _borre boeka`kankeOFF reaction-bnc1 wiggan Zenhto TUX|ximmy hariiss HS|JagaleX^Offl ohm-bnc4 Iam hawkztr wibbaan Stamina\Proteus rME st4rl\heawen cursed-^^ _LarssoN_ Empis KnaspeR freez Deja-OFF QseBNC ninjaFREDDE ReTrez^Bnc^Away Divid0 mosklubba XnoW MozzyOFF mZ`Freddy Kladden^bnc alkh`aw Prood nIIICKOOOOO CR^SquierBNC H9jE^ b`hoffenOFF grikko sevonOFF :port80c.se.quakenet.org 353 matricks_ = #pcw :Vexey avdunkad Rizley razzz BJARTMAR PlayHardGoFat Bubstah Gaffel [imbaOFF]sajkez mooaern emric Znap Hyso[csP] Kvasten^-off @Fabi Ind`laaKen amsrOFF Stamina\Achtung aceit\MorianA- c^KNDOO DAJMEN`AW runpuff Drunke fisken10 Let_It_Whip Poxi boeka`zeppOFF bodil avlid^bnc markisen`bnc qurry oBiee PZ|FiC-Aw Jonirl_gone luttman _micro Cr33d^Away Anderss^OFF rasmus11 axl0n17 pAjk Vibban\OFF zAt-off `tyrantBNC HB`off|djnatnat mP`off|Redfir3 TS|kolben_afk :port80c.se.quakenet.org 353 matricks_ = #pcw :Manual\AFK mP`off|Redbot RetardacE ewh`FL1NK\away TaeferN`aw Divan^KaLa^BNC Divan^myRan^BNC DUMBASS`BNC sudden21 Cyber`Mnisaway [BFF]-REeLexX AEEEEEEEEEEEEEE ZMLB-Odis deaf-cs|Lille Ninjan` bojer^off freaKKKy_BNC Replay` GuFFe D3nim smn-_- jerry[bnc] D`timex a5\eqiNawaY inviz maRkN_ Brodda^SKOLAN zG|CBB^Off TisPik_off AFK^[TC]pvp chiva0FF hughi-off amokz^BNC SteelpliX^BNC Bioonic nIELSENoFF OFF|fZoe OliverL2`AWAY babb Chuck_N SNOEN^OFF [CYBER]niijaz :port80c.se.quakenet.org 353 matricks_ = #pcw :LilleGris^BnC zG|Flod__ \lEGO`OFF LinusOFF SaX`Gubbi`OFF kolmio m|Smith Mitt3 iluen haMp gDesigns Reb_6ff blank|tox^off Unf[BNC]JLS SYNTEK|bArk FJERLEND PerSpelmann toXq` ieS|make`away pwang12 wajk\aw InV^Raccoon-OFF ComsyS ElakSomFan^^ @m3z @pimpo @MYM|Muesli`off ADAMeh^zzzz DLM^b1ue^Off Hootarn croz kylan_off ing\\tsabNC Offson n1mez`off spanier^off dieNasty`brb [D]Bamb DKB|Night[oFF] Basket-off xS|HeliuM Hardcorehilda attixoff thorr_ minib :port80c.se.quakenet.org 353 matricks_ = #pcw :rwn ironic|Haunted khalannz PCW-Poker spitz Hiippari- iMrClean C5|Jakobervaek Casa`berssaBNC gamer`away myNKOFF Tjalfeen^off_ ^cooling noisi-a-way JennaDD mySKi-[a]ngeh mav0FF sanoj\ dicti KLADDIS`AWAY OFF|ShAmOnE dollface WoC^RuFi selo|elloAFK LnC-Kezse kn1^Mole__ haVec- BorgareN^ steddan Verga PawP SAAAID onemind`xent dyfu`viciouz Ice`OFF_ kEbAbMaNnEn gamax|luN_ guragoa`off xorTon Kirka bruikki SkarvaNOFF empton nessaia|noHn-OF iNet\xerp :port80c.se.quakenet.org 353 matricks_ = #pcw :]5[kbz tjaeder sulaN^OFFLAJN Relayish mr-o oxido drulen CR1M3Z^off_ ziNx` Local`MickeMann deaf-cs|Brajen cL\\ninjaBNC tomh^soet eriik^ Carn4tioN`away Rapt0r KAAAALLLEE`BNC raY^^ aNnaa` ^apan LpY|p0sh[kol] dempAWAY zuxen\OFF aztro ToggeN [A1]No_52 [A1]etuxia Jusa Playm|DjToppi- Bodoom BCS^OFF|mkiss skau ThumbSucker^BNC tOFF-FuSe fnpOFF|aes ^SlappFisa^ Bhz`OFF Unf[BNC]Lion b00z\away Raised|ProBlem [A]fittb extinct`zake blike|AplE`oFF eNtiC MeLLKeR :port80c.se.quakenet.org 353 matricks_ = #pcw :SNELHEST Nexo rkO`aw zG|Numse_ Maff n9way|mIkLo bEnz SpiderA _cgx GZ`cAD RICK1DAH fun|Skippsen INFAME|eRIKa\aw SS|xtinqt _mys|da HolySmoke Rq hoorai\naolein qutip mYth|schnaLz_M rengo`off aRa|Voilala^Off skilleAWAY BCS^OFF|dexer @FSHost-com aeom`away tvekaOFF`haMME Smog^ PartyPoker Sp|SpeTLighT^OF [Fixx]Olle sIMMe`offline panik_herman avu\partz0r rekyL^_- BCS^OFF|AMPARI Fluen^BNC Wkd^off eXm-SunnY^ ^hej Kniks DiXeR`off rfwdm_ TPI_piggerN_ Mataza|off :port80c.se.quakenet.org 353 matricks_ = #pcw :epzBNC Ampro @hardstep goL|craJpAW WwG-Muste E|Evil^off MADREFLEX`rhZ adde` Crazy^SpexXI Jerker alq-andreA H1Xer aGILITY`POLYMOX Joker^BNC Mohkis [LEGE]HeJLeN^ Caprice Intgen`BAERB{J} VILLIG-7thAWAY Neehajd`BNC Batti LewfeN^Off Ravnn sky\bangz0ff`` SkenaN^bnc GladPanda fausti pittins^BNC SaX|f|Gubbi^ rM|pIx^^ Rms- RANGERBOY`aw FixxeR^ Edvnz uga BoSS|Benal`BNC sjonasm8k PND\s humpyskump SKOVDE|Snasi @HighTech @spam-scan @S @Q @[-hoorai-] STEN11 :port80c.se.quakenet.org 353 matricks_ = #pcw :Voteski xP|Puhbaer^off Yoshi_ CWE`Flippen CeveRR [ShaKa]CoOoL`AW h3h3 LnC-iNZANEoff_ Wu-djaoff Zerooo Pieper_ chica`SanziLOFF BB4FRAGS|XTM`A limespOFF`malle oPS|JBbnc staphe G`Quix NItron\bnc c55-feros hejx HighG`wdE_OFF eco`zN Myt willybob`bnc Rh-G^TippeR^ JUHP-BNC|Jumert mthz Moldskred MxG\\MailBoX MeejtAWAY [c]eKipz dkz`xfx zaped`off ptrNo_OFF Jeamu c`Crelle-R^off rew`away Ak-87^ TOOOMMY\off L2D_-_Rappi Ghost^BNC _AraCi SKytteN^ ^StoKer^ :port80c.se.quakenet.org 353 matricks_ = #pcw :zNei mYth|LucK3r n-N|TarriC poohi hamasbnc Coutz1 Char|ieBoY AZ^LEVING-BNC plike^HuliaN___ uR`saniOFF Gtrip|Hebo`OFF Redical`Score IceBlu EvilEye_bnc maaxi`off [AWAY]Darkling Noobet|StajOFF bjarne-_- zG|Eriksen^Off venom^off mHuen utini_off eveni\OFF Xqe MefistoFX`oFF bas-off|f4me TRiCK`iDfye MAAUNS CamiK^ GrQnaerten blike|amns`oFF sandersan Lt`HipPus Mossepo siOFF \zimze`BNC R33t Gs\BaZe^OFF zaney drateR^OFF Free1337 off|Hunter ifrit apfelmus :port80c.se.quakenet.org 353 matricks_ = #pcw :eu-off|Blade jfl-oFF`miD Uniline charlie` painkiller`kool OFF|ShOcK telk0^BNC gh|jack^off EX-adrin^bnc w\Hairboi osfa|puddy^off CruisE-OFF- [A1]EnGud kungeeN^^ CMAX|[m]addilo Sk-off|MichYs9N NTL-Sentinal Tjalfuglen^off KapteWN`BNC cichlide^AWAY ChomP`away paltieBNC^[cz] WGV|PwnZ^Off pidde-_- TELETUBBIE Ecka fazer|NoxtrnOFF Lolad-net^ diRectAWAY evil|parasite xultRoNaw genics^BNC steri`off RaliAWAY oxid`zsiltsoff xazury`bnc IRLHELTEN r0ntti :port80c.se.quakenet.org 353 matricks_ = #pcw :searon_ Saturn` Nimra jOHNSONN KegleN^AFK JC|PlaNke d4NNY`0fflajn MuGGe^Bnc _4P|StyLish^bnc s8`swinnnk Jackkis F`off`NickyH F5_rakkeeee Thuriaz inzym Moriz edom z1ax^0FFL1NE eXm-nex0r|bNc unstuck|L- aimstyle`vzn\a Gaylorden WrD ShadowOfAMaN gh|8Ball^off Retard-- SAGG-Lipton backyard\KoWORK awaylen BCS^OFF|Pipe TPI`Ferro fredde` xeet_ BlaZe180 Macan_ biblas^BNC Cyeclone Vali[away] BK|awayman armoryh oKend _cB-Us3-Bnc_ Kefir [nerd]Kurr3 ================================================ FILE: scripts/png.py ================================================ import struct, zlib, sys class image: w = 0 h = 0 data = [] def read_tga(f): image = f.read() img_type = struct.unpack("<B", image[2:3])[0] img_bpp = struct.unpack("<B", image[16:17])[0] img_width = struct.unpack("<H", image[12:14])[0] img_height = struct.unpack("<H", image[14:16])[0] if img_type != 2 or img_bpp != 32: print "image must be a RGBA" start = 18+struct.unpack("B", image[0])[0] end = start + img_width*img_height*4 image_data = image[start:end] # fetch raw data return image_data def write_tga(f, w, h, bpp, data): f.write(struct.pack("<BBBHHBHHHHBB", 0, 0, 2, 0, 0, 0, 0, 0, w, h, bpp, 0) + data) def load_png(f): def read(fmt): return struct.unpack("!"+fmt, f.read(struct.calcsize("!"+fmt))) def skip(count): f.read(count) # read signature if read("cccccccc") != ('\x89', 'P', 'N', 'G', '\r', '\n', '\x1a', '\n'): return 0 # read chunks width = -1 height = -1 imagedata = "" while 1: size, id = read("I4s") if id == "IHDR": # read header width, height, bpp, colortype, compression, filter, interlace = read("IIBBBBB") if bpp != 8 or compression != 0 or filter != 0 or interlace != 0 or (colortype != 2 and colortype != 6): print "can't handle png of this type" print width, height, bpp, colortype, compression, filter, interlace return 0 skip(4) elif id == "IDAT": imagedata += f.read(size) skip(4) # read data elif id == "IEND": break # we are done! \o/ else: skip(size+4) # skip unknown chunks # decompress image data rawdata = map(ord, zlib.decompress(imagedata)) # apply per scanline filters pitch = width*4+1 bpp = 4 imgdata = [] prevline = [0 for x in xrange(0, (width+1)*bpp)] for y in xrange(0,height): filter = rawdata[pitch*y] pixeldata = rawdata[pitch*y+1:pitch*y+pitch] thisline = [0 for x in xrange(0,bpp)] def paeth(a, b, c): p = a + b - c pa = abs(p - a) pb = abs(p - b) pc = abs(p - c) if pa <= pb and pa <= pc: return a if pb <= pc: return b return c if filter == 0: f = lambda a,b,c: 0 elif filter == 1: f = lambda a,b,c: a elif filter == 2: f = lambda a,b,c: b elif filter == 3: f = lambda a,b,c: (a+b)/2 elif filter == 4: f = paeth for x in xrange(0, width*bpp): thisline += [(pixeldata[x] + f(thisline[x], prevline[x+bpp], prevline[x])) % 256] prevline = thisline imgdata += thisline[4:] raw = "" for x in imgdata: raw += struct.pack("B", x) #print len(raw), width*height*4 write_tga(file("test2.tga", "w"), width, height, 32, raw) return 0 load_png(file("butterfly2.png", "rb")) ================================================ FILE: scripts/process_blame.py ================================================ import sys user_map = {"kma":"matricks", "teetow":"matricks", "jlha":"matricks", "jdv":"void", "jaf":"serp"} users = {} for line in sys.stdin: fields = line.split() name = user_map.get(fields[1], fields[1]) users[name] = users.get(name, 0) + 1 total = reduce(lambda x,y: x+y, users.values()) for u in users: print "%6s %6d %s" % ("%03.2f"%(users[u]*100.0/total), users[u], u) print "%03.2f %6d %s" % (100, total, "Total") ================================================ FILE: scripts/refactor_count.py ================================================ import os, re, sys alphanum = "0123456789abcdefghijklmnopqrstuvwzyxABCDEFGHIJKLMNOPQRSTUVWXYZ_" cpp_keywords = ["auto", "const", "double", "float", "int", "short", "struct", "unsigned", # C "break", "continue", "else", "for", "long", "signed", "switch", "void", "case", "default", "enum", "goto", "register", "sizeof", "typedef", "volatile", "char", "do", "extern", "if", "return", "static", "union", "while", "asm", "dynamic_cast", "namespace", "reinterpret_cast", "try", # C++ "bool", "explicit", "new", "static_cast", "typeid", "catch", "false", "operator", "template", "typename", "class", "friend", "private", "this", "using", "const_cast", "inline", "public", "throw", "virtual", "delete", "mutable", "protected", "true", "wchar_t"] allowed_words = [] #allowed_words += ["bitmap_left", "advance", "glyph"] # ft2 allowed_words += ["qsort"] # stdio / stdlib allowed_words += ["size_t", "cosf", "sinf", "asinf", "acosf", "atanf", "powf", "fabs", "rand", "powf", "fmod", "sqrtf"] # math.h allowed_words += ["time_t", "time", "strftime", "localtime"] # time.h allowed_words += [ # system.h "int64", "dbg_assert", "dbg_msg", "dbg_break", "dbg_logger_stdout", "dbg_logger_debugger", "dbg_logger_file", "mem_alloc", "mem_zero", "mem_free", "mem_copy", "mem_move", "mem_comp", "mem_stats", "total_allocations", "allocated", "thread_create", "thread_sleep", "lock_wait", "lock_create", "lock_release", "lock_destroy", "swap_endian", "io_open", "io_read", "io_read", "io_write", "io_flush", "io_close", "io_seek", "io_skip", "io_tell", "io_length", "str_comp", "str_length", "str_quickhash", "str_format", "str_copy", "str_comp_nocase", "str_sanitize", "str_append", "str_comp_num", "str_find_nocase", "str_sanitize_strong", "str_uppercase", "str_toint", "str_tofloat", "str_utf8_encode", "str_utf8_rewind", "str_utf8_forward", "str_utf8_decode", "str_sanitize_cc", "str_skip_whitespaces", "fs_makedir", "fs_listdir", "fs_storage_path", "fs_is_dir", "net_init", "net_addr_comp", "net_host_lookup", "net_addr_str", "type", "port", "net_addr_from_str", "net_udp_create", "net_udp_send", "net_udp_recv", "net_udp_close", "net_socket_read_wait", "net_stats", "sent_bytes", "recv_bytes", "recv_packets", "sent_packets", "time_get", "time_freq", "time_timestamp"] allowed_words += ["vec2", "vec3", "vec4", "round", "clamp", "length", "dot", "normalize", "frandom", "mix", "distance", "min", "closest_point_on_line", "max", "absolute"] # math.hpp allowed_words += [ # tl "array", "sorted_array", "string", "all", "sort", "add", "remove_index", "remove", "delete_all", "set_size", "base_ptr", "size", "swap", "empty", "front", "pop_front", "find_binary", "find_linear", "clear", "range", "end", "cstr", "partition_linear", "partition_binary"] allowed_words += ["fx2f", "f2fx"] # fixed point math def CheckIdentifier(ident): return False class Checker: def CheckStart(self, checker, filename): pass def CheckLine(self, checker, line): pass def CheckEnd(self, checker): pass class FilenameExtentionChecker(Checker): def __init__(self): self.allowed = [".cpp", ".h"] def CheckStart(self, checker, filename): ext = os.path.splitext(filename)[1] if not ext in self.allowed: checker.Error("file extention '%s' is not allowed" % ext) class IncludeChecker(Checker): def __init__(self): self.disallowed_headers = ["stdio.h", "stdlib.h", "string.h", "memory.h"] def CheckLine(self, checker, line): if "#include" in line: include_file = "" if '<' in line: include_file = line.split('<')[1].split(">")[0] #if not "/" in include_file: # checker.Error("%s is not allowed" % include_file) elif '"' in line: include_file = line.split('"')[1] #print include_file if include_file in self.disallowed_headers: checker.Error("%s is not allowed" % include_file) class HeaderGuardChecker(Checker): def CheckStart(self, checker, filename): self.check = ".h" in filename self.guard = "#ifndef " + filename[4:].replace("/", "_").replace(".hpp", "").replace(".h", "").upper() + "_H" def CheckLine(self, checker, line): if self.check: #if "#" in line: self.check = False #if not self.check: if line.strip() == self.guard: pass else: checker.Error("malformed or missing header guard. Should be '%s'" % self.guard) class CommentChecker(Checker): def CheckLine(self, checker, line): if line.strip()[-2:] == "*/" and "/*" in line: checker.Error("single line multiline comment") class FileChecker: def __init__(self): self.checkers = [] self.checkers += [FilenameExtentionChecker()] self.checkers += [HeaderGuardChecker()] self.checkers += [IncludeChecker()] self.checkers += [CommentChecker()] def Error(self, errormessage): self.current_errors += [(self.current_line, errormessage)] def CheckLine(self, line): for c in self.checkers: c.CheckLine(self, line) return True def CheckFile(self, filename): self.current_file = filename self.current_line = 0 self.current_errors = [] for c in self.checkers: c.CheckStart(self, filename) for line in file(filename).readlines(): self.current_line += 1 if "ignore_check" in line: continue self.CheckLine(line) for c in self.checkers: c.CheckEnd(self) def GetErrors(self): return self.current_errors def cstrip(lines): d = "" for l in lines: if "ignore_convention" in l: continue l = re.sub("^[\t ]*#.*", "", l) l = re.sub("//.*", "", l) l = re.sub('\".*?\"', '"String"', l) # remove strings d += l.strip() + " " d = re.sub('\/\*.*?\*\/', "", d) # remove /* */ comments d = d.replace("\t", " ") # tab to space d = re.sub(" *", " ", d) # remove double spaces #d = re.sub("", "", d) # remove /* */ comments d = d.strip() # this eats up cases like 'n {' i = 1 while i < len(d)-2: if d[i] == ' ': if not (d[i-1] in alphanum and d[i+1] in alphanum): d = d[:i] + d[i+1:] i += 1 return d #def stripstrings(data): # return re.sub('\".*?\"', 'STRING', data) def get_identifiers(data): idents = {} data = " "+data+" " regexp = re.compile("[^a-zA-Z0-9_][a-zA-Z_][a-zA-Z0-9_]+[^a-zA-Z0-9_]") start = 0 while 1: m = regexp.search(data, start) if m == None: break start = m.end()-1 name = data[m.start()+1:m.end()-1] if name in idents: idents[name] += 1 else: idents[name] = 1 return idents grand_total = 0 grand_offenders = 0 gen_html = 1 if gen_html: print "<head>" print '<link href="/style.css" rel="stylesheet" type="text/css" />' print "</head>" print "<body>" print '<div id="outer">' print '<div id="top_left"><div id="top_right"><div id="top_mid">' print '<a href="/"><img src="/images/twlogo.png" alt="teeworlds logo" /></a>' print '</div></div></div>' print '<div id="menu_left"><div id="menu_right"><div id="menu_mid">' print '</div></div></div>' print '<div id="tlc"><div id="trc"><div id="tb"> </div></div></div>' print '<div id="lb"><div id="rb"><div id="mid">' print '<div id="container">' print '<p class="topic_text">' print '<h1>Code Refactoring Progress</h1>' print '''This is generated by a script that find identifiers in the code that doesn't conform to the code standard. Right now it only shows headers because they need to be fixed before we can do the rest of the source. This is a ROUGH estimate of the progress''' print '</p>' print '<p class="topic_text">' print '<table>' #print "<tr><td><b>%</b></td><td><b>#</b></td><td><b>File</b></td><td><b>Offenders</b></td></tr>" line_order = 1 total_files = 0 complete_files = 0 total_errors = 0 for (root,dirs,files) in os.walk("src"): for filename in files: filename = os.path.join(root, filename) if "/." in filename or "/external/" in filename or "/base/" in filename or "/generated/" in filename: continue if "src/osxlaunch/client.h" in filename: # ignore this file, ObjC file continue if "e_config_variables.h" in filename: # ignore config files continue if "src/game/variables.hpp" in filename: # ignore config files continue if not (".hpp" in filename or ".h" in filename or ".cpp" in filename): continue #total_files += 1 #if not "src/engine/client/ec_client.cpp" in filename: # continue f = FileChecker() f.CheckFile(filename) num_errors = len(f.GetErrors()) total_errors += num_errors if num_errors: print '<tr style="background: #e0e0e0"><td colspan="2">%s, %d errors</td></tr>' % (filename, num_errors), for line, msg in f.GetErrors(): print '<tr"><td>%d</td><td>%s</td></tr>' % (line, msg) #print '<table>' #GetErrors() if 0: text = cstrip(file(filename).readlines()) # remove all preprocessor stuff and comments #text = stripstrings(text) # remove strings (does not solve all cases however) #print text idents = get_identifiers(text) offenders = 0 total = 0 offender_list = {} for name in idents: #print name if len(name) <= 2: # skip things that are too small continue if name in cpp_keywords: # skip keywords continue if name in allowed_words: # skip allowed keywords continue total += idents[name] if name != name.lower(): # strip names that are not only lower case continue offender_list[name] = idents[name] if not gen_html: print "[%d] %s"%(idents[name], name) offenders += idents[name] grand_total += total grand_offenders += offenders if total == 0: total = 1 line_order = -line_order done = int((1-(offenders / float(total))) * 100) if done == 100: complete_files += 1 if done != 100 and gen_html: color = "#ffa0a0" if done > 20: color = "#ffd080" if done > 50: color = "#ffff80" if done > 75: color = "#e0ff80" if done == 100: color = "#80ff80" line_color = "#f0efd5" if line_order > 0: line_color = "#ffffff" offender_string = "" count = 0 for name in offender_list: count += 1 offender_string += "[%d]%s " % (offender_list[name], name) if count%5 == 0: offender_string += "<br/>" print '<tr style="background: %s">' % line_color, print '<td style="text-align: right; background: %s"><b>%d%%</b></td><td style="text-align: center">%d</td><td>%s</td>' % (color, done, offenders, filename), print '<td style="text-align: right">%s</td>' % offender_string print "</tr>" count = 0 if gen_html: print "</table>" print "<h1>%d errors</h1>" % total_errors if 0: print "<h1>%.1f%% Identifiers done</h1>" % ((1-(grand_offenders / float(grand_total))) * 100) print "%d left of %d" % (grand_offenders, grand_total) print "<h1>%.1f%% Files done</h1>" % ((complete_files / float(total_files)) * 100) print "%d left of %d" % (total_files-complete_files, total_files) print "</p>" print "<div style='clear:both;'></div>" print '</div>' print '</div></div></div>' print '<div id="blc"><div id="brc"><div id="bb"> </div></div></div>' print '</div>' print "</body>" ================================================ FILE: scripts/tw_api.py ================================================ # coding: utf-8 from socket import * import struct import sys import threading import time NUM_MASTERSERVERS = 4 MASTERSERVER_PORT = 8300 TIMEOUT = 2 SERVERTYPE_NORMAL = 0 SERVERTYPE_LEGACY = 1 PACKET_GETLIST = "\x20\x00\x00\x00\x00\x00\xff\xff\xff\xffreqt" PACKET_GETLIST2 = "\x20\x00\x00\x00\x00\x00\xff\xff\xff\xffreq2" PACKET_GETINFO = "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xffgief" PACKET_GETINFO2 = "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xffgie2" + "\x00" PACKET_GETINFO3 = "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xffgie3" + "\x00" class Server_Info(threading.Thread): def __init__(self, address, type): self.address = address self.type = type self.finished = False threading.Thread.__init__(self, target = self.run) def run(self): self.info = None if self.type == SERVERTYPE_NORMAL: self.info = get_server_info3(self.address) elif self.type == SERVERTYPE_LEGACY: self.info = get_server_info(self.address) if self.info: self.info = get_server_info2(self.address) self.finished = True def get_server_info(address): try: sock = socket(AF_INET, SOCK_DGRAM) sock.settimeout(TIMEOUT); sock.sendto(PACKET_GETINFO, address) data, addr = sock.recvfrom(1024) sock.close() data = data[14:] # skip header slots = data.split("\x00") server_info = {} server_info["version"] = slots[0] server_info["name"] = slots[1] server_info["map"] = slots[2] server_info["gametype"] = slots[3] server_info["flags"] = int(slots[4]) server_info["progression"] = int(slots[5]) server_info["num_players"] = int(slots[6]) server_info["max_players"] = int(slots[7]) server_info["players"] = [] for i in xrange(0, server_info["num_players"]): player = {} player["name"] = slots[8+i*2] player["score"] = int(slots[8+i*2+1]) server_info["players"].append(player) return server_info except: sock.close() return None def get_server_info2(address): try: sock = socket(AF_INET, SOCK_DGRAM) sock.settimeout(TIMEOUT); sock.sendto(PACKET_GETINFO2, address) data, addr = sock.recvfrom(1024) sock.close() data = data[14:] # skip header slots = data.split("\x00") server_info = {} server_info["token"] = slots[0] server_info["version"] = slots[1] server_info["name"] = slots[2] server_info["map"] = slots[3] server_info["gametype"] = slots[4] server_info["flags"] = int(slots[5]) server_info["progression"] = int(slots[6]) server_info["num_players"] = int(slots[7]) server_info["max_players"] = int(slots[8]) server_info["players"] = [] for i in xrange(0, server_info["num_players"]): player = {} player["name"] = slots[9+i*2] player["score"] = int(slots[9+i*2+1]) server_info["players"].append(player) return server_info except: sock.close() return None def get_server_info3(address): try: sock = socket(AF_INET, SOCK_DGRAM) sock.settimeout(TIMEOUT); sock.sendto(PACKET_GETINFO3, address) data, addr = sock.recvfrom(1400) sock.close() data = data[14:] # skip header slots = data.split("\x00") server_info = {} server_info["token"] = slots[0] server_info["version"] = slots[1] server_info["name"] = slots[2] server_info["map"] = slots[3] server_info["gametype"] = slots[4] server_info["flags"] = int(slots[5]) server_info["num_players"] = int(slots[6]) server_info["max_players"] = int(slots[7]) server_info["num_clients"] = int(slots[8]) server_info["max_clients"] = int(slots[9]) server_info["players"] = [] for i in xrange(0, server_info["num_clients"]): player = {} player["name"] = slots[10+i*5] player["clan"] = slots[10+i*5+1] player["country"] = int(slots[10+i*5+2]) player["score"] = int(slots[10+i*5+3]) if int(slots[10+i*5+4]): player["player"] = True else: player["player"] = False server_info["players"].append(player) return server_info except: sock.close() return None class Master_Server_Info(threading.Thread): def __init__(self, address): self.address = address self.finished = False threading.Thread.__init__(self, target = self.run) def run(self): self.servers = get_list(self.address) + get_list2(self.address) self.finished = True def get_list(address): servers = [] try: sock = socket(AF_INET, SOCK_DGRAM) sock.settimeout(TIMEOUT) sock.sendto(PACKET_GETLIST, address) while 1: data, addr = sock.recvfrom(1024) data = data[14:] num_servers = len(data) / 6 for n in range(0, num_servers): ip = ".".join(map(str, map(ord, data[n*6:n*6+4]))) port = ord(data[n*6+5]) * 256 + ord(data[n*6+4]) servers += [[(ip, port), SERVERTYPE_LEGACY]] except: sock.close() return servers def get_list2(address): servers = [] try: sock = socket(AF_INET, SOCK_DGRAM) sock.settimeout(TIMEOUT) sock.sendto(PACKET_GETLIST2, address) while 1: data, addr = sock.recvfrom(1400) data = data[14:] num_servers = len(data) / 18 for n in range(0, num_servers): if data[n*18:n*18+12] == "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff": ip = ".".join(map(str, map(ord, data[n*18+12:n*18+16]))) else: ip = ":".join(map(str, map(ord, data[n*18:n*18+16]))) port = (ord(data[n*18+16])<<8) + ord(data[n*18+17]) servers += [[(ip, port), SERVERTYPE_NORMAL]] except: sock.close() return servers master_servers = [] for i in range(1, NUM_MASTERSERVERS+1): m = Master_Server_Info(("master%d.teeworlds.com"%i, MASTERSERVER_PORT)) master_servers.append(m) m.start() time.sleep(0.001) # avoid issues servers = [] while len(master_servers) != 0: if master_servers[0].finished == True: if master_servers[0].servers: servers += master_servers[0].servers del master_servers[0] time.sleep(0.001) # be nice servers_info = [] print str(len(servers)) + " servers" for server in servers: s = Server_Info(server[0], server[1]) servers_info.append(s) s.start() time.sleep(0.001) # avoid issues num_players = 0 num_clients = 0 while len(servers_info) != 0: if servers_info[0].finished == True: if servers_info[0].info: num_players += servers_info[0].info["num_players"] if servers_info[0].type == SERVERTYPE_NORMAL: num_clients += servers_info[0].info["num_clients"] else: num_clients += servers_info[0].info["num_players"] del servers_info[0] time.sleep(0.001) # be nice print str(num_players) + " players and " + str(num_clients-num_players) + " spectators" ================================================ FILE: scripts/twlib.py ================================================ import sys if sys.version_info[0] == 2: import urllib url_lib = urllib elif sys.version_info[0] == 3: import urllib.request url_lib = urllib.request def fetch_file(url): try: print("trying %s" % url) local = dict(url_lib.urlopen(url).info())["content-disposition"].split("=")[1] url_lib.urlretrieve(url, local) return local except: return False ================================================ FILE: scripts/update_localization.py ================================================ import os, re, sys match = re.search('(.*)/', sys.argv[0]) if match != None: os.chdir(match.group(1)) source_exts = [".c", ".cpp", ".h"] content_author = "" def parse_source(): stringtable = {} def process_line(line): if 'Localize("'.encode() in line: fields = line.split('Localize("'.encode(), 1)[1].split('"'.encode(), 1) stringtable[fields[0]] = "" process_line(fields[1]) for root, dirs, files in os.walk("src"): for name in files: filename = os.path.join(root, name) if os.sep + "external" + os.sep in filename: continue if filename[-2:] in source_exts or filename[-4:] in source_exts: for line in open(filename, "rb"): process_line(line) return stringtable def load_languagefile(filename): f = open(filename, "rb") lines = f.readlines() f.close() stringtable = {} authorpart = 0 global content_author for i in range(0, len(lines)-1): if authorpart == 0 and "\"authors\":".encode() in lines[i]: authorpart = 1 content_author = lines[i] elif authorpart == 1: if "\"translated strings\":".encode() in lines[i]: authorpart = 2 else: content_author += lines[i] elif "\"or\":".encode() in lines[i]: stringtable[lines[i].strip()[7:-2]] = lines[i+1].strip()[7:-1] return stringtable def generate_languagefile(outputfilename, srctable, loctable): f = open(outputfilename, "wb") num_items = 0 new_items = 0 old_items = 0 srctable_keys = [] for key in srctable: srctable_keys.append(key) srctable_keys.sort() content = content_author content += "\"translated strings\": [\n".encode() for k in srctable_keys: if k in loctable and len(loctable[k]): if not num_items == 0: content += ",\n".encode() content += "\t{\n\t\t\"or\": \"".encode() + k + "\",\n\t\t\"tr\": \"".encode() + loctable[k] + "\"\n\t}".encode() num_items += 1 content += "],\n".encode() content += "\"needs translation\": [\n".encode() for k in srctable_keys: if not k in loctable or len(loctable[k]) == 0: if not new_items == 0: content += ",\n".encode() content += "\t{\n\t\t\"or\": \"".encode() + k + "\",\n\t\t\"tr\": \"\"\n\t}".encode() num_items += 1 new_items += 1 content += "],\n".encode() content += "\"old translations\": [\n".encode() for k in loctable: if not k in srctable: if not old_items == 0: content += ",\n".encode() content += "\t{\n\t\t\"or\": \"".encode() + k + "\",\n\t\t\"tr\": \"".encode() + loctable[k] + "\"\n\t}".encode() num_items += 1 old_items += 1 content += "]\n}\n".encode() f.write(content) f.close() print("%-40s %8d %8d %8d" % (outputfilename, num_items, new_items, old_items)) srctable = parse_source() print("%-40s %8s %8s %8s" % ("filename", "total", "new", "old")) for filename in os.listdir("data/languages"): if not filename[-5:] == ".json" or filename == "index.json": continue filename = "data/languages/" + filename generate_languagefile(filename, srctable, load_languagefile(filename)) ================================================ FILE: src/base/detect.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef BASE_DETECT_H #define BASE_DETECT_H /* this file detected the family, platform and architecture to compile for. */ /* platforms */ /* windows Family */ #if defined(WIN64) || defined(_WIN64) /* Hmm, is this IA64 or x86-64? */ #define CONF_FAMILY_WINDOWS 1 #define CONF_FAMILY_STRING "windows" #define CONF_PLATFORM_WIN64 1 #define CONF_PLATFORM_STRING "win64" #elif defined(WIN32) || defined(_WIN32) || defined(__CYGWIN32__) || defined(__MINGW32__) #define CONF_FAMILY_WINDOWS 1 #define CONF_FAMILY_STRING "windows" #define CONF_PLATFORM_WIN32 1 #define CONF_PLATFORM_STRING "win32" #endif /* unix family */ #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) #define CONF_FAMILY_UNIX 1 #define CONF_FAMILY_STRING "unix" #define CONF_PLATFORM_FREEBSD 1 #define CONF_PLATFORM_STRING "freebsd" #endif #if defined(__OpenBSD__) #define CONF_FAMILY_UNIX 1 #define CONF_FAMILY_STRING "unix" #define CONF_PLATFORM_OPENBSD 1 #define CONF_PLATFORM_STRING "openbsd" #endif #if defined(__LINUX__) || defined(__linux__) #define CONF_FAMILY_UNIX 1 #define CONF_FAMILY_STRING "unix" #define CONF_PLATFORM_LINUX 1 #define CONF_PLATFORM_STRING "linux" #endif #if defined(__GNU__) || defined(__gnu__) #define CONF_FAMILY_UNIX 1 #define CONF_FAMILY_STRING "unix" #define CONF_PLATFORM_HURD 1 #define CONF_PLATFORM_STRING "gnu" #endif #if defined(MACOSX) || defined(__APPLE__) || defined(__DARWIN__) #define CONF_FAMILY_UNIX 1 #define CONF_FAMILY_STRING "unix" #define CONF_PLATFORM_MACOSX 1 #define CONF_PLATFORM_STRING "macosx" #endif #if defined(__sun) #define CONF_FAMILY_UNIX 1 #define CONF_FAMILY_STRING "unix" #define CONF_PLATFORM_SOLARIS 1 #define CONF_PLATFORM_STRING "solaris" #endif /* beos family */ #if defined(__BeOS) || defined(__BEOS__) #define CONF_FAMILY_BEOS 1 #define CONF_FAMILY_STRING "beos" #define CONF_PLATFORM_BEOS 1 #define CONF_PLATFORM_STRING "beos" #endif /* use gcc endianness definitions when available */ #if defined(__GNUC__) && !defined(__APPLE__) && !defined(__MINGW32__) && !defined(__sun) #if defined(__FreeBSD__) || defined(__OpenBSD__) #include <sys/endian.h> #else #include <endian.h> #endif #if __BYTE_ORDER == __LITTLE_ENDIAN #define CONF_ARCH_ENDIAN_LITTLE 1 #elif __BYTE_ORDER == __BIG_ENDIAN #define CONF_ARCH_ENDIAN_BIG 1 #endif #endif /* architectures */ #if defined(i386) || defined(__i386__) || defined(__x86__) || defined(CONF_PLATFORM_WIN32) #define CONF_ARCH_IA32 1 #define CONF_ARCH_STRING "ia32" #if !defined(CONF_ARCH_ENDIAN_LITTLE) && !defined(CONF_ARCH_ENDIAN_BIG) #define CONF_ARCH_ENDIAN_LITTLE 1 #endif #endif #if defined(__ia64__) || defined(_M_IA64) #define CONF_ARCH_IA64 1 #define CONF_ARCH_STRING "ia64" #if !defined(CONF_ARCH_ENDIAN_LITTLE) && !defined(CONF_ARCH_ENDIAN_BIG) #define CONF_ARCH_ENDIAN_LITTLE 1 #endif #endif #if defined(__amd64__) || defined(__x86_64__) || defined(_M_X64) #define CONF_ARCH_AMD64 1 #define CONF_ARCH_STRING "amd64" #if !defined(CONF_ARCH_ENDIAN_LITTLE) && !defined(CONF_ARCH_ENDIAN_BIG) #define CONF_ARCH_ENDIAN_LITTLE 1 #endif #endif #if defined(__powerpc__) || defined(__ppc__) #define CONF_ARCH_PPC 1 #define CONF_ARCH_STRING "ppc" #if !defined(CONF_ARCH_ENDIAN_LITTLE) && !defined(CONF_ARCH_ENDIAN_BIG) #define CONF_ARCH_ENDIAN_BIG 1 #endif #endif #if defined(__sparc__) #define CONF_ARCH_SPARC 1 #define CONF_ARCH_STRING "sparc" #if !defined(CONF_ARCH_ENDIAN_LITTLE) && !defined(CONF_ARCH_ENDIAN_BIG) #define CONF_ARCH_ENDIAN_BIG 1 #endif #endif #ifndef CONF_FAMILY_STRING #define CONF_FAMILY_STRING "unknown" #endif #ifndef CONF_PLATFORM_STRING #define CONF_PLATFORM_STRING "unknown" #endif #ifndef CONF_ARCH_STRING #define CONF_ARCH_STRING "unknown" #endif #endif ================================================ FILE: src/base/math.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef BASE_MATH_H #define BASE_MATH_H #include <stdlib.h> template <typename T> inline T clamp(T val, T min, T max) { if(val < min) return min; if(val > max) return max; return val; } inline float sign(float f) { return f<0.0f?-1.0f:1.0f; } inline int round(float f) { if(f > 0) return (int)(f+0.5f); return (int)(f-0.5f); } template<typename T, typename TB> inline T mix(const T a, const T b, TB amount) { return a + (b-a)*amount; } inline float frandom() { return rand()/(float)(RAND_MAX); } // float to fixed inline int f2fx(float v) { return (int)(v*(float)(1<<10)); } inline float fx2f(int v) { return v*(1.0f/(1<<10)); } inline int gcd(int a, int b) { while(b != 0) { int c = a % b; a = b; b = c; } return a; } class fxp { int value; public: void set(int v) { value = v; } int get() const { return value; } fxp &operator = (int v) { value = v<<10; return *this; } fxp &operator = (float v) { value = (int)(v*(float)(1<<10)); return *this; } operator float() const { return value/(float)(1<<10); } }; const float pi = 3.1415926535897932384626433f; template <typename T> inline T min(T a, T b) { return a<b?a:b; } template <typename T> inline T max(T a, T b) { return a>b?a:b; } template <typename T> inline T absolute(T a) { return a<T(0)?-a:a; } #endif // BASE_MATH_H ================================================ FILE: src/base/system.c ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <stdlib.h> #include <stdio.h> #include <stdarg.h> #include <string.h> #include <ctype.h> #include <time.h> #include "system.h" #if defined(CONF_FAMILY_UNIX) #include <sys/time.h> #include <unistd.h> /* unix net includes */ #include <sys/stat.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <errno.h> #include <netdb.h> #include <netinet/in.h> #include <fcntl.h> #include <pthread.h> #include <arpa/inet.h> #include <dirent.h> #if defined(CONF_PLATFORM_MACOSX) #include <Carbon/Carbon.h> #endif #elif defined(CONF_FAMILY_WINDOWS) #define WIN32_LEAN_AND_MEAN #define _WIN32_WINNT 0x0501 /* required for mingw to get getaddrinfo to work */ #include <windows.h> #include <winsock2.h> #include <ws2tcpip.h> #include <fcntl.h> #include <direct.h> #include <errno.h> #else #error NOT IMPLEMENTED #endif #if defined(CONF_PLATFORM_SOLARIS) #include <sys/filio.h> #endif #if defined(__cplusplus) extern "C" { #endif IOHANDLE io_stdin() { return (IOHANDLE)stdin; } IOHANDLE io_stdout() { return (IOHANDLE)stdout; } IOHANDLE io_stderr() { return (IOHANDLE)stderr; } static DBG_LOGGER loggers[16]; static int num_loggers = 0; static NETSTATS network_stats = {0}; static MEMSTATS memory_stats = {0}; static NETSOCKET invalid_socket = {NETTYPE_INVALID, -1, -1}; void dbg_logger(DBG_LOGGER logger) { loggers[num_loggers++] = logger; } void dbg_assert_imp(const char *filename, int line, int test, const char *msg) { if(!test) { dbg_msg("assert", "%s(%d): %s", filename, line, msg); dbg_break(); } } void dbg_break() { *((volatile unsigned*)0) = 0x0; } void dbg_msg(const char *sys, const char *fmt, ...) { va_list args; char str[1024*4]; char *msg; int i, len; str_format(str, sizeof(str), "[%08x][%s]: ", (int)time(0), sys); len = strlen(str); msg = (char *)str + len; va_start(args, fmt); #if defined(CONF_FAMILY_WINDOWS) _vsnprintf(msg, sizeof(str)-len, fmt, args); #else vsnprintf(msg, sizeof(str)-len, fmt, args); #endif va_end(args); for(i = 0; i < num_loggers; i++) loggers[i](str); } static void logger_stdout(const char *line) { printf("%s\n", line); fflush(stdout); } static void logger_debugger(const char *line) { #if defined(CONF_FAMILY_WINDOWS) OutputDebugString(line); OutputDebugString("\n"); #endif } static IOHANDLE logfile = 0; static void logger_file(const char *line) { io_write(logfile, line, strlen(line)); io_write_newline(logfile); io_flush(logfile); } void dbg_logger_stdout() { dbg_logger(logger_stdout); } void dbg_logger_debugger() { dbg_logger(logger_debugger); } void dbg_logger_file(const char *filename) { logfile = io_open(filename, IOFLAG_WRITE); if(logfile) dbg_logger(logger_file); else dbg_msg("dbg/logger", "failed to open '%s' for logging", filename); } /* */ typedef struct MEMHEADER { const char *filename; int line; int size; struct MEMHEADER *prev; struct MEMHEADER *next; } MEMHEADER; typedef struct MEMTAIL { int guard; } MEMTAIL; static struct MEMHEADER *first = 0; static const int MEM_GUARD_VAL = 0xbaadc0de; void *mem_alloc_debug(const char *filename, int line, unsigned size, unsigned alignment) { /* TODO: fix alignment */ /* TODO: add debugging */ MEMTAIL *tail; MEMHEADER *header = (struct MEMHEADER *)malloc(size+sizeof(MEMHEADER)+sizeof(MEMTAIL)); dbg_assert(header != 0, "mem_alloc failure"); if(!header) return NULL; tail = (struct MEMTAIL *)(((char*)(header+1))+size); header->size = size; header->filename = filename; header->line = line; memory_stats.allocated += header->size; memory_stats.total_allocations++; memory_stats.active_allocations++; tail->guard = MEM_GUARD_VAL; header->prev = (MEMHEADER *)0; header->next = first; if(first) first->prev = header; first = header; /*dbg_msg("mem", "++ %p", header+1); */ return header+1; } void mem_free(void *p) { if(p) { MEMHEADER *header = (MEMHEADER *)p - 1; MEMTAIL *tail = (MEMTAIL *)(((char*)(header+1))+header->size); if(tail->guard != MEM_GUARD_VAL) dbg_msg("mem", "!! %p", p); /* dbg_msg("mem", "-- %p", p); */ memory_stats.allocated -= header->size; memory_stats.active_allocations--; if(header->prev) header->prev->next = header->next; else first = header->next; if(header->next) header->next->prev = header->prev; free(header); } } void mem_debug_dump(IOHANDLE file) { char buf[1024]; MEMHEADER *header = first; if(!file) file = io_open("memory.txt", IOFLAG_WRITE); if(file) { while(header) { str_format(buf, sizeof(buf), "%s(%d): %d", header->filename, header->line, header->size); io_write(file, buf, strlen(buf)); io_write_newline(file); header = header->next; } io_close(file); } } void mem_copy(void *dest, const void *source, unsigned size) { memcpy(dest, source, size); } void mem_move(void *dest, const void *source, unsigned size) { memmove(dest, source, size); } void mem_zero(void *block,unsigned size) { memset(block, 0, size); } int mem_check_imp() { MEMHEADER *header = first; while(header) { MEMTAIL *tail = (MEMTAIL *)(((char*)(header+1))+header->size); if(tail->guard != MEM_GUARD_VAL) { dbg_msg("mem", "Memory check failed at %s(%d): %d", header->filename, header->line, header->size); return 0; } header = header->next; } return 1; } IOHANDLE io_open(const char *filename, int flags) { if(flags == IOFLAG_READ) { #if defined(CONF_FAMILY_WINDOWS) // check for filename case sensitive WIN32_FIND_DATA finddata; HANDLE handle; int length; length = str_length(filename); if(!filename || !length || filename[length-1] == '\\') return 0x0; handle = FindFirstFile(filename, &finddata); if(handle == INVALID_HANDLE_VALUE) return 0x0; else if(str_comp(filename+length-str_length(finddata.cFileName), finddata.cFileName) != 0) { FindClose(handle); return 0x0; } FindClose(handle); #endif return (IOHANDLE)fopen(filename, "rb"); } if(flags == IOFLAG_WRITE) return (IOHANDLE)fopen(filename, "wb"); return 0x0; } unsigned io_read(IOHANDLE io, void *buffer, unsigned size) { return fread(buffer, 1, size, (FILE*)io); } unsigned io_skip(IOHANDLE io, int size) { fseek((FILE*)io, size, SEEK_CUR); return size; } int io_seek(IOHANDLE io, int offset, int origin) { int real_origin; switch(origin) { case IOSEEK_START: real_origin = SEEK_SET; break; case IOSEEK_CUR: real_origin = SEEK_CUR; break; case IOSEEK_END: real_origin = SEEK_END; break; default: return -1; } return fseek((FILE*)io, offset, real_origin); } long int io_tell(IOHANDLE io) { return ftell((FILE*)io); } long int io_length(IOHANDLE io) { long int length; io_seek(io, 0, IOSEEK_END); length = io_tell(io); io_seek(io, 0, IOSEEK_START); return length; } unsigned io_write(IOHANDLE io, const void *buffer, unsigned size) { return fwrite(buffer, 1, size, (FILE*)io); } unsigned io_write_newline(IOHANDLE io) { #if defined(CONF_FAMILY_WINDOWS) return fwrite("\r\n", 1, 2, (FILE*)io); #else return fwrite("\n", 1, 1, (FILE*)io); #endif } int io_close(IOHANDLE io) { fclose((FILE*)io); return 1; } int io_flush(IOHANDLE io) { fflush((FILE*)io); return 0; } void *thread_create(void (*threadfunc)(void *), void *u) { #if defined(CONF_FAMILY_UNIX) pthread_t id; pthread_create(&id, NULL, (void *(*)(void*))threadfunc, u); return (void*)id; #elif defined(CONF_FAMILY_WINDOWS) return CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)threadfunc, u, 0, NULL); #else #error not implemented #endif } void thread_wait(void *thread) { #if defined(CONF_FAMILY_UNIX) pthread_join((pthread_t)thread, NULL); #elif defined(CONF_FAMILY_WINDOWS) WaitForSingleObject((HANDLE)thread, INFINITE); #else #error not implemented #endif } void thread_destroy(void *thread) { #if defined(CONF_FAMILY_UNIX) void *r = 0; pthread_join((pthread_t)thread, &r); #else /*#error not implemented*/ #endif } void thread_yield() { #if defined(CONF_FAMILY_UNIX) sched_yield(); #elif defined(CONF_FAMILY_WINDOWS) Sleep(0); #else #error not implemented #endif } void thread_sleep(int milliseconds) { #if defined(CONF_FAMILY_UNIX) usleep(milliseconds*1000); #elif defined(CONF_FAMILY_WINDOWS) Sleep(milliseconds); #else #error not implemented #endif } void thread_detach(void *thread) { #if defined(CONF_FAMILY_UNIX) pthread_detach((pthread_t)(thread)); #elif defined(CONF_FAMILY_WINDOWS) CloseHandle(thread); #else #error not implemented #endif } #if defined(CONF_FAMILY_UNIX) typedef pthread_mutex_t LOCKINTERNAL; #elif defined(CONF_FAMILY_WINDOWS) typedef CRITICAL_SECTION LOCKINTERNAL; #else #error not implemented on this platform #endif LOCK lock_create() { LOCKINTERNAL *lock = (LOCKINTERNAL*)mem_alloc(sizeof(LOCKINTERNAL), 4); #if defined(CONF_FAMILY_UNIX) pthread_mutex_init(lock, 0x0); #elif defined(CONF_FAMILY_WINDOWS) InitializeCriticalSection((LPCRITICAL_SECTION)lock); #else #error not implemented on this platform #endif return (LOCK)lock; } void lock_destroy(LOCK lock) { #if defined(CONF_FAMILY_UNIX) pthread_mutex_destroy((LOCKINTERNAL *)lock); #elif defined(CONF_FAMILY_WINDOWS) DeleteCriticalSection((LPCRITICAL_SECTION)lock); #else #error not implemented on this platform #endif mem_free(lock); } int lock_try(LOCK lock) { #if defined(CONF_FAMILY_UNIX) return pthread_mutex_trylock((LOCKINTERNAL *)lock); #elif defined(CONF_FAMILY_WINDOWS) return !TryEnterCriticalSection((LPCRITICAL_SECTION)lock); #else #error not implemented on this platform #endif } void lock_wait(LOCK lock) { #if defined(CONF_FAMILY_UNIX) pthread_mutex_lock((LOCKINTERNAL *)lock); #elif defined(CONF_FAMILY_WINDOWS) EnterCriticalSection((LPCRITICAL_SECTION)lock); #else #error not implemented on this platform #endif } void lock_release(LOCK lock) { #if defined(CONF_FAMILY_UNIX) pthread_mutex_unlock((LOCKINTERNAL *)lock); #elif defined(CONF_FAMILY_WINDOWS) LeaveCriticalSection((LPCRITICAL_SECTION)lock); #else #error not implemented on this platform #endif } #if !defined(CONF_PLATFORM_MACOSX) #if defined(CONF_FAMILY_UNIX) void semaphore_init(SEMAPHORE *sem) { sem_init(sem, 0, 0); } void semaphore_wait(SEMAPHORE *sem) { sem_wait(sem); } void semaphore_signal(SEMAPHORE *sem) { sem_post(sem); } void semaphore_destroy(SEMAPHORE *sem) { sem_destroy(sem); } #elif defined(CONF_FAMILY_WINDOWS) void semaphore_init(SEMAPHORE *sem) { *sem = CreateSemaphore(0, 0, 10000, 0); } void semaphore_wait(SEMAPHORE *sem) { WaitForSingleObject((HANDLE)*sem, INFINITE); } void semaphore_signal(SEMAPHORE *sem) { ReleaseSemaphore((HANDLE)*sem, 1, NULL); } void semaphore_destroy(SEMAPHORE *sem) { CloseHandle((HANDLE)*sem); } #else #error not implemented on this platform #endif #endif /* ----- time ----- */ int64 time_get() { #if defined(CONF_FAMILY_UNIX) struct timeval val; gettimeofday(&val, NULL); return (int64)val.tv_sec*(int64)1000000+(int64)val.tv_usec; #elif defined(CONF_FAMILY_WINDOWS) static int64 last = 0; int64 t; QueryPerformanceCounter((PLARGE_INTEGER)&t); if(t<last) /* for some reason, QPC can return values in the past */ return last; last = t; return t; #else #error not implemented #endif } int64 time_freq() { #if defined(CONF_FAMILY_UNIX) return 1000000; #elif defined(CONF_FAMILY_WINDOWS) int64 t; QueryPerformanceFrequency((PLARGE_INTEGER)&t); return t; #else #error not implemented #endif } /* ----- network ----- */ static void netaddr_to_sockaddr_in(const NETADDR *src, struct sockaddr_in *dest) { mem_zero(dest, sizeof(struct sockaddr_in)); if(src->type != NETTYPE_IPV4) { dbg_msg("system", "couldn't convert NETADDR of type %d to ipv4", src->type); return; } dest->sin_family = AF_INET; dest->sin_port = htons(src->port); mem_copy(&dest->sin_addr.s_addr, src->ip, 4); } static void netaddr_to_sockaddr_in6(const NETADDR *src, struct sockaddr_in6 *dest) { mem_zero(dest, sizeof(struct sockaddr_in6)); if(src->type != NETTYPE_IPV6) { dbg_msg("system", "couldn't not convert NETADDR of type %d to ipv6", src->type); return; } dest->sin6_family = AF_INET6; dest->sin6_port = htons(src->port); mem_copy(&dest->sin6_addr.s6_addr, src->ip, 16); } static void sockaddr_to_netaddr(const struct sockaddr *src, NETADDR *dst) { if(src->sa_family == AF_INET) { mem_zero(dst, sizeof(NETADDR)); dst->type = NETTYPE_IPV4; dst->port = htons(((struct sockaddr_in*)src)->sin_port); mem_copy(dst->ip, &((struct sockaddr_in*)src)->sin_addr.s_addr, 4); } else if(src->sa_family == AF_INET6) { mem_zero(dst, sizeof(NETADDR)); dst->type = NETTYPE_IPV6; dst->port = htons(((struct sockaddr_in6*)src)->sin6_port); mem_copy(dst->ip, &((struct sockaddr_in6*)src)->sin6_addr.s6_addr, 16); } else { mem_zero(dst, sizeof(struct sockaddr)); dbg_msg("system", "couldn't convert sockaddr of family %d", src->sa_family); } } int net_addr_comp(const NETADDR *a, const NETADDR *b) { return mem_comp(a, b, sizeof(NETADDR)); } void net_addr_str(const NETADDR *addr, char *string, int max_length, int add_port) { if(addr->type == NETTYPE_IPV4) { if(add_port != 0) str_format(string, max_length, "%d.%d.%d.%d:%d", addr->ip[0], addr->ip[1], addr->ip[2], addr->ip[3], addr->port); else str_format(string, max_length, "%d.%d.%d.%d", addr->ip[0], addr->ip[1], addr->ip[2], addr->ip[3]); } else if(addr->type == NETTYPE_IPV6) { if(add_port != 0) str_format(string, max_length, "[%x:%x:%x:%x:%x:%x:%x:%x]:%d", (addr->ip[0]<<8)|addr->ip[1], (addr->ip[2]<<8)|addr->ip[3], (addr->ip[4]<<8)|addr->ip[5], (addr->ip[6]<<8)|addr->ip[7], (addr->ip[8]<<8)|addr->ip[9], (addr->ip[10]<<8)|addr->ip[11], (addr->ip[12]<<8)|addr->ip[13], (addr->ip[14]<<8)|addr->ip[15], addr->port); else str_format(string, max_length, "[%x:%x:%x:%x:%x:%x:%x:%x]", (addr->ip[0]<<8)|addr->ip[1], (addr->ip[2]<<8)|addr->ip[3], (addr->ip[4]<<8)|addr->ip[5], (addr->ip[6]<<8)|addr->ip[7], (addr->ip[8]<<8)|addr->ip[9], (addr->ip[10]<<8)|addr->ip[11], (addr->ip[12]<<8)|addr->ip[13], (addr->ip[14]<<8)|addr->ip[15]); } else str_format(string, max_length, "unknown type %d", addr->type); } static int priv_net_extract(const char *hostname, char *host, int max_host, int *port) { int i; *port = 0; host[0] = 0; if(hostname[0] == '[') { // ipv6 mode for(i = 1; i < max_host && hostname[i] && hostname[i] != ']'; i++) host[i-1] = hostname[i]; host[i-1] = 0; if(hostname[i] != ']') // malformatted return -1; i++; if(hostname[i] == ':') *port = atol(hostname+i+1); } else { // generic mode (ipv4, hostname etc) for(i = 0; i < max_host-1 && hostname[i] && hostname[i] != ':'; i++) host[i] = hostname[i]; host[i] = 0; if(hostname[i] == ':') *port = atol(hostname+i+1); } return 0; } int net_host_lookup(const char *hostname, NETADDR *addr, int types) { struct addrinfo hints; struct addrinfo *result; int e; char host[256]; int port = 0; if(priv_net_extract(hostname, host, sizeof(host), &port)) return -1; /* dbg_msg("host lookup", "host='%s' port=%d %d", host, port, types); */ mem_zero(&hints, sizeof(hints)); hints.ai_family = AF_UNSPEC; if(types == NETTYPE_IPV4) hints.ai_family = AF_INET; else if(types == NETTYPE_IPV6) hints.ai_family = AF_INET6; e = getaddrinfo(host, NULL, &hints, &result); if(e != 0 || !result) return -1; sockaddr_to_netaddr(result->ai_addr, addr); freeaddrinfo(result); addr->port = port; return 0; } static int parse_int(int *out, const char **str) { int i = 0; *out = 0; if(**str < '0' || **str > '9') return -1; i = **str - '0'; (*str)++; while(1) { if(**str < '0' || **str > '9') { *out = i; return 0; } i = (i*10) + (**str - '0'); (*str)++; } return 0; } static int parse_char(char c, const char **str) { if(**str != c) return -1; (*str)++; return 0; } static int parse_uint8(unsigned char *out, const char **str) { int i; if(parse_int(&i, str) != 0) return -1; if(i < 0 || i > 0xff) return -1; *out = i; return 0; } static int parse_uint16(unsigned short *out, const char **str) { int i; if(parse_int(&i, str) != 0) return -1; if(i < 0 || i > 0xffff) return -1; *out = i; return 0; } int net_addr_from_str(NETADDR *addr, const char *string) { const char *str = string; mem_zero(addr, sizeof(NETADDR)); if(str[0] == '[') { /* ipv6 */ struct sockaddr_in6 sa6; char buf[128]; int i; str++; for(i = 0; i < 127 && str[i] && str[i] != ']'; i++) buf[i] = str[i]; buf[i] = 0; str += i; #if defined(CONF_FAMILY_WINDOWS) { int size; sa6.sin6_family = AF_INET6; size = (int)sizeof(sa6); if(WSAStringToAddress(buf, AF_INET6, NULL, (struct sockaddr *)&sa6, &size) != 0) return -1; } #else if(inet_pton(AF_INET6, buf, &sa6) != 1) return -1; #endif sockaddr_to_netaddr((struct sockaddr *)&sa6, addr); if(*str == ']') { str++; if(*str == ':') { str++; if(parse_uint16(&addr->port, &str)) return -1; } } else return -1; return 0; } else { /* ipv4 */ if(parse_uint8(&addr->ip[0], &str)) return -1; if(parse_char('.', &str)) return -1; if(parse_uint8(&addr->ip[1], &str)) return -1; if(parse_char('.', &str)) return -1; if(parse_uint8(&addr->ip[2], &str)) return -1; if(parse_char('.', &str)) return -1; if(parse_uint8(&addr->ip[3], &str)) return -1; if(*str == ':') { str++; if(parse_uint16(&addr->port, &str)) return -1; } addr->type = NETTYPE_IPV4; } return 0; } static void priv_net_close_socket(int sock) { #if defined(CONF_FAMILY_WINDOWS) closesocket(sock); #else close(sock); #endif } static int priv_net_close_all_sockets(NETSOCKET sock) { /* close down ipv4 */ if(sock.ipv4sock >= 0) { priv_net_close_socket(sock.ipv4sock); sock.ipv4sock = -1; sock.type &= ~NETTYPE_IPV4; } /* close down ipv6 */ if(sock.ipv6sock >= 0) { priv_net_close_socket(sock.ipv6sock); sock.ipv6sock = -1; sock.type &= ~NETTYPE_IPV6; } return 0; } static int priv_net_create_socket(int domain, int type, struct sockaddr *addr, int sockaddrlen) { int sock, e; /* create socket */ sock = socket(domain, type, 0); if(sock < 0) { #if defined(CONF_FAMILY_WINDOWS) char buf[128]; int error = WSAGetLastError(); if(FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS, 0, error, 0, buf, sizeof(buf), 0) == 0) buf[0] = 0; dbg_msg("net", "failed to create socket with domain %d and type %d (%d '%s')", domain, type, error, buf); #else dbg_msg("net", "failed to create socket with domain %d and type %d (%d '%s')", domain, type, errno, strerror(errno)); #endif return -1; } /* set to IPv6 only if thats what we are creating */ #if defined(IPV6_V6ONLY) /* windows sdk 6.1 and higher */ if(domain == AF_INET6) { int ipv6only = 1; setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&ipv6only, sizeof(ipv6only)); } #endif /* bind the socket */ e = bind(sock, addr, sockaddrlen); if(e != 0) { #if defined(CONF_FAMILY_WINDOWS) char buf[128]; int error = WSAGetLastError(); if(FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS, 0, error, 0, buf, sizeof(buf), 0) == 0) buf[0] = 0; dbg_msg("net", "failed to bind socket with domain %d and type %d (%d '%s')", domain, type, error, buf); #else dbg_msg("net", "failed to bind socket with domain %d and type %d (%d '%s')", domain, type, errno, strerror(errno)); #endif priv_net_close_socket(sock); return -1; } /* return the newly created socket */ return sock; } NETSOCKET net_udp_create(NETADDR bindaddr) { NETSOCKET sock = invalid_socket; NETADDR tmpbindaddr = bindaddr; int broadcast = 1; int recvsize = 65536; if(bindaddr.type&NETTYPE_IPV4) { struct sockaddr_in addr; int socket = -1; /* bind, we should check for error */ tmpbindaddr.type = NETTYPE_IPV4; netaddr_to_sockaddr_in(&tmpbindaddr, &addr); socket = priv_net_create_socket(AF_INET, SOCK_DGRAM, (struct sockaddr *)&addr, sizeof(addr)); if(socket >= 0) { sock.type |= NETTYPE_IPV4; sock.ipv4sock = socket; /* set broadcast */ setsockopt(socket, SOL_SOCKET, SO_BROADCAST, (const char*)&broadcast, sizeof(broadcast)); /* set receive buffer size */ setsockopt(socket, SOL_SOCKET, SO_RCVBUF, (char*)&recvsize, sizeof(recvsize)); } } if(bindaddr.type&NETTYPE_IPV6) { struct sockaddr_in6 addr; int socket = -1; /* bind, we should check for error */ tmpbindaddr.type = NETTYPE_IPV6; netaddr_to_sockaddr_in6(&tmpbindaddr, &addr); socket = priv_net_create_socket(AF_INET6, SOCK_DGRAM, (struct sockaddr *)&addr, sizeof(addr)); if(socket >= 0) { sock.type |= NETTYPE_IPV6; sock.ipv6sock = socket; /* set broadcast */ setsockopt(socket, SOL_SOCKET, SO_BROADCAST, (const char*)&broadcast, sizeof(broadcast)); /* set receive buffer size */ setsockopt(socket, SOL_SOCKET, SO_RCVBUF, (char*)&recvsize, sizeof(recvsize)); } } /* set non-blocking */ net_set_non_blocking(sock); /* return */ return sock; } int net_udp_send(NETSOCKET sock, const NETADDR *addr, const void *data, int size) { int d = -1; if(addr->type&NETTYPE_IPV4) { if(sock.ipv4sock >= 0) { struct sockaddr_in sa; if(addr->type&NETTYPE_LINK_BROADCAST) { mem_zero(&sa, sizeof(sa)); sa.sin_port = htons(addr->port); sa.sin_family = AF_INET; sa.sin_addr.s_addr = INADDR_BROADCAST; } else netaddr_to_sockaddr_in(addr, &sa); d = sendto((int)sock.ipv4sock, (const char*)data, size, 0, (struct sockaddr *)&sa, sizeof(sa)); } else dbg_msg("net", "can't sent ipv4 traffic to this socket"); } if(addr->type&NETTYPE_IPV6) { if(sock.ipv6sock >= 0) { struct sockaddr_in6 sa; if(addr->type&NETTYPE_LINK_BROADCAST) { mem_zero(&sa, sizeof(sa)); sa.sin6_port = htons(addr->port); sa.sin6_family = AF_INET6; sa.sin6_addr.s6_addr[0] = 0xff; /* multicast */ sa.sin6_addr.s6_addr[1] = 0x02; /* link local scope */ sa.sin6_addr.s6_addr[15] = 1; /* all nodes */ } else netaddr_to_sockaddr_in6(addr, &sa); d = sendto((int)sock.ipv6sock, (const char*)data, size, 0, (struct sockaddr *)&sa, sizeof(sa)); } else dbg_msg("net", "can't sent ipv6 traffic to this socket"); } /* else dbg_msg("net", "can't sent to network of type %d", addr->type); */ /*if(d < 0) { char addrstr[256]; net_addr_str(addr, addrstr, sizeof(addrstr)); dbg_msg("net", "sendto error (%d '%s')", errno, strerror(errno)); dbg_msg("net", "\tsock = %d %x", sock, sock); dbg_msg("net", "\tsize = %d %x", size, size); dbg_msg("net", "\taddr = %s", addrstr); }*/ network_stats.sent_bytes += size; network_stats.sent_packets++; return d; } int net_udp_recv(NETSOCKET sock, NETADDR *addr, void *data, int maxsize) { char sockaddrbuf[128]; socklen_t fromlen;// = sizeof(sockaddrbuf); int bytes = 0; if(bytes == 0 && sock.ipv4sock >= 0) { fromlen = sizeof(struct sockaddr_in); bytes = recvfrom(sock.ipv4sock, (char*)data, maxsize, 0, (struct sockaddr *)&sockaddrbuf, &fromlen); } if(bytes <= 0 && sock.ipv6sock >= 0) { fromlen = sizeof(struct sockaddr_in6); bytes = recvfrom(sock.ipv6sock, (char*)data, maxsize, 0, (struct sockaddr *)&sockaddrbuf, &fromlen); } if(bytes > 0) { sockaddr_to_netaddr((struct sockaddr *)&sockaddrbuf, addr); network_stats.recv_bytes += bytes; network_stats.recv_packets++; return bytes; } else if(bytes == 0) return 0; return -1; /* error */ } int net_udp_close(NETSOCKET sock) { return priv_net_close_all_sockets(sock); } NETSOCKET net_tcp_create(NETADDR bindaddr) { NETSOCKET sock = invalid_socket; NETADDR tmpbindaddr = bindaddr; if(bindaddr.type&NETTYPE_IPV4) { struct sockaddr_in addr; int socket = -1; /* bind, we should check for error */ tmpbindaddr.type = NETTYPE_IPV4; netaddr_to_sockaddr_in(&tmpbindaddr, &addr); socket = priv_net_create_socket(AF_INET, SOCK_STREAM, (struct sockaddr *)&addr, sizeof(addr)); if(socket >= 0) { sock.type |= NETTYPE_IPV4; sock.ipv4sock = socket; } } if(bindaddr.type&NETTYPE_IPV6) { struct sockaddr_in6 addr; int socket = -1; /* bind, we should check for error */ tmpbindaddr.type = NETTYPE_IPV6; netaddr_to_sockaddr_in6(&tmpbindaddr, &addr); socket = priv_net_create_socket(AF_INET6, SOCK_STREAM, (struct sockaddr *)&addr, sizeof(addr)); if(socket >= 0) { sock.type |= NETTYPE_IPV6; sock.ipv6sock = socket; } } /* return */ return sock; } int net_set_non_blocking(NETSOCKET sock) { unsigned long mode = 1; if(sock.ipv4sock >= 0) { #if defined(CONF_FAMILY_WINDOWS) ioctlsocket(sock.ipv4sock, FIONBIO, (unsigned long *)&mode); #else ioctl(sock.ipv4sock, FIONBIO, (unsigned long *)&mode); #endif } if(sock.ipv6sock >= 0) { #if defined(CONF_FAMILY_WINDOWS) ioctlsocket(sock.ipv6sock, FIONBIO, (unsigned long *)&mode); #else ioctl(sock.ipv6sock, FIONBIO, (unsigned long *)&mode); #endif } return 0; } int net_set_blocking(NETSOCKET sock) { unsigned long mode = 0; if(sock.ipv4sock >= 0) { #if defined(CONF_FAMILY_WINDOWS) ioctlsocket(sock.ipv4sock, FIONBIO, (unsigned long *)&mode); #else ioctl(sock.ipv4sock, FIONBIO, (unsigned long *)&mode); #endif } if(sock.ipv6sock >= 0) { #if defined(CONF_FAMILY_WINDOWS) ioctlsocket(sock.ipv6sock, FIONBIO, (unsigned long *)&mode); #else ioctl(sock.ipv6sock, FIONBIO, (unsigned long *)&mode); #endif } return 0; } int net_tcp_listen(NETSOCKET sock, int backlog) { int err = -1; if(sock.ipv4sock >= 0) err = listen(sock.ipv4sock, backlog); if(sock.ipv6sock >= 0) err = listen(sock.ipv6sock, backlog); return err; } int net_tcp_accept(NETSOCKET sock, NETSOCKET *new_sock, NETADDR *a) { int s; socklen_t sockaddr_len; *new_sock = invalid_socket; if(sock.ipv4sock >= 0) { struct sockaddr_in addr; sockaddr_len = sizeof(addr); s = accept(sock.ipv4sock, (struct sockaddr *)&addr, &sockaddr_len); if (s != -1) { sockaddr_to_netaddr((const struct sockaddr *)&addr, a); new_sock->type = NETTYPE_IPV4; new_sock->ipv4sock = s; return s; } } if(sock.ipv6sock >= 0) { struct sockaddr_in6 addr; sockaddr_len = sizeof(addr); s = accept(sock.ipv6sock, (struct sockaddr *)&addr, &sockaddr_len); if (s != -1) { sockaddr_to_netaddr((const struct sockaddr *)&addr, a); new_sock->type = NETTYPE_IPV6; new_sock->ipv6sock = s; return s; } } return -1; } int net_tcp_connect(NETSOCKET sock, const NETADDR *a) { if(a->type&NETTYPE_IPV4) { struct sockaddr_in addr; netaddr_to_sockaddr_in(a, &addr); return connect(sock.ipv4sock, (struct sockaddr *)&addr, sizeof(addr)); } if(a->type&NETTYPE_IPV6) { struct sockaddr_in6 addr; netaddr_to_sockaddr_in6(a, &addr); return connect(sock.ipv6sock, (struct sockaddr *)&addr, sizeof(addr)); } return -1; } int net_tcp_connect_non_blocking(NETSOCKET sock, NETADDR bindaddr) { int res = 0; net_set_non_blocking(sock); res = net_tcp_connect(sock, &bindaddr); net_set_blocking(sock); return res; } int net_tcp_send(NETSOCKET sock, const void *data, int size) { int bytes = -1; if(sock.ipv4sock >= 0) bytes = send((int)sock.ipv4sock, (const char*)data, size, 0); if(sock.ipv6sock >= 0) bytes = send((int)sock.ipv6sock, (const char*)data, size, 0); return bytes; } int net_tcp_recv(NETSOCKET sock, void *data, int maxsize) { int bytes = -1; if(sock.ipv4sock >= 0) bytes = recv((int)sock.ipv4sock, (char*)data, maxsize, 0); if(sock.ipv6sock >= 0) bytes = recv((int)sock.ipv6sock, (char*)data, maxsize, 0); return bytes; } int net_tcp_close(NETSOCKET sock) { return priv_net_close_all_sockets(sock); } int net_errno() { #if defined(CONF_FAMILY_WINDOWS) return WSAGetLastError(); #else return errno; #endif } int net_would_block() { #if defined(CONF_FAMILY_WINDOWS) return net_errno() == WSAEWOULDBLOCK; #else return net_errno() == EWOULDBLOCK; #endif } int net_init() { #if defined(CONF_FAMILY_WINDOWS) WSADATA wsaData; int err = WSAStartup(MAKEWORD(1, 1), &wsaData); dbg_assert(err == 0, "network initialization failed."); return err==0?0:1; #endif return 0; } int fs_listdir(const char *dir, FS_LISTDIR_CALLBACK cb, int type, void *user) { #if defined(CONF_FAMILY_WINDOWS) WIN32_FIND_DATA finddata; HANDLE handle; char buffer[1024*2]; int length; str_format(buffer, sizeof(buffer), "%s/*", dir); handle = FindFirstFileA(buffer, &finddata); if (handle == INVALID_HANDLE_VALUE) return 0; str_format(buffer, sizeof(buffer), "%s/", dir); length = str_length(buffer); /* add all the entries */ do { str_copy(buffer+length, finddata.cFileName, (int)sizeof(buffer)-length); if(cb(finddata.cFileName, fs_is_dir(buffer), type, user)) break; } while (FindNextFileA(handle, &finddata)); FindClose(handle); return 0; #else struct dirent *entry; char buffer[1024*2]; int length; DIR *d = opendir(dir); if(!d) return 0; str_format(buffer, sizeof(buffer), "%s/", dir); length = str_length(buffer); while((entry = readdir(d)) != NULL) { str_copy(buffer+length, entry->d_name, (int)sizeof(buffer)-length); if(cb(entry->d_name, fs_is_dir(buffer), type, user)) break; } /* close the directory and return */ closedir(d); return 0; #endif } int fs_storage_path(const char *appname, char *path, int max) { #if defined(CONF_FAMILY_WINDOWS) char *home = getenv("APPDATA"); if(!home) return -1; _snprintf(path, max, "%s/%s", home, appname); return 0; #else char *home = getenv("HOME"); #if !defined(CONF_PLATFORM_MACOSX) int i; #endif if(!home) return -1; #if defined(CONF_PLATFORM_MACOSX) snprintf(path, max, "%s/Library/Application Support/%s", home, appname); #else snprintf(path, max, "%s/.%s", home, appname); for(i = strlen(home)+2; path[i]; i++) path[i] = tolower(path[i]); #endif return 0; #endif } int fs_makedir(const char *path) { #if defined(CONF_FAMILY_WINDOWS) if(_mkdir(path) == 0) return 0; if(errno == EEXIST) return 0; return -1; #else if(mkdir(path, 0755) == 0) return 0; if(errno == EEXIST) return 0; return -1; #endif } int fs_is_dir(const char *path) { #if defined(CONF_FAMILY_WINDOWS) /* TODO: do this smarter */ WIN32_FIND_DATA finddata; HANDLE handle; char buffer[1024*2]; str_format(buffer, sizeof(buffer), "%s/*", path); if ((handle = FindFirstFileA(buffer, &finddata)) == INVALID_HANDLE_VALUE) return 0; FindClose(handle); return 1; #else struct stat sb; if (stat(path, &sb) == -1) return 0; if (S_ISDIR(sb.st_mode)) return 1; else return 0; #endif } int fs_chdir(const char *path) { if(fs_is_dir(path)) { if(chdir(path)) return 1; else return 0; } else return 1; } char *fs_getcwd(char *buffer, int buffer_size) { if(buffer == 0) return 0; #if defined(CONF_FAMILY_WINDOWS) return _getcwd(buffer, buffer_size); #else return getcwd(buffer, buffer_size); #endif } int fs_parent_dir(char *path) { char *parent = 0; for(; *path; ++path) { if(*path == '/' || *path == '\\') parent = path; } if(parent) { *parent = 0; return 0; } return 1; } int fs_remove(const char *filename) { if(remove(filename) != 0) return 1; return 0; } int fs_rename(const char *oldname, const char *newname) { if(rename(oldname, newname) != 0) return 1; return 0; } void swap_endian(void *data, unsigned elem_size, unsigned num) { char *src = (char*) data; char *dst = src + (elem_size - 1); while(num) { unsigned n = elem_size>>1; char tmp; while(n) { tmp = *src; *src = *dst; *dst = tmp; src++; dst--; n--; } src = src + (elem_size>>1); dst = src + (elem_size - 1); num--; } } int net_socket_read_wait(NETSOCKET sock, int time) { struct timeval tv; fd_set readfds; int sockid; tv.tv_sec = 0; tv.tv_usec = 1000*time; sockid = 0; FD_ZERO(&readfds); if(sock.ipv4sock >= 0) { FD_SET(sock.ipv4sock, &readfds); sockid = sock.ipv4sock; } if(sock.ipv6sock >= 0) { FD_SET(sock.ipv6sock, &readfds); if(sock.ipv6sock > sockid) sockid = sock.ipv6sock; } /* don't care about writefds and exceptfds */ select(sockid+1, &readfds, NULL, NULL, &tv); if(sock.ipv4sock >= 0 && FD_ISSET(sock.ipv4sock, &readfds)) return 1; if(sock.ipv6sock >= 0 && FD_ISSET(sock.ipv6sock, &readfds)) return 1; return 0; } int time_timestamp() { return time(0); } void str_append(char *dst, const char *src, int dst_size) { int s = strlen(dst); int i = 0; while(s < dst_size) { dst[s] = src[i]; if(!src[i]) /* check for null termination */ break; s++; i++; } dst[dst_size-1] = 0; /* assure null termination */ } void str_copy(char *dst, const char *src, int dst_size) { strncpy(dst, src, dst_size); dst[dst_size-1] = 0; /* assure null termination */ } int str_length(const char *str) { return (int)strlen(str); } void str_format(char *buffer, int buffer_size, const char *format, ...) { #if defined(CONF_FAMILY_WINDOWS) va_list ap; va_start(ap, format); _vsnprintf(buffer, buffer_size, format, ap); va_end(ap); #else va_list ap; va_start(ap, format); vsnprintf(buffer, buffer_size, format, ap); va_end(ap); #endif buffer[buffer_size-1] = 0; /* assure null termination */ } /* makes sure that the string only contains the characters between 32 and 127 */ void str_sanitize_strong(char *str_in) { unsigned char *str = (unsigned char *)str_in; while(*str) { *str &= 0x7f; if(*str < 32) *str = 32; str++; } } /* makes sure that the string only contains the characters between 32 and 255 */ void str_sanitize_cc(char *str_in) { unsigned char *str = (unsigned char *)str_in; while(*str) { if(*str < 32) *str = ' '; str++; } } /* makes sure that the string only contains the characters between 32 and 255 + \r\n\t */ void str_sanitize(char *str_in) { unsigned char *str = (unsigned char *)str_in; while(*str) { if(*str < 32 && !(*str == '\r') && !(*str == '\n') && !(*str == '\t')) *str = ' '; str++; } } char *str_skip_to_whitespace(char *str) { while(*str && (*str != ' ' && *str != '\t' && *str != '\n')) str++; return str; } char *str_skip_whitespaces(char *str) { while(*str && (*str == ' ' || *str == '\t' || *str == '\n' || *str == '\r')) str++; return str; } /* case */ int str_comp_nocase(const char *a, const char *b) { #if defined(CONF_FAMILY_WINDOWS) return _stricmp(a,b); #else return strcasecmp(a,b); #endif } int str_comp_nocase_num(const char *a, const char *b, const int num) { #if defined(CONF_FAMILY_WINDOWS) return _strnicmp(a, b, num); #else return strncasecmp(a, b, num); #endif } int str_comp(const char *a, const char *b) { return strcmp(a, b); } int str_comp_num(const char *a, const char *b, const int num) { return strncmp(a, b, num); } int str_comp_filenames(const char *a, const char *b) { int result; for(; *a && *b; ++a, ++b) { if(*a >= '0' && *a <= '9' && *b >= '0' && *b <= '9') { result = 0; do { if(!result) result = *a - *b; ++a; ++b; } while(*a >= '0' && *a <= '9' && *b >= '0' && *b <= '9'); if(*a >= '0' && *a <= '9') return 1; else if(*b >= '0' && *b <= '9') return -1; else if(result) return result; } if(tolower(*a) != tolower(*b)) break; } return tolower(*a) - tolower(*b); } const char *str_find_nocase(const char *haystack, const char *needle) { while(*haystack) /* native implementation */ { const char *a = haystack; const char *b = needle; while(*a && *b && tolower(*a) == tolower(*b)) { a++; b++; } if(!(*b)) return haystack; haystack++; } return 0; } const char *str_find(const char *haystack, const char *needle) { while(*haystack) /* native implementation */ { const char *a = haystack; const char *b = needle; while(*a && *b && *a == *b) { a++; b++; } if(!(*b)) return haystack; haystack++; } return 0; } void str_hex(char *dst, int dst_size, const void *data, int data_size) { static const char hex[] = "0123456789ABCDEF"; int b; for(b = 0; b < data_size && b < dst_size/4-4; b++) { dst[b*3] = hex[((const unsigned char *)data)[b]>>4]; dst[b*3+1] = hex[((const unsigned char *)data)[b]&0xf]; dst[b*3+2] = ' '; dst[b*3+3] = 0; } } void str_timestamp(char *buffer, int buffer_size) { time_t time_data; struct tm *time_info; time(&time_data); time_info = localtime(&time_data); strftime(buffer, buffer_size, "%Y-%m-%d_%H-%M-%S", time_info); buffer[buffer_size-1] = 0; /* assure null termination */ } int mem_comp(const void *a, const void *b, int size) { return memcmp(a,b,size); } const MEMSTATS *mem_stats() { return &memory_stats; } void net_stats(NETSTATS *stats_inout) { *stats_inout = network_stats; } void gui_messagebox(const char *title, const char *message) { #if defined(CONF_PLATFORM_MACOSX) DialogRef theItem; DialogItemIndex itemIndex; /* FIXME: really needed? can we rely on glfw? */ /* HACK - get events without a bundle */ ProcessSerialNumber psn; GetCurrentProcess(&psn); TransformProcessType(&psn,kProcessTransformToForegroundApplication); SetFrontProcess(&psn); /* END HACK */ CreateStandardAlert(kAlertStopAlert, CFStringCreateWithCString(NULL, title, kCFStringEncodingASCII), CFStringCreateWithCString(NULL, message, kCFStringEncodingASCII), NULL, &theItem); RunStandardAlert(theItem, NULL, &itemIndex); #elif defined(CONF_FAMILY_UNIX) static char cmd[1024]; int err; /* use xmessage which is available on nearly every X11 system */ snprintf(cmd, sizeof(cmd), "xmessage -center -title '%s' '%s'", title, message); err = system(cmd); dbg_msg("gui/msgbox", "result = %i", err); #elif defined(CONF_FAMILY_WINDOWS) MessageBox(NULL, message, title, MB_ICONEXCLAMATION | MB_OK); #else /* this is not critical */ #warning not implemented #endif } int str_isspace(char c) { return c == ' ' || c == '\n' || c == '\t'; } char str_uppercase(char c) { if(c >= 'a' && c <= 'z') return 'A' + (c-'a'); return c; } int str_toint(const char *str) { return atoi(str); } float str_tofloat(const char *str) { return atof(str); } static int str_utf8_isstart(char c) { if((c&0xC0) == 0x80) /* 10xxxxxx */ return 0; return 1; } int str_utf8_rewind(const char *str, int cursor) { while(cursor) { cursor--; if(str_utf8_isstart(*(str + cursor))) break; } return cursor; } int str_utf8_forward(const char *str, int cursor) { const char *buf = str + cursor; if(!buf[0]) return cursor; if((*buf&0x80) == 0x0) /* 0xxxxxxx */ return cursor+1; else if((*buf&0xE0) == 0xC0) /* 110xxxxx */ { if(!buf[1]) return cursor+1; return cursor+2; } else if((*buf & 0xF0) == 0xE0) /* 1110xxxx */ { if(!buf[1]) return cursor+1; if(!buf[2]) return cursor+2; return cursor+3; } else if((*buf & 0xF8) == 0xF0) /* 11110xxx */ { if(!buf[1]) return cursor+1; if(!buf[2]) return cursor+2; if(!buf[3]) return cursor+3; return cursor+4; } /* invalid */ return cursor+1; } int str_utf8_encode(char *ptr, int chr) { /* encode */ if(chr <= 0x7F) { ptr[0] = (char)chr; return 1; } else if(chr <= 0x7FF) { ptr[0] = 0xC0|((chr>>6)&0x1F); ptr[1] = 0x80|(chr&0x3F); return 2; } else if(chr <= 0xFFFF) { ptr[0] = 0xE0|((chr>>12)&0x0F); ptr[1] = 0x80|((chr>>6)&0x3F); ptr[2] = 0x80|(chr&0x3F); return 3; } else if(chr <= 0x10FFFF) { ptr[0] = 0xF0|((chr>>18)&0x07); ptr[1] = 0x80|((chr>>12)&0x3F); ptr[2] = 0x80|((chr>>6)&0x3F); ptr[3] = 0x80|(chr&0x3F); return 4; } return 0; } int str_utf8_decode(const char **ptr) { const char *buf = *ptr; int ch = 0; do { if((*buf&0x80) == 0x0) /* 0xxxxxxx */ { ch = *buf; buf++; } else if((*buf&0xE0) == 0xC0) /* 110xxxxx */ { ch = (*buf++ & 0x3F) << 6; if(!(*buf)) break; ch += (*buf++ & 0x3F); if(ch == 0) ch = -1; } else if((*buf & 0xF0) == 0xE0) /* 1110xxxx */ { ch = (*buf++ & 0x1F) << 12; if(!(*buf)) break; ch += (*buf++ & 0x3F) << 6; if(!(*buf)) break; ch += (*buf++ & 0x3F); if(ch == 0) ch = -1; } else if((*buf & 0xF8) == 0xF0) /* 11110xxx */ { ch = (*buf++ & 0x0F) << 18; if(!(*buf)) break; ch += (*buf++ & 0x3F) << 12; if(!(*buf)) break; ch += (*buf++ & 0x3F) << 6; if(!(*buf)) break; ch += (*buf++ & 0x3F); if(ch == 0) ch = -1; } else { /* invalid */ buf++; break; } *ptr = buf; return ch; } while(0); /* out of bounds */ *ptr = buf; return -1; } int str_utf8_check(const char *str) { while(*str) { if((*str&0x80) == 0x0) str++; else if((*str&0xE0) == 0xC0 && (*(str+1)&0xC0) == 0x80) str += 2; else if((*str&0xF0) == 0xE0 && (*(str+1)&0xC0) == 0x80 && (*(str+2)&0xC0) == 0x80) str += 3; else if((*str&0xF8) == 0xF0 && (*(str+1)&0xC0) == 0x80 && (*(str+2)&0xC0) == 0x80 && (*(str+3)&0xC0) == 0x80) str += 4; else return 0; } return 1; } unsigned str_quickhash(const char *str) { unsigned hash = 5381; for(; *str; str++) hash = ((hash << 5) + hash) + (*str); /* hash * 33 + c */ return hash; } #if defined(__cplusplus) } #endif ================================================ FILE: src/base/system.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ /* Title: OS Abstraction */ #ifndef BASE_SYSTEM_H #define BASE_SYSTEM_H #include "detect.h" #ifdef __cplusplus extern "C" { #endif /* Group: Debug */ /* Function: dbg_assert Breaks into the debugger based on a test. Parameters: test - Result of the test. msg - Message that should be printed if the test fails. Remarks: Does nothing in release version of the library. See Also: <dbg_break> */ void dbg_assert(int test, const char *msg); #define dbg_assert(test,msg) dbg_assert_imp(__FILE__, __LINE__, test, msg) void dbg_assert_imp(const char *filename, int line, int test, const char *msg); #ifdef __clang_analyzer__ #include <assert.h> #undef dbg_assert #define dbg_assert(test,msg) assert(test) #endif /* Function: dbg_break Breaks into the debugger. Remarks: Does nothing in release version of the library. See Also: <dbg_assert> */ void dbg_break(); /* Function: dbg_msg Prints a debug message. Parameters: sys - A string that describes what system the message belongs to fmt - A printf styled format string. Remarks: Does nothing in release version of the library. See Also: <dbg_assert> */ void dbg_msg(const char *sys, const char *fmt, ...); /* Group: Memory */ /* Function: mem_alloc Allocates memory. Parameters: size - Size of the needed block. alignment - Alignment for the block. Returns: Returns a pointer to the newly allocated block. Returns a null pointer if the memory couldn't be allocated. Remarks: - Passing 0 to size will allocated the smallest amount possible and return a unique pointer. See Also: <mem_free> */ void *mem_alloc_debug(const char *filename, int line, unsigned size, unsigned alignment); #define mem_alloc(s,a) mem_alloc_debug(__FILE__, __LINE__, (s), (a)) /* Function: mem_free Frees a block allocated through <mem_alloc>. Remarks: - In the debug version of the library the function will assert if a non-valid block is passed, like a null pointer or a block that isn't allocated. See Also: <mem_alloc> */ void mem_free(void *block); /* Function: mem_copy Copies a a memory block. Parameters: dest - Destination. source - Source to copy. size - Size of the block to copy. Remarks: - This functions DOES NOT handles cases where source and destination is overlapping. See Also: <mem_move> */ void mem_copy(void *dest, const void *source, unsigned size); /* Function: mem_move Copies a a memory block Parameters: dest - Destination source - Source to copy size - Size of the block to copy Remarks: - This functions handles cases where source and destination is overlapping See Also: <mem_copy> */ void mem_move(void *dest, const void *source, unsigned size); /* Function: mem_zero Sets a complete memory block to 0 Parameters: block - Pointer to the block to zero out size - Size of the block */ void mem_zero(void *block, unsigned size); /* Function: mem_comp Compares two blocks of memory Parameters: a - First block of data b - Second block of data size - Size of the data to compare Returns: <0 - Block a is lesser then block b 0 - Block a is equal to block b >0 - Block a is greater then block b */ int mem_comp(const void *a, const void *b, int size); /* Function: mem_check Validates the heap Will trigger a assert if memory has failed. */ int mem_check_imp(); #define mem_check() dbg_assert_imp(__FILE__, __LINE__, mem_check_imp(), "Memory check failed") /* Group: File IO */ enum { IOFLAG_READ = 1, IOFLAG_WRITE = 2, IOFLAG_RANDOM = 4, IOSEEK_START = 0, IOSEEK_CUR = 1, IOSEEK_END = 2 }; typedef struct IOINTERNAL *IOHANDLE; /* Function: io_open Opens a file. Parameters: filename - File to open. flags - A set of flags. IOFLAG_READ, IOFLAG_WRITE, IOFLAG_RANDOM. Returns: Returns a handle to the file on success and 0 on failure. */ IOHANDLE io_open(const char *filename, int flags); /* Function: io_read Reads data into a buffer from a file. Parameters: io - Handle to the file to read data from. buffer - Pointer to the buffer that will recive the data. size - Number of bytes to read from the file. Returns: Number of bytes read. */ unsigned io_read(IOHANDLE io, void *buffer, unsigned size); /* Function: io_skip Skips data in a file. Parameters: io - Handle to the file. size - Number of bytes to skip. Returns: Number of bytes skipped. */ unsigned io_skip(IOHANDLE io, int size); /* Function: io_write Writes data from a buffer to file. Parameters: io - Handle to the file. buffer - Pointer to the data that should be written. size - Number of bytes to write. Returns: Number of bytes written. */ unsigned io_write(IOHANDLE io, const void *buffer, unsigned size); /* Function: io_write_newline Writes newline to file. Parameters: io - Handle to the file. Returns: Number of bytes written. */ unsigned io_write_newline(IOHANDLE io); /* Function: io_seek Seeks to a specified offset in the file. Parameters: io - Handle to the file. offset - Offset from pos to stop. origin - Position to start searching from. Returns: Returns 0 on success. */ int io_seek(IOHANDLE io, int offset, int origin); /* Function: io_tell Gets the current position in the file. Parameters: io - Handle to the file. Returns: Returns the current position. -1L if an error occured. */ long int io_tell(IOHANDLE io); /* Function: io_length Gets the total length of the file. Resetting cursor to the beginning Parameters: io - Handle to the file. Returns: Returns the total size. -1L if an error occured. */ long int io_length(IOHANDLE io); /* Function: io_close Closes a file. Parameters: io - Handle to the file. Returns: Returns 0 on success. */ int io_close(IOHANDLE io); /* Function: io_flush Empties all buffers and writes all pending data. Parameters: io - Handle to the file. Returns: Returns 0 on success. */ int io_flush(IOHANDLE io); /* Function: io_stdin Returns an <IOHANDLE> to the standard input. */ IOHANDLE io_stdin(); /* Function: io_stdout Returns an <IOHANDLE> to the standard output. */ IOHANDLE io_stdout(); /* Function: io_stderr Returns an <IOHANDLE> to the standard error. */ IOHANDLE io_stderr(); /* Group: Threads */ /* Function: thread_sleep Suspends the current thread for a given period. Parameters: milliseconds - Number of milliseconds to sleep. */ void thread_sleep(int milliseconds); /* Function: thread_create Creates a new thread. Parameters: threadfunc - Entry point for the new thread. user - Pointer to pass to the thread. */ void *thread_create(void (*threadfunc)(void *), void *user); /* Function: thread_wait Waits for a thread to be done or destroyed. Parameters: thread - Thread to wait for. */ void thread_wait(void *thread); /* Function: thread_destroy Destroys a thread. Parameters: thread - Thread to destroy. */ void thread_destroy(void *thread); /* Function: thread_yeild Yeild the current threads execution slice. */ void thread_yield(); /* Function: thread_detach Puts the thread in the detached thread, guaranteeing that resources of the thread will be freed immediately when the thread terminates. Parameters: thread - Thread to detach */ void thread_detach(void *thread); /* Group: Locks */ typedef void* LOCK; LOCK lock_create(); void lock_destroy(LOCK lock); int lock_try(LOCK lock); void lock_wait(LOCK lock); void lock_release(LOCK lock); /* Group: Semaphores */ #if !defined(CONF_PLATFORM_MACOSX) #if defined(CONF_FAMILY_UNIX) #include <semaphore.h> typedef sem_t SEMAPHORE; #elif defined(CONF_FAMILY_WINDOWS) typedef void* SEMAPHORE; #else #error missing sempahore implementation #endif void semaphore_init(SEMAPHORE *sem); void semaphore_wait(SEMAPHORE *sem); void semaphore_signal(SEMAPHORE *sem); void semaphore_destroy(SEMAPHORE *sem); #endif /* Group: Timer */ #ifdef __GNUC__ /* if compiled with -pedantic-errors it will complain about long not being a C90 thing. */ __extension__ typedef long long int64; #else typedef long long int64; #endif /* Function: time_get Fetches a sample from a high resolution timer. Returns: Current value of the timer. Remarks: To know how fast the timer is ticking, see <time_freq>. */ int64 time_get(); /* Function: time_freq Returns the frequency of the high resolution timer. Returns: Returns the frequency of the high resolution timer. */ int64 time_freq(); /* Function: time_timestamp Retrives the current time as a UNIX timestamp Returns: The time as a UNIX timestamp */ int time_timestamp(); /* Group: Network General */ typedef struct { int type; int ipv4sock; int ipv6sock; } NETSOCKET; enum { NETADDR_MAXSTRSIZE = 1+(8*4+7)+1+1+5+1, // [XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:XXXX]:XXXXX NETTYPE_INVALID = 0, NETTYPE_IPV4 = 1, NETTYPE_IPV6 = 2, NETTYPE_LINK_BROADCAST = 4, NETTYPE_ALL = NETTYPE_IPV4|NETTYPE_IPV6 }; typedef struct { unsigned int type; unsigned char ip[16]; unsigned short port; } NETADDR; /* Function: net_init Initiates network functionallity. Returns: Returns 0 on success, Remarks: You must call this function before using any other network functions. */ int net_init(); /* Function: net_host_lookup Does a hostname lookup by name and fills out the passed NETADDR struct with the recieved details. Returns: 0 on success. */ int net_host_lookup(const char *hostname, NETADDR *addr, int types); /* Function: net_addr_comp Compares two network addresses. Parameters: a - Address to compare b - Address to compare to. Returns: <0 - Address a is lesser then address b 0 - Address a is equal to address b >0 - Address a is greater then address b */ int net_addr_comp(const NETADDR *a, const NETADDR *b); /* Function: net_addr_str Turns a network address into a representive string. Parameters: addr - Address to turn into a string. string - Buffer to fill with the string. max_length - Maximum size of the string. add_port - add port to string or not Remarks: - The string will always be zero terminated */ void net_addr_str(const NETADDR *addr, char *string, int max_length, int add_port); /* Function: net_addr_from_str Turns string into a network address. Returns: 0 on success Parameters: addr - Address to fill in. string - String to parse. */ int net_addr_from_str(NETADDR *addr, const char *string); /* Group: Network UDP */ /* Function: net_udp_create Creates a UDP socket and binds it to a port. Parameters: bindaddr - Address to bind the socket to. Returns: On success it returns an handle to the socket. On failure it returns NETSOCKET_INVALID. */ NETSOCKET net_udp_create(NETADDR bindaddr); /* Function: net_udp_send Sends a packet over an UDP socket. Parameters: sock - Socket to use. addr - Where to send the packet. data - Pointer to the packet data to send. size - Size of the packet. Returns: On success it returns the number of bytes sent. Returns -1 on error. */ int net_udp_send(NETSOCKET sock, const NETADDR *addr, const void *data, int size); /* Function: net_udp_recv Recives a packet over an UDP socket. Parameters: sock - Socket to use. addr - Pointer to an NETADDR that will recive the address. data - Pointer to a buffer that will recive the data. maxsize - Maximum size to recive. Returns: On success it returns the number of bytes recived. Returns -1 on error. */ int net_udp_recv(NETSOCKET sock, NETADDR *addr, void *data, int maxsize); /* Function: net_udp_close Closes an UDP socket. Parameters: sock - Socket to close. Returns: Returns 0 on success. -1 on error. */ int net_udp_close(NETSOCKET sock); /* Group: Network TCP */ /* Function: net_tcp_create Creates a TCP socket. Parameters: bindaddr - Address to bind the socket to. Returns: On success it returns an handle to the socket. On failure it returns NETSOCKET_INVALID. */ NETSOCKET net_tcp_create(NETADDR bindaddr); /* Function: net_tcp_listen Makes the socket start listening for new connections. Parameters: sock - Socket to start listen to. backlog - Size of the queue of incomming connections to keep. Returns: Returns 0 on success. */ int net_tcp_listen(NETSOCKET sock, int backlog); /* Function: net_tcp_accept Polls a listning socket for a new connection. Parameters: sock - Listning socket to poll. new_sock - Pointer to a socket to fill in with the new socket. addr - Pointer to an address that will be filled in the remote address (optional, can be NULL). Returns: Returns a non-negative integer on success. Negative integer on failure. */ int net_tcp_accept(NETSOCKET sock, NETSOCKET *new_sock, NETADDR *addr); /* Function: net_tcp_connect Connects one socket to another. Parameters: sock - Socket to connect. addr - Address to connect to. Returns: Returns 0 on success. */ int net_tcp_connect(NETSOCKET sock, const NETADDR *addr); /* Function: net_tcp_send Sends data to a TCP stream. Parameters: sock - Socket to send data to. data - Pointer to the data to send. size - Size of the data to send. Returns: Number of bytes sent. Negative value on failure. */ int net_tcp_send(NETSOCKET sock, const void *data, int size); /* Function: net_tcp_recv Recvives data from a TCP stream. Parameters: sock - Socket to recvive data from. data - Pointer to a buffer to write the data to max_size - Maximum of data to write to the buffer. Returns: Number of bytes recvived. Negative value on failure. When in non-blocking mode, it returns 0 when there is no more data to be fetched. */ int net_tcp_recv(NETSOCKET sock, void *data, int maxsize); /* Function: net_tcp_close Closes a TCP socket. Parameters: sock - Socket to close. Returns: Returns 0 on success. Negative value on failure. */ int net_tcp_close(NETSOCKET sock); /* Group: Strings */ /* Function: str_append Appends a string to another. Parameters: dst - Pointer to a buffer that contains a string. src - String to append. dst_size - Size of the buffer of the dst string. Remarks: - The strings are treated as zero-termineted strings. - Garantees that dst string will contain zero-termination. */ void str_append(char *dst, const char *src, int dst_size); /* Function: str_copy Copies a string to another. Parameters: dst - Pointer to a buffer that shall recive the string. src - String to be copied. dst_size - Size of the buffer dst. Remarks: - The strings are treated as zero-termineted strings. - Garantees that dst string will contain zero-termination. */ void str_copy(char *dst, const char *src, int dst_size); /* Function: str_length Returns the length of a zero terminated string. Parameters: str - Pointer to the string. Returns: Length of string in bytes excluding the zero termination. */ int str_length(const char *str); /* Function: str_format Performs printf formating into a buffer. Parameters: buffer - Pointer to the buffer to recive the formated string. buffer_size - Size of the buffer. format - printf formating string. ... - Parameters for the formating. Remarks: - See the C manual for syntax for the printf formating string. - The strings are treated as zero-termineted strings. - Garantees that dst string will contain zero-termination. */ void str_format(char *buffer, int buffer_size, const char *format, ...); /* Function: str_sanitize_strong Replaces all characters below 32 and above 127 with whitespace. Parameters: str - String to sanitize. Remarks: - The strings are treated as zero-termineted strings. */ void str_sanitize_strong(char *str); /* Function: str_sanitize_cc Replaces all characters below 32 with whitespace. Parameters: str - String to sanitize. Remarks: - The strings are treated as zero-termineted strings. */ void str_sanitize_cc(char *str); /* Function: str_sanitize Replaces all characters below 32 with whitespace with exception to \t, \n and \r. Parameters: str - String to sanitize. Remarks: - The strings are treated as zero-termineted strings. */ void str_sanitize(char *str); /* Function: str_skip_to_whitespace Skips leading non-whitespace characters(all but ' ', '\t', '\n', '\r'). Parameters: str - Pointer to the string. Returns: Pointer to the first whitespace character found within the string. Remarks: - The strings are treated as zero-termineted strings. */ char *str_skip_to_whitespace(char *str); /* Function: str_skip_whitespaces Skips leading whitespace characters(' ', '\t', '\n', '\r'). Parameters: str - Pointer to the string. Returns: Pointer to the first non-whitespace character found within the string. Remarks: - The strings are treated as zero-termineted strings. */ char *str_skip_whitespaces(char *str); /* Function: str_comp_nocase Compares to strings case insensitive. Parameters: a - String to compare. b - String to compare. Returns: <0 - String a is lesser then string b 0 - String a is equal to string b >0 - String a is greater then string b Remarks: - Only garanted to work with a-z/A-Z. - The strings are treated as zero-termineted strings. */ int str_comp_nocase(const char *a, const char *b); /* Function: str_comp_nocase_num Compares up to num characters of two strings case insensitive. Parameters: a - String to compare. b - String to compare. num - Maximum characters to compare Returns: <0 - String a is lesser than string b 0 - String a is equal to string b >0 - String a is greater than string b Remarks: - Only garanted to work with a-z/A-Z. - The strings are treated as zero-termineted strings. */ int str_comp_nocase_num(const char *a, const char *b, const int num); /* Function: str_comp Compares to strings case sensitive. Parameters: a - String to compare. b - String to compare. Returns: <0 - String a is lesser then string b 0 - String a is equal to string b >0 - String a is greater then string b Remarks: - The strings are treated as zero-termineted strings. */ int str_comp(const char *a, const char *b); /* Function: str_comp_num Compares up to num characters of two strings case sensitive. Parameters: a - String to compare. b - String to compare. num - Maximum characters to compare Returns: <0 - String a is lesser then string b 0 - String a is equal to string b >0 - String a is greater then string b Remarks: - The strings are treated as zero-termineted strings. */ int str_comp_num(const char *a, const char *b, const int num); /* Function: str_comp_filenames Compares two strings case sensitive, digit chars will be compared as numbers. Parameters: a - String to compare. b - String to compare. Returns: <0 - String a is lesser then string b 0 - String a is equal to string b >0 - String a is greater then string b Remarks: - The strings are treated as zero-termineted strings. */ int str_comp_filenames(const char *a, const char *b); /* Function: str_find_nocase Finds a string inside another string case insensitive. Parameters: haystack - String to search in needle - String to search for Returns: A pointer into haystack where the needle was found. Returns NULL of needle could not be found. Remarks: - Only garanted to work with a-z/A-Z. - The strings are treated as zero-termineted strings. */ const char *str_find_nocase(const char *haystack, const char *needle); /* Function: str_find Finds a string inside another string case sensitive. Parameters: haystack - String to search in needle - String to search for Returns: A pointer into haystack where the needle was found. Returns NULL of needle could not be found. Remarks: - The strings are treated as zero-termineted strings. */ const char *str_find(const char *haystack, const char *needle); /* Function: str_hex Takes a datablock and generates a hexstring of it. Parameters: dst - Buffer to fill with hex data dst_size - size of the buffer data - Data to turn into hex data - Size of the data Remarks: - The desination buffer will be zero-terminated */ void str_hex(char *dst, int dst_size, const void *data, int data_size); /* Function: str_timestamp Copies a time stamp in the format year-month-day_hour-minute-second to the string. Parameters: buffer - Pointer to a buffer that shall receive the time stamp string. buffer_size - Size of the buffer. Remarks: - Guarantees that buffer string will contain zero-termination. */ void str_timestamp(char *buffer, int buffer_size); /* Group: Filesystem */ /* Function: fs_listdir Lists the files in a directory Parameters: dir - Directory to list cb - Callback function to call for each entry type - Type of the directory user - Pointer to give to the callback Returns: Always returns 0. */ typedef int (*FS_LISTDIR_CALLBACK)(const char *name, int is_dir, int dir_type, void *user); int fs_listdir(const char *dir, FS_LISTDIR_CALLBACK cb, int type, void *user); /* Function: fs_makedir Creates a directory Parameters: path - Directory to create Returns: Returns 0 on success. Negative value on failure. Remarks: Does not create several directories if needed. "a/b/c" will result in a failure if b or a does not exist. */ int fs_makedir(const char *path); /* Function: fs_storage_path Fetches per user configuration directory. Returns: Returns 0 on success. Negative value on failure. Remarks: - Returns ~/.appname on UNIX based systems - Returns ~/Library/Applications Support/appname on Mac OS X - Returns %APPDATA%/Appname on Windows based systems */ int fs_storage_path(const char *appname, char *path, int max); /* Function: fs_is_dir Checks if directory exists Returns: Returns 1 on success, 0 on failure. */ int fs_is_dir(const char *path); /* Function: fs_chdir Changes current working directory Returns: Returns 0 on success, 1 on failure. */ int fs_chdir(const char *path); /* Function: fs_getcwd Gets the current working directory. Returns: Returns a pointer to the buffer on success, 0 on failure. */ char *fs_getcwd(char *buffer, int buffer_size); /* Function: fs_parent_dir Get the parent directory of a directory Parameters: path - The directory string Returns: Returns 0 on success, 1 on failure. Remarks: - The string is treated as zero-termineted string. */ int fs_parent_dir(char *path); /* Function: fs_remove Deletes the file with the specified name. Parameters: filename - The file to delete Returns: Returns 0 on success, 1 on failure. Remarks: - The strings are treated as zero-terminated strings. */ int fs_remove(const char *filename); /* Function: fs_rename Renames the file or directory. If the paths differ the file will be moved. Parameters: oldname - The actual name newname - The new name Returns: Returns 0 on success, 1 on failure. Remarks: - The strings are treated as zero-terminated strings. */ int fs_rename(const char *oldname, const char *newname); /* Group: Undocumented */ /* Function: net_tcp_connect_non_blocking DOCTODO: serp */ int net_tcp_connect_non_blocking(NETSOCKET sock, NETADDR bindaddr); /* Function: net_set_non_blocking DOCTODO: serp */ int net_set_non_blocking(NETSOCKET sock); /* Function: net_set_non_blocking DOCTODO: serp */ int net_set_blocking(NETSOCKET sock); /* Function: net_errno DOCTODO: serp */ int net_errno(); /* Function: net_would_block DOCTODO: serp */ int net_would_block(); int net_socket_read_wait(NETSOCKET sock, int time); void mem_debug_dump(IOHANDLE file); void swap_endian(void *data, unsigned elem_size, unsigned num); typedef void (*DBG_LOGGER)(const char *line); void dbg_logger(DBG_LOGGER logger); void dbg_logger_stdout(); void dbg_logger_debugger(); void dbg_logger_file(const char *filename); typedef struct { int allocated; int active_allocations; int total_allocations; } MEMSTATS; const MEMSTATS *mem_stats(); typedef struct { int sent_packets; int sent_bytes; int recv_packets; int recv_bytes; } NETSTATS; void net_stats(NETSTATS *stats); int str_toint(const char *str); float str_tofloat(const char *str); int str_isspace(char c); char str_uppercase(char c); unsigned str_quickhash(const char *str); /* Function: gui_messagebox Display plain OS-dependent message box Parameters: title - title of the message box message - text to display */ void gui_messagebox(const char *title, const char *message); /* Function: str_utf8_rewind Moves a cursor backwards in an utf8 string Parameters: str - utf8 string cursor - position in the string Returns: New cursor position. Remarks: - Won't move the cursor less then 0 */ int str_utf8_rewind(const char *str, int cursor); /* Function: str_utf8_forward Moves a cursor forwards in an utf8 string Parameters: str - utf8 string cursor - position in the string Returns: New cursor position. Remarks: - Won't move the cursor beyond the zero termination marker */ int str_utf8_forward(const char *str, int cursor); /* Function: str_utf8_decode Decodes an utf8 character Parameters: ptr - pointer to an utf8 string. this pointer will be moved forward Returns: Unicode value for the character. -1 for invalid characters and 0 for end of string. Remarks: - This function will also move the pointer forward. */ int str_utf8_decode(const char **ptr); /* Function: str_utf8_encode Encode an utf8 character Parameters: ptr - Pointer to a buffer that should recive the data. Should be able to hold at least 4 bytes. Returns: Number of bytes put into the buffer. Remarks: - Does not do zero termination of the string. */ int str_utf8_encode(char *ptr, int chr); /* Function: str_utf8_check Checks if a strings contains just valid utf8 characters. Parameters: str - Pointer to a possible utf8 string. Returns: 0 - invalid characters found. 1 - only valid characters found. Remarks: - The string is treated as zero-terminated utf8 string. */ int str_utf8_check(const char *str); #ifdef __cplusplus } #endif #endif ================================================ FILE: src/base/tl/algorithm.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef BASE_TL_ALGORITHM_H #define BASE_TL_ALGORITHM_H #include "range.h" /* insert 4 v 1 2 3 4 5 6 */ template<class R, class T> R partition_linear(R range, T value) { concept_empty::check(range); concept_forwarditeration::check(range); concept_sorted::check(range); for(; !range.empty(); range.pop_front()) { if(!(range.front() < value)) return range; } return range; } template<class R, class T> R partition_binary(R range, T value) { concept_empty::check(range); concept_index::check(range); concept_size::check(range); concept_slice::check(range); concept_sorted::check(range); if(range.empty()) return range; if(range.back() < value) return R(); while(range.size() > 1) { unsigned pivot = (range.size()-1)/2; if(range.index(pivot) < value) range = range.slice(pivot+1, range.size()-1); else range = range.slice(0, pivot+1); } return range; } template<class R, class T> R find_linear(R range, T value) { concept_empty::check(range); concept_forwarditeration::check(range); for(; !range.empty(); range.pop_front()) if(value == range.front()) break; return range; } template<class R, class T> R find_binary(R range, T value) { range = partition_linear(range, value); if(range.empty()) return range; if(range.front() == value) return range; return R(); } template<class R> void sort_bubble(R range) { concept_empty::check(range); concept_forwarditeration::check(range); concept_backwarditeration::check(range); // slow bubblesort :/ for(; !range.empty(); range.pop_back()) { R section = range; typename R::type *prev = §ion.front(); section.pop_front(); for(; !section.empty(); section.pop_front()) { typename R::type *cur = §ion.front(); if(*cur < *prev) swap(*cur, *prev); prev = cur; } } } /* template<class R> void sort_quick(R range) { concept_index::check(range); }*/ template<class R> void sort(R range) { sort_bubble(range); } template<class R> bool sort_verify(R range) { concept_empty::check(range); concept_forwarditeration::check(range); typename R::type *prev = &range.front(); range.pop_front(); for(; !range.empty(); range.pop_front()) { typename R::type *cur = &range.front(); if(*cur < *prev) return false; prev = cur; } return true; } #endif // TL_FILE_ALGORITHMS_HPP ================================================ FILE: src/base/tl/allocator.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef BASE_TL_ALLOCATOR_H #define BASE_TL_ALLOCATOR_H template <class T> class allocator_default { public: static T *alloc() { return new T; } static void free(T *p) { delete p; } static T *alloc_array(int size) { return new T [size]; } static void free_array(T *p) { delete [] p; } }; #endif // TL_FILE_ALLOCATOR_HPP ================================================ FILE: src/base/tl/array.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef BASE_TL_ARRAY_H #define BASE_TL_ARRAY_H #include "range.h" #include "allocator.h" /* Class: array Normal dynamic array class Remarks: - Grows 50% each time it needs to fit new items - Use set_size() if you know how many elements - Use optimize() to reduce the needed space. */ template <class T, class ALLOCATOR = allocator_default<T> > class array : private ALLOCATOR { void init() { list = 0x0; clear(); } public: typedef plain_range<T> range; /* Function: array constructor */ array() { init(); } /* Function: array copy constructor */ array(const array &other) { init(); set_size(other.size()); for(int i = 0; i < size(); i++) (*this)[i] = other[i]; } /* Function: array destructor */ ~array() { ALLOCATOR::free_array(list); list = 0x0; } /* Function: delete_all Remarks: - Invalidates ranges */ void delete_all() { for(int i = 0; i < size(); i++) delete list[i]; clear(); } /* Function: clear Remarks: - Invalidates ranges */ void clear() { ALLOCATOR::free_array(list); list_size = 1; list = ALLOCATOR::alloc_array(list_size); num_elements = 0; } /* Function: size */ int size() const { return num_elements; } /* Function: remove_index_fast Remarks: - Invalidates ranges */ void remove_index_fast(int index) { list[index] = list[num_elements-1]; set_size(size()-1); } /* Function: remove_fast Remarks: - Invalidates ranges */ void remove_fast(const T& item) { for(int i = 0; i < size(); i++) if(list[i] == item) { remove_index_fast(i); return; } } /* Function: remove_index Remarks: - Invalidates ranges */ void remove_index(int index) { for(int i = index+1; i < num_elements; i++) list[i-1] = list[i]; set_size(size()-1); } /* Function: remove Remarks: - Invalidates ranges */ bool remove(const T& item) { for(int i = 0; i < size(); i++) if(list[i] == item) { remove_index(i); return true; } return false; } /* Function: add Adds an item to the array. Arguments: item - Item to add. Remarks: - Invalidates ranges - See remarks about <array> how the array grows. */ int add(const T& item) { incsize(); set_size(size()+1); list[num_elements-1] = item; return num_elements-1; } /* Function: insert Inserts an item into the array at a specified location. Arguments: item - Item to insert. r - Range where to insert the item Remarks: - Invalidates ranges - See remarks about <array> how the array grows. */ int insert(const T& item, range r) { if(r.empty()) return add(item); int index = (int)(&r.front()-list); incsize(); set_size(size()+1); for(int i = num_elements-1; i > index; i--) list[i] = list[i-1]; list[index] = item; return num_elements-1; } /* Function: operator[] */ T& operator[] (int index) { return list[index]; } /* Function: const operator[] */ const T& operator[] (int index) const { return list[index]; } /* Function: base_ptr */ T *base_ptr() { return list; } /* Function: base_ptr */ const T *base_ptr() const { return list; } /* Function: set_size Resizes the array to the specified size. Arguments: new_size - The new size for the array. */ void set_size(int new_size) { if(list_size < new_size) alloc(new_size); num_elements = new_size; } /* Function: hint_size Allocates the number of elements wanted but does not increase the list size. Arguments: hint - Size to allocate. Remarks: - If the hint is smaller then the number of elements, nothing will be done. - Invalidates ranges */ void hint_size(int hint) { if(num_elements < hint) alloc(hint); } /* Function: optimize Removes unnessasary data, returns how many bytes was earned. Remarks: - Invalidates ranges */ int optimize() { int before = memusage(); alloc(num_elements); return before - memusage(); } /* Function: memusage Returns how much memory this dynamic array is using */ int memusage() { return sizeof(array) + sizeof(T)*list_size; } /* Function: operator=(array) Remarks: - Invalidates ranges */ array &operator = (const array &other) { set_size(other.size()); for(int i = 0; i < size(); i++) (*this)[i] = other[i]; return *this; } /* Function: all Returns a range that contains the whole array. */ range all() { return range(list, list+num_elements); } protected: void incsize() { if(num_elements == list_size) { if(list_size < 2) alloc(list_size+1); else alloc(list_size+list_size/2); } } void alloc(int new_len) { list_size = new_len; T *new_list = ALLOCATOR::alloc_array(list_size); int end = num_elements < list_size ? num_elements : list_size; for(int i = 0; i < end; i++) new_list[i] = list[i]; ALLOCATOR::free_array(list); num_elements = num_elements < list_size ? num_elements : list_size; list = new_list; } T *list; int list_size; int num_elements; }; #endif // TL_FILE_ARRAY_HPP ================================================ FILE: src/base/tl/base.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef BASE_TL_BASE_H #define BASE_TL_BASE_H #include <base/system.h> inline void tl_assert(bool statement) { dbg_assert(statement, "assert!"); } template<class T> inline void swap(T &a, T &b) { T c = b; b = a; a = c; } #endif ================================================ FILE: src/base/tl/range.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef BASE_TL_RANGE_H #define BASE_TL_RANGE_H #include "base.h" /* Group: Range concepts */ /* Concept: concept_empty template<class T> struct range { bool empty() const; }; */ struct concept_empty { template<typename T> static void check(T &t) { if(0) t.empty(); }; }; /* Concept: concept_index template<class T> struct range { T &index(size_t); }; */ struct concept_index { template<typename T> static void check(T &t) { if(0) t.index(0); }; }; /* Concept: concept_size template<class T> struct range { size_t size(); }; */ struct concept_size { template<typename T> static void check(T &t) { if(0) t.size(); }; }; /* Concept: concept_slice template<class T> struct range { range slice(size_t start, size_t count); }; */ struct concept_slice { template<typename T> static void check(T &t) { if(0) t.slice(0, 0); }; }; /* Concept: concept_sorted template<class T> struct range { void sorted(); }; */ struct concept_sorted { template<typename T> static void check(T &t) { if(0) t.sorted(); }; }; /* Concept: concept_forwarditeration Checks for the front and pop_front methods template<class T> struct range { void pop_front(); T &front() const; }; */ struct concept_forwarditeration { template<typename T> static void check(T &t) { if(0) { t.front(); t.pop_front(); } }; }; /* Concept: concept_backwarditeration Checks for the back and pop_back methods template<class T> struct range { void pop_back(); T &back() const; }; */ struct concept_backwarditeration { template<typename T> static void check(T &t) { if(0) { t.back(); t.pop_back(); } }; }; /* Group: Range classes */ /* Class: plain_range Concepts: <concept_empty> <concept_index> <concept_slice> <concept_forwardinteration> <concept_backwardinteration> */ template<class T> class plain_range { public: typedef T type; plain_range() { begin = 0x0; end = 0x0; } plain_range(const plain_range &r) { *this = r; } plain_range(T *b, T *e) { begin = b; end = e; } bool empty() const { return begin >= end; } void pop_front() { tl_assert(!empty()); begin++; } void pop_back() { tl_assert(!empty()); end--; } T& front() { tl_assert(!empty()); return *begin; } T& back() { tl_assert(!empty()); return *(end-1); } T& index(unsigned i) { tl_assert(i < (unsigned)(end-begin)); return begin[i]; } unsigned size() const { return (unsigned)(end-begin); } plain_range slice(unsigned startindex, unsigned endindex) { return plain_range(begin+startindex, begin+endindex); } protected: T *begin; T *end; }; /* Class: plain_range_sorted Concepts: Same as <plain_range> but with these additions: <concept_sorted> */ template<class T> class plain_range_sorted : public plain_range<T> { typedef plain_range<T> parent; public: /* sorted concept */ void sorted() const { } plain_range_sorted() {} plain_range_sorted(const plain_range_sorted &r) { *this = r; } plain_range_sorted(T *b, T *e) : parent(b, e) {} plain_range_sorted slice(unsigned start, unsigned count) { return plain_range_sorted(parent::begin+start, parent::begin+start+count); } }; template<class R> class reverse_range { private: reverse_range() {} public: typedef typename R::type type; reverse_range(R r) { range = r; } reverse_range(const reverse_range &other) { range = other.range; } bool empty() const { return range.empty(); } void pop_front() { range.pop_back(); } void pop_back() { range.pop_front(); } type& front() { return range.back(); } type& back() { return range.front(); } R range; }; template<class R> reverse_range<R> reverse(R range) { return reverse_range<R>(range); } template<class R> R reverse(reverse_range<R> range) { return range.range; } #endif // TL_FILE_RANGE_HPP ================================================ FILE: src/base/tl/sorted_array.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef BASE_TL_SORTED_ARRAY_H #define BASE_TL_SORTED_ARRAY_H #include "algorithm.h" #include "array.h" template <class T, class ALLOCATOR = allocator_default<T> > class sorted_array : public array<T, ALLOCATOR> { typedef array<T, ALLOCATOR> parent; // insert and size is not allowed int insert(const T& item, typename parent::range r) { dbg_break(); return 0; } int set_size(int new_size) { dbg_break(); return 0; } public: typedef plain_range_sorted<T> range; int add(const T& item) { return parent::insert(item, partition_binary(all(), item)); } int add_unsorted(const T& item) { return parent::add(item); } void sort_range() { sort(all()); } /* Function: all Returns a sorted range that contains the whole array. */ range all() { return range(parent::list, parent::list+parent::num_elements); } }; #endif // TL_FILE_SORTED_ARRAY_HPP ================================================ FILE: src/base/tl/string.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef BASE_TL_STRING_H #define BASE_TL_STRING_H #include "base.h" #include "allocator.h" template<class ALLOCATOR > class string_base : private ALLOCATOR { char *str; int length; void reset() { str = 0; length = 0; } void free() { ALLOCATOR::free_array(str); reset(); } void copy(const char *other_str, int other_length) { length = other_length; str = ALLOCATOR::alloc_array(length+1); mem_copy(str, other_str, length+1); } void copy(const string_base &other) { if(!other.str) return; copy(other.str, other.length); } public: string_base() { reset(); } string_base(const char *other_str) { copy(other_str, str_length(other_str)); } string_base(const string_base &other) { reset(); copy(other); } ~string_base() { free(); } string_base &operator = (const char *other) { free(); if(other) copy(other, str_length(other)); return *this; } string_base &operator = (const string_base &other) { free(); copy(other); return *this; } bool operator < (const char *other_str) const { return str_comp(str, other_str) < 0; } operator const char *() const { return str; } const char *cstr() const { return str; } }; /* normal allocated string */ typedef string_base<allocator_default<char> > string; #endif // TL_FILE_STRING_HPP ================================================ FILE: src/base/tl/threading.h ================================================ #pragma once #include "../system.h" /* atomic_inc - should return the value after increment atomic_dec - should return the value after decrement atomic_compswap - should return the value before the eventual swap sync_barrier - creates a full hardware fence */ #if defined(__GNUC__) inline unsigned atomic_inc(volatile unsigned *pValue) { return __sync_add_and_fetch(pValue, 1); } inline unsigned atomic_dec(volatile unsigned *pValue) { return __sync_add_and_fetch(pValue, -1); } inline unsigned atomic_compswap(volatile unsigned *pValue, unsigned comperand, unsigned value) { return __sync_val_compare_and_swap(pValue, comperand, value); } inline void sync_barrier() { __sync_synchronize(); } #elif defined(_MSC_VER) #include <intrin.h> #define WIN32_LEAN_AND_MEAN #include <windows.h> inline unsigned atomic_inc(volatile unsigned *pValue) { return _InterlockedIncrement((volatile long *)pValue); } inline unsigned atomic_dec(volatile unsigned *pValue) { return _InterlockedDecrement((volatile long *)pValue); } inline unsigned atomic_compswap(volatile unsigned *pValue, unsigned comperand, unsigned value) { return _InterlockedCompareExchange((volatile long *)pValue, (long)value, (long)comperand); } inline void sync_barrier() { MemoryBarrier(); } #else #error missing atomic implementation for this compiler #endif #if defined(CONF_PLATFORM_MACOSX) /* use semaphore provided by SDL on macosx */ #else class semaphore { SEMAPHORE sem; public: semaphore() { semaphore_init(&sem); } ~semaphore() { semaphore_destroy(&sem); } void wait() { semaphore_wait(&sem); } void signal() { semaphore_signal(&sem); } }; #endif class lock { friend class scope_lock; LOCK var; void take() { lock_wait(var); } void release() { lock_release(var); } public: lock() { var = lock_create(); } ~lock() { lock_destroy(var); } }; class scope_lock { lock *var; public: scope_lock(lock *l) { var = l; var->take(); } ~scope_lock() { var->release(); } }; ================================================ FILE: src/base/vmath.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef BASE_VMATH_H #define BASE_VMATH_H #include <math.h> #include "math.h" // mix // ------------------------------------ template<typename T> class vector2_base { public: union { T x,u; }; union { T y,v; }; vector2_base() {} vector2_base(float nx, float ny) { x = nx; y = ny; } vector2_base operator -() const { return vector2_base(-x, -y); } vector2_base operator -(const vector2_base &v) const { return vector2_base(x-v.x, y-v.y); } vector2_base operator +(const vector2_base &v) const { return vector2_base(x+v.x, y+v.y); } vector2_base operator *(const T v) const { return vector2_base(x*v, y*v); } vector2_base operator *(const vector2_base &v) const { return vector2_base(x*v.x, y*v.y); } vector2_base operator /(const T v) const { return vector3_base(x/v, y/v); } vector2_base operator /(const vector2_base &v) const { return vector2_base(x/v.x, y/v.y); } const vector2_base &operator =(const vector2_base &v) { x = v.x; y = v.y; return *this; } const vector2_base &operator +=(const vector2_base &v) { x += v.x; y += v.y; return *this; } const vector2_base &operator -=(const vector2_base &v) { x -= v.x; y -= v.y; return *this; } const vector2_base &operator *=(const T v) { x *= v; y *= v; return *this; } const vector2_base &operator *=(const vector2_base &v) { x *= v.x; y *= v.y; return *this; } const vector2_base &operator /=(const T v) { x /= v; y /= v; return *this; } const vector2_base &operator /=(const vector2_base &v) { x /= v.x; y /= v.y; return *this; } bool operator ==(const vector2_base &v) const { return x == v.x && y == v.y; } //TODO: do this with an eps instead operator const T* () { return &x; } }; template<typename T> inline vector2_base<T> rotate(const vector2_base<T> &a, float angle) { angle = angle * pi / 180.0f; float s = sin(angle); float c = cos(angle); return vector2_base<T>((T)(c*a.x - s*a.y), (T)(s*a.x + c*a.y)); } template<typename T> inline T length(const vector2_base<T> &a) { return sqrtf(a.x*a.x + a.y*a.y); } template<typename T> inline T distance(const vector2_base<T> a, const vector2_base<T> &b) { return length(a-b); } template<typename T> inline T dot(const vector2_base<T> a, const vector2_base<T> &b) { return a.x*b.x + a.y*b.y; } template<typename T> inline vector2_base<T> normalize(const vector2_base<T> &v) { T l = (T)(1.0f/sqrtf(v.x*v.x + v.y*v.y)); return vector2_base<T>(v.x*l, v.y*l); } typedef vector2_base<float> vec2; typedef vector2_base<bool> bvec2; typedef vector2_base<int> ivec2; template<typename T> inline vector2_base<T> closest_point_on_line(vector2_base<T> line_point0, vector2_base<T> line_point1, vector2_base<T> target_point) { vector2_base<T> c = target_point - line_point0; vector2_base<T> v = (line_point1 - line_point0); v = normalize(v); T d = length(line_point0-line_point1); T t = dot(v, c)/d; return mix(line_point0, line_point1, clamp(t, (T)0, (T)1)); /* if (t < 0) t = 0; if (t > 1.0f) return 1.0f; return t;*/ } // ------------------------------------ template<typename T> class vector3_base { public: union { T x,r,h; }; union { T y,g,s; }; union { T z,b,v,l; }; vector3_base() {} vector3_base(float nx, float ny, float nz) { x = nx; y = ny; z = nz; } const vector3_base &operator =(const vector3_base &v) { x = v.x; y = v.y; z = v.z; return *this; } vector3_base operator -(const vector3_base &v) const { return vector3_base(x-v.x, y-v.y, z-v.z); } vector3_base operator -() const { return vector3_base(-x, -y, -z); } vector3_base operator +(const vector3_base &v) const { return vector3_base(x+v.x, y+v.y, z+v.z); } vector3_base operator *(const T v) const { return vector3_base(x*v, y*v, z*v); } vector3_base operator *(const vector3_base &v) const { return vector3_base(x*v.x, y*v.y, z*v.z); } vector3_base operator /(const T v) const { return vector3_base(x/v, y/v, z/v); } vector3_base operator /(const vector3_base &v) const { return vector3_base(x/v.x, y/v.y, z/v.z); } const vector3_base &operator +=(const vector3_base &v) { x += v.x; y += v.y; z += v.z; return *this; } const vector3_base &operator -=(const vector3_base &v) { x -= v.x; y -= v.y; z -= v.z; return *this; } const vector3_base &operator *=(const T v) { x *= v; y *= v; z *= v; return *this; } const vector3_base &operator *=(const vector3_base &v) { x *= v.x; y *= v.y; z *= v.z; return *this; } const vector3_base &operator /=(const T v) { x /= v; y /= v; z /= v; return *this; } const vector3_base &operator /=(const vector3_base &v) { x /= v.x; y /= v.y; z /= v.z; return *this; } bool operator ==(const vector3_base &v) const { return x == v.x && y == v.y && z == v.z; } //TODO: do this with an eps instead operator const T* () { return &x; } }; template<typename T> inline T length(const vector3_base<T> &a) { return sqrtf(a.x*a.x + a.y*a.y + a.z*a.z); } template<typename T> inline T distance(const vector3_base<T> &a, const vector3_base<T> &b) { return length(a-b); } template<typename T> inline T dot(const vector3_base<T> &a, const vector3_base<T> &b) { return a.x*b.x + a.y*b.y + a.z*b.z; } template<typename T> inline vector3_base<T> normalize(const vector3_base<T> &v) { T l = (T)(1.0f/sqrtf(v.x*v.x + v.y*v.y + v.z*v.z)); return vector3_base<T>(v.x*l, v.y*l, v.z*l); } template<typename T> inline vector3_base<T> cross(const vector3_base<T> &a, const vector3_base<T> &b) { return vector3_base<T>( a.y*b.z - a.z*b.y, a.z*b.x - a.x*b.z, a.x*b.y - a.y*b.x); } typedef vector3_base<float> vec3; typedef vector3_base<bool> bvec3; typedef vector3_base<int> ivec3; // ------------------------------------ template<typename T> class vector4_base { public: union { T x,r; }; union { T y,g; }; union { T z,b; }; union { T w,a; }; vector4_base() {} vector4_base(float nx, float ny, float nz, float nw) { x = nx; y = ny; z = nz; w = nw; } vector4_base operator +(const vector4_base &v) const { return vector4_base(x+v.x, y+v.y, z+v.z, w+v.w); } vector4_base operator -(const vector4_base &v) const { return vector4_base(x-v.x, y-v.y, z-v.z, w-v.w); } vector4_base operator -() const { return vector4_base(-x, -y, -z, -w); } vector4_base operator *(const vector4_base &v) const { return vector4_base(x*v.x, y*v.y, z*v.z, w*v.w); } vector4_base operator *(const T v) const { return vector4_base(x*v, y*v, z*v, w*v); } vector4_base operator /(const vector4_base &v) const { return vector4_base(x/v.x, y/v.y, z/v.z, w/v.w); } vector4_base operator /(const T v) const { return vector4_base(x/v, y/v, z/v, w/v); } const vector4_base &operator =(const vector4_base &v) { x = v.x; y = v.y; z = v.z; w = v.w; return *this; } const vector4_base &operator +=(const vector4_base &v) { x += v.x; y += v.y; z += v.z; w += v.w; return *this; } const vector4_base &operator -=(const vector4_base &v) { x -= v.x; y -= v.y; z -= v.z; w -= v.w; return *this; } const vector4_base &operator *=(const T v) { x *= v; y *= v; z *= v; w *= v; return *this; } const vector4_base &operator *=(const vector4_base &v) { x *= v.x; y *= v.y; z *= v.z; w *= v.w; return *this; } const vector4_base &operator /=(const T v) { x /= v; y /= v; z /= v; w /= v; return *this; } const vector4_base &operator /=(const vector4_base &v) { x /= v.x; y /= v.y; z /= v.z; w /= v.w; return *this; } bool operator ==(const vector4_base &v) const { return x == v.x && y == v.y && z == v.z && w == v.w; } //TODO: do this with an eps instead operator const T* () { return &x; } }; typedef vector4_base<float> vec4; typedef vector4_base<bool> bvec4; typedef vector4_base<int> ivec4; #endif ================================================ FILE: src/engine/client/backend_sdl.cpp ================================================ #include "SDL.h" #include "SDL_opengl.h" #include <base/tl/threading.h> #include "graphics_threaded.h" #include "backend_sdl.h" // ------------ CGraphicsBackend_Threaded void CGraphicsBackend_Threaded::ThreadFunc(void *pUser) { #ifdef CONF_PLATFORM_MACOSX CAutoreleasePool AutoreleasePool; #endif CGraphicsBackend_Threaded *pThis = (CGraphicsBackend_Threaded *)pUser; while(!pThis->m_Shutdown) { pThis->m_Activity.wait(); if(pThis->m_pBuffer) { pThis->m_pProcessor->RunBuffer(pThis->m_pBuffer); sync_barrier(); pThis->m_pBuffer = 0x0; pThis->m_BufferDone.signal(); } } } CGraphicsBackend_Threaded::CGraphicsBackend_Threaded() { m_pBuffer = 0x0; m_pProcessor = 0x0; m_pThread = 0x0; } void CGraphicsBackend_Threaded::StartProcessor(ICommandProcessor *pProcessor) { m_Shutdown = false; m_pProcessor = pProcessor; m_pThread = thread_create(ThreadFunc, this); m_BufferDone.signal(); } void CGraphicsBackend_Threaded::StopProcessor() { m_Shutdown = true; m_Activity.signal(); thread_wait(m_pThread); thread_destroy(m_pThread); } void CGraphicsBackend_Threaded::RunBuffer(CCommandBuffer *pBuffer) { WaitForIdle(); m_pBuffer = pBuffer; m_Activity.signal(); } bool CGraphicsBackend_Threaded::IsIdle() const { return m_pBuffer == 0x0; } void CGraphicsBackend_Threaded::WaitForIdle() { while(m_pBuffer != 0x0) m_BufferDone.wait(); } // ------------ CCommandProcessorFragment_General void CCommandProcessorFragment_General::Cmd_Signal(const CCommandBuffer::SCommand_Signal *pCommand) { pCommand->m_pSemaphore->signal(); } bool CCommandProcessorFragment_General::RunCommand(const CCommandBuffer::SCommand * pBaseCommand) { switch(pBaseCommand->m_Cmd) { case CCommandBuffer::CMD_NOP: break; case CCommandBuffer::CMD_SIGNAL: Cmd_Signal(static_cast<const CCommandBuffer::SCommand_Signal *>(pBaseCommand)); break; default: return false; } return true; } // ------------ CCommandProcessorFragment_OpenGL int CCommandProcessorFragment_OpenGL::TexFormatToOpenGLFormat(int TexFormat) { if(TexFormat == CCommandBuffer::TEXFORMAT_RGB) return GL_RGB; if(TexFormat == CCommandBuffer::TEXFORMAT_ALPHA) return GL_ALPHA; if(TexFormat == CCommandBuffer::TEXFORMAT_RGBA) return GL_RGBA; return GL_RGBA; } unsigned char CCommandProcessorFragment_OpenGL::Sample(int w, int h, const unsigned char *pData, int u, int v, int Offset, int ScaleW, int ScaleH, int Bpp) { int Value = 0; for(int x = 0; x < ScaleW; x++) for(int y = 0; y < ScaleH; y++) Value += pData[((v+y)*w+(u+x))*Bpp+Offset]; return Value/(ScaleW*ScaleH); } void *CCommandProcessorFragment_OpenGL::Rescale(int Width, int Height, int NewWidth, int NewHeight, int Format, const unsigned char *pData) { unsigned char *pTmpData; int ScaleW = Width/NewWidth; int ScaleH = Height/NewHeight; int Bpp = 3; if(Format == CCommandBuffer::TEXFORMAT_RGBA) Bpp = 4; pTmpData = (unsigned char *)mem_alloc(NewWidth*NewHeight*Bpp, 1); int c = 0; for(int y = 0; y < NewHeight; y++) for(int x = 0; x < NewWidth; x++, c++) { pTmpData[c*Bpp] = Sample(Width, Height, pData, x*ScaleW, y*ScaleH, 0, ScaleW, ScaleH, Bpp); pTmpData[c*Bpp+1] = Sample(Width, Height, pData, x*ScaleW, y*ScaleH, 1, ScaleW, ScaleH, Bpp); pTmpData[c*Bpp+2] = Sample(Width, Height, pData, x*ScaleW, y*ScaleH, 2, ScaleW, ScaleH, Bpp); if(Bpp == 4) pTmpData[c*Bpp+3] = Sample(Width, Height, pData, x*ScaleW, y*ScaleH, 3, ScaleW, ScaleH, Bpp); } return pTmpData; } void CCommandProcessorFragment_OpenGL::SetState(const CCommandBuffer::SState &State) { // blend switch(State.m_BlendMode) { case CCommandBuffer::BLEND_NONE: glDisable(GL_BLEND); break; case CCommandBuffer::BLEND_ALPHA: glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); break; case CCommandBuffer::BLEND_ADDITIVE: glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE); break; default: dbg_msg("render", "unknown blendmode %d\n", State.m_BlendMode); }; // clip if(State.m_ClipEnable) { glScissor(State.m_ClipX, State.m_ClipY, State.m_ClipW, State.m_ClipH); glEnable(GL_SCISSOR_TEST); } else glDisable(GL_SCISSOR_TEST); // texture if(State.m_Texture >= 0 && State.m_Texture < CCommandBuffer::MAX_TEXTURES) { glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, m_aTextures[State.m_Texture].m_Tex); } else glDisable(GL_TEXTURE_2D); switch(State.m_WrapMode) { case CCommandBuffer::WRAP_REPEAT: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); break; case CCommandBuffer::WRAP_CLAMP: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); break; default: dbg_msg("render", "unknown wrapmode %d\n", State.m_WrapMode); }; // screen mapping glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(State.m_ScreenTL.x, State.m_ScreenBR.x, State.m_ScreenBR.y, State.m_ScreenTL.y, 1.0f, 10.f); } void CCommandProcessorFragment_OpenGL::Cmd_Init(const SCommand_Init *pCommand) { m_pTextureMemoryUsage = pCommand->m_pTextureMemoryUsage; } void CCommandProcessorFragment_OpenGL::Cmd_Texture_Update(const CCommandBuffer::SCommand_Texture_Update *pCommand) { glBindTexture(GL_TEXTURE_2D, m_aTextures[pCommand->m_Slot].m_Tex); glTexSubImage2D(GL_TEXTURE_2D, 0, pCommand->m_X, pCommand->m_Y, pCommand->m_Width, pCommand->m_Height, TexFormatToOpenGLFormat(pCommand->m_Format), GL_UNSIGNED_BYTE, pCommand->m_pData); mem_free(pCommand->m_pData); } void CCommandProcessorFragment_OpenGL::Cmd_Texture_Destroy(const CCommandBuffer::SCommand_Texture_Destroy *pCommand) { glDeleteTextures(1, &m_aTextures[pCommand->m_Slot].m_Tex); *m_pTextureMemoryUsage -= m_aTextures[pCommand->m_Slot].m_MemSize; } void CCommandProcessorFragment_OpenGL::Cmd_Texture_Create(const CCommandBuffer::SCommand_Texture_Create *pCommand) { int Width = pCommand->m_Width; int Height = pCommand->m_Height; void *pTexData = pCommand->m_pData; // resample if needed if(pCommand->m_Format == CCommandBuffer::TEXFORMAT_RGBA || pCommand->m_Format == CCommandBuffer::TEXFORMAT_RGB) { int MaxTexSize; glGetIntegerv(GL_MAX_TEXTURE_SIZE, &MaxTexSize); if(Width > MaxTexSize || Height > MaxTexSize) { do { Width>>=1; Height>>=1; } while(Width > MaxTexSize || Height > MaxTexSize); void *pTmpData = Rescale(pCommand->m_Width, pCommand->m_Height, Width, Height, pCommand->m_Format, static_cast<const unsigned char *>(pCommand->m_pData)); mem_free(pTexData); pTexData = pTmpData; } else if(Width > 16 && Height > 16 && (pCommand->m_Flags&CCommandBuffer::TEXFLAG_QUALITY) == 0) { Width>>=1; Height>>=1; void *pTmpData = Rescale(pCommand->m_Width, pCommand->m_Height, Width, Height, pCommand->m_Format, static_cast<const unsigned char *>(pCommand->m_pData)); mem_free(pTexData); pTexData = pTmpData; } } int Oglformat = TexFormatToOpenGLFormat(pCommand->m_Format); int StoreOglformat = TexFormatToOpenGLFormat(pCommand->m_StoreFormat); if(pCommand->m_Flags&CCommandBuffer::TEXFLAG_COMPRESSED) { switch(StoreOglformat) { case GL_RGB: StoreOglformat = GL_COMPRESSED_RGB_ARB; break; case GL_ALPHA: StoreOglformat = GL_COMPRESSED_ALPHA_ARB; break; case GL_RGBA: StoreOglformat = GL_COMPRESSED_RGBA_ARB; break; default: StoreOglformat = GL_COMPRESSED_RGBA_ARB; } } glGenTextures(1, &m_aTextures[pCommand->m_Slot].m_Tex); glBindTexture(GL_TEXTURE_2D, m_aTextures[pCommand->m_Slot].m_Tex); if(pCommand->m_Flags&CCommandBuffer::TEXFLAG_NOMIPMAPS) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, StoreOglformat, Width, Height, 0, Oglformat, GL_UNSIGNED_BYTE, pTexData); } else { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST); gluBuild2DMipmaps(GL_TEXTURE_2D, StoreOglformat, Width, Height, Oglformat, GL_UNSIGNED_BYTE, pTexData); } // calculate memory usage m_aTextures[pCommand->m_Slot].m_MemSize = Width*Height*pCommand->m_PixelSize; while(Width > 2 && Height > 2) { Width>>=1; Height>>=1; m_aTextures[pCommand->m_Slot].m_MemSize += Width*Height*pCommand->m_PixelSize; } *m_pTextureMemoryUsage += m_aTextures[pCommand->m_Slot].m_MemSize; mem_free(pTexData); } void CCommandProcessorFragment_OpenGL::Cmd_Clear(const CCommandBuffer::SCommand_Clear *pCommand) { glClearColor(pCommand->m_Color.r, pCommand->m_Color.g, pCommand->m_Color.b, 0.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } void CCommandProcessorFragment_OpenGL::Cmd_Render(const CCommandBuffer::SCommand_Render *pCommand) { SetState(pCommand->m_State); glVertexPointer(3, GL_FLOAT, sizeof(CCommandBuffer::SVertex), (char*)pCommand->m_pVertices); glTexCoordPointer(2, GL_FLOAT, sizeof(CCommandBuffer::SVertex), (char*)pCommand->m_pVertices + sizeof(float)*3); glColorPointer(4, GL_FLOAT, sizeof(CCommandBuffer::SVertex), (char*)pCommand->m_pVertices + sizeof(float)*5); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glEnableClientState(GL_COLOR_ARRAY); switch(pCommand->m_PrimType) { case CCommandBuffer::PRIMTYPE_QUADS: glDrawArrays(GL_QUADS, 0, pCommand->m_PrimCount*4); break; case CCommandBuffer::PRIMTYPE_LINES: glDrawArrays(GL_LINES, 0, pCommand->m_PrimCount*2); break; default: dbg_msg("render", "unknown primtype %d\n", pCommand->m_Cmd); }; } void CCommandProcessorFragment_OpenGL::Cmd_Screenshot(const CCommandBuffer::SCommand_Screenshot *pCommand) { // fetch image data GLint aViewport[4] = {0,0,0,0}; glGetIntegerv(GL_VIEWPORT, aViewport); int w = aViewport[2]; int h = aViewport[3]; // we allocate one more row to use when we are flipping the texture unsigned char *pPixelData = (unsigned char *)mem_alloc(w*(h+1)*3, 1); unsigned char *pTempRow = pPixelData+w*h*3; // fetch the pixels GLint Alignment; glGetIntegerv(GL_PACK_ALIGNMENT, &Alignment); glPixelStorei(GL_PACK_ALIGNMENT, 1); glReadPixels(0,0, w, h, GL_RGB, GL_UNSIGNED_BYTE, pPixelData); glPixelStorei(GL_PACK_ALIGNMENT, Alignment); // flip the pixel because opengl works from bottom left corner for(int y = 0; y < h/2; y++) { mem_copy(pTempRow, pPixelData+y*w*3, w*3); mem_copy(pPixelData+y*w*3, pPixelData+(h-y-1)*w*3, w*3); mem_copy(pPixelData+(h-y-1)*w*3, pTempRow,w*3); } // fill in the information pCommand->m_pImage->m_Width = w; pCommand->m_pImage->m_Height = h; pCommand->m_pImage->m_Format = CImageInfo::FORMAT_RGB; pCommand->m_pImage->m_pData = pPixelData; } CCommandProcessorFragment_OpenGL::CCommandProcessorFragment_OpenGL() { mem_zero(m_aTextures, sizeof(m_aTextures)); m_pTextureMemoryUsage = 0; } bool CCommandProcessorFragment_OpenGL::RunCommand(const CCommandBuffer::SCommand * pBaseCommand) { switch(pBaseCommand->m_Cmd) { case CMD_INIT: Cmd_Init(static_cast<const SCommand_Init *>(pBaseCommand)); break; case CCommandBuffer::CMD_TEXTURE_CREATE: Cmd_Texture_Create(static_cast<const CCommandBuffer::SCommand_Texture_Create *>(pBaseCommand)); break; case CCommandBuffer::CMD_TEXTURE_DESTROY: Cmd_Texture_Destroy(static_cast<const CCommandBuffer::SCommand_Texture_Destroy *>(pBaseCommand)); break; case CCommandBuffer::CMD_TEXTURE_UPDATE: Cmd_Texture_Update(static_cast<const CCommandBuffer::SCommand_Texture_Update *>(pBaseCommand)); break; case CCommandBuffer::CMD_CLEAR: Cmd_Clear(static_cast<const CCommandBuffer::SCommand_Clear *>(pBaseCommand)); break; case CCommandBuffer::CMD_RENDER: Cmd_Render(static_cast<const CCommandBuffer::SCommand_Render *>(pBaseCommand)); break; case CCommandBuffer::CMD_SCREENSHOT: Cmd_Screenshot(static_cast<const CCommandBuffer::SCommand_Screenshot *>(pBaseCommand)); break; default: return false; } return true; } // ------------ CCommandProcessorFragment_SDL void CCommandProcessorFragment_SDL::Cmd_Init(const SCommand_Init *pCommand) { m_GLContext = pCommand->m_Context; GL_MakeCurrent(m_GLContext); // set some default settings glEnable(GL_BLEND); glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glAlphaFunc(GL_GREATER, 0); glEnable(GL_ALPHA_TEST); glDepthMask(0); } void CCommandProcessorFragment_SDL::Cmd_Shutdown(const SCommand_Shutdown *pCommand) { GL_ReleaseContext(m_GLContext); } void CCommandProcessorFragment_SDL::Cmd_Swap(const CCommandBuffer::SCommand_Swap *pCommand) { GL_SwapBuffers(m_GLContext); if(pCommand->m_Finish) glFinish(); } void CCommandProcessorFragment_SDL::Cmd_VideoModes(const CCommandBuffer::SCommand_VideoModes *pCommand) { // TODO: fix this code on osx or windows SDL_Rect **ppModes = SDL_ListModes(NULL, SDL_OPENGL|SDL_GL_DOUBLEBUFFER|SDL_FULLSCREEN); if(ppModes == NULL) { // no modes *pCommand->m_pNumModes = 0; } else if(ppModes == (SDL_Rect**)-1) { // no modes *pCommand->m_pNumModes = 0; } else { int NumModes = 0; for(int i = 0; ppModes[i]; ++i) { if(NumModes == pCommand->m_MaxModes) break; pCommand->m_pModes[NumModes].m_Width = ppModes[i]->w; pCommand->m_pModes[NumModes].m_Height = ppModes[i]->h; pCommand->m_pModes[NumModes].m_Red = 8; pCommand->m_pModes[NumModes].m_Green = 8; pCommand->m_pModes[NumModes].m_Blue = 8; NumModes++; } *pCommand->m_pNumModes = NumModes; } } CCommandProcessorFragment_SDL::CCommandProcessorFragment_SDL() { } bool CCommandProcessorFragment_SDL::RunCommand(const CCommandBuffer::SCommand *pBaseCommand) { switch(pBaseCommand->m_Cmd) { case CCommandBuffer::CMD_SWAP: Cmd_Swap(static_cast<const CCommandBuffer::SCommand_Swap *>(pBaseCommand)); break; case CCommandBuffer::CMD_VIDEOMODES: Cmd_VideoModes(static_cast<const CCommandBuffer::SCommand_VideoModes *>(pBaseCommand)); break; case CMD_INIT: Cmd_Init(static_cast<const SCommand_Init *>(pBaseCommand)); break; case CMD_SHUTDOWN: Cmd_Shutdown(static_cast<const SCommand_Shutdown *>(pBaseCommand)); break; default: return false; } return true; } // ------------ CCommandProcessor_SDL_OpenGL void CCommandProcessor_SDL_OpenGL::RunBuffer(CCommandBuffer *pBuffer) { unsigned CmdIndex = 0; while(1) { const CCommandBuffer::SCommand *pBaseCommand = pBuffer->GetCommand(&CmdIndex); if(pBaseCommand == 0x0) break; if(m_OpenGL.RunCommand(pBaseCommand)) continue; if(m_SDL.RunCommand(pBaseCommand)) continue; if(m_General.RunCommand(pBaseCommand)) continue; dbg_msg("graphics", "unknown command %d", pBaseCommand->m_Cmd); } } // ------------ CGraphicsBackend_SDL_OpenGL int CGraphicsBackend_SDL_OpenGL::Init(const char *pName, int *Width, int *Height, int FsaaSamples, int Flags, int *pDesktopWidth, int *pDesktopHeight) { if(!SDL_WasInit(SDL_INIT_VIDEO)) { if(SDL_InitSubSystem(SDL_INIT_VIDEO) < 0) { dbg_msg("gfx", "unable to init SDL video: %s", SDL_GetError()); return -1; } #ifdef CONF_FAMILY_WINDOWS if(!getenv("SDL_VIDEO_WINDOW_POS") && !getenv("SDL_VIDEO_CENTERED")) // ignore_convention putenv("SDL_VIDEO_WINDOW_POS=8,27"); // ignore_convention #endif } const SDL_VideoInfo *pInfo = SDL_GetVideoInfo(); SDL_EventState(SDL_MOUSEMOTION, SDL_IGNORE); // prevent stuck mouse cursor sdl-bug when loosing fullscreen focus in windows // use current resolution as default if(*Width == 0 || *Height == 0) { *Width = pInfo->current_w; *Height = pInfo->current_h; } // store desktop resolution for settings reset button *pDesktopWidth = pInfo->current_w; *pDesktopHeight = pInfo->current_h; // set flags int SdlFlags = SDL_OPENGL; if(Flags&IGraphicsBackend::INITFLAG_RESIZABLE) SdlFlags |= SDL_RESIZABLE; if(pInfo->hw_available) // ignore_convention SdlFlags |= SDL_HWSURFACE; else SdlFlags |= SDL_SWSURFACE; if(pInfo->blit_hw) // ignore_convention SdlFlags |= SDL_HWACCEL; dbg_assert(!(Flags&IGraphicsBackend::INITFLAG_BORDERLESS) || !(Flags&IGraphicsBackend::INITFLAG_FULLSCREEN), "only one of borderless and fullscreen may be activated at the same time"); if(Flags&IGraphicsBackend::INITFLAG_BORDERLESS) SdlFlags |= SDL_NOFRAME; if(Flags&IGraphicsBackend::INITFLAG_FULLSCREEN) SdlFlags |= SDL_FULLSCREEN; // set gl attributes if(FsaaSamples) { SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, FsaaSamples); } else { SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0); } SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, Flags&IGraphicsBackend::INITFLAG_VSYNC ? 1 : 0); // set caption SDL_WM_SetCaption(pName, pName); // create window m_pScreenSurface = SDL_SetVideoMode(*Width, *Height, 0, SdlFlags); if(!m_pScreenSurface) { dbg_msg("gfx", "unable to set video mode: %s", SDL_GetError()); //*pCommand->m_pResult = -1; return -1; } SDL_ShowCursor(0); // fetch gl contexts and release the context from this thread m_GLContext = GL_GetCurrentContext(); GL_ReleaseContext(m_GLContext); // start the command processor m_pProcessor = new CCommandProcessor_SDL_OpenGL; StartProcessor(m_pProcessor); // issue init commands for OpenGL and SDL CCommandBuffer CmdBuffer(1024, 512); CCommandProcessorFragment_OpenGL::SCommand_Init CmdOpenGL; CmdOpenGL.m_pTextureMemoryUsage = &m_TextureMemoryUsage; CmdBuffer.AddCommand(CmdOpenGL); CCommandProcessorFragment_SDL::SCommand_Init CmdSDL; CmdSDL.m_Context = m_GLContext; CmdBuffer.AddCommand(CmdSDL); RunBuffer(&CmdBuffer); WaitForIdle(); // return return 0; } int CGraphicsBackend_SDL_OpenGL::Shutdown() { // issue a shutdown command CCommandBuffer CmdBuffer(1024, 512); CCommandProcessorFragment_SDL::SCommand_Shutdown Cmd; CmdBuffer.AddCommand(Cmd); RunBuffer(&CmdBuffer); WaitForIdle(); // stop and delete the processor StopProcessor(); delete m_pProcessor; m_pProcessor = 0; SDL_QuitSubSystem(SDL_INIT_VIDEO); return 0; } int CGraphicsBackend_SDL_OpenGL::MemoryUsage() const { return m_TextureMemoryUsage; } void CGraphicsBackend_SDL_OpenGL::Minimize() { SDL_WM_IconifyWindow(); } void CGraphicsBackend_SDL_OpenGL::Maximize() { // TODO: SDL } int CGraphicsBackend_SDL_OpenGL::WindowActive() { return SDL_GetAppState()&SDL_APPINPUTFOCUS; } int CGraphicsBackend_SDL_OpenGL::WindowOpen() { return SDL_GetAppState()&SDL_APPACTIVE; } IGraphicsBackend *CreateGraphicsBackend() { return new CGraphicsBackend_SDL_OpenGL; } ================================================ FILE: src/engine/client/backend_sdl.h ================================================ #pragma once #include "graphics_threaded.h" // platform dependent implementations for transfering render context from the main thread to the graphics thread // TODO: when SDL 1.3 comes, this can be removed #if defined(CONF_FAMILY_WINDOWS) struct SGLContext { HDC m_hDC; HGLRC m_hGLRC; }; static SGLContext GL_GetCurrentContext() { SGLContext Context; Context.m_hDC = wglGetCurrentDC(); Context.m_hGLRC = wglGetCurrentContext(); return Context; } static void GL_MakeCurrent(const SGLContext &Context) { wglMakeCurrent(Context.m_hDC, Context.m_hGLRC); } static void GL_ReleaseContext(const SGLContext &Context) { wglMakeCurrent(NULL, NULL); } static void GL_SwapBuffers(const SGLContext &Context) { SwapBuffers(Context.m_hDC); } #elif defined(CONF_PLATFORM_MACOSX) #include <objc/objc-runtime.h> class semaphore { SDL_sem *sem; public: semaphore() { sem = SDL_CreateSemaphore(0); } ~semaphore() { SDL_DestroySemaphore(sem); } void wait() { SDL_SemWait(sem); } void signal() { SDL_SemPost(sem); } }; struct SGLContext { id m_Context; }; static SGLContext GL_GetCurrentContext() { SGLContext Context; Class NSOpenGLContextClass = (Class) objc_getClass("NSOpenGLContext"); SEL selector = sel_registerName("currentContext"); Context.m_Context = objc_msgSend((objc_object*) NSOpenGLContextClass, selector); return Context; } static void GL_MakeCurrent(const SGLContext &Context) { SEL selector = sel_registerName("makeCurrentContext"); objc_msgSend(Context.m_Context, selector); } static void GL_ReleaseContext(const SGLContext &Context) { Class NSOpenGLContextClass = (Class) objc_getClass("NSOpenGLContext"); SEL selector = sel_registerName("clearCurrentContext"); objc_msgSend((objc_object*) NSOpenGLContextClass, selector); } static void GL_SwapBuffers(const SGLContext &Context) { SEL selector = sel_registerName("flushBuffer"); objc_msgSend(Context.m_Context, selector); } class CAutoreleasePool { private: id m_Pool; public: CAutoreleasePool() { Class NSAutoreleasePoolClass = (Class) objc_getClass("NSAutoreleasePool"); m_Pool = class_createInstance(NSAutoreleasePoolClass, 0); SEL selector = sel_registerName("init"); objc_msgSend(m_Pool, selector); } ~CAutoreleasePool() { SEL selector = sel_registerName("drain"); objc_msgSend(m_Pool, selector); } }; #elif defined(CONF_FAMILY_UNIX) #include <GL/glx.h> struct SGLContext { Display *m_pDisplay; GLXDrawable m_Drawable; GLXContext m_Context; }; static SGLContext GL_GetCurrentContext() { SGLContext Context; Context.m_pDisplay = glXGetCurrentDisplay(); Context.m_Drawable = glXGetCurrentDrawable(); Context.m_Context = glXGetCurrentContext(); return Context; } static void GL_MakeCurrent(const SGLContext &Context) { glXMakeCurrent(Context.m_pDisplay, Context.m_Drawable, Context.m_Context); } static void GL_ReleaseContext(const SGLContext &Context) { glXMakeCurrent(Context.m_pDisplay, None, 0x0); } static void GL_SwapBuffers(const SGLContext &Context) { glXSwapBuffers(Context.m_pDisplay, Context.m_Drawable); } #else #error missing implementation #endif // basic threaded backend, abstract, missing init and shutdown functions class CGraphicsBackend_Threaded : public IGraphicsBackend { public: // constructed on the main thread, the rest of the functions is runned on the render thread class ICommandProcessor { public: virtual ~ICommandProcessor() {} virtual void RunBuffer(CCommandBuffer *pBuffer) = 0; }; CGraphicsBackend_Threaded(); virtual void RunBuffer(CCommandBuffer *pBuffer); virtual bool IsIdle() const; virtual void WaitForIdle(); protected: void StartProcessor(ICommandProcessor *pProcessor); void StopProcessor(); private: ICommandProcessor *m_pProcessor; CCommandBuffer * volatile m_pBuffer; volatile bool m_Shutdown; semaphore m_Activity; semaphore m_BufferDone; void *m_pThread; static void ThreadFunc(void *pUser); }; // takes care of implementation independent operations class CCommandProcessorFragment_General { void Cmd_Nop(); void Cmd_Signal(const CCommandBuffer::SCommand_Signal *pCommand); public: bool RunCommand(const CCommandBuffer::SCommand * pBaseCommand); }; // takes care of opengl related rendering class CCommandProcessorFragment_OpenGL { struct CTexture { GLuint m_Tex; int m_MemSize; }; CTexture m_aTextures[CCommandBuffer::MAX_TEXTURES]; volatile int *m_pTextureMemoryUsage; public: enum { CMD_INIT = CCommandBuffer::CMDGROUP_PLATFORM_OPENGL, }; struct SCommand_Init : public CCommandBuffer::SCommand { SCommand_Init() : SCommand(CMD_INIT) {} volatile int *m_pTextureMemoryUsage; }; private: static int TexFormatToOpenGLFormat(int TexFormat); static unsigned char Sample(int w, int h, const unsigned char *pData, int u, int v, int Offset, int ScaleW, int ScaleH, int Bpp); static void *Rescale(int Width, int Height, int NewWidth, int NewHeight, int Format, const unsigned char *pData); void SetState(const CCommandBuffer::SState &State); void Cmd_Init(const SCommand_Init *pCommand); void Cmd_Texture_Update(const CCommandBuffer::SCommand_Texture_Update *pCommand); void Cmd_Texture_Destroy(const CCommandBuffer::SCommand_Texture_Destroy *pCommand); void Cmd_Texture_Create(const CCommandBuffer::SCommand_Texture_Create *pCommand); void Cmd_Clear(const CCommandBuffer::SCommand_Clear *pCommand); void Cmd_Render(const CCommandBuffer::SCommand_Render *pCommand); void Cmd_Screenshot(const CCommandBuffer::SCommand_Screenshot *pCommand); public: CCommandProcessorFragment_OpenGL(); bool RunCommand(const CCommandBuffer::SCommand * pBaseCommand); }; // takes care of sdl related commands class CCommandProcessorFragment_SDL { // SDL stuff SGLContext m_GLContext; public: enum { CMD_INIT = CCommandBuffer::CMDGROUP_PLATFORM_SDL, CMD_SHUTDOWN, }; struct SCommand_Init : public CCommandBuffer::SCommand { SCommand_Init() : SCommand(CMD_INIT) {} SGLContext m_Context; }; struct SCommand_Shutdown : public CCommandBuffer::SCommand { SCommand_Shutdown() : SCommand(CMD_SHUTDOWN) {} }; private: void Cmd_Init(const SCommand_Init *pCommand); void Cmd_Shutdown(const SCommand_Shutdown *pCommand); void Cmd_Swap(const CCommandBuffer::SCommand_Swap *pCommand); void Cmd_VideoModes(const CCommandBuffer::SCommand_VideoModes *pCommand); public: CCommandProcessorFragment_SDL(); bool RunCommand(const CCommandBuffer::SCommand *pBaseCommand); }; // command processor impelementation, uses the fragments to combine into one processor class CCommandProcessor_SDL_OpenGL : public CGraphicsBackend_Threaded::ICommandProcessor { CCommandProcessorFragment_OpenGL m_OpenGL; CCommandProcessorFragment_SDL m_SDL; CCommandProcessorFragment_General m_General; public: virtual void RunBuffer(CCommandBuffer *pBuffer); }; // graphics backend implemented with SDL and OpenGL class CGraphicsBackend_SDL_OpenGL : public CGraphicsBackend_Threaded { SDL_Surface *m_pScreenSurface; ICommandProcessor *m_pProcessor; SGLContext m_GLContext; volatile int m_TextureMemoryUsage; public: virtual int Init(const char *pName, int *Width, int *Height, int FsaaSamples, int Flags, int *pDesktopWidth, int *pDesktopHeight); virtual int Shutdown(); virtual int MemoryUsage() const; virtual void Minimize(); virtual void Maximize(); virtual int WindowActive(); virtual int WindowOpen(); }; ================================================ FILE: src/engine/client/client.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <new> #include <stdlib.h> // qsort #include <stdarg.h> #include <base/math.h> #include <base/system.h> #include <engine/client.h> #include <engine/config.h> #include <engine/console.h> #include <engine/editor.h> #include <engine/engine.h> #include <engine/graphics.h> #include <engine/input.h> #include <engine/keys.h> #include <engine/map.h> #include <engine/masterserver.h> #include <engine/serverbrowser.h> #include <engine/sound.h> #include <engine/storage.h> #include <engine/textrender.h> #include <engine/shared/config.h> #include <engine/shared/compression.h> #include <engine/shared/datafile.h> #include <engine/shared/demo.h> #include <engine/shared/filecollection.h> #include <engine/shared/mapchecker.h> #include <engine/shared/network.h> #include <engine/shared/packer.h> #include <engine/shared/protocol.h> #include <engine/shared/ringbuffer.h> #include <engine/shared/snapshot.h> #include <game/version.h> #include <mastersrv/mastersrv.h> #include <versionsrv/versionsrv.h> #include "friends.h" #include "serverbrowser.h" #include "client.h" #if defined(CONF_FAMILY_WINDOWS) #define _WIN32_WINNT 0x0501 #define WIN32_LEAN_AND_MEAN #include <windows.h> #endif #include "SDL.h" #ifdef main #undef main #endif void CGraph::Init(float Min, float Max) { m_Min = Min; m_Max = Max; m_Index = 0; } void CGraph::ScaleMax() { int i = 0; m_Max = 0; for(i = 0; i < MAX_VALUES; i++) { if(m_aValues[i] > m_Max) m_Max = m_aValues[i]; } } void CGraph::ScaleMin() { int i = 0; m_Min = m_Max; for(i = 0; i < MAX_VALUES; i++) { if(m_aValues[i] < m_Min) m_Min = m_aValues[i]; } } void CGraph::Add(float v, float r, float g, float b) { m_Index = (m_Index+1)&(MAX_VALUES-1); m_aValues[m_Index] = v; m_aColors[m_Index][0] = r; m_aColors[m_Index][1] = g; m_aColors[m_Index][2] = b; } void CGraph::Render(IGraphics *pGraphics, IGraphics::CTextureHandle FontTexture, float x, float y, float w, float h, const char *pDescription) { //m_pGraphics->BlendNormal(); pGraphics->TextureClear(); pGraphics->QuadsBegin(); pGraphics->SetColor(0, 0, 0, 0.75f); IGraphics::CQuadItem QuadItem(x, y, w, h); pGraphics->QuadsDrawTL(&QuadItem, 1); pGraphics->QuadsEnd(); pGraphics->LinesBegin(); pGraphics->SetColor(0.95f, 0.95f, 0.95f, 1.00f); IGraphics::CLineItem LineItem(x, y+h/2, x+w, y+h/2); pGraphics->LinesDraw(&LineItem, 1); pGraphics->SetColor(0.5f, 0.5f, 0.5f, 0.75f); IGraphics::CLineItem Array[2] = { IGraphics::CLineItem(x, y+(h*3)/4, x+w, y+(h*3)/4), IGraphics::CLineItem(x, y+h/4, x+w, y+h/4)}; pGraphics->LinesDraw(Array, 2); for(int i = 1; i < MAX_VALUES; i++) { float a0 = (i-1)/(float)MAX_VALUES; float a1 = i/(float)MAX_VALUES; int i0 = (m_Index+i-1)&(MAX_VALUES-1); int i1 = (m_Index+i)&(MAX_VALUES-1); float v0 = (m_aValues[i0]-m_Min) / (m_Max-m_Min); float v1 = (m_aValues[i1]-m_Min) / (m_Max-m_Min); IGraphics::CColorVertex Array[2] = { IGraphics::CColorVertex(0, m_aColors[i0][0], m_aColors[i0][1], m_aColors[i0][2], 0.75f), IGraphics::CColorVertex(1, m_aColors[i1][0], m_aColors[i1][1], m_aColors[i1][2], 0.75f)}; pGraphics->SetColorVertex(Array, 2); IGraphics::CLineItem LineItem(x+a0*w, y+h-v0*h, x+a1*w, y+h-v1*h); pGraphics->LinesDraw(&LineItem, 1); } pGraphics->LinesEnd(); pGraphics->TextureSet(FontTexture); pGraphics->QuadsBegin(); pGraphics->QuadsText(x+2, y+h-16, 16, pDescription); char aBuf[32]; str_format(aBuf, sizeof(aBuf), "%.2f", m_Max); pGraphics->QuadsText(x+w-8*str_length(aBuf)-8, y+2, 16, aBuf); str_format(aBuf, sizeof(aBuf), "%.2f", m_Min); pGraphics->QuadsText(x+w-8*str_length(aBuf)-8, y+h-16, 16, aBuf); pGraphics->QuadsEnd(); } void CSmoothTime::Init(int64 Target) { m_Snap = time_get(); m_Current = Target; m_Target = Target; m_aAdjustSpeed[0] = 0.3f; m_aAdjustSpeed[1] = 0.3f; m_Graph.Init(0.0f, 0.5f); } void CSmoothTime::SetAdjustSpeed(int Direction, float Value) { m_aAdjustSpeed[Direction] = Value; } int64 CSmoothTime::Get(int64 Now) { int64 c = m_Current + (Now - m_Snap); int64 t = m_Target + (Now - m_Snap); // it's faster to adjust upward instead of downward // we might need to adjust these abit float AdjustSpeed = m_aAdjustSpeed[0]; if(t > c) AdjustSpeed = m_aAdjustSpeed[1]; float a = ((Now-m_Snap)/(float)time_freq()) * AdjustSpeed; if(a > 1.0f) a = 1.0f; int64 r = c + (int64)((t-c)*a); m_Graph.Add(a+0.5f,1,1,1); return r; } void CSmoothTime::UpdateInt(int64 Target) { int64 Now = time_get(); m_Current = Get(Now); m_Snap = Now; m_Target = Target; } void CSmoothTime::Update(CGraph *pGraph, int64 Target, int TimeLeft, int AdjustDirection) { int UpdateTimer = 1; if(TimeLeft < 0) { int IsSpike = 0; if(TimeLeft < -50) { IsSpike = 1; m_SpikeCounter += 5; if(m_SpikeCounter > 50) m_SpikeCounter = 50; } if(IsSpike && m_SpikeCounter < 15) { // ignore this ping spike UpdateTimer = 0; pGraph->Add(TimeLeft, 1,1,0); } else { pGraph->Add(TimeLeft, 1,0,0); if(m_aAdjustSpeed[AdjustDirection] < 30.0f) m_aAdjustSpeed[AdjustDirection] *= 2.0f; } } else { if(m_SpikeCounter) m_SpikeCounter--; pGraph->Add(TimeLeft, 0,1,0); m_aAdjustSpeed[AdjustDirection] *= 0.95f; if(m_aAdjustSpeed[AdjustDirection] < 2.0f) m_aAdjustSpeed[AdjustDirection] = 2.0f; } if(UpdateTimer) UpdateInt(Target); } CClient::CClient() : m_DemoPlayer(&m_SnapshotDelta), m_DemoRecorder(&m_SnapshotDelta) { m_pEditor = 0; m_pInput = 0; m_pGraphics = 0; m_pSound = 0; m_pGameClient = 0; m_pMap = 0; m_pConsole = 0; m_RenderFrameTime = 0.0001f; m_RenderFrameTimeLow = 1.0f; m_RenderFrameTimeHigh = 0.0f; m_RenderFrames = 0; m_LastRenderTime = time_get(); m_GameTickSpeed = SERVER_TICK_SPEED; m_WindowMustRefocus = 0; m_SnapCrcErrors = 0; m_AutoScreenshotRecycle = false; m_EditorActive = false; m_AckGameTick = -1; m_CurrentRecvTick = 0; m_RconAuthed = 0; // version-checking m_aVersionStr[0] = '0'; m_aVersionStr[1] = 0; // pinging m_PingStartTime = 0; // m_aCurrentMap[0] = 0; m_CurrentMapCrc = 0; // m_aCmdConnect[0] = 0; // map download m_aMapdownloadFilename[0] = 0; m_aMapdownloadName[0] = 0; m_MapdownloadFile = 0; m_MapdownloadChunk = 0; m_MapdownloadCrc = 0; m_MapdownloadAmount = -1; m_MapdownloadTotalsize = -1; m_CurrentServerInfoRequestTime = -1; m_CurrentInput = 0; m_State = IClient::STATE_OFFLINE; m_aServerAddressStr[0] = 0; mem_zero(m_aSnapshots, sizeof(m_aSnapshots)); m_SnapshotStorage.Init(); m_RecivedSnapshots = 0; m_VersionInfo.m_State = CVersionInfo::STATE_INIT; } // ----- send functions ----- int CClient::SendMsg(CMsgPacker *pMsg, int Flags) { CNetChunk Packet; if(State() == IClient::STATE_OFFLINE) return 0; mem_zero(&Packet, sizeof(CNetChunk)); Packet.m_ClientID = 0; Packet.m_pData = pMsg->Data(); Packet.m_DataSize = pMsg->Size(); if(Flags&MSGFLAG_VITAL) Packet.m_Flags |= NETSENDFLAG_VITAL; if(Flags&MSGFLAG_FLUSH) Packet.m_Flags |= NETSENDFLAG_FLUSH; if(Flags&MSGFLAG_RECORD) { if(m_DemoRecorder.IsRecording()) m_DemoRecorder.RecordMessage(Packet.m_pData, Packet.m_DataSize); } if(!(Flags&MSGFLAG_NOSEND)) m_NetClient.Send(&Packet); return 0; } void CClient::SendInfo() { CMsgPacker Msg(NETMSG_INFO, true); Msg.AddString(GameClient()->NetVersion(), 128); Msg.AddString(g_Config.m_Password, 128); SendMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_FLUSH); } void CClient::SendEnterGame() { CMsgPacker Msg(NETMSG_ENTERGAME, true); SendMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_FLUSH); } void CClient::SendReady() { CMsgPacker Msg(NETMSG_READY, true); SendMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_FLUSH); } void CClient::RconAuth(const char *pName, const char *pPassword) { if(RconAuthed()) return; CMsgPacker Msg(NETMSG_RCON_AUTH, true); Msg.AddString(pPassword, 32); SendMsg(&Msg, MSGFLAG_VITAL); } void CClient::Rcon(const char *pCmd) { CMsgPacker Msg(NETMSG_RCON_CMD, true); Msg.AddString(pCmd, 256); SendMsg(&Msg, MSGFLAG_VITAL); } bool CClient::ConnectionProblems() { return m_NetClient.GotProblems() != 0; } void CClient::DirectInput(int *pInput, int Size) { CMsgPacker Msg(NETMSG_INPUT, true); Msg.AddInt(m_AckGameTick); Msg.AddInt(m_PredTick); Msg.AddInt(Size); for(int i = 0; i < Size/4; i++) Msg.AddInt(pInput[i]); SendMsg(&Msg, 0); } void CClient::SendInput() { int64 Now = time_get(); if(m_PredTick <= 0) return; // fetch input int Size = GameClient()->OnSnapInput(m_aInputs[m_CurrentInput].m_aData); if(!Size) return; // pack input CMsgPacker Msg(NETMSG_INPUT, true); Msg.AddInt(m_AckGameTick); Msg.AddInt(m_PredTick); Msg.AddInt(Size); m_aInputs[m_CurrentInput].m_Tick = m_PredTick; m_aInputs[m_CurrentInput].m_PredictedTime = m_PredictedTime.Get(Now); m_aInputs[m_CurrentInput].m_Time = Now; // pack it for(int i = 0; i < Size/4; i++) Msg.AddInt(m_aInputs[m_CurrentInput].m_aData[i]); m_CurrentInput++; m_CurrentInput%=200; SendMsg(&Msg, MSGFLAG_FLUSH); } const char *CClient::LatestVersion() { return m_aVersionStr; } // TODO: OPT: do this alot smarter! int *CClient::GetInput(int Tick) { int Best = -1; for(int i = 0; i < 200; i++) { if(m_aInputs[i].m_Tick <= Tick && (Best == -1 || m_aInputs[Best].m_Tick < m_aInputs[i].m_Tick)) Best = i; } if(Best != -1) return (int *)m_aInputs[Best].m_aData; return 0; } // ------ state handling ----- void CClient::SetState(int s) { if(m_State == IClient::STATE_QUITING) return; int Old = m_State; if(g_Config.m_Debug) { char aBuf[128]; str_format(aBuf, sizeof(aBuf), "state change. last=%d current=%d", m_State, s); m_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, "client", aBuf); } m_State = s; if(Old != s) GameClient()->OnStateChange(m_State, Old); } // called when the map is loaded and we should init for a new round void CClient::OnEnterGame() { // reset input int i; for(i = 0; i < 200; i++) m_aInputs[i].m_Tick = -1; m_CurrentInput = 0; // reset snapshots m_aSnapshots[SNAP_CURRENT] = 0; m_aSnapshots[SNAP_PREV] = 0; m_SnapshotStorage.PurgeAll(); m_RecivedSnapshots = 0; m_SnapshotParts = 0; m_PredTick = 0; m_CurrentRecvTick = 0; m_CurGameTick = 0; m_PrevGameTick = 0; m_CurMenuTick = 0; } void CClient::EnterGame() { if(State() == IClient::STATE_DEMOPLAYBACK) return; // now we will wait for two snapshots // to finish the connection SendEnterGame(); OnEnterGame(); } void CClient::Connect(const char *pAddress) { char aBuf[512]; int Port = 8303; Disconnect(); str_copy(m_aServerAddressStr, pAddress, sizeof(m_aServerAddressStr)); str_format(aBuf, sizeof(aBuf), "connecting to '%s'", m_aServerAddressStr); m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "client", aBuf); ServerInfoRequest(); if(net_addr_from_str(&m_ServerAddress, m_aServerAddressStr) != 0 && net_host_lookup(m_aServerAddressStr, &m_ServerAddress, m_NetClient.NetType()) != 0) { char aBufMsg[256]; str_format(aBufMsg, sizeof(aBufMsg), "could not find the address of %s, connecting to localhost", aBuf); m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "client", aBufMsg); net_host_lookup("localhost", &m_ServerAddress, m_NetClient.NetType()); } m_RconAuthed = 0; if(m_ServerAddress.port == 0) m_ServerAddress.port = Port; m_NetClient.Connect(&m_ServerAddress); SetState(IClient::STATE_CONNECTING); if(m_DemoRecorder.IsRecording()) DemoRecorder_Stop(); m_InputtimeMarginGraph.Init(-150.0f, 150.0f); m_GametimeMarginGraph.Init(-150.0f, 150.0f); } void CClient::DisconnectWithReason(const char *pReason) { char aBuf[512]; str_format(aBuf, sizeof(aBuf), "disconnecting. reason='%s'", pReason?pReason:"unknown"); m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "client", aBuf); // stop demo playback and recorder m_DemoPlayer.Stop(); DemoRecorder_Stop(); // m_RconAuthed = 0; m_UseTempRconCommands = 0; m_pConsole->DeregisterTempAll(); m_NetClient.Disconnect(pReason); SetState(IClient::STATE_OFFLINE); m_pMap->Unload(); // disable all downloads m_MapdownloadChunk = 0; if(m_MapdownloadFile) io_close(m_MapdownloadFile); m_MapdownloadFile = 0; m_MapdownloadCrc = 0; m_MapdownloadTotalsize = -1; m_MapdownloadAmount = 0; // clear the current server info mem_zero(&m_CurrentServerInfo, sizeof(m_CurrentServerInfo)); mem_zero(&m_ServerAddress, sizeof(m_ServerAddress)); // clear snapshots m_aSnapshots[SNAP_CURRENT] = 0; m_aSnapshots[SNAP_PREV] = 0; m_RecivedSnapshots = 0; } void CClient::Disconnect() { DisconnectWithReason(0); } void CClient::GetServerInfo(CServerInfo *pServerInfo) { mem_copy(pServerInfo, &m_CurrentServerInfo, sizeof(m_CurrentServerInfo)); } void CClient::ServerInfoRequest() { mem_zero(&m_CurrentServerInfo, sizeof(m_CurrentServerInfo)); m_CurrentServerInfoRequestTime = 0; } int CClient::LoadData() { m_DebugFont = Graphics()->LoadTexture("debug_font.png", IStorage::TYPE_ALL, CImageInfo::FORMAT_AUTO, IGraphics::TEXLOAD_NORESAMPLE); return 1; } // --- void *CClient::SnapGetItem(int SnapID, int Index, CSnapItem *pItem) { CSnapshotItem *i; dbg_assert(SnapID >= 0 && SnapID < NUM_SNAPSHOT_TYPES, "invalid SnapID"); i = m_aSnapshots[SnapID]->m_pAltSnap->GetItem(Index); pItem->m_DataSize = m_aSnapshots[SnapID]->m_pAltSnap->GetItemSize(Index); pItem->m_Type = i->Type(); pItem->m_ID = i->ID(); return (void *)i->Data(); } void CClient::SnapInvalidateItem(int SnapID, int Index) { CSnapshotItem *i; dbg_assert(SnapID >= 0 && SnapID < NUM_SNAPSHOT_TYPES, "invalid SnapID"); i = m_aSnapshots[SnapID]->m_pAltSnap->GetItem(Index); if(i) { if((char *)i < (char *)m_aSnapshots[SnapID]->m_pAltSnap || (char *)i > (char *)m_aSnapshots[SnapID]->m_pAltSnap + m_aSnapshots[SnapID]->m_SnapSize) m_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, "client", "snap invalidate problem"); if((char *)i >= (char *)m_aSnapshots[SnapID]->m_pSnap && (char *)i < (char *)m_aSnapshots[SnapID]->m_pSnap + m_aSnapshots[SnapID]->m_SnapSize) m_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, "client", "snap invalidate problem"); i->m_TypeAndID = -1; } } void *CClient::SnapFindItem(int SnapID, int Type, int ID) { // TODO: linear search. should be fixed. int i; if(!m_aSnapshots[SnapID]) return 0x0; for(i = 0; i < m_aSnapshots[SnapID]->m_pSnap->NumItems(); i++) { CSnapshotItem *pItem = m_aSnapshots[SnapID]->m_pAltSnap->GetItem(i); if(pItem->Type() == Type && pItem->ID() == ID) return (void *)pItem->Data(); } return 0x0; } int CClient::SnapNumItems(int SnapID) { dbg_assert(SnapID >= 0 && SnapID < NUM_SNAPSHOT_TYPES, "invalid SnapID"); if(!m_aSnapshots[SnapID]) return 0; return m_aSnapshots[SnapID]->m_pSnap->NumItems(); } void *CClient::SnapNewItem(int Type, int ID, int Size) { dbg_assert(Type >= 0 && Type <=0xffff, "incorrect type"); dbg_assert(ID >= 0 && ID <=0xffff, "incorrect id"); return ID < 0 ? 0 : m_DemoRecSnapshotBuilder.NewItem(Type, ID, Size); } void CClient::SnapSetStaticsize(int ItemType, int Size) { m_SnapshotDelta.SetStaticsize(ItemType, Size); } void CClient::DebugRender() { static NETSTATS Prev, Current; static int64 LastSnap = 0; static float FrameTimeAvg = 0; int64 Now = time_get(); char aBuffer[512]; if(!g_Config.m_Debug) return; //m_pGraphics->BlendNormal(); Graphics()->TextureSet(m_DebugFont); Graphics()->MapScreen(0,0,Graphics()->ScreenWidth(),Graphics()->ScreenHeight()); Graphics()->QuadsBegin(); if(time_get()-LastSnap > time_freq()) { LastSnap = time_get(); Prev = Current; net_stats(&Current); } /* eth = 14 ip = 20 udp = 8 total = 42 */ FrameTimeAvg = FrameTimeAvg*0.9f + m_RenderFrameTime*0.1f; str_format(aBuffer, sizeof(aBuffer), "ticks: %8d %8d mem %dk %d gfxmem: %dk fps: %3d", m_CurGameTick, m_PredTick, mem_stats()->allocated/1024, mem_stats()->total_allocations, Graphics()->MemoryUsage()/1024, (int)(1.0f/FrameTimeAvg + 0.5f)); Graphics()->QuadsText(2, 2, 16, aBuffer); { int SendPackets = (Current.sent_packets-Prev.sent_packets); int SendBytes = (Current.sent_bytes-Prev.sent_bytes); int SendTotal = SendBytes + SendPackets*42; int RecvPackets = (Current.recv_packets-Prev.recv_packets); int RecvBytes = (Current.recv_bytes-Prev.recv_bytes); int RecvTotal = RecvBytes + RecvPackets*42; if(!SendPackets) SendPackets++; if(!RecvPackets) RecvPackets++; str_format(aBuffer, sizeof(aBuffer), "send: %3d %5d+%4d=%5d (%3d kbps) avg: %5d\nrecv: %3d %5d+%4d=%5d (%3d kbps) avg: %5d", SendPackets, SendBytes, SendPackets*42, SendTotal, (SendTotal*8)/1024, SendBytes/SendPackets, RecvPackets, RecvBytes, RecvPackets*42, RecvTotal, (RecvTotal*8)/1024, RecvBytes/RecvPackets); Graphics()->QuadsText(2, 14, 16, aBuffer); } // render rates { int y = 0; int i; for(i = 0; i < 256; i++) { if(m_SnapshotDelta.GetDataRate(i)) { str_format(aBuffer, sizeof(aBuffer), "%4d %20s: %8d %8d %8d", i, GameClient()->GetItemName(i), m_SnapshotDelta.GetDataRate(i)/8, m_SnapshotDelta.GetDataUpdates(i), (m_SnapshotDelta.GetDataRate(i)/m_SnapshotDelta.GetDataUpdates(i))/8); Graphics()->QuadsText(2, 100+y*12, 16, aBuffer); y++; } } } str_format(aBuffer, sizeof(aBuffer), "pred: %d ms", (int)((m_PredictedTime.Get(Now)-m_GameTime.Get(Now))*1000/(float)time_freq())); Graphics()->QuadsText(2, 70, 16, aBuffer); Graphics()->QuadsEnd(); // render graphs if(g_Config.m_DbgGraphs) { //Graphics()->MapScreen(0,0,400.0f,300.0f); float w = Graphics()->ScreenWidth()/4.0f; float h = Graphics()->ScreenHeight()/6.0f; float sp = Graphics()->ScreenWidth()/100.0f; float x = Graphics()->ScreenWidth()-w-sp; m_FpsGraph.ScaleMax(); m_FpsGraph.ScaleMin(); m_FpsGraph.Render(Graphics(), m_DebugFont, x, sp*5, w, h, "FPS"); m_InputtimeMarginGraph.Render(Graphics(), m_DebugFont, x, sp*5+h+sp, w, h, "Prediction Margin"); m_GametimeMarginGraph.Render(Graphics(), m_DebugFont, x, sp*5+h+sp+h+sp, w, h, "Gametime Margin"); } } void CClient::Quit() { SetState(IClient::STATE_QUITING); } const char *CClient::ErrorString() { return m_NetClient.ErrorString(); } void CClient::Render() { if(g_Config.m_GfxClear) Graphics()->Clear(1,1,0); GameClient()->OnRender(); DebugRender(); } const char *CClient::LoadMap(const char *pName, const char *pFilename, unsigned WantedCrc) { static char aErrorMsg[128]; SetState(IClient::STATE_LOADING); if(!m_pMap->Load(pFilename)) { str_format(aErrorMsg, sizeof(aErrorMsg), "map '%s' not found", pFilename); return aErrorMsg; } // get the crc of the map if(m_pMap->Crc() != WantedCrc) { str_format(aErrorMsg, sizeof(aErrorMsg), "map differs from the server. %08x != %08x", m_pMap->Crc(), WantedCrc); m_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "client", aErrorMsg); m_pMap->Unload(); return aErrorMsg; } // stop demo recording if we loaded a new map DemoRecorder_Stop(); char aBuf[256]; str_format(aBuf, sizeof(aBuf), "loaded map '%s'", pFilename); m_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "client", aBuf); m_RecivedSnapshots = 0; str_copy(m_aCurrentMap, pName, sizeof(m_aCurrentMap)); m_CurrentMapCrc = m_pMap->Crc(); return 0x0; } const char *CClient::LoadMapSearch(const char *pMapName, int WantedCrc) { const char *pError = 0; char aBuf[512]; str_format(aBuf, sizeof(aBuf), "loading map, map=%s wanted crc=%08x", pMapName, WantedCrc); m_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "client", aBuf); SetState(IClient::STATE_LOADING); // try the normal maps folder str_format(aBuf, sizeof(aBuf), "maps/%s.map", pMapName); pError = LoadMap(pMapName, aBuf, WantedCrc); if(!pError) return pError; // try the downloaded maps str_format(aBuf, sizeof(aBuf), "downloadedmaps/%s_%08x.map", pMapName, WantedCrc); pError = LoadMap(pMapName, aBuf, WantedCrc); if(!pError) return pError; // search for the map within subfolders char aFilename[128]; str_format(aFilename, sizeof(aFilename), "%s.map", pMapName); if(Storage()->FindFile(aFilename, "maps", IStorage::TYPE_ALL, aBuf, sizeof(aBuf))) pError = LoadMap(pMapName, aBuf, WantedCrc); return pError; } int CClient::PlayerScoreComp(const void *a, const void *b) { CServerInfo::CClient *p0 = (CServerInfo::CClient *)a; CServerInfo::CClient *p1 = (CServerInfo::CClient *)b; if(p0->m_Player && !p1->m_Player) return -1; if(!p0->m_Player && p1->m_Player) return 1; if(p0->m_Score == p1->m_Score) return 0; if(p0->m_Score < p1->m_Score) return 1; return -1; } void CClient::ProcessConnlessPacket(CNetChunk *pPacket) { // version server if(m_VersionInfo.m_State == CVersionInfo::STATE_READY && net_addr_comp(&pPacket->m_Address, &m_VersionInfo.m_VersionServeraddr.m_Addr) == 0) { // version info if(pPacket->m_DataSize == (int)(sizeof(VERSIONSRV_VERSION) + sizeof(GAME_RELEASE_VERSION)) && mem_comp(pPacket->m_pData, VERSIONSRV_VERSION, sizeof(VERSIONSRV_VERSION)) == 0) { char *pVersionData = (char*)pPacket->m_pData + sizeof(VERSIONSRV_VERSION); int VersionMatch = !mem_comp(pVersionData, GAME_RELEASE_VERSION, sizeof(GAME_RELEASE_VERSION)); char aVersion[sizeof(GAME_RELEASE_VERSION)]; str_copy(aVersion, pVersionData, sizeof(aVersion)); char aBuf[256]; str_format(aBuf, sizeof(aBuf), "version does %s (%s)", VersionMatch ? "match" : "NOT match", aVersion); m_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "client/version", aBuf); // assume version is out of date when version-data doesn't match if(!VersionMatch) { str_copy(m_aVersionStr, aVersion, sizeof(m_aVersionStr)); } // request the map version list now CNetChunk Packet; mem_zero(&Packet, sizeof(Packet)); Packet.m_ClientID = -1; Packet.m_Address = m_VersionInfo.m_VersionServeraddr.m_Addr; Packet.m_pData = VERSIONSRV_GETMAPLIST; Packet.m_DataSize = sizeof(VERSIONSRV_GETMAPLIST); Packet.m_Flags = NETSENDFLAG_CONNLESS; m_NetClient.Send(&Packet); } // map version list if(pPacket->m_DataSize >= (int)sizeof(VERSIONSRV_MAPLIST) && mem_comp(pPacket->m_pData, VERSIONSRV_MAPLIST, sizeof(VERSIONSRV_MAPLIST)) == 0) { int Size = pPacket->m_DataSize-sizeof(VERSIONSRV_MAPLIST); int Num = Size/sizeof(CMapVersion); m_MapChecker.AddMaplist((CMapVersion *)((char*)pPacket->m_pData+sizeof(VERSIONSRV_MAPLIST)), Num); } } // server list from master server if(pPacket->m_DataSize >= (int)sizeof(SERVERBROWSE_LIST) && mem_comp(pPacket->m_pData, SERVERBROWSE_LIST, sizeof(SERVERBROWSE_LIST)) == 0) { // check for valid master server address bool Valid = false; for(int i = 0; i < IMasterServer::MAX_MASTERSERVERS; ++i) { if(m_pMasterServer->IsValid(i)) { NETADDR Addr = m_pMasterServer->GetAddr(i); if(net_addr_comp(&pPacket->m_Address, &Addr) == 0) { Valid = true; break; } } } if(!Valid) return; int Size = pPacket->m_DataSize-sizeof(SERVERBROWSE_LIST); int Num = Size/sizeof(CMastersrvAddr); CMastersrvAddr *pAddrs = (CMastersrvAddr *)((char*)pPacket->m_pData+sizeof(SERVERBROWSE_LIST)); for(int i = 0; i < Num; i++) { NETADDR Addr; static unsigned char s_aIPV4Mapping[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF}; // copy address if(!mem_comp(s_aIPV4Mapping, pAddrs[i].m_aIp, sizeof(s_aIPV4Mapping))) { mem_zero(&Addr, sizeof(Addr)); Addr.type = NETTYPE_IPV4; Addr.ip[0] = pAddrs[i].m_aIp[12]; Addr.ip[1] = pAddrs[i].m_aIp[13]; Addr.ip[2] = pAddrs[i].m_aIp[14]; Addr.ip[3] = pAddrs[i].m_aIp[15]; } else { Addr.type = NETTYPE_IPV6; mem_copy(Addr.ip, pAddrs[i].m_aIp, sizeof(Addr.ip)); } Addr.port = (pAddrs[i].m_aPort[0]<<8) | pAddrs[i].m_aPort[1]; m_ServerBrowser.Set(Addr, CServerBrowser::SET_MASTER_ADD, -1, 0x0); } } // server info if(pPacket->m_DataSize >= (int)sizeof(SERVERBROWSE_INFO) && mem_comp(pPacket->m_pData, SERVERBROWSE_INFO, sizeof(SERVERBROWSE_INFO)) == 0) { // we got ze info CUnpacker Up; CServerInfo Info = {0}; Up.Reset((unsigned char*)pPacket->m_pData+sizeof(SERVERBROWSE_INFO), pPacket->m_DataSize-sizeof(SERVERBROWSE_INFO)); int Token = Up.GetInt(); str_copy(Info.m_aVersion, Up.GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES), sizeof(Info.m_aVersion)); str_copy(Info.m_aName, Up.GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES), sizeof(Info.m_aName)); str_copy(Info.m_aHostname, Up.GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES), sizeof(Info.m_aHostname)); str_copy(Info.m_aMap, Up.GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES), sizeof(Info.m_aMap)); str_copy(Info.m_aGameType, Up.GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES), sizeof(Info.m_aGameType)); Info.m_Flags = (Up.GetInt()&SERVERINFO_FLAG_PASSWORD) ? IServerBrowser::FLAG_PASSWORD : 0; Info.m_ServerLevel = clamp<int>(Up.GetInt(), SERVERINFO_LEVEL_MIN, SERVERINFO_LEVEL_MAX); Info.m_NumPlayers = Up.GetInt(); Info.m_MaxPlayers = Up.GetInt(); Info.m_NumClients = Up.GetInt(); Info.m_MaxClients = Up.GetInt(); // don't add invalid info to the server browser list if(Info.m_NumClients < 0 || Info.m_NumClients > MAX_CLIENTS || Info.m_MaxClients < 0 || Info.m_MaxClients > MAX_CLIENTS || Info.m_NumPlayers < 0 || Info.m_NumPlayers > Info.m_NumClients || Info.m_MaxPlayers < 0 || Info.m_MaxPlayers > Info.m_MaxClients) return; net_addr_str(&pPacket->m_Address, Info.m_aAddress, sizeof(Info.m_aAddress), true); if(Info.m_aHostname[0] == 0) str_copy(Info.m_aHostname, Info.m_aAddress, sizeof(Info.m_aHostname)); for(int i = 0; i < Info.m_NumClients; i++) { str_copy(Info.m_aClients[i].m_aName, Up.GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES), sizeof(Info.m_aClients[i].m_aName)); str_copy(Info.m_aClients[i].m_aClan, Up.GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES), sizeof(Info.m_aClients[i].m_aClan)); Info.m_aClients[i].m_Country = Up.GetInt(); Info.m_aClients[i].m_Score = Up.GetInt(); Info.m_aClients[i].m_Player = Up.GetInt() != 0 ? true : false; } if(!Up.Error()) { // sort players qsort(Info.m_aClients, Info.m_NumClients, sizeof(*Info.m_aClients), PlayerScoreComp); if(net_addr_comp(&m_ServerAddress, &pPacket->m_Address) == 0) { mem_copy(&m_CurrentServerInfo, &Info, sizeof(m_CurrentServerInfo)); m_CurrentServerInfo.m_NetAddr = m_ServerAddress; m_CurrentServerInfoRequestTime = -1; } else m_ServerBrowser.Set(pPacket->m_Address, CServerBrowser::SET_TOKEN, Token, &Info); } } } void CClient::ProcessServerPacket(CNetChunk *pPacket) { CUnpacker Unpacker; Unpacker.Reset(pPacket->m_pData, pPacket->m_DataSize); // unpack msgid and system flag int Msg = Unpacker.GetInt(); int Sys = Msg&1; Msg >>= 1; if(Unpacker.Error()) return; if(Sys) { // system message if(Msg == NETMSG_MAP_CHANGE) { const char *pMap = Unpacker.GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES); int MapCrc = Unpacker.GetInt(); int MapSize = Unpacker.GetInt(); int MapChunkNum = Unpacker.GetInt(); int MapChunkSize = Unpacker.GetInt(); const char *pError = 0; if(Unpacker.Error()) return; // check for valid standard map if(!m_MapChecker.IsMapValid(pMap, MapCrc, MapSize)) pError = "invalid standard map"; // protect the player from nasty map names for(int i = 0; pMap[i]; i++) { if(pMap[i] == '/' || pMap[i] == '\\') pError = "strange character in map name"; } if(MapSize <= 0) pError = "invalid map size"; if(pError) DisconnectWithReason(pError); else { pError = LoadMapSearch(pMap, MapCrc); if(!pError) { m_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "client/network", "loading done"); SendReady(); } else { // start map download str_format(m_aMapdownloadFilename, sizeof(m_aMapdownloadFilename), "downloadedmaps/%s_%08x.map", pMap, MapCrc); char aBuf[256]; str_format(aBuf, sizeof(aBuf), "starting to download map to '%s'", m_aMapdownloadFilename); m_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "client/network", aBuf); str_copy(m_aMapdownloadName, pMap, sizeof(m_aMapdownloadName)); if(m_MapdownloadFile) io_close(m_MapdownloadFile); m_MapdownloadFile = Storage()->OpenFile(m_aMapdownloadFilename, IOFLAG_WRITE, IStorage::TYPE_SAVE); m_MapdownloadChunk = 0; m_MapdownloadChunkNum = MapChunkNum; m_MapDownloadChunkSize = MapChunkSize; m_MapdownloadCrc = MapCrc; m_MapdownloadTotalsize = MapSize; m_MapdownloadAmount = 0; // request first chunk package of map data CMsgPacker Msg(NETMSG_REQUEST_MAP_DATA, true); SendMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_FLUSH); if(g_Config.m_Debug) m_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, "client/network", "requested first chunk package"); } } } else if(Msg == NETMSG_MAP_DATA) { if(!m_MapdownloadFile) return; int Size = min(m_MapDownloadChunkSize, m_MapdownloadTotalsize-m_MapdownloadAmount); const unsigned char *pData = Unpacker.GetRaw(Size); if(Unpacker.Error()) return; io_write(m_MapdownloadFile, pData, Size); ++m_MapdownloadChunk; m_MapdownloadAmount += Size; if(m_MapdownloadAmount == m_MapdownloadTotalsize) { // map download complete m_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "client/network", "download complete, loading map"); if(m_MapdownloadFile) io_close(m_MapdownloadFile); m_MapdownloadFile = 0; m_MapdownloadAmount = 0; m_MapdownloadTotalsize = -1; // load map const char *pError = LoadMap(m_aMapdownloadName, m_aMapdownloadFilename, m_MapdownloadCrc); if(!pError) { m_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "client/network", "loading done"); SendReady(); } else DisconnectWithReason(pError); } else if(m_MapdownloadChunk%m_MapdownloadChunkNum == 0) { // request next chunk package of map data CMsgPacker Msg(NETMSG_REQUEST_MAP_DATA, true); SendMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_FLUSH); if(g_Config.m_Debug) m_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, "client/network", "requested next chunk package"); } } else if(Msg == NETMSG_CON_READY) { GameClient()->OnConnected(); } else if(Msg == NETMSG_PING) { CMsgPacker Msg(NETMSG_PING_REPLY, true); SendMsg(&Msg, 0); } else if(Msg == NETMSG_RCON_CMD_ADD) { const char *pName = Unpacker.GetString(CUnpacker::SANITIZE_CC); const char *pHelp = Unpacker.GetString(CUnpacker::SANITIZE_CC); const char *pParams = Unpacker.GetString(CUnpacker::SANITIZE_CC); if(Unpacker.Error() == 0) m_pConsole->RegisterTemp(pName, pParams, CFGFLAG_SERVER, pHelp); } else if(Msg == NETMSG_RCON_CMD_REM) { const char *pName = Unpacker.GetString(CUnpacker::SANITIZE_CC); if(Unpacker.Error() == 0) m_pConsole->DeregisterTemp(pName); } else if(Msg == NETMSG_RCON_AUTH_ON) { m_RconAuthed = 1; m_UseTempRconCommands = 1; } else if(Msg == NETMSG_RCON_AUTH_OFF) { m_RconAuthed = 0; if(m_UseTempRconCommands) m_pConsole->DeregisterTempAll(); m_UseTempRconCommands = 0; } else if(Msg == NETMSG_RCON_LINE) { const char *pLine = Unpacker.GetString(); if(Unpacker.Error() == 0) GameClient()->OnRconLine(pLine); } else if(Msg == NETMSG_PING_REPLY) { char aBuf[256]; str_format(aBuf, sizeof(aBuf), "latency %.2f", (time_get() - m_PingStartTime)*1000 / (float)time_freq()); m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "client/network", aBuf); } else if(Msg == NETMSG_INPUTTIMING) { int InputPredTick = Unpacker.GetInt(); int TimeLeft = Unpacker.GetInt(); // adjust our prediction time int64 Target = 0; for(int k = 0; k < 200; k++) { if(m_aInputs[k].m_Tick == InputPredTick) { Target = m_aInputs[k].m_PredictedTime + (time_get() - m_aInputs[k].m_Time); Target = Target - (int64)(((TimeLeft-PREDICTION_MARGIN)/1000.0f)*time_freq()); break; } } if(Target) m_PredictedTime.Update(&m_InputtimeMarginGraph, Target, TimeLeft, 1); } else if(Msg == NETMSG_SNAP || Msg == NETMSG_SNAPSINGLE || Msg == NETMSG_SNAPEMPTY) { int NumParts = 1; int Part = 0; int GameTick = Unpacker.GetInt(); int DeltaTick = GameTick-Unpacker.GetInt(); int PartSize = 0; int Crc = 0; int CompleteSize = 0; const char *pData = 0; // we are not allowed to process snapshot yet if(State() < IClient::STATE_LOADING) return; if(Msg == NETMSG_SNAP) { NumParts = Unpacker.GetInt(); Part = Unpacker.GetInt(); } if(Msg != NETMSG_SNAPEMPTY) { Crc = Unpacker.GetInt(); PartSize = Unpacker.GetInt(); } pData = (const char *)Unpacker.GetRaw(PartSize); if(Unpacker.Error()) return; if(GameTick >= m_CurrentRecvTick) { if(GameTick != m_CurrentRecvTick) { m_SnapshotParts = 0; m_CurrentRecvTick = GameTick; } // TODO: clean this up abit mem_copy((char*)m_aSnapshotIncommingData + Part*MAX_SNAPSHOT_PACKSIZE, pData, PartSize); m_SnapshotParts |= 1<<Part; if(m_SnapshotParts == (unsigned)((1<<NumParts)-1)) { static CSnapshot Emptysnap; CSnapshot *pDeltaShot = &Emptysnap; int PurgeTick; void *pDeltaData; int DeltaSize; unsigned char aTmpBuffer2[CSnapshot::MAX_SIZE]; unsigned char aTmpBuffer3[CSnapshot::MAX_SIZE]; CSnapshot *pTmpBuffer3 = (CSnapshot*)aTmpBuffer3; // Fix compiler warning for strict-aliasing int SnapSize; CompleteSize = (NumParts-1) * MAX_SNAPSHOT_PACKSIZE + PartSize; // reset snapshoting m_SnapshotParts = 0; // find snapshot that we should use as delta Emptysnap.Clear(); // find delta if(DeltaTick >= 0) { int DeltashotSize = m_SnapshotStorage.Get(DeltaTick, 0, &pDeltaShot, 0); if(DeltashotSize < 0) { // couldn't find the delta snapshots that the server used // to compress this snapshot. force the server to resync if(g_Config.m_Debug) { char aBuf[256]; str_format(aBuf, sizeof(aBuf), "error, couldn't find the delta snapshot"); m_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, "client", aBuf); } // ack snapshot // TODO: combine this with the input message m_AckGameTick = -1; return; } } // decompress snapshot pDeltaData = m_SnapshotDelta.EmptyDelta(); DeltaSize = sizeof(int)*3; if(CompleteSize) { int IntSize = CVariableInt::Decompress(m_aSnapshotIncommingData, CompleteSize, aTmpBuffer2); if(IntSize < 0) // failure during decompression, bail return; pDeltaData = aTmpBuffer2; DeltaSize = IntSize; } // unpack delta SnapSize = m_SnapshotDelta.UnpackDelta(pDeltaShot, pTmpBuffer3, pDeltaData, DeltaSize); if(SnapSize < 0) { m_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, "client", "delta unpack failed!"); return; } if(Msg != NETMSG_SNAPEMPTY && pTmpBuffer3->Crc() != Crc) { if(g_Config.m_Debug) { char aBuf[256]; str_format(aBuf, sizeof(aBuf), "snapshot crc error #%d - tick=%d wantedcrc=%d gotcrc=%d compressed_size=%d delta_tick=%d", m_SnapCrcErrors, GameTick, Crc, pTmpBuffer3->Crc(), CompleteSize, DeltaTick); m_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, "client", aBuf); } m_SnapCrcErrors++; if(m_SnapCrcErrors > 10) { // to many errors, send reset m_AckGameTick = -1; SendInput(); m_SnapCrcErrors = 0; } return; } else { if(m_SnapCrcErrors) m_SnapCrcErrors--; } // purge old snapshots PurgeTick = DeltaTick; if(m_aSnapshots[SNAP_PREV] && m_aSnapshots[SNAP_PREV]->m_Tick < PurgeTick) PurgeTick = m_aSnapshots[SNAP_PREV]->m_Tick; if(m_aSnapshots[SNAP_CURRENT] && m_aSnapshots[SNAP_CURRENT]->m_Tick < PurgeTick) PurgeTick = m_aSnapshots[SNAP_CURRENT]->m_Tick; m_SnapshotStorage.PurgeUntil(PurgeTick); // add new m_SnapshotStorage.Add(GameTick, time_get(), SnapSize, pTmpBuffer3, 1); // add snapshot to demo if(m_DemoRecorder.IsRecording()) { // build up snapshot and add local messages m_DemoRecSnapshotBuilder.Init(pTmpBuffer3); GameClient()->OnDemoRecSnap(); SnapSize = m_DemoRecSnapshotBuilder.Finish(pTmpBuffer3); // write snapshot m_DemoRecorder.RecordSnapshot(GameTick, pTmpBuffer3, SnapSize); } // apply snapshot, cycle pointers m_RecivedSnapshots++; m_CurrentRecvTick = GameTick; // we got two snapshots until we see us self as connected if(m_RecivedSnapshots == 2) { // start at 200ms and work from there m_PredictedTime.Init(GameTick*time_freq()/50); m_PredictedTime.SetAdjustSpeed(1, 1000.0f); m_GameTime.Init((GameTick-1)*time_freq()/50); m_aSnapshots[SNAP_PREV] = m_SnapshotStorage.m_pFirst; m_aSnapshots[SNAP_CURRENT] = m_SnapshotStorage.m_pLast; m_LocalStartTime = time_get(); SetState(IClient::STATE_ONLINE); DemoRecorder_HandleAutoStart(); } // adjust game time if(m_RecivedSnapshots > 2) { int64 Now = m_GameTime.Get(time_get()); int64 TickStart = GameTick*time_freq()/50; int64 TimeLeft = (TickStart-Now)*1000 / time_freq(); m_GameTime.Update(&m_GametimeMarginGraph, (GameTick-1)*time_freq()/50, TimeLeft, 0); } // ack snapshot m_AckGameTick = GameTick; } } } } else { // game message GameClient()->OnMessage(Msg, &Unpacker); if(m_RecordGameMessage && m_DemoRecorder.IsRecording()) m_DemoRecorder.RecordMessage(pPacket->m_pData, pPacket->m_DataSize); } } void CClient::PumpNetwork() { m_NetClient.Update(); if(State() != IClient::STATE_DEMOPLAYBACK) { // check for errors if(State() != IClient::STATE_OFFLINE && State() != IClient::STATE_QUITING && m_NetClient.State() == NETSTATE_OFFLINE) { SetState(IClient::STATE_OFFLINE); Disconnect(); char aBuf[256]; str_format(aBuf, sizeof(aBuf), "offline error='%s'", m_NetClient.ErrorString()); m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "client", aBuf); } // if(State() == IClient::STATE_CONNECTING && m_NetClient.State() == NETSTATE_ONLINE) { // we switched to online m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "client", "connected, sending info"); SetState(IClient::STATE_LOADING); SendInfo(); } } // process packets CNetChunk Packet; while(m_NetClient.Recv(&Packet)) { if(Packet.m_ClientID == -1) ProcessConnlessPacket(&Packet); else ProcessServerPacket(&Packet); } } void CClient::OnDemoPlayerSnapshot(void *pData, int Size) { // update ticks, they could have changed const CDemoPlayer::CPlaybackInfo *pInfo = m_DemoPlayer.Info(); CSnapshotStorage::CHolder *pTemp; m_CurGameTick = pInfo->m_Info.m_CurrentTick; m_PrevGameTick = pInfo->m_PreviousTick; // handle snapshots pTemp = m_aSnapshots[SNAP_PREV]; m_aSnapshots[SNAP_PREV] = m_aSnapshots[SNAP_CURRENT]; m_aSnapshots[SNAP_CURRENT] = pTemp; mem_copy(m_aSnapshots[SNAP_CURRENT]->m_pSnap, pData, Size); mem_copy(m_aSnapshots[SNAP_CURRENT]->m_pAltSnap, pData, Size); GameClient()->OnNewSnapshot(); } void CClient::OnDemoPlayerMessage(void *pData, int Size) { CUnpacker Unpacker; Unpacker.Reset(pData, Size); // unpack msgid and system flag int Msg = Unpacker.GetInt(); int Sys = Msg&1; Msg >>= 1; if(Unpacker.Error()) return; if(!Sys) GameClient()->OnMessage(Msg, &Unpacker); } /* const IDemoPlayer::CInfo *client_demoplayer_getinfo() { static DEMOPLAYBACK_INFO ret; const DEMOREC_PLAYBACKINFO *info = m_DemoPlayer.Info(); ret.first_tick = info->first_tick; ret.last_tick = info->last_tick; ret.current_tick = info->current_tick; ret.paused = info->paused; ret.speed = info->speed; return &ret; }*/ /* void DemoPlayer()->SetPos(float percent) { demorec_playback_set(percent); } void DemoPlayer()->SetSpeed(float speed) { demorec_playback_setspeed(speed); } void DemoPlayer()->SetPause(int paused) { if(paused) demorec_playback_pause(); else demorec_playback_unpause(); }*/ void CClient::Update() { if(State() == IClient::STATE_DEMOPLAYBACK) { m_DemoPlayer.Update(); if(m_DemoPlayer.IsPlaying()) { // update timers const CDemoPlayer::CPlaybackInfo *pInfo = m_DemoPlayer.Info(); m_CurGameTick = pInfo->m_Info.m_CurrentTick; m_PrevGameTick = pInfo->m_PreviousTick; m_GameIntraTick = pInfo->m_IntraTick; m_GameTickTime = pInfo->m_TickTime; } else { // disconnect on error Disconnect(); } } else if(State() == IClient::STATE_ONLINE && m_RecivedSnapshots >= 3) { // switch snapshot int Repredict = 0; int64 Freq = time_freq(); int64 Now = m_GameTime.Get(time_get()); int64 PredNow = m_PredictedTime.Get(time_get()); while(1) { CSnapshotStorage::CHolder *pCur = m_aSnapshots[SNAP_CURRENT]; int64 TickStart = (pCur->m_Tick)*time_freq()/50; if(TickStart < Now) { CSnapshotStorage::CHolder *pNext = m_aSnapshots[SNAP_CURRENT]->m_pNext; if(pNext) { m_aSnapshots[SNAP_PREV] = m_aSnapshots[SNAP_CURRENT]; m_aSnapshots[SNAP_CURRENT] = pNext; // set ticks m_CurGameTick = m_aSnapshots[SNAP_CURRENT]->m_Tick; m_PrevGameTick = m_aSnapshots[SNAP_PREV]->m_Tick; if(m_aSnapshots[SNAP_CURRENT] && m_aSnapshots[SNAP_PREV]) { GameClient()->OnNewSnapshot(); Repredict = 1; } } else break; } else break; } if(m_aSnapshots[SNAP_CURRENT] && m_aSnapshots[SNAP_PREV]) { int64 CurtickStart = (m_aSnapshots[SNAP_CURRENT]->m_Tick)*time_freq()/50; int64 PrevtickStart = (m_aSnapshots[SNAP_PREV]->m_Tick)*time_freq()/50; int PrevPredTick = (int)(PredNow*50/time_freq()); int NewPredTick = PrevPredTick+1; m_GameIntraTick = (Now - PrevtickStart) / (float)(CurtickStart-PrevtickStart); m_GameTickTime = (Now - PrevtickStart) / (float)Freq; //(float)SERVER_TICK_SPEED); CurtickStart = NewPredTick*time_freq()/50; PrevtickStart = PrevPredTick*time_freq()/50; m_PredIntraTick = (PredNow - PrevtickStart) / (float)(CurtickStart-PrevtickStart); if(NewPredTick < m_aSnapshots[SNAP_PREV]->m_Tick-SERVER_TICK_SPEED || NewPredTick > m_aSnapshots[SNAP_PREV]->m_Tick+SERVER_TICK_SPEED) { m_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "client", "prediction time reset!"); m_PredictedTime.Init(m_aSnapshots[SNAP_CURRENT]->m_Tick*time_freq()/50); } if(NewPredTick > m_PredTick) { m_PredTick = NewPredTick; Repredict = 1; // send input SendInput(); } } // only do sane predictions if(Repredict) { if(m_PredTick > m_CurGameTick && m_PredTick < m_CurGameTick+50) GameClient()->OnPredict(); } // fetch server info if we don't have it if(State() >= IClient::STATE_LOADING && m_CurrentServerInfoRequestTime >= 0 && time_get() > m_CurrentServerInfoRequestTime) { m_ServerBrowser.Request(m_ServerAddress); m_CurrentServerInfoRequestTime = time_get()+time_freq()*2; } } // STRESS TEST: join the server again if(g_Config.m_DbgStress) { static int64 ActionTaken = 0; int64 Now = time_get(); if(State() == IClient::STATE_OFFLINE) { if(Now > ActionTaken+time_freq()*2) { m_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, "stress", "reconnecting!"); Connect(g_Config.m_DbgStressServer); ActionTaken = Now; } } else { if(Now > ActionTaken+time_freq()*(10+g_Config.m_DbgStress)) { m_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, "stress", "disconnecting!"); Disconnect(); ActionTaken = Now; } } } // pump the network PumpNetwork(); // update the maser server registry MasterServer()->Update(); // update the server browser m_ServerBrowser.Update(m_ResortServerBrowser); m_ResortServerBrowser = false; } void CClient::VersionUpdate() { if(m_VersionInfo.m_State == CVersionInfo::STATE_INIT) { Engine()->HostLookup(&m_VersionInfo.m_VersionServeraddr, g_Config.m_ClVersionServer, m_NetClient.NetType()); m_VersionInfo.m_State = CVersionInfo::STATE_START; } else if(m_VersionInfo.m_State == CVersionInfo::STATE_START) { if(m_VersionInfo.m_VersionServeraddr.m_Job.Status() == CJob::STATE_DONE) { CNetChunk Packet; mem_zero(&Packet, sizeof(Packet)); m_VersionInfo.m_VersionServeraddr.m_Addr.port = VERSIONSRV_PORT; Packet.m_ClientID = -1; Packet.m_Address = m_VersionInfo.m_VersionServeraddr.m_Addr; Packet.m_pData = VERSIONSRV_GETVERSION; Packet.m_DataSize = sizeof(VERSIONSRV_GETVERSION); Packet.m_Flags = NETSENDFLAG_CONNLESS; m_NetClient.Send(&Packet); m_VersionInfo.m_State = CVersionInfo::STATE_READY; } } } void CClient::RegisterInterfaces() { Kernel()->RegisterInterface(static_cast<IDemoRecorder*>(&m_DemoRecorder)); Kernel()->RegisterInterface(static_cast<IDemoPlayer*>(&m_DemoPlayer)); Kernel()->RegisterInterface(static_cast<IServerBrowser*>(&m_ServerBrowser)); Kernel()->RegisterInterface(static_cast<IFriends*>(&m_Friends)); } void CClient::InitInterfaces() { // fetch interfaces m_pEngine = Kernel()->RequestInterface<IEngine>(); m_pEditor = Kernel()->RequestInterface<IEditor>(); //m_pGraphics = Kernel()->RequestInterface<IEngineGraphics>(); m_pSound = Kernel()->RequestInterface<IEngineSound>(); m_pGameClient = Kernel()->RequestInterface<IGameClient>(); m_pInput = Kernel()->RequestInterface<IEngineInput>(); m_pMap = Kernel()->RequestInterface<IEngineMap>(); m_pMasterServer = Kernel()->RequestInterface<IEngineMasterServer>(); m_pStorage = Kernel()->RequestInterface<IStorage>(); // m_ServerBrowser.SetBaseInfo(&m_NetClient, m_pGameClient->NetVersion()); m_Friends.Init(); } void CClient::Run() { m_LocalStartTime = time_get(); m_SnapshotParts = 0; // init SDL { if(SDL_Init(0) < 0) { dbg_msg("client", "unable to init SDL base: %s", SDL_GetError()); return; } atexit(SDL_Quit); // ignore_convention } m_MenuStartTime = time_get(); // init graphics { m_pGraphics = CreateEngineGraphicsThreaded(); bool RegisterFail = false; RegisterFail = RegisterFail || !Kernel()->RegisterInterface(static_cast<IEngineGraphics*>(m_pGraphics)); // register graphics as both RegisterFail = RegisterFail || !Kernel()->RegisterInterface(static_cast<IGraphics*>(m_pGraphics)); if(RegisterFail || m_pGraphics->Init() != 0) { dbg_msg("client", "couldn't init graphics"); return; } } // init sound, allowed to fail m_SoundInitFailed = Sound()->Init() != 0; // open socket { NETADDR BindAddr; if(g_Config.m_Bindaddr[0] && net_host_lookup(g_Config.m_Bindaddr, &BindAddr, NETTYPE_ALL) == 0) { // got bindaddr BindAddr.type = NETTYPE_ALL; } else { mem_zero(&BindAddr, sizeof(BindAddr)); BindAddr.type = NETTYPE_ALL; } if(!m_NetClient.Open(BindAddr, 0)) { dbg_msg("client", "couldn't open socket"); return; } } // init font rendering Kernel()->RequestInterface<IEngineTextRender>()->Init(); // init the input Input()->Init(); // start refreshing addresses while we load MasterServer()->RefreshAddresses(m_NetClient.NetType()); // init the editor m_pEditor->Init(); // load data if(!LoadData()) return; GameClient()->OnInit(); char aBuf[256]; str_format(aBuf, sizeof(aBuf), "version %s", GameClient()->NetVersion()); m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "client", aBuf); // connect to the server if wanted /* if(config.cl_connect[0] != 0) Connect(config.cl_connect); config.cl_connect[0] = 0; */ // m_FpsGraph.Init(0.0f, 200.0f); // never start with the editor g_Config.m_ClEditor = 0; Input()->MouseModeRelative(); // process pending commands m_pConsole->StoreCommands(false); while (1) { // VersionUpdate(); // handle pending connects if(m_aCmdConnect[0]) { str_copy(g_Config.m_UiServerAddress, m_aCmdConnect, sizeof(g_Config.m_UiServerAddress)); Connect(m_aCmdConnect); m_aCmdConnect[0] = 0; } // update input if(Input()->Update()) break; // SDL_QUIT // update sound Sound()->Update(); // release focus if(!m_pGraphics->WindowActive()) { if(m_WindowMustRefocus == 0) Input()->MouseModeAbsolute(); m_WindowMustRefocus = 1; } else if (g_Config.m_DbgFocus && Input()->KeyPressed(KEY_ESCAPE)) { Input()->MouseModeAbsolute(); m_WindowMustRefocus = 1; } // refocus if(m_WindowMustRefocus && m_pGraphics->WindowActive()) { if(m_WindowMustRefocus < 3) { Input()->MouseModeAbsolute(); m_WindowMustRefocus++; } if(m_WindowMustRefocus >= 3 || Input()->KeyPressed(KEY_MOUSE_1)) { Input()->MouseModeRelative(); m_WindowMustRefocus = 0; } } // panic quit button if(Input()->KeyPressed(KEY_LCTRL) && Input()->KeyPressed(KEY_LSHIFT) && Input()->KeyPressed('q')) { Quit(); break; } if(Input()->KeyPressed(KEY_LCTRL) && Input()->KeyPressed(KEY_LSHIFT) && Input()->KeyDown('d')) g_Config.m_Debug ^= 1; if(Input()->KeyPressed(KEY_LCTRL) && Input()->KeyPressed(KEY_LSHIFT) && Input()->KeyDown('g')) g_Config.m_DbgGraphs ^= 1; if(Input()->KeyPressed(KEY_LCTRL) && Input()->KeyPressed(KEY_LSHIFT) && Input()->KeyDown('e')) { g_Config.m_ClEditor = g_Config.m_ClEditor^1; Input()->MouseModeRelative(); } /* if(!gfx_window_open()) break; */ // render { if(g_Config.m_ClEditor) { if(!m_EditorActive) { GameClient()->OnActivateEditor(); m_EditorActive = true; } } else if(m_EditorActive) m_EditorActive = false; Update(); if(!g_Config.m_GfxAsyncRender || m_pGraphics->IsIdle()) { m_RenderFrames++; // update frametime int64 Now = time_get(); m_RenderFrameTime = (Now - m_LastRenderTime) / (float)time_freq(); if(m_RenderFrameTime < m_RenderFrameTimeLow) m_RenderFrameTimeLow = m_RenderFrameTime; if(m_RenderFrameTime > m_RenderFrameTimeHigh) m_RenderFrameTimeHigh = m_RenderFrameTime; m_FpsGraph.Add(1.0f/m_RenderFrameTime, 1,1,1); m_LastRenderTime = Now; // when we are stress testing only render every 10th frame if(!g_Config.m_DbgStress || (m_RenderFrames%10) == 0 ) { if(!m_EditorActive) Render(); else { m_pEditor->UpdateAndRender(); DebugRender(); } m_pGraphics->Swap(); } } } AutoScreenshot_Cleanup(); // check conditions if(State() == IClient::STATE_QUITING) break; // menu tick if(State() == IClient::STATE_OFFLINE) { int64 t = time_get(); while(t > TickStartTime(m_CurMenuTick+1)) m_CurMenuTick++; } // beNice if(g_Config.m_ClCpuThrottle) thread_sleep(g_Config.m_ClCpuThrottle); else if(g_Config.m_DbgStress || !m_pGraphics->WindowActive()) thread_sleep(5); if(g_Config.m_DbgHitch) { thread_sleep(g_Config.m_DbgHitch); g_Config.m_DbgHitch = 0; } /* if(ReportTime < time_get()) { if(0 && g_Config.m_Debug) { dbg_msg("client/report", "fps=%.02f (%.02f %.02f) netstate=%d", m_Frames/(float)(ReportInterval/time_freq()), 1.0f/m_RenderFrameTimeHigh, 1.0f/m_RenderFrameTimeLow, m_NetClient.State()); } m_RenderFrameTimeLow = 1; m_RenderFrameTimeHigh = 0; m_RenderFrames = 0; ReportTime += ReportInterval; }*/ // update local time m_LocalTime = (time_get()-m_LocalStartTime)/(float)time_freq(); } GameClient()->OnShutdown(); Disconnect(); m_pGraphics->Shutdown(); m_pSound->Shutdown(); // shutdown SDL { SDL_Quit(); } } int64 CClient::TickStartTime(int Tick) { return m_MenuStartTime + (time_freq()*Tick)/m_GameTickSpeed; } void CClient::Con_Connect(IConsole::IResult *pResult, void *pUserData) { CClient *pSelf = (CClient *)pUserData; str_copy(pSelf->m_aCmdConnect, pResult->GetString(0), sizeof(pSelf->m_aCmdConnect)); } void CClient::Con_Disconnect(IConsole::IResult *pResult, void *pUserData) { CClient *pSelf = (CClient *)pUserData; pSelf->Disconnect(); } void CClient::Con_Quit(IConsole::IResult *pResult, void *pUserData) { CClient *pSelf = (CClient *)pUserData; pSelf->Quit(); } void CClient::Con_Minimize(IConsole::IResult *pResult, void *pUserData) { CClient *pSelf = (CClient *)pUserData; pSelf->Graphics()->Minimize(); } void CClient::Con_Ping(IConsole::IResult *pResult, void *pUserData) { CClient *pSelf = (CClient *)pUserData; CMsgPacker Msg(NETMSG_PING, true); pSelf->SendMsg(&Msg, 0); pSelf->m_PingStartTime = time_get(); } void CClient::AutoScreenshot_Start() { if(g_Config.m_ClAutoScreenshot) { Graphics()->TakeScreenshot("auto/autoscreen"); m_AutoScreenshotRecycle = true; } } void CClient::AutoScreenshot_Cleanup() { if(m_AutoScreenshotRecycle) { if(g_Config.m_ClAutoScreenshotMax) { // clean up auto taken screens CFileCollection AutoScreens; AutoScreens.Init(Storage(), "screenshots/auto", "autoscreen", ".png", g_Config.m_ClAutoScreenshotMax); } m_AutoScreenshotRecycle = false; } } void CClient::Con_Screenshot(IConsole::IResult *pResult, void *pUserData) { CClient *pSelf = (CClient *)pUserData; pSelf->Graphics()->TakeScreenshot(0); } void CClient::Con_Rcon(IConsole::IResult *pResult, void *pUserData) { CClient *pSelf = (CClient *)pUserData; pSelf->Rcon(pResult->GetString(0)); } void CClient::Con_RconAuth(IConsole::IResult *pResult, void *pUserData) { CClient *pSelf = (CClient *)pUserData; pSelf->RconAuth("", pResult->GetString(0)); } const char *CClient::DemoPlayer_Play(const char *pFilename, int StorageType) { int Crc; Disconnect(); m_NetClient.ResetErrorString(); // try to start playback m_DemoPlayer.SetListner(this); const char *pError = m_DemoPlayer.Load(Storage(), m_pConsole, pFilename, StorageType, GameClient()->NetVersion()); if(pError) return pError; // load map Crc = (m_DemoPlayer.Info()->m_Header.m_aMapCrc[0]<<24)| (m_DemoPlayer.Info()->m_Header.m_aMapCrc[1]<<16)| (m_DemoPlayer.Info()->m_Header.m_aMapCrc[2]<<8)| (m_DemoPlayer.Info()->m_Header.m_aMapCrc[3]); pError = LoadMapSearch(m_DemoPlayer.Info()->m_Header.m_aMapName, Crc); if(pError) { DisconnectWithReason(pError); return pError; } GameClient()->OnConnected(); // setup buffers mem_zero(m_aDemorecSnapshotData, sizeof(m_aDemorecSnapshotData)); m_aSnapshots[SNAP_CURRENT] = &m_aDemorecSnapshotHolders[SNAP_CURRENT]; m_aSnapshots[SNAP_PREV] = &m_aDemorecSnapshotHolders[SNAP_PREV]; m_aSnapshots[SNAP_CURRENT]->m_pSnap = (CSnapshot *)m_aDemorecSnapshotData[SNAP_CURRENT][0]; m_aSnapshots[SNAP_CURRENT]->m_pAltSnap = (CSnapshot *)m_aDemorecSnapshotData[SNAP_CURRENT][1]; m_aSnapshots[SNAP_CURRENT]->m_SnapSize = 0; m_aSnapshots[SNAP_CURRENT]->m_Tick = -1; m_aSnapshots[SNAP_PREV]->m_pSnap = (CSnapshot *)m_aDemorecSnapshotData[SNAP_PREV][0]; m_aSnapshots[SNAP_PREV]->m_pAltSnap = (CSnapshot *)m_aDemorecSnapshotData[SNAP_PREV][1]; m_aSnapshots[SNAP_PREV]->m_SnapSize = 0; m_aSnapshots[SNAP_PREV]->m_Tick = -1; // enter demo playback state SetState(IClient::STATE_DEMOPLAYBACK); m_DemoPlayer.Play(); GameClient()->OnEnterGame(); return 0; } void CClient::Con_Play(IConsole::IResult *pResult, void *pUserData) { CClient *pSelf = (CClient *)pUserData; pSelf->DemoPlayer_Play(pResult->GetString(0), IStorage::TYPE_ALL); } void CClient::DemoRecorder_Start(const char *pFilename, bool WithTimestamp) { if(State() != IClient::STATE_ONLINE) m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "demorec/record", "client is not online"); else { char aFilename[128]; if(WithTimestamp) { char aDate[20]; str_timestamp(aDate, sizeof(aDate)); str_format(aFilename, sizeof(aFilename), "demos/%s_%s.demo", pFilename, aDate); } else str_format(aFilename, sizeof(aFilename), "demos/%s.demo", pFilename); m_DemoRecorder.Start(Storage(), m_pConsole, aFilename, GameClient()->NetVersion(), m_aCurrentMap, m_CurrentMapCrc, "client"); } } void CClient::DemoRecorder_HandleAutoStart() { if(g_Config.m_ClAutoDemoRecord) { DemoRecorder_Stop(); DemoRecorder_Start("auto/autorecord", true); if(g_Config.m_ClAutoDemoMax) { // clean up auto recorded demos CFileCollection AutoDemos; AutoDemos.Init(Storage(), "demos/auto", "autorecord", ".demo", g_Config.m_ClAutoDemoMax); } } } void CClient::DemoRecorder_Stop() { m_DemoRecorder.Stop(); } void CClient::DemoRecorder_AddDemoMarker() { m_DemoRecorder.AddDemoMarker(); } void CClient::Con_Record(IConsole::IResult *pResult, void *pUserData) { CClient *pSelf = (CClient *)pUserData; if(pResult->NumArguments()) pSelf->DemoRecorder_Start(pResult->GetString(0), false); else pSelf->DemoRecorder_Start("demo", true); } void CClient::Con_StopRecord(IConsole::IResult *pResult, void *pUserData) { CClient *pSelf = (CClient *)pUserData; pSelf->DemoRecorder_Stop(); } void CClient::Con_AddDemoMarker(IConsole::IResult *pResult, void *pUserData) { CClient *pSelf = (CClient *)pUserData; pSelf->DemoRecorder_AddDemoMarker(); } void CClient::ServerBrowserUpdate() { m_ResortServerBrowser = true; } void CClient::ConchainServerBrowserUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData) { pfnCallback(pResult, pCallbackUserData); if(pResult->NumArguments()) ((CClient *)pUserData)->ServerBrowserUpdate(); } void CClient::RegisterCommands() { m_pConsole = Kernel()->RequestInterface<IConsole>(); m_pConsole->Register("quit", "", CFGFLAG_CLIENT|CFGFLAG_STORE, Con_Quit, this, "Quit Teeworlds"); m_pConsole->Register("exit", "", CFGFLAG_CLIENT|CFGFLAG_STORE, Con_Quit, this, "Quit Teeworlds"); m_pConsole->Register("minimize", "", CFGFLAG_CLIENT|CFGFLAG_STORE, Con_Minimize, this, "Minimize Teeworlds"); m_pConsole->Register("connect", "s", CFGFLAG_CLIENT, Con_Connect, this, "Connect to the specified host/ip"); m_pConsole->Register("disconnect", "", CFGFLAG_CLIENT, Con_Disconnect, this, "Disconnect from the server"); m_pConsole->Register("ping", "", CFGFLAG_CLIENT, Con_Ping, this, "Ping the current server"); m_pConsole->Register("screenshot", "", CFGFLAG_CLIENT, Con_Screenshot, this, "Take a screenshot"); m_pConsole->Register("rcon", "r", CFGFLAG_CLIENT, Con_Rcon, this, "Send specified command to rcon"); m_pConsole->Register("rcon_auth", "s", CFGFLAG_CLIENT, Con_RconAuth, this, "Authenticate to rcon"); m_pConsole->Register("play", "r", CFGFLAG_CLIENT|CFGFLAG_STORE, Con_Play, this, "Play the file specified"); m_pConsole->Register("record", "?s", CFGFLAG_CLIENT, Con_Record, this, "Record to the file"); m_pConsole->Register("stoprecord", "", CFGFLAG_CLIENT, Con_StopRecord, this, "Stop recording"); m_pConsole->Register("add_demomarker", "", CFGFLAG_CLIENT, Con_AddDemoMarker, this, "Add demo timeline marker"); // used for server browser update m_pConsole->Chain("br_filter_string", ConchainServerBrowserUpdate, this); m_pConsole->Chain("br_filter_gametype", ConchainServerBrowserUpdate, this); m_pConsole->Chain("br_filter_serveraddress", ConchainServerBrowserUpdate, this); } static CClient *CreateClient() { CClient *pClient = static_cast<CClient *>(mem_alloc(sizeof(CClient), 1)); mem_zero(pClient, sizeof(CClient)); return new(pClient) CClient; } /* Server Time Client Mirror Time Client Predicted Time Snapshot Latency Downstream latency Prediction Latency Upstream latency */ #if defined(CONF_PLATFORM_MACOSX) extern "C" int SDL_main(int argc, char **argv_) // ignore_convention { const char **argv = const_cast<const char **>(argv_); #else int main(int argc, const char **argv) // ignore_convention { #endif #if defined(CONF_FAMILY_WINDOWS) for(int i = 1; i < argc; i++) // ignore_convention { if(str_comp("-s", argv[i]) == 0 || str_comp("--silent", argv[i]) == 0) // ignore_convention { FreeConsole(); break; } } #endif CClient *pClient = CreateClient(); IKernel *pKernel = IKernel::Create(); pKernel->RegisterInterface(pClient); pClient->RegisterInterfaces(); // create the components IEngine *pEngine = CreateEngine("Teeworlds"); IConsole *pConsole = CreateConsole(CFGFLAG_CLIENT); IStorage *pStorage = CreateStorage("Teeworlds", IStorage::STORAGETYPE_CLIENT, argc, argv); // ignore_convention IConfig *pConfig = CreateConfig(); IEngineSound *pEngineSound = CreateEngineSound(); IEngineInput *pEngineInput = CreateEngineInput(); IEngineTextRender *pEngineTextRender = CreateEngineTextRender(); IEngineMap *pEngineMap = CreateEngineMap(); IEngineMasterServer *pEngineMasterServer = CreateEngineMasterServer(); { bool RegisterFail = false; RegisterFail = RegisterFail || !pKernel->RegisterInterface(pEngine); RegisterFail = RegisterFail || !pKernel->RegisterInterface(pConsole); RegisterFail = RegisterFail || !pKernel->RegisterInterface(pConfig); RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<IEngineSound*>(pEngineSound)); // register as both RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<ISound*>(pEngineSound)); RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<IEngineInput*>(pEngineInput)); // register as both RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<IInput*>(pEngineInput)); RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<IEngineTextRender*>(pEngineTextRender)); // register as both RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<ITextRender*>(pEngineTextRender)); RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<IEngineMap*>(pEngineMap)); // register as both RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<IMap*>(pEngineMap)); RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<IEngineMasterServer*>(pEngineMasterServer)); // register as both RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<IMasterServer*>(pEngineMasterServer)); RegisterFail = RegisterFail || !pKernel->RegisterInterface(CreateEditor()); RegisterFail = RegisterFail || !pKernel->RegisterInterface(CreateGameClient()); RegisterFail = RegisterFail || !pKernel->RegisterInterface(pStorage); if(RegisterFail) return -1; } pEngine->Init(); pConfig->Init(); pEngineMasterServer->Init(); pEngineMasterServer->Load(); // register all console commands pClient->RegisterCommands(); // init client's interfaces pClient->InitInterfaces(); pKernel->RequestInterface<IGameClient>()->OnConsoleInit(); // execute config file pConsole->ExecuteFile("settings.cfg"); // execute autoexec file pConsole->ExecuteFile("autoexec.cfg"); // parse the command line arguments if(argc > 1) // ignore_convention pConsole->ParseArguments(argc-1, &argv[1]); // ignore_convention // restore empty config strings to their defaults pConfig->RestoreStrings(); pClient->Engine()->InitLogfile(); // run the client dbg_msg("client", "starting..."); pClient->Run(); // write down the config and quit pConfig->Save(); // free components mem_free(pClient); delete pKernel; delete pEngine; delete pConsole; delete pStorage; delete pConfig; delete pEngineSound; delete pEngineInput; delete pEngineTextRender; delete pEngineMap; delete pEngineMasterServer; return 0; } ================================================ FILE: src/engine/client/client.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef ENGINE_CLIENT_CLIENT_H #define ENGINE_CLIENT_CLIENT_H class CGraph { public: enum { // restrictions: Must be power of two MAX_VALUES=128, }; float m_Min, m_Max; float m_aValues[MAX_VALUES]; float m_aColors[MAX_VALUES][3]; int m_Index; void Init(float Min, float Max); void ScaleMax(); void ScaleMin(); void Add(float v, float r, float g, float b); void Render(IGraphics *pGraphics, IGraphics::CTextureHandle FontTexture, float x, float y, float w, float h, const char *pDescription); }; class CSmoothTime { int64 m_Snap; int64 m_Current; int64 m_Target; int64 m_RLast; int64 m_TLast; CGraph m_Graph; int m_SpikeCounter; float m_aAdjustSpeed[2]; // 0 = down, 1 = up public: void Init(int64 Target); void SetAdjustSpeed(int Direction, float Value); int64 Get(int64 Now); void UpdateInt(int64 Target); void Update(CGraph *pGraph, int64 Target, int TimeLeft, int AdjustDirection); }; class CClient : public IClient, public CDemoPlayer::IListner { // needed interfaces IEngine *m_pEngine; IEditor *m_pEditor; IEngineInput *m_pInput; IEngineGraphics *m_pGraphics; IEngineSound *m_pSound; IGameClient *m_pGameClient; IEngineMap *m_pMap; IConsole *m_pConsole; IStorage *m_pStorage; IEngineMasterServer *m_pMasterServer; enum { NUM_SNAPSHOT_TYPES=2, PREDICTION_MARGIN=1000/50/2, // magic network prediction value }; class CNetClient m_NetClient; class CDemoPlayer m_DemoPlayer; class CDemoRecorder m_DemoRecorder; class CServerBrowser m_ServerBrowser; class CFriends m_Friends; class CMapChecker m_MapChecker; char m_aServerAddressStr[256]; unsigned m_SnapshotParts; int64 m_LocalStartTime; IGraphics::CTextureHandle m_DebugFont; int64 m_LastRenderTime; float m_RenderFrameTimeLow; float m_RenderFrameTimeHigh; int m_RenderFrames; NETADDR m_ServerAddress; int m_WindowMustRefocus; int m_SnapCrcErrors; bool m_AutoScreenshotRecycle; bool m_EditorActive; bool m_SoundInitFailed; bool m_ResortServerBrowser; bool m_RecordGameMessage; int m_AckGameTick; int m_CurrentRecvTick; int m_RconAuthed; int m_UseTempRconCommands; // version-checking char m_aVersionStr[10]; // pinging int64 m_PingStartTime; // char m_aCurrentMap[256]; unsigned m_CurrentMapCrc; // char m_aCmdConnect[256]; // map download char m_aMapdownloadFilename[256]; char m_aMapdownloadName[256]; IOHANDLE m_MapdownloadFile; int m_MapdownloadChunk; int m_MapdownloadChunkNum; int m_MapDownloadChunkSize; int m_MapdownloadCrc; int m_MapdownloadAmount; int m_MapdownloadTotalsize; // time CSmoothTime m_GameTime; CSmoothTime m_PredictedTime; // input struct // TODO: handle input better { int m_aData[MAX_INPUT_SIZE]; // the input data int m_Tick; // the tick that the input is for int64 m_PredictedTime; // prediction latency when we sent this input int64 m_Time; } m_aInputs[200]; int m_CurrentInput; // graphs CGraph m_InputtimeMarginGraph; CGraph m_GametimeMarginGraph; CGraph m_FpsGraph; // the game snapshots are modifiable by the game class CSnapshotStorage m_SnapshotStorage; CSnapshotStorage::CHolder *m_aSnapshots[NUM_SNAPSHOT_TYPES]; int m_RecivedSnapshots; char m_aSnapshotIncommingData[CSnapshot::MAX_SIZE]; class CSnapshotStorage::CHolder m_aDemorecSnapshotHolders[NUM_SNAPSHOT_TYPES]; char *m_aDemorecSnapshotData[NUM_SNAPSHOT_TYPES][2][CSnapshot::MAX_SIZE]; class CSnapshotBuilder m_DemoRecSnapshotBuilder; class CSnapshotDelta m_SnapshotDelta; // class CServerInfo m_CurrentServerInfo; int64 m_CurrentServerInfoRequestTime; // >= 0 should request, == -1 got info // version info struct CVersionInfo { enum { STATE_INIT=0, STATE_START, STATE_READY, }; int m_State; class CHostLookup m_VersionServeraddr; } m_VersionInfo; volatile int m_GfxState; static void GraphicsThreadProxy(void *pThis) { ((CClient*)pThis)->GraphicsThread(); } void GraphicsThread(); int64 TickStartTime(int Tick); public: IEngine *Engine() { return m_pEngine; } IEngineGraphics *Graphics() { return m_pGraphics; } IEngineInput *Input() { return m_pInput; } IEngineSound *Sound() { return m_pSound; } IGameClient *GameClient() { return m_pGameClient; } IEngineMasterServer *MasterServer() { return m_pMasterServer; } IStorage *Storage() { return m_pStorage; } CClient(); // ----- send functions ----- virtual int SendMsg(CMsgPacker *pMsg, int Flags); void SendInfo(); void SendEnterGame(); void SendReady(); virtual bool RconAuthed() { return m_RconAuthed != 0; } virtual bool UseTempRconCommands() { return m_UseTempRconCommands != 0; } void RconAuth(const char *pName, const char *pPassword); virtual void Rcon(const char *pCmd); virtual bool ConnectionProblems(); virtual bool SoundInitFailed() { return m_SoundInitFailed; } virtual IGraphics::CTextureHandle GetDebugFont() { return m_DebugFont; } void DirectInput(int *pInput, int Size); void SendInput(); // TODO: OPT: do this alot smarter! virtual int *GetInput(int Tick); const char *LatestVersion(); void VersionUpdate(); // ------ state handling ----- void SetState(int s); // called when the map is loaded and we should init for a new round void OnEnterGame(); virtual void EnterGame(); virtual void Connect(const char *pAddress); void DisconnectWithReason(const char *pReason); virtual void Disconnect(); virtual void GetServerInfo(CServerInfo *pServerInfo); void ServerInfoRequest(); int LoadData(); // --- void *SnapGetItem(int SnapID, int Index, CSnapItem *pItem); void SnapInvalidateItem(int SnapID, int Index); void *SnapFindItem(int SnapID, int Type, int ID); int SnapNumItems(int SnapID); void *SnapNewItem(int Type, int ID, int Size); void SnapSetStaticsize(int ItemType, int Size); void Render(); void DebugRender(); virtual void Quit(); virtual const char *ErrorString(); const char *LoadMap(const char *pName, const char *pFilename, unsigned WantedCrc); const char *LoadMapSearch(const char *pMapName, int WantedCrc); static int PlayerScoreComp(const void *a, const void *b); void ProcessConnlessPacket(CNetChunk *pPacket); void ProcessServerPacket(CNetChunk *pPacket); virtual int MapDownloadAmount() { return m_MapdownloadAmount; } virtual int MapDownloadTotalsize() { return m_MapdownloadTotalsize; } void PumpNetwork(); virtual void OnDemoPlayerSnapshot(void *pData, int Size); virtual void OnDemoPlayerMessage(void *pData, int Size); void Update(); void RegisterInterfaces(); void InitInterfaces(); void Run(); static void Con_Connect(IConsole::IResult *pResult, void *pUserData); static void Con_Disconnect(IConsole::IResult *pResult, void *pUserData); static void Con_Quit(IConsole::IResult *pResult, void *pUserData); static void Con_Minimize(IConsole::IResult *pResult, void *pUserData); static void Con_Ping(IConsole::IResult *pResult, void *pUserData); static void Con_Screenshot(IConsole::IResult *pResult, void *pUserData); static void Con_Rcon(IConsole::IResult *pResult, void *pUserData); static void Con_RconAuth(IConsole::IResult *pResult, void *pUserData); static void Con_AddFavorite(IConsole::IResult *pResult, void *pUserData); static void Con_RemoveFavorite(IConsole::IResult *pResult, void *pUserData); static void Con_Play(IConsole::IResult *pResult, void *pUserData); static void Con_Record(IConsole::IResult *pResult, void *pUserData); static void Con_StopRecord(IConsole::IResult *pResult, void *pUserData); static void Con_AddDemoMarker(IConsole::IResult *pResult, void *pUserData); static void ConchainServerBrowserUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData); void RegisterCommands(); const char *DemoPlayer_Play(const char *pFilename, int StorageType); void DemoRecorder_Start(const char *pFilename, bool WithTimestamp); void DemoRecorder_HandleAutoStart(); void DemoRecorder_Stop(); void DemoRecorder_AddDemoMarker(); void RecordGameMessage(bool State) { m_RecordGameMessage = State; } void AutoScreenshot_Start(); void AutoScreenshot_Cleanup(); void ServerBrowserUpdate(); }; #endif ================================================ FILE: src/engine/client/friends.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <base/math.h> #include <base/system.h> #include <engine/config.h> #include <engine/console.h> #include <engine/shared/config.h> #include "friends.h" CFriends::CFriends() { mem_zero(m_aFriends, sizeof(m_aFriends)); m_NumFriends = 0; } void CFriends::ConAddFriend(IConsole::IResult *pResult, void *pUserData) { CFriends *pSelf = (CFriends *)pUserData; pSelf->AddFriend(pResult->GetString(0), pResult->GetString(1)); } void CFriends::ConRemoveFriend(IConsole::IResult *pResult, void *pUserData) { CFriends *pSelf = (CFriends *)pUserData; pSelf->RemoveFriend(pResult->GetString(0), pResult->GetString(1)); } void CFriends::Init() { IConfig *pConfig = Kernel()->RequestInterface<IConfig>(); if(pConfig) pConfig->RegisterCallback(ConfigSaveCallback, this); IConsole *pConsole = Kernel()->RequestInterface<IConsole>(); if(pConsole) { pConsole->Register("add_friend", "ss", CFGFLAG_CLIENT, ConAddFriend, this, "Add a friend"); pConsole->Register("remove_friend", "ss", CFGFLAG_CLIENT, ConRemoveFriend, this, "Remove a friend"); } } const CFriendInfo *CFriends::GetFriend(int Index) const { return &m_aFriends[max(0, Index%m_NumFriends)]; } int CFriends::GetFriendState(const char *pName, const char *pClan) const { int Result = FRIEND_NO; unsigned NameHash = str_quickhash(pName); unsigned ClanHash = str_quickhash(pClan); for(int i = 0; i < m_NumFriends; ++i) { if(m_aFriends[i].m_ClanHash == ClanHash) { if(m_aFriends[i].m_aName[0] == 0) Result = FRIEND_CLAN; else if(m_aFriends[i].m_NameHash == NameHash) { Result = FRIEND_PLAYER; break; } } } return Result; } bool CFriends::IsFriend(const char *pName, const char *pClan, bool PlayersOnly) const { unsigned NameHash = str_quickhash(pName); unsigned ClanHash = str_quickhash(pClan); for(int i = 0; i < m_NumFriends; ++i) { if(m_aFriends[i].m_ClanHash == ClanHash && ((!PlayersOnly && m_aFriends[i].m_aName[0] == 0) || m_aFriends[i].m_NameHash == NameHash)) return true; } return false; } void CFriends::AddFriend(const char *pName, const char *pClan) { if(m_NumFriends == MAX_FRIENDS || (pName[0] == 0 && pClan[0] == 0)) return; // make sure we don't have the friend already unsigned NameHash = str_quickhash(pName); unsigned ClanHash = str_quickhash(pClan); for(int i = 0; i < m_NumFriends; ++i) { if(m_aFriends[i].m_NameHash == NameHash && m_aFriends[i].m_ClanHash == ClanHash) return; } str_copy(m_aFriends[m_NumFriends].m_aName, pName, sizeof(m_aFriends[m_NumFriends].m_aName)); str_copy(m_aFriends[m_NumFriends].m_aClan, pClan, sizeof(m_aFriends[m_NumFriends].m_aClan)); m_aFriends[m_NumFriends].m_NameHash = NameHash; m_aFriends[m_NumFriends].m_ClanHash = ClanHash; ++m_NumFriends; } void CFriends::RemoveFriend(const char *pName, const char *pClan) { unsigned NameHash = str_quickhash(pName); unsigned ClanHash = str_quickhash(pClan); for(int i = 0; i < m_NumFriends; ++i) { if(m_aFriends[i].m_NameHash == NameHash && m_aFriends[i].m_ClanHash == ClanHash) { RemoveFriend(i); return; } } } void CFriends::RemoveFriend(int Index) { if(Index >= 0 && Index < m_NumFriends) { mem_move(&m_aFriends[Index], &m_aFriends[Index+1], sizeof(CFriendInfo)*(m_NumFriends-(Index+1))); --m_NumFriends; } return; } void CFriends::ConfigSaveCallback(IConfig *pConfig, void *pUserData) { CFriends *pSelf = (CFriends *)pUserData; char aBuf[128]; const char *pEnd = aBuf+sizeof(aBuf)-4; for(int i = 0; i < pSelf->m_NumFriends; ++i) { str_copy(aBuf, "add_friend ", sizeof(aBuf)); const char *pSrc = pSelf->m_aFriends[i].m_aName; char *pDst = aBuf+str_length(aBuf); *pDst++ = '"'; while(*pSrc && pDst < pEnd) { if(*pSrc == '"' || *pSrc == '\\') // escape \ and " *pDst++ = '\\'; *pDst++ = *pSrc++; } *pDst++ = '"'; *pDst++ = ' '; pSrc = pSelf->m_aFriends[i].m_aClan; *pDst++ = '"'; while(*pSrc && pDst < pEnd) { if(*pSrc == '"' || *pSrc == '\\') // escape \ and " *pDst++ = '\\'; *pDst++ = *pSrc++; } *pDst++ = '"'; *pDst++ = 0; pConfig->WriteLine(aBuf); } } ================================================ FILE: src/engine/client/friends.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef ENGINE_CLIENT_FRIENDS_H #define ENGINE_CLIENT_FRIENDS_H #include <engine/friends.h> class CFriends : public IFriends { CFriendInfo m_aFriends[MAX_FRIENDS]; int m_NumFriends; static void ConAddFriend(IConsole::IResult *pResult, void *pUserData); static void ConRemoveFriend(IConsole::IResult *pResult, void *pUserData); static void ConfigSaveCallback(IConfig *pConfig, void *pUserData); public: CFriends(); void Init(); int NumFriends() const { return m_NumFriends; } const CFriendInfo *GetFriend(int Index) const; int GetFriendState(const char *pName, const char *pClan) const; bool IsFriend(const char *pName, const char *pClan, bool PlayersOnly) const; void AddFriend(const char *pName, const char *pClan); void RemoveFriend(const char *pName, const char *pClan); void RemoveFriend(int Index); }; #endif ================================================ FILE: src/engine/client/graphics_threaded.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <base/detect.h> #include <base/math.h> #include <base/tl/threading.h> #include <base/system.h> #include <engine/external/pnglite/pnglite.h> #include <engine/shared/config.h> #include <engine/graphics.h> #include <engine/storage.h> #include <engine/keys.h> #include <engine/console.h> #include <math.h> // cosf, sinf #include "graphics_threaded.h" static CVideoMode g_aFakeModes[] = { {320,200,8,8,8}, {320,240,8,8,8}, {400,300,8,8,8}, {512,384,8,8,8}, {640,400,8,8,8}, {640,480,8,8,8}, {720,400,8,8,8}, {768,576,8,8,8}, {800,600,8,8,8}, {1024,600,8,8,8}, {1024,768,8,8,8}, {1152,864,8,8,8}, {1280,600,8,8,8}, {1280,720,8,8,8}, {1280,768,8,8,8}, {1280,800,8,8,8}, {1280,960,8,8,8}, {1280,1024,8,8,8}, {1360,768,8,8,8}, {1366,768,8,8,8}, {1368,768,8,8,8}, {1400,1050,8,8,8}, {1440,900,8,8,8}, {1440,1050,8,8,8}, {1600,900,8,8,8}, {1600,1000,8,8,8}, {1600,1200,8,8,8}, {1680,1050,8,8,8}, {1792,1344,8,8,8}, {1800,1440,8,8,8}, {1856,1392,8,8,8}, {1920,1080,8,8,8}, {1920,1200,8,8,8}, {1920,1440,8,8,8}, {1920,2400,8,8,8}, {2048,1536,8,8,8} }; void CGraphics_Threaded::FlushVertices() { if(m_NumVertices == 0) return; int NumVerts = m_NumVertices; m_NumVertices = 0; CCommandBuffer::SCommand_Render Cmd; Cmd.m_State = m_State; if(m_Drawing == DRAWING_QUADS) { Cmd.m_PrimType = CCommandBuffer::PRIMTYPE_QUADS; Cmd.m_PrimCount = NumVerts/4; } else if(m_Drawing == DRAWING_LINES) { Cmd.m_PrimType = CCommandBuffer::PRIMTYPE_LINES; Cmd.m_PrimCount = NumVerts/2; } else return; Cmd.m_pVertices = (CCommandBuffer::SVertex *)m_pCommandBuffer->AllocData(sizeof(CCommandBuffer::SVertex)*NumVerts); if(Cmd.m_pVertices == 0x0) { // kick command buffer and try again KickCommandBuffer(); Cmd.m_pVertices = (CCommandBuffer::SVertex *)m_pCommandBuffer->AllocData(sizeof(CCommandBuffer::SVertex)*NumVerts); if(Cmd.m_pVertices == 0x0) { dbg_msg("graphics", "failed to allocate data for vertices"); return; } } // check if we have enough free memory in the commandbuffer if(!m_pCommandBuffer->AddCommand(Cmd)) { // kick command buffer and try again KickCommandBuffer(); Cmd.m_pVertices = (CCommandBuffer::SVertex *)m_pCommandBuffer->AllocData(sizeof(CCommandBuffer::SVertex)*NumVerts); if(Cmd.m_pVertices == 0x0) { dbg_msg("graphics", "failed to allocate data for vertices"); return; } if(!m_pCommandBuffer->AddCommand(Cmd)) { dbg_msg("graphics", "failed to allocate memory for render command"); return; } } mem_copy(Cmd.m_pVertices, m_aVertices, sizeof(CCommandBuffer::SVertex)*NumVerts); } void CGraphics_Threaded::AddVertices(int Count) { m_NumVertices += Count; if((m_NumVertices + Count) >= MAX_VERTICES) FlushVertices(); } void CGraphics_Threaded::Rotate4(const CCommandBuffer::SPoint &rCenter, CCommandBuffer::SVertex *pPoints) { float c = cosf(m_Rotation); float s = sinf(m_Rotation); float x, y; int i; for(i = 0; i < 4; i++) { x = pPoints[i].m_Pos.x - rCenter.x; y = pPoints[i].m_Pos.y - rCenter.y; pPoints[i].m_Pos.x = x * c - y * s + rCenter.x; pPoints[i].m_Pos.y = x * s + y * c + rCenter.y; } } CGraphics_Threaded::CGraphics_Threaded() { m_State.m_ScreenTL.x = 0; m_State.m_ScreenTL.y = 0; m_State.m_ScreenBR.x = 0; m_State.m_ScreenBR.y = 0; m_State.m_ClipEnable = false; m_State.m_ClipX = 0; m_State.m_ClipY = 0; m_State.m_ClipW = 0; m_State.m_ClipH = 0; m_State.m_Texture = -1; m_State.m_BlendMode = CCommandBuffer::BLEND_NONE; m_State.m_WrapMode = CCommandBuffer::WRAP_REPEAT; m_CurrentCommandBuffer = 0; m_pCommandBuffer = 0x0; m_apCommandBuffers[0] = 0x0; m_apCommandBuffers[1] = 0x0; m_NumVertices = 0; m_ScreenWidth = -1; m_ScreenHeight = -1; m_Rotation = 0; m_Drawing = 0; m_TextureMemoryUsage = 0; m_RenderEnable = true; m_DoScreenshot = false; } void CGraphics_Threaded::ClipEnable(int x, int y, int w, int h) { if(x < 0) w += x; if(y < 0) h += y; x = clamp(x, 0, ScreenWidth()); y = clamp(y, 0, ScreenHeight()); w = clamp(w, 0, ScreenWidth()-x); h = clamp(h, 0, ScreenHeight()-y); m_State.m_ClipEnable = true; m_State.m_ClipX = x; m_State.m_ClipY = ScreenHeight()-(y+h); m_State.m_ClipW = w; m_State.m_ClipH = h; } void CGraphics_Threaded::ClipDisable() { m_State.m_ClipEnable = false; } void CGraphics_Threaded::BlendNone() { m_State.m_BlendMode = CCommandBuffer::BLEND_NONE; } void CGraphics_Threaded::BlendNormal() { m_State.m_BlendMode = CCommandBuffer::BLEND_ALPHA; } void CGraphics_Threaded::BlendAdditive() { m_State.m_BlendMode = CCommandBuffer::BLEND_ADDITIVE; } void CGraphics_Threaded::WrapNormal() { m_State.m_WrapMode = CCommandBuffer::WRAP_REPEAT; } void CGraphics_Threaded::WrapClamp() { m_State.m_WrapMode = CCommandBuffer::WRAP_CLAMP; } int CGraphics_Threaded::MemoryUsage() const { return m_pBackend->MemoryUsage(); } void CGraphics_Threaded::MapScreen(float TopLeftX, float TopLeftY, float BottomRightX, float BottomRightY) { m_State.m_ScreenTL.x = TopLeftX; m_State.m_ScreenTL.y = TopLeftY; m_State.m_ScreenBR.x = BottomRightX; m_State.m_ScreenBR.y = BottomRightY; } void CGraphics_Threaded::GetScreen(float *pTopLeftX, float *pTopLeftY, float *pBottomRightX, float *pBottomRightY) { *pTopLeftX = m_State.m_ScreenTL.x; *pTopLeftY = m_State.m_ScreenTL.y; *pBottomRightX = m_State.m_ScreenBR.x; *pBottomRightY = m_State.m_ScreenBR.y; } void CGraphics_Threaded::LinesBegin() { dbg_assert(m_Drawing == 0, "called Graphics()->LinesBegin twice"); m_Drawing = DRAWING_LINES; SetColor(1,1,1,1); } void CGraphics_Threaded::LinesEnd() { dbg_assert(m_Drawing == DRAWING_LINES, "called Graphics()->LinesEnd without begin"); FlushVertices(); m_Drawing = 0; } void CGraphics_Threaded::LinesDraw(const CLineItem *pArray, int Num) { dbg_assert(m_Drawing == DRAWING_LINES, "called Graphics()->LinesDraw without begin"); for(int i = 0; i < Num; ++i) { m_aVertices[m_NumVertices + 2*i].m_Pos.x = pArray[i].m_X0; m_aVertices[m_NumVertices + 2*i].m_Pos.y = pArray[i].m_Y0; m_aVertices[m_NumVertices + 2*i].m_Tex = m_aTexture[0]; m_aVertices[m_NumVertices + 2*i].m_Color = m_aColor[0]; m_aVertices[m_NumVertices + 2*i + 1].m_Pos.x = pArray[i].m_X1; m_aVertices[m_NumVertices + 2*i + 1].m_Pos.y = pArray[i].m_Y1; m_aVertices[m_NumVertices + 2*i + 1].m_Tex = m_aTexture[1]; m_aVertices[m_NumVertices + 2*i + 1].m_Color = m_aColor[1]; } AddVertices(2*Num); } int CGraphics_Threaded::UnloadTexture(CTextureHandle Index) { if(Index.Id() == m_InvalidTexture.Id()) return 0; if(!Index.IsValid()) return 0; CCommandBuffer::SCommand_Texture_Destroy Cmd; Cmd.m_Slot = Index.Id(); m_pCommandBuffer->AddCommand(Cmd); m_aTextureIndices[Index.Id()] = m_FirstFreeTexture; m_FirstFreeTexture = Index.Id(); return 0; } static int ImageFormatToTexFormat(int Format) { if(Format == CImageInfo::FORMAT_RGB) return CCommandBuffer::TEXFORMAT_RGB; if(Format == CImageInfo::FORMAT_RGBA) return CCommandBuffer::TEXFORMAT_RGBA; if(Format == CImageInfo::FORMAT_ALPHA) return CCommandBuffer::TEXFORMAT_ALPHA; return CCommandBuffer::TEXFORMAT_RGBA; } static int ImageFormatToPixelSize(int Format) { switch(Format) { case CImageInfo::FORMAT_RGB: return 3; case CImageInfo::FORMAT_ALPHA: return 1; default: return 4; } } int CGraphics_Threaded::LoadTextureRawSub(CTextureHandle TextureID, int x, int y, int Width, int Height, int Format, const void *pData) { CCommandBuffer::SCommand_Texture_Update Cmd; Cmd.m_Slot = TextureID.Id(); Cmd.m_X = x; Cmd.m_Y = y; Cmd.m_Width = Width; Cmd.m_Height = Height; Cmd.m_Format = ImageFormatToTexFormat(Format); // calculate memory usage int MemSize = Width*Height*ImageFormatToPixelSize(Format); // copy texture data void *pTmpData = mem_alloc(MemSize, sizeof(void*)); mem_copy(pTmpData, pData, MemSize); Cmd.m_pData = pTmpData; // m_pCommandBuffer->AddCommand(Cmd); return 0; } IGraphics::CTextureHandle CGraphics_Threaded::LoadTextureRaw(int Width, int Height, int Format, const void *pData, int StoreFormat, int Flags) { // don't waste memory on texture if we are stress testing if(g_Config.m_DbgStress) return m_InvalidTexture; // grab texture int Tex = m_FirstFreeTexture; m_FirstFreeTexture = m_aTextureIndices[Tex]; m_aTextureIndices[Tex] = -1; CCommandBuffer::SCommand_Texture_Create Cmd; Cmd.m_Slot = Tex; Cmd.m_Width = Width; Cmd.m_Height = Height; Cmd.m_PixelSize = ImageFormatToPixelSize(Format); Cmd.m_Format = ImageFormatToTexFormat(Format); Cmd.m_StoreFormat = ImageFormatToTexFormat(StoreFormat); // flags Cmd.m_Flags = 0; if(Flags&IGraphics::TEXLOAD_NOMIPMAPS) Cmd.m_Flags |= CCommandBuffer::TEXFLAG_NOMIPMAPS; if(g_Config.m_GfxTextureCompression) Cmd.m_Flags |= CCommandBuffer::TEXFLAG_COMPRESSED; if(g_Config.m_GfxTextureQuality || Flags&TEXLOAD_NORESAMPLE) Cmd.m_Flags |= CCommandBuffer::TEXFLAG_QUALITY; // copy texture data int MemSize = Width*Height*Cmd.m_PixelSize; void *pTmpData = mem_alloc(MemSize, sizeof(void*)); mem_copy(pTmpData, pData, MemSize); Cmd.m_pData = pTmpData; // m_pCommandBuffer->AddCommand(Cmd); return CreateTextureHandle(Tex); } // simple uncompressed RGBA loaders IGraphics::CTextureHandle CGraphics_Threaded::LoadTexture(const char *pFilename, int StorageType, int StoreFormat, int Flags) { int l = str_length(pFilename); IGraphics::CTextureHandle ID; CImageInfo Img; if(l < 3) return CTextureHandle(); if(LoadPNG(&Img, pFilename, StorageType)) { if (StoreFormat == CImageInfo::FORMAT_AUTO) StoreFormat = Img.m_Format; ID = LoadTextureRaw(Img.m_Width, Img.m_Height, Img.m_Format, Img.m_pData, StoreFormat, Flags); mem_free(Img.m_pData); if(ID.Id() != m_InvalidTexture.Id() && g_Config.m_Debug) dbg_msg("graphics/texture", "loaded %s", pFilename); return ID; } return m_InvalidTexture; } int CGraphics_Threaded::LoadPNG(CImageInfo *pImg, const char *pFilename, int StorageType) { char aCompleteFilename[512]; unsigned char *pBuffer; png_t Png; // ignore_convention // open file for reading png_init(0,0); // ignore_convention IOHANDLE File = m_pStorage->OpenFile(pFilename, IOFLAG_READ, StorageType, aCompleteFilename, sizeof(aCompleteFilename)); if(File) io_close(File); else { dbg_msg("game/png", "failed to open file. filename='%s'", pFilename); return 0; } int Error = png_open_file(&Png, aCompleteFilename); // ignore_convention if(Error != PNG_NO_ERROR) { dbg_msg("game/png", "failed to open file. filename='%s'", aCompleteFilename); if(Error != PNG_FILE_ERROR) png_close_file(&Png); // ignore_convention return 0; } if(Png.depth != 8 || (Png.color_type != PNG_TRUECOLOR && Png.color_type != PNG_TRUECOLOR_ALPHA)) // ignore_convention { dbg_msg("game/png", "invalid format. filename='%s'", aCompleteFilename); png_close_file(&Png); // ignore_convention return 0; } pBuffer = (unsigned char *)mem_alloc(Png.width * Png.height * Png.bpp, 1); // ignore_convention png_get_data(&Png, pBuffer); // ignore_convention png_close_file(&Png); // ignore_convention pImg->m_Width = Png.width; // ignore_convention pImg->m_Height = Png.height; // ignore_convention if(Png.color_type == PNG_TRUECOLOR) // ignore_convention pImg->m_Format = CImageInfo::FORMAT_RGB; else if(Png.color_type == PNG_TRUECOLOR_ALPHA) // ignore_convention pImg->m_Format = CImageInfo::FORMAT_RGBA; pImg->m_pData = pBuffer; return 1; } void CGraphics_Threaded::KickCommandBuffer() { m_pBackend->RunBuffer(m_pCommandBuffer); // swap buffer m_CurrentCommandBuffer ^= 1; m_pCommandBuffer = m_apCommandBuffers[m_CurrentCommandBuffer]; m_pCommandBuffer->Reset(); } void CGraphics_Threaded::ScreenshotDirect(const char *pFilename) { // add swap command CImageInfo Image; mem_zero(&Image, sizeof(Image)); CCommandBuffer::SCommand_Screenshot Cmd; Cmd.m_pImage = &Image; m_pCommandBuffer->AddCommand(Cmd); // kick the buffer and wait for the result KickCommandBuffer(); WaitForIdle(); if(Image.m_pData) { // find filename char aWholePath[1024]; png_t Png; // ignore_convention IOHANDLE File = m_pStorage->OpenFile(pFilename, IOFLAG_WRITE, IStorage::TYPE_SAVE, aWholePath, sizeof(aWholePath)); if(File) io_close(File); // save png char aBuf[256]; str_format(aBuf, sizeof(aBuf), "saved screenshot to '%s'", aWholePath); m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "client", aBuf); png_open_file_write(&Png, aWholePath); // ignore_convention png_set_data(&Png, Image.m_Width, Image.m_Height, 8, PNG_TRUECOLOR, (unsigned char *)Image.m_pData); // ignore_convention png_close_file(&Png); // ignore_convention mem_free(Image.m_pData); } } void CGraphics_Threaded::TextureSet(CTextureHandle TextureID) { dbg_assert(m_Drawing == 0, "called Graphics()->TextureSet within begin"); m_State.m_Texture = TextureID.Id(); } void CGraphics_Threaded::Clear(float r, float g, float b) { CCommandBuffer::SCommand_Clear Cmd; Cmd.m_Color.r = r; Cmd.m_Color.g = g; Cmd.m_Color.b = b; Cmd.m_Color.a = 0; m_pCommandBuffer->AddCommand(Cmd); } void CGraphics_Threaded::QuadsBegin() { dbg_assert(m_Drawing == 0, "called Graphics()->QuadsBegin twice"); m_Drawing = DRAWING_QUADS; QuadsSetSubset(0,0,1,1); QuadsSetRotation(0); SetColor(1,1,1,1); } void CGraphics_Threaded::QuadsEnd() { dbg_assert(m_Drawing == DRAWING_QUADS, "called Graphics()->QuadsEnd without begin"); FlushVertices(); m_Drawing = 0; } void CGraphics_Threaded::QuadsSetRotation(float Angle) { dbg_assert(m_Drawing == DRAWING_QUADS, "called Graphics()->QuadsSetRotation without begin"); m_Rotation = Angle; } void CGraphics_Threaded::SetColorVertex(const CColorVertex *pArray, int Num) { dbg_assert(m_Drawing != 0, "called Graphics()->SetColorVertex without begin"); for(int i = 0; i < Num; ++i) { m_aColor[pArray[i].m_Index].r = pArray[i].m_R; m_aColor[pArray[i].m_Index].g = pArray[i].m_G; m_aColor[pArray[i].m_Index].b = pArray[i].m_B; m_aColor[pArray[i].m_Index].a = pArray[i].m_A; } } void CGraphics_Threaded::SetColor(float r, float g, float b, float a) { dbg_assert(m_Drawing != 0, "called Graphics()->SetColor without begin"); CColorVertex Array[4] = { CColorVertex(0, r, g, b, a), CColorVertex(1, r, g, b, a), CColorVertex(2, r, g, b, a), CColorVertex(3, r, g, b, a)}; SetColorVertex(Array, 4); } void CGraphics_Threaded::SetColor4(vec4 TopLeft, vec4 TopRight, vec4 BottomLeft, vec4 BottomRight) { dbg_assert(m_Drawing != 0, "called Graphics()->SetColor without begin"); CColorVertex Array[4] = { CColorVertex(0, TopLeft.r, TopLeft.g, TopLeft.b, TopLeft.a), CColorVertex(1, TopRight.r, TopRight.g, TopRight.b, TopRight.a), CColorVertex(2, BottomRight.r, BottomRight.g, BottomRight.b, BottomRight.a), CColorVertex(3, BottomLeft.r, BottomLeft.g, BottomLeft.b, BottomLeft.a)}; SetColorVertex(Array, 4); } void CGraphics_Threaded::QuadsSetSubset(float TlU, float TlV, float BrU, float BrV) { dbg_assert(m_Drawing == DRAWING_QUADS, "called Graphics()->QuadsSetSubset without begin"); m_aTexture[0].u = TlU; m_aTexture[1].u = BrU; m_aTexture[0].v = TlV; m_aTexture[1].v = TlV; m_aTexture[3].u = TlU; m_aTexture[2].u = BrU; m_aTexture[3].v = BrV; m_aTexture[2].v = BrV; } void CGraphics_Threaded::QuadsSetSubsetFree( float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3) { m_aTexture[0].u = x0; m_aTexture[0].v = y0; m_aTexture[1].u = x1; m_aTexture[1].v = y1; m_aTexture[2].u = x2; m_aTexture[2].v = y2; m_aTexture[3].u = x3; m_aTexture[3].v = y3; } void CGraphics_Threaded::QuadsDraw(CQuadItem *pArray, int Num) { for(int i = 0; i < Num; ++i) { pArray[i].m_X -= pArray[i].m_Width/2; pArray[i].m_Y -= pArray[i].m_Height/2; } QuadsDrawTL(pArray, Num); } void CGraphics_Threaded::QuadsDrawTL(const CQuadItem *pArray, int Num) { CCommandBuffer::SPoint Center; Center.z = 0; dbg_assert(m_Drawing == DRAWING_QUADS, "called Graphics()->QuadsDrawTL without begin"); for(int i = 0; i < Num; ++i) { m_aVertices[m_NumVertices + 4*i].m_Pos.x = pArray[i].m_X; m_aVertices[m_NumVertices + 4*i].m_Pos.y = pArray[i].m_Y; m_aVertices[m_NumVertices + 4*i].m_Tex = m_aTexture[0]; m_aVertices[m_NumVertices + 4*i].m_Color = m_aColor[0]; m_aVertices[m_NumVertices + 4*i + 1].m_Pos.x = pArray[i].m_X + pArray[i].m_Width; m_aVertices[m_NumVertices + 4*i + 1].m_Pos.y = pArray[i].m_Y; m_aVertices[m_NumVertices + 4*i + 1].m_Tex = m_aTexture[1]; m_aVertices[m_NumVertices + 4*i + 1].m_Color = m_aColor[1]; m_aVertices[m_NumVertices + 4*i + 2].m_Pos.x = pArray[i].m_X + pArray[i].m_Width; m_aVertices[m_NumVertices + 4*i + 2].m_Pos.y = pArray[i].m_Y + pArray[i].m_Height; m_aVertices[m_NumVertices + 4*i + 2].m_Tex = m_aTexture[2]; m_aVertices[m_NumVertices + 4*i + 2].m_Color = m_aColor[2]; m_aVertices[m_NumVertices + 4*i + 3].m_Pos.x = pArray[i].m_X; m_aVertices[m_NumVertices + 4*i + 3].m_Pos.y = pArray[i].m_Y + pArray[i].m_Height; m_aVertices[m_NumVertices + 4*i + 3].m_Tex = m_aTexture[3]; m_aVertices[m_NumVertices + 4*i + 3].m_Color = m_aColor[3]; if(m_Rotation != 0) { Center.x = pArray[i].m_X + pArray[i].m_Width/2; Center.y = pArray[i].m_Y + pArray[i].m_Height/2; Rotate4(Center, &m_aVertices[m_NumVertices + 4*i]); } } AddVertices(4*Num); } void CGraphics_Threaded::QuadsDrawFreeform(const CFreeformItem *pArray, int Num) { dbg_assert(m_Drawing == DRAWING_QUADS, "called Graphics()->QuadsDrawFreeform without begin"); for(int i = 0; i < Num; ++i) { m_aVertices[m_NumVertices + 4*i].m_Pos.x = pArray[i].m_X0; m_aVertices[m_NumVertices + 4*i].m_Pos.y = pArray[i].m_Y0; m_aVertices[m_NumVertices + 4*i].m_Tex = m_aTexture[0]; m_aVertices[m_NumVertices + 4*i].m_Color = m_aColor[0]; m_aVertices[m_NumVertices + 4*i + 1].m_Pos.x = pArray[i].m_X1; m_aVertices[m_NumVertices + 4*i + 1].m_Pos.y = pArray[i].m_Y1; m_aVertices[m_NumVertices + 4*i + 1].m_Tex = m_aTexture[1]; m_aVertices[m_NumVertices + 4*i + 1].m_Color = m_aColor[1]; m_aVertices[m_NumVertices + 4*i + 2].m_Pos.x = pArray[i].m_X3; m_aVertices[m_NumVertices + 4*i + 2].m_Pos.y = pArray[i].m_Y3; m_aVertices[m_NumVertices + 4*i + 2].m_Tex = m_aTexture[3]; m_aVertices[m_NumVertices + 4*i + 2].m_Color = m_aColor[3]; m_aVertices[m_NumVertices + 4*i + 3].m_Pos.x = pArray[i].m_X2; m_aVertices[m_NumVertices + 4*i + 3].m_Pos.y = pArray[i].m_Y2; m_aVertices[m_NumVertices + 4*i + 3].m_Tex = m_aTexture[2]; m_aVertices[m_NumVertices + 4*i + 3].m_Color = m_aColor[2]; } AddVertices(4*Num); } void CGraphics_Threaded::QuadsText(float x, float y, float Size, const char *pText) { float StartX = x; while(*pText) { char c = *pText; pText++; if(c == '\n') { x = StartX; y += Size; } else { QuadsSetSubset( (c%16)/16.0f, (c/16)/16.0f, (c%16)/16.0f+1.0f/16.0f, (c/16)/16.0f+1.0f/16.0f); CQuadItem QuadItem(x, y, Size, Size); QuadsDrawTL(&QuadItem, 1); x += Size/2; } } } int CGraphics_Threaded::IssueInit() { int Flags = 0; if(g_Config.m_GfxBorderless && g_Config.m_GfxFullscreen) { dbg_msg("gfx", "both borderless and fullscreen activated, disabling borderless"); g_Config.m_GfxBorderless = 0; } if(g_Config.m_GfxBorderless) Flags |= IGraphicsBackend::INITFLAG_BORDERLESS; else if(g_Config.m_GfxFullscreen) Flags |= IGraphicsBackend::INITFLAG_FULLSCREEN; if(g_Config.m_GfxVsync) Flags |= IGraphicsBackend::INITFLAG_VSYNC; if(g_Config.m_DbgResizable) Flags |= IGraphicsBackend::INITFLAG_RESIZABLE; return m_pBackend->Init("Teeworlds", &g_Config.m_GfxScreenWidth, &g_Config.m_GfxScreenHeight, g_Config.m_GfxFsaaSamples, Flags, &m_DesktopScreenWidth, &m_DesktopScreenHeight); } int CGraphics_Threaded::InitWindow() { if(IssueInit() == 0) return 0; // try disabling fsaa while(g_Config.m_GfxFsaaSamples) { g_Config.m_GfxFsaaSamples--; if(g_Config.m_GfxFsaaSamples) dbg_msg("gfx", "lowering FSAA to %d and trying again", g_Config.m_GfxFsaaSamples); else dbg_msg("gfx", "disabling FSAA and trying again"); if(IssueInit() == 0) return 0; } // try lowering the resolution if(g_Config.m_GfxScreenWidth != 640 || g_Config.m_GfxScreenHeight != 480) { dbg_msg("gfx", "setting resolution to 640x480 and trying again"); g_Config.m_GfxScreenWidth = 640; g_Config.m_GfxScreenHeight = 480; if(IssueInit() == 0) return 0; } dbg_msg("gfx", "out of ideas. failed to init graphics"); return -1; } int CGraphics_Threaded::Init() { // fetch pointers m_pStorage = Kernel()->RequestInterface<IStorage>(); m_pConsole = Kernel()->RequestInterface<IConsole>(); // Set all z to -5.0f for(int i = 0; i < MAX_VERTICES; i++) m_aVertices[i].m_Pos.z = -5.0f; // init textures m_FirstFreeTexture = 0; for(int i = 0; i < MAX_TEXTURES-1; i++) m_aTextureIndices[i] = i+1; m_aTextureIndices[MAX_TEXTURES-1] = -1; m_pBackend = CreateGraphicsBackend(); if(InitWindow() != 0) return -1; // fetch final resolusion m_ScreenWidth = g_Config.m_GfxScreenWidth; m_ScreenHeight = g_Config.m_GfxScreenHeight; // create command buffers for(int i = 0; i < NUM_CMDBUFFERS; i++) m_apCommandBuffers[i] = new CCommandBuffer(128*1024, 2*1024*1024); m_pCommandBuffer = m_apCommandBuffers[0]; // create null texture, will get id=0 static const unsigned char aNullTextureData[] = { 0xff,0x00,0x00,0xff, 0xff,0x00,0x00,0xff, 0x00,0xff,0x00,0xff, 0x00,0xff,0x00,0xff, 0xff,0x00,0x00,0xff, 0xff,0x00,0x00,0xff, 0x00,0xff,0x00,0xff, 0x00,0xff,0x00,0xff, 0x00,0x00,0xff,0xff, 0x00,0x00,0xff,0xff, 0xff,0xff,0x00,0xff, 0xff,0xff,0x00,0xff, 0x00,0x00,0xff,0xff, 0x00,0x00,0xff,0xff, 0xff,0xff,0x00,0xff, 0xff,0xff,0x00,0xff, }; m_InvalidTexture = LoadTextureRaw(4,4,CImageInfo::FORMAT_RGBA,aNullTextureData,CImageInfo::FORMAT_RGBA,TEXLOAD_NORESAMPLE); return 0; } void CGraphics_Threaded::Shutdown() { // shutdown the backend m_pBackend->Shutdown(); delete m_pBackend; m_pBackend = 0x0; // delete the command buffers for(int i = 0; i < NUM_CMDBUFFERS; i++) delete m_apCommandBuffers[i]; } void CGraphics_Threaded::Minimize() { m_pBackend->Minimize(); } void CGraphics_Threaded::Maximize() { // TODO: SDL m_pBackend->Maximize(); } int CGraphics_Threaded::WindowActive() { return m_pBackend->WindowActive(); } int CGraphics_Threaded::WindowOpen() { return m_pBackend->WindowOpen(); } void CGraphics_Threaded::TakeScreenshot(const char *pFilename) { // TODO: screenshot support char aDate[20]; str_timestamp(aDate, sizeof(aDate)); str_format(m_aScreenshotName, sizeof(m_aScreenshotName), "screenshots/%s_%s.png", pFilename?pFilename:"screenshot", aDate); m_DoScreenshot = true; } void CGraphics_Threaded::Swap() { // TODO: screenshot support if(m_DoScreenshot) { if(WindowActive()) ScreenshotDirect(m_aScreenshotName); m_DoScreenshot = false; } // add swap command CCommandBuffer::SCommand_Swap Cmd; Cmd.m_Finish = g_Config.m_GfxFinish; m_pCommandBuffer->AddCommand(Cmd); // kick the command buffer KickCommandBuffer(); } // syncronization void CGraphics_Threaded::InsertSignal(semaphore *pSemaphore) { CCommandBuffer::SCommand_Signal Cmd; Cmd.m_pSemaphore = pSemaphore; m_pCommandBuffer->AddCommand(Cmd); } bool CGraphics_Threaded::IsIdle() { return m_pBackend->IsIdle(); } void CGraphics_Threaded::WaitForIdle() { m_pBackend->WaitForIdle(); } int CGraphics_Threaded::GetVideoModes(CVideoMode *pModes, int MaxModes) { if(g_Config.m_GfxDisplayAllModes) { int Count = sizeof(g_aFakeModes)/sizeof(CVideoMode); mem_copy(pModes, g_aFakeModes, sizeof(g_aFakeModes)); if(MaxModes < Count) Count = MaxModes; return Count; } // add videomodes command CImageInfo Image; mem_zero(&Image, sizeof(Image)); int NumModes = 0; CCommandBuffer::SCommand_VideoModes Cmd; Cmd.m_pModes = pModes; Cmd.m_MaxModes = MaxModes; Cmd.m_pNumModes = &NumModes; m_pCommandBuffer->AddCommand(Cmd); // kick the buffer and wait for the result and return it KickCommandBuffer(); WaitForIdle(); return NumModes; } extern IEngineGraphics *CreateEngineGraphicsThreaded() { return new CGraphics_Threaded(); } ================================================ FILE: src/engine/client/graphics_threaded.h ================================================ #pragma once #include <engine/graphics.h> class CCommandBuffer { class CBuffer { unsigned char *m_pData; unsigned m_Size; unsigned m_Used; public: CBuffer(unsigned BufferSize) { m_Size = BufferSize; m_pData = new unsigned char[m_Size]; m_Used = 0; } ~CBuffer() { delete [] m_pData; m_pData = 0x0; m_Used = 0; m_Size = 0; } void Reset() { m_Used = 0; } void *Alloc(unsigned Requested) { if(Requested + m_Used > m_Size) return 0; void *pPtr = &m_pData[m_Used]; m_Used += Requested; return pPtr; } unsigned char *DataPtr() { return m_pData; } unsigned DataSize() { return m_Size; } unsigned DataUsed() { return m_Used; } }; public: CBuffer m_CmdBuffer; CBuffer m_DataBuffer; enum { MAX_TEXTURES=1024*4, }; enum { // commadn groups CMDGROUP_CORE = 0, // commands that everyone has to implement CMDGROUP_PLATFORM_OPENGL = 10000, // commands specific to a platform CMDGROUP_PLATFORM_SDL = 20000, // CMD_NOP = CMDGROUP_CORE, // CMD_RUNBUFFER, // syncronization CMD_SIGNAL, // texture commands CMD_TEXTURE_CREATE, CMD_TEXTURE_DESTROY, CMD_TEXTURE_UPDATE, // rendering CMD_CLEAR, CMD_RENDER, // swap CMD_SWAP, // misc CMD_SCREENSHOT, CMD_VIDEOMODES, }; enum { TEXFORMAT_INVALID = 0, TEXFORMAT_RGB, TEXFORMAT_RGBA, TEXFORMAT_ALPHA, TEXFLAG_NOMIPMAPS = 1, TEXFLAG_COMPRESSED = 2, TEXFLAG_QUALITY = 4, }; enum { // PRIMTYPE_INVALID = 0, PRIMTYPE_LINES, PRIMTYPE_QUADS, }; enum { BLEND_NONE = 0, BLEND_ALPHA, BLEND_ADDITIVE, }; enum { WRAP_REPEAT = 0, WRAP_CLAMP, }; struct SPoint { float x, y, z; }; struct STexCoord { float u, v; }; struct SColor { float r, g, b, a; }; struct SVertex { SPoint m_Pos; STexCoord m_Tex; SColor m_Color; }; struct SCommand { public: SCommand(unsigned Cmd) : m_Cmd(Cmd), m_Size(0) {} unsigned m_Cmd; unsigned m_Size; }; struct SState { int m_BlendMode; int m_WrapMode; int m_Texture; SPoint m_ScreenTL; SPoint m_ScreenBR; // clip bool m_ClipEnable; int m_ClipX; int m_ClipY; int m_ClipW; int m_ClipH; }; struct SCommand_Clear : public SCommand { SCommand_Clear() : SCommand(CMD_CLEAR) {} SColor m_Color; }; struct SCommand_Signal : public SCommand { SCommand_Signal() : SCommand(CMD_SIGNAL) {} semaphore *m_pSemaphore; }; struct SCommand_RunBuffer : public SCommand { SCommand_RunBuffer() : SCommand(CMD_RUNBUFFER) {} CCommandBuffer *m_pOtherBuffer; }; struct SCommand_Render : public SCommand { SCommand_Render() : SCommand(CMD_RENDER) {} SState m_State; unsigned m_PrimType; unsigned m_PrimCount; SVertex *m_pVertices; // you should use the command buffer data to allocate vertices for this command }; struct SCommand_Screenshot : public SCommand { SCommand_Screenshot() : SCommand(CMD_SCREENSHOT) {} CImageInfo *m_pImage; // processor will fill this out, the one who adds this command must free the data as well }; struct SCommand_VideoModes : public SCommand { SCommand_VideoModes() : SCommand(CMD_VIDEOMODES) {} CVideoMode *m_pModes; // processor will fill this in int m_MaxModes; // maximum of modes the processor can write to the m_pModes int *m_pNumModes; // processor will write to this pointer }; struct SCommand_Swap : public SCommand { SCommand_Swap() : SCommand(CMD_SWAP) {} int m_Finish; }; struct SCommand_Texture_Create : public SCommand { SCommand_Texture_Create() : SCommand(CMD_TEXTURE_CREATE) {} // texture information int m_Slot; int m_Width; int m_Height; int m_PixelSize; int m_Format; int m_StoreFormat; int m_Flags; void *m_pData; // will be freed by the command processor }; struct SCommand_Texture_Update : public SCommand { SCommand_Texture_Update() : SCommand(CMD_TEXTURE_UPDATE) {} // texture information int m_Slot; int m_X; int m_Y; int m_Width; int m_Height; int m_Format; void *m_pData; // will be freed by the command processor }; struct SCommand_Texture_Destroy : public SCommand { SCommand_Texture_Destroy() : SCommand(CMD_TEXTURE_DESTROY) {} // texture information int m_Slot; }; // CCommandBuffer(unsigned CmdBufferSize, unsigned DataBufferSize) : m_CmdBuffer(CmdBufferSize), m_DataBuffer(DataBufferSize) { } void *AllocData(unsigned WantedSize) { return m_DataBuffer.Alloc(WantedSize); } template<class T> bool AddCommand(const T &Command) { // make sure that we don't do something stupid like ->AddCommand(&Cmd); (void)static_cast<const SCommand *>(&Command); // allocate and copy the command into the buffer SCommand *pCmd = (SCommand *)m_CmdBuffer.Alloc(sizeof(Command)); if(!pCmd) return false; mem_copy(pCmd, &Command, sizeof(Command)); pCmd->m_Size = sizeof(Command); return true; } SCommand *GetCommand(unsigned *pIndex) { if(*pIndex >= m_CmdBuffer.DataUsed()) return NULL; SCommand *pCommand = (SCommand *)&m_CmdBuffer.DataPtr()[*pIndex]; *pIndex += pCommand->m_Size; return pCommand; } void Reset() { m_CmdBuffer.Reset(); m_DataBuffer.Reset(); } }; // interface for the graphics backend // all these functions are called on the main thread class IGraphicsBackend { public: enum { INITFLAG_FULLSCREEN = 1, INITFLAG_VSYNC = 2, INITFLAG_RESIZABLE = 4, INITFLAG_BORDERLESS = 8, }; virtual ~IGraphicsBackend() {} virtual int Init(const char *pName, int *Width, int *Height, int FsaaSamples, int Flags, int *pDesktopWidth, int *pDesktopHeight) = 0; virtual int Shutdown() = 0; virtual int MemoryUsage() const = 0; virtual void Minimize() = 0; virtual void Maximize() = 0; virtual int WindowActive() = 0; virtual int WindowOpen() = 0; virtual void RunBuffer(CCommandBuffer *pBuffer) = 0; virtual bool IsIdle() const = 0; virtual void WaitForIdle() = 0; }; class CGraphics_Threaded : public IEngineGraphics { enum { NUM_CMDBUFFERS = 2, MAX_VERTICES = 32*1024, MAX_TEXTURES = 1024*4, DRAWING_QUADS=1, DRAWING_LINES=2 }; CCommandBuffer::SState m_State; IGraphicsBackend *m_pBackend; CCommandBuffer *m_apCommandBuffers[NUM_CMDBUFFERS]; CCommandBuffer *m_pCommandBuffer; unsigned m_CurrentCommandBuffer; // class IStorage *m_pStorage; class IConsole *m_pConsole; CCommandBuffer::SVertex m_aVertices[MAX_VERTICES]; int m_NumVertices; CCommandBuffer::SColor m_aColor[4]; CCommandBuffer::STexCoord m_aTexture[4]; bool m_RenderEnable; float m_Rotation; int m_Drawing; bool m_DoScreenshot; char m_aScreenshotName[128]; CTextureHandle m_InvalidTexture; int m_aTextureIndices[MAX_TEXTURES]; int m_FirstFreeTexture; int m_TextureMemoryUsage; void FlushVertices(); void AddVertices(int Count); void Rotate4(const CCommandBuffer::SPoint &rCenter, CCommandBuffer::SVertex *pPoints); void KickCommandBuffer(); int IssueInit(); int InitWindow(); public: CGraphics_Threaded(); virtual void ClipEnable(int x, int y, int w, int h); virtual void ClipDisable(); virtual void BlendNone(); virtual void BlendNormal(); virtual void BlendAdditive(); virtual void WrapNormal(); virtual void WrapClamp(); virtual int MemoryUsage() const; virtual void MapScreen(float TopLeftX, float TopLeftY, float BottomRightX, float BottomRightY); virtual void GetScreen(float *pTopLeftX, float *pTopLeftY, float *pBottomRightX, float *pBottomRightY); virtual void LinesBegin(); virtual void LinesEnd(); virtual void LinesDraw(const CLineItem *pArray, int Num); virtual int UnloadTexture(IGraphics::CTextureHandle Index); virtual IGraphics::CTextureHandle LoadTextureRaw(int Width, int Height, int Format, const void *pData, int StoreFormat, int Flags); virtual int LoadTextureRawSub(IGraphics::CTextureHandle TextureID, int x, int y, int Width, int Height, int Format, const void *pData); // simple uncompressed RGBA loaders virtual IGraphics::CTextureHandle LoadTexture(const char *pFilename, int StorageType, int StoreFormat, int Flags); virtual int LoadPNG(CImageInfo *pImg, const char *pFilename, int StorageType); void ScreenshotDirect(const char *pFilename); virtual void TextureSet(CTextureHandle TextureID); virtual void Clear(float r, float g, float b); virtual void QuadsBegin(); virtual void QuadsEnd(); virtual void QuadsSetRotation(float Angle); virtual void SetColorVertex(const CColorVertex *pArray, int Num); virtual void SetColor(float r, float g, float b, float a); virtual void SetColor4(vec4 TopLeft, vec4 TopRight, vec4 BottomLeft, vec4 BottomRight); virtual void QuadsSetSubset(float TlU, float TlV, float BrU, float BrV); virtual void QuadsSetSubsetFree( float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3); virtual void QuadsDraw(CQuadItem *pArray, int Num); virtual void QuadsDrawTL(const CQuadItem *pArray, int Num); virtual void QuadsDrawFreeform(const CFreeformItem *pArray, int Num); virtual void QuadsText(float x, float y, float Size, const char *pText); virtual void Minimize(); virtual void Maximize(); virtual int WindowActive(); virtual int WindowOpen(); virtual int Init(); virtual void Shutdown(); virtual void TakeScreenshot(const char *pFilename); virtual void Swap(); virtual int GetVideoModes(CVideoMode *pModes, int MaxModes); virtual int GetDesktopScreenWidth() { return m_DesktopScreenWidth; } virtual int GetDesktopScreenHeight() { return m_DesktopScreenHeight; } // syncronization virtual void InsertSignal(semaphore *pSemaphore); virtual bool IsIdle(); virtual void WaitForIdle(); }; extern IGraphicsBackend *CreateGraphicsBackend(); ================================================ FILE: src/engine/client/input.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include "SDL.h" #include <base/system.h> #include <engine/shared/config.h> #include <engine/graphics.h> #include <engine/input.h> #include <engine/keys.h> #include "input.h" //print >>f, "int inp_key_code(const char *key_name) { int i; if (!strcmp(key_name, \"-?-\")) return -1; else for (i = 0; i < 512; i++) if (!strcmp(key_strings[i], key_name)) return i; return -1; }" // this header is protected so you don't include it from anywere #define KEYS_INCLUDE #include "keynames.h" #undef KEYS_INCLUDE void CInput::AddEvent(int Unicode, int Key, int Flags) { if(m_NumEvents != INPUT_BUFFER_SIZE) { m_aInputEvents[m_NumEvents].m_Unicode = Unicode; m_aInputEvents[m_NumEvents].m_Key = Key; m_aInputEvents[m_NumEvents].m_Flags = Flags; m_NumEvents++; } } CInput::CInput() { mem_zero(m_aInputCount, sizeof(m_aInputCount)); mem_zero(m_aInputState, sizeof(m_aInputState)); m_InputCurrent = 0; m_InputGrabbed = 0; m_InputDispatched = false; m_LastRelease = 0; m_ReleaseDelta = -1; m_NumEvents = 0; } void CInput::Init() { m_pGraphics = Kernel()->RequestInterface<IEngineGraphics>(); SDL_EnableUNICODE(1); SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL); } void CInput::MouseRelative(float *x, float *y) { int nx = 0, ny = 0; float Sens = g_Config.m_InpMousesens/100.0f; if(g_Config.m_InpGrab) SDL_GetRelativeMouseState(&nx, &ny); else { if(m_InputGrabbed) { SDL_GetMouseState(&nx,&ny); SDL_WarpMouse(Graphics()->ScreenWidth()/2,Graphics()->ScreenHeight()/2); nx -= Graphics()->ScreenWidth()/2; ny -= Graphics()->ScreenHeight()/2; } } *x = nx*Sens; *y = ny*Sens; } void CInput::MouseModeAbsolute() { SDL_ShowCursor(1); m_InputGrabbed = 0; if(g_Config.m_InpGrab) SDL_WM_GrabInput(SDL_GRAB_OFF); } void CInput::MouseModeRelative() { SDL_ShowCursor(0); m_InputGrabbed = 1; if(g_Config.m_InpGrab) SDL_WM_GrabInput(SDL_GRAB_ON); } int CInput::MouseDoubleClick() { if(m_ReleaseDelta >= 0 && m_ReleaseDelta < (time_freq() >> 2)) { m_LastRelease = 0; m_ReleaseDelta = -1; return 1; } return 0; } void CInput::ClearKeyStates() { mem_zero(m_aInputState, sizeof(m_aInputState)); mem_zero(m_aInputCount, sizeof(m_aInputCount)); } int CInput::KeyState(int Key) { return m_aInputState[m_InputCurrent][Key]; } int CInput::Update() { if(m_InputGrabbed && !Graphics()->WindowActive()) MouseModeAbsolute(); /*if(!input_grabbed && Graphics()->WindowActive()) Input()->MouseModeRelative();*/ if(m_InputDispatched) { // clear and begin count on the other one m_InputCurrent^=1; mem_zero(&m_aInputCount[m_InputCurrent], sizeof(m_aInputCount[m_InputCurrent])); mem_zero(&m_aInputState[m_InputCurrent], sizeof(m_aInputState[m_InputCurrent])); m_InputDispatched = false; } { int i; Uint8 *pState = SDL_GetKeyState(&i); if(i >= KEY_LAST) i = KEY_LAST-1; mem_copy(m_aInputState[m_InputCurrent], pState, i); } // these states must always be updated manually because they are not in the GetKeyState from SDL int i = SDL_GetMouseState(NULL, NULL); if(i&SDL_BUTTON(1)) m_aInputState[m_InputCurrent][KEY_MOUSE_1] = 1; // 1 is left if(i&SDL_BUTTON(3)) m_aInputState[m_InputCurrent][KEY_MOUSE_2] = 1; // 3 is right if(i&SDL_BUTTON(2)) m_aInputState[m_InputCurrent][KEY_MOUSE_3] = 1; // 2 is middle if(i&SDL_BUTTON(4)) m_aInputState[m_InputCurrent][KEY_MOUSE_4] = 1; if(i&SDL_BUTTON(5)) m_aInputState[m_InputCurrent][KEY_MOUSE_5] = 1; if(i&SDL_BUTTON(6)) m_aInputState[m_InputCurrent][KEY_MOUSE_6] = 1; if(i&SDL_BUTTON(7)) m_aInputState[m_InputCurrent][KEY_MOUSE_7] = 1; if(i&SDL_BUTTON(8)) m_aInputState[m_InputCurrent][KEY_MOUSE_8] = 1; { SDL_Event Event; while(SDL_PollEvent(&Event)) { int Key = -1; int Action = IInput::FLAG_PRESS; switch (Event.type) { // handle keys case SDL_KEYDOWN: // skip private use area of the BMP(contains the unicodes for keyboard function keys on MacOS) if(Event.key.keysym.unicode < 0xE000 || Event.key.keysym.unicode > 0xF8FF) // ignore_convention AddEvent(Event.key.keysym.unicode, 0, 0); // ignore_convention Key = Event.key.keysym.sym; // ignore_convention break; case SDL_KEYUP: Action = IInput::FLAG_RELEASE; Key = Event.key.keysym.sym; // ignore_convention break; // handle mouse buttons case SDL_MOUSEBUTTONUP: Action = IInput::FLAG_RELEASE; if(Event.button.button == 1) // ignore_convention { m_ReleaseDelta = time_get() - m_LastRelease; m_LastRelease = time_get(); } // fall through case SDL_MOUSEBUTTONDOWN: if(Event.button.button == SDL_BUTTON_LEFT) Key = KEY_MOUSE_1; // ignore_convention if(Event.button.button == SDL_BUTTON_RIGHT) Key = KEY_MOUSE_2; // ignore_convention if(Event.button.button == SDL_BUTTON_MIDDLE) Key = KEY_MOUSE_3; // ignore_convention if(Event.button.button == SDL_BUTTON_WHEELUP) Key = KEY_MOUSE_WHEEL_UP; // ignore_convention if(Event.button.button == SDL_BUTTON_WHEELDOWN) Key = KEY_MOUSE_WHEEL_DOWN; // ignore_convention if(Event.button.button == 6) Key = KEY_MOUSE_6; // ignore_convention if(Event.button.button == 7) Key = KEY_MOUSE_7; // ignore_convention if(Event.button.button == 8) Key = KEY_MOUSE_8; // ignore_convention break; // other messages case SDL_QUIT: return 1; } // if(Key != -1) { m_aInputCount[m_InputCurrent][Key].m_Presses++; if(Action == IInput::FLAG_PRESS) m_aInputState[m_InputCurrent][Key] = 1; AddEvent(0, Key, Action); } } } return 0; } IEngineInput *CreateEngineInput() { return new CInput; } ================================================ FILE: src/engine/client/input.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef ENGINE_CLIENT_INPUT_H #define ENGINE_CLIENT_INPUT_H class CInput : public IEngineInput { IEngineGraphics *m_pGraphics; int m_InputGrabbed; int64 m_LastRelease; int64 m_ReleaseDelta; void AddEvent(int Unicode, int Key, int Flags); IEngineGraphics *Graphics() { return m_pGraphics; } public: CInput(); virtual void Init(); virtual void MouseRelative(float *x, float *y); virtual void MouseModeAbsolute(); virtual void MouseModeRelative(); virtual int MouseDoubleClick(); void ClearKeyStates(); int KeyState(int Key); int ButtonPressed(int Button) { return m_aInputState[m_InputCurrent][Button]; } virtual int Update(); }; #endif ================================================ FILE: src/engine/client/keynames.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ /* AUTO GENERATED! DO NOT EDIT MANUALLY! */ #ifndef KEYS_INCLUDE #error do not include this header! #endif #include <string.h> const char g_aaKeyStrings[512][16] = { "first", "&1", "&2", "&3", "&4", "&5", "&6", "&7", "backspace", "tab", "&10", "&11", "clear", "return", "&14", "&15", "&16", "&17", "&18", "pause", "&20", "&21", "&22", "&23", "&24", "&25", "&26", "escape", "&28", "&29", "&30", "&31", "space", "exclaim", "quotedbl", "hash", "dollar", "&37", "ampersand", "quote", "leftparen", "rightparen", "asterisk", "plus", "comma", "minus", "period", "slash", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "colon", "semicolon", "less", "equals", "greater", "question", "at", "&65", "&66", "&67", "&68", "&69", "&70", "&71", "&72", "&73", "&74", "&75", "&76", "&77", "&78", "&79", "&80", "&81", "&82", "&83", "&84", "&85", "&86", "&87", "&88", "&89", "&90", "leftbracket", "backslash", "rightbracket", "caret", "underscore", "backquote", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "&123", "&124", "&125", "&126", "delete", "&128", "&129", "&130", "&131", "&132", "&133", "&134", "&135", "&136", "&137", "&138", "&139", "&140", "&141", "&142", "&143", "&144", "&145", "&146", "&147", "&148", "&149", "&150", "&151", "&152", "&153", "&154", "&155", "&156", "&157", "&158", "&159", "world_0", "world_1", "world_2", "world_3", "world_4", "world_5", "world_6", "world_7", "world_8", "world_9", "world_10", "world_11", "world_12", "world_13", "world_14", "world_15", "world_16", "world_17", "world_18", "world_19", "world_20", "world_21", "world_22", "world_23", "world_24", "world_25", "world_26", "world_27", "world_28", "world_29", "world_30", "world_31", "world_32", "world_33", "world_34", "world_35", "world_36", "world_37", "world_38", "world_39", "world_40", "world_41", "world_42", "world_43", "world_44", "world_45", "world_46", "world_47", "world_48", "world_49", "world_50", "world_51", "world_52", "world_53", "world_54", "world_55", "world_56", "world_57", "world_58", "world_59", "world_60", "world_61", "world_62", "world_63", "world_64", "world_65", "world_66", "world_67", "world_68", "world_69", "world_70", "world_71", "world_72", "world_73", "world_74", "world_75", "world_76", "world_77", "world_78", "world_79", "world_80", "world_81", "world_82", "world_83", "world_84", "world_85", "world_86", "world_87", "world_88", "world_89", "world_90", "world_91", "world_92", "world_93", "world_94", "world_95", "kp0", "kp1", "kp2", "kp3", "kp4", "kp5", "kp6", "kp7", "kp8", "kp9", "kp_period", "kp_divide", "kp_multiply", "kp_minus", "kp_plus", "kp_enter", "kp_equals", "up", "down", "right", "left", "insert", "home", "end", "pageup", "pagedown", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "f10", "f11", "f12", "f13", "f14", "f15", "&297", "&298", "&299", "numlock", "capslock", "scrollock", "rshift", "lshift", "rctrl", "lctrl", "ralt", "lalt", "rmeta", "lmeta", "lsuper", "rsuper", "mode", "compose", "help", "print", "sysreq", "break", "menu", "power", "euro", "undo", "mouse1", "mouse2", "mouse3", "mouse4", "mouse5", "mouse6", "mouse7", "mouse8", "mousewheelup", "mousewheeldown", "&333", "&334", "&335", "&336", "&337", "&338", "&339", "&340", "&341", "&342", "&343", "&344", "&345", "&346", "&347", "&348", "&349", "&350", "&351", "&352", "&353", "&354", "&355", "&356", "&357", "&358", "&359", "&360", "&361", "&362", "&363", "&364", "&365", "&366", "&367", "&368", "&369", "&370", "&371", "&372", "&373", "&374", "&375", "&376", "&377", "&378", "&379", "&380", "&381", "&382", "&383", "&384", "&385", "&386", "&387", "&388", "&389", "&390", "&391", "&392", "&393", "&394", "&395", "&396", "&397", "&398", "&399", "&400", "&401", "&402", "&403", "&404", "&405", "&406", "&407", "&408", "&409", "&410", "&411", "&412", "&413", "&414", "&415", "&416", "&417", "&418", "&419", "&420", "&421", "&422", "&423", "&424", "&425", "&426", "&427", "&428", "&429", "&430", "&431", "&432", "&433", "&434", "&435", "&436", "&437", "&438", "&439", "&440", "&441", "&442", "&443", "&444", "&445", "&446", "&447", "&448", "&449", "&450", "&451", "&452", "&453", "&454", "&455", "&456", "&457", "&458", "&459", "&460", "&461", "&462", "&463", "&464", "&465", "&466", "&467", "&468", "&469", "&470", "&471", "&472", "&473", "&474", "&475", "&476", "&477", "&478", "&479", "&480", "&481", "&482", "&483", "&484", "&485", "&486", "&487", "&488", "&489", "&490", "&491", "&492", "&493", "&494", "&495", "&496", "&497", "&498", "&499", "&500", "&501", "&502", "&503", "&504", "&505", "&506", "&507", "&508", "&509", "&510", "&511", }; ================================================ FILE: src/engine/client/serverbrowser.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <algorithm> // sort TODO: remove this #include <base/math.h> #include <base/system.h> #include <engine/shared/config.h> #include <engine/shared/memheap.h> #include <engine/shared/network.h> #include <engine/shared/protocol.h> #include <engine/config.h> #include <engine/console.h> #include <engine/engine.h> #include <engine/friends.h> #include <engine/masterserver.h> #include <mastersrv/mastersrv.h> #include "serverbrowser.h" class SortWrap { typedef bool (CServerBrowser::CServerFilter::*SortFunc)(int, int) const; SortFunc m_pfnSort; CServerBrowser::CServerFilter *m_pThis; public: SortWrap(CServerBrowser::CServerFilter *t, SortFunc f) : m_pfnSort(f), m_pThis(t) {} bool operator()(int a, int b) { return (g_Config.m_BrSortOrder ? (m_pThis->*m_pfnSort)(b, a) : (m_pThis->*m_pfnSort)(a, b)); } }; CServerBrowser::CServerBrowser() { m_pMasterServer = 0; // favorites m_NumFavoriteServers = 0; m_FavLookup.m_LookupCount = 0; m_FavLookup.m_Active = false; // mem_zero(m_aServerlistIp, sizeof(m_aServerlistIp)); m_pFirstReqServer = 0; // request list m_pLastReqServer = 0; m_NumRequests = 0; m_NeedRefresh = 0; m_NumServers = 0; m_NumServerCapacity = 0; m_NumPlayers = 0; // the token is to keep server refresh separated from each other m_CurrentToken = 1; m_ServerlistType = 0; m_BroadcastTime = 0; } int CServerBrowser::AddFilter(int SortHash, int Ping, int Country, const char* pGametype, const char* pServerAddress) { CServerFilter Filter; Filter.m_SortHash = SortHash; Filter.m_Ping = Ping; Filter.m_Country = Country; str_copy(Filter.m_aGametype, pGametype, sizeof(Filter.m_aGametype)); str_copy(Filter.m_aServerAddress, pServerAddress, sizeof(Filter.m_aServerAddress)); Filter.m_pSortedServerlist = 0; Filter.m_NumSortedServers = 0; Filter.m_NumSortedServersCapacity = 0; Filter.m_NumPlayers = 0; Filter.m_pServerBrowser = this; m_lFilters.add(Filter); return m_lFilters.size()-1; } void CServerBrowser::GetFilter(int Index, int *pSortHash, int *pPing, int *pCountry, char* pGametype, char* pServerAddress) { CServerFilter *pFilter = &m_lFilters[Index]; *pSortHash = pFilter->m_SortHash; *pPing = pFilter->m_Ping; *pCountry = pFilter->m_Country; str_copy(pGametype, pFilter->m_aGametype, sizeof(pFilter->m_aGametype)); str_copy(pServerAddress, pFilter->m_aServerAddress, sizeof(pFilter->m_aServerAddress)); } void CServerBrowser::SetFilter(int Index, int SortHash, int Ping, int Country, const char* pGametype, const char* pServerAddress) { CServerFilter *pFilter = &m_lFilters[Index]; pFilter->m_SortHash = SortHash; pFilter->m_Ping = Ping; pFilter->m_Country = Country; str_copy(pFilter->m_aGametype, pGametype, sizeof(pFilter->m_aGametype)); str_copy(pFilter->m_aServerAddress, pServerAddress, sizeof(pFilter->m_aServerAddress)); pFilter->m_pServerBrowser->Update(true); } void CServerBrowser::RemoveFilter(int Index) { m_lFilters.remove_index(Index); } void CServerBrowser::SetBaseInfo(class CNetClient *pClient, const char *pNetVersion) { m_pNetClient = pClient; str_copy(m_aNetVersion, pNetVersion, sizeof(m_aNetVersion)); m_pMasterServer = Kernel()->RequestInterface<IMasterServer>(); m_pConsole = Kernel()->RequestInterface<IConsole>(); m_pEngine = Kernel()->RequestInterface<IEngine>(); m_pFriends = Kernel()->RequestInterface<IFriends>(); IConfig *pConfig = Kernel()->RequestInterface<IConfig>(); if(pConfig) pConfig->RegisterCallback(ConfigSaveCallback, this); m_pConsole->Register("add_favorite", "s", CFGFLAG_CLIENT, ConAddFavorite, this, "Add a server as a favorite"); m_pConsole->Register("remove_favorite", "s", CFGFLAG_CLIENT, ConRemoveFavorite, this, "Remove a server from favorites"); } const CServerInfo *CServerBrowser::SortedGet(int FilterIndex, int Index) const { if(Index < 0 || Index >= m_lFilters[FilterIndex].m_NumSortedServers) return 0; return &m_ppServerlist[m_lFilters[FilterIndex].m_pSortedServerlist[Index]]->m_Info; } const void *CServerBrowser::GetID(int FilterIndex, int Index) const { return &m_lFilters[FilterIndex].m_pSortedServerlist[Index]; } CServerBrowser::CServerFilter::~CServerFilter() { mem_free(m_pSortedServerlist); } bool CServerBrowser::CServerFilter::SortCompareName(int Index1, int Index2) const { CServerEntry *a = m_pServerBrowser->m_ppServerlist[Index1]; CServerEntry *b = m_pServerBrowser->m_ppServerlist[Index2]; // make sure empty entries are listed last return (a->m_GotInfo && b->m_GotInfo) || (!a->m_GotInfo && !b->m_GotInfo) ? str_comp_nocase(a->m_Info.m_aName, b->m_Info.m_aName) < 0 : a->m_GotInfo ? true : false; } bool CServerBrowser::CServerFilter::SortCompareMap(int Index1, int Index2) const { CServerEntry *a = m_pServerBrowser->m_ppServerlist[Index1]; CServerEntry *b = m_pServerBrowser->m_ppServerlist[Index2]; int Result = str_comp_nocase(a->m_Info.m_aMap, b->m_Info.m_aMap); return Result < 0 || (Result == 0 && (a->m_Info.m_Flags&FLAG_PURE) && !(b->m_Info.m_Flags&FLAG_PURE)); } bool CServerBrowser::CServerFilter::SortComparePing(int Index1, int Index2) const { CServerEntry *a = m_pServerBrowser->m_ppServerlist[Index1]; CServerEntry *b = m_pServerBrowser->m_ppServerlist[Index2]; return a->m_Info.m_Latency < b->m_Info.m_Latency || (a->m_Info.m_Latency == b->m_Info.m_Latency && (a->m_Info.m_Flags&FLAG_PURE) && !(b->m_Info.m_Flags&FLAG_PURE)); } bool CServerBrowser::CServerFilter::SortCompareGametype(int Index1, int Index2) const { CServerEntry *a = m_pServerBrowser->m_ppServerlist[Index1]; CServerEntry *b = m_pServerBrowser->m_ppServerlist[Index2]; return str_comp_nocase(a->m_Info.m_aGameType, b->m_Info.m_aGameType) < 0; } bool CServerBrowser::CServerFilter::SortCompareNumPlayers(int Index1, int Index2) const { CServerEntry *a = m_pServerBrowser->m_ppServerlist[Index1]; CServerEntry *b = m_pServerBrowser->m_ppServerlist[Index2]; return a->m_Info.m_NumPlayers < b->m_Info.m_NumPlayers || (a->m_Info.m_NumPlayers == b->m_Info.m_NumPlayers && !(a->m_Info.m_Flags&FLAG_PURE) && (b->m_Info.m_Flags&FLAG_PURE)); } bool CServerBrowser::CServerFilter::SortCompareNumClients(int Index1, int Index2) const { CServerEntry *a = m_pServerBrowser->m_ppServerlist[Index1]; CServerEntry *b = m_pServerBrowser->m_ppServerlist[Index2]; return a->m_Info.m_NumClients < b->m_Info.m_NumClients || (a->m_Info.m_NumClients == b->m_Info.m_NumClients && !(a->m_Info.m_Flags&FLAG_PURE) && (b->m_Info.m_Flags&FLAG_PURE)); } void CServerBrowser::CServerFilter::Filter() { int NumServers = m_pServerBrowser->m_NumServers; m_NumSortedServers = 0; m_NumPlayers = 0; // allocate the sorted list if(m_NumSortedServersCapacity < NumServers) { if(m_pSortedServerlist) mem_free(m_pSortedServerlist); m_NumSortedServersCapacity = max(1000, NumServers+NumServers/2); m_pSortedServerlist = (int *)mem_alloc(m_NumSortedServersCapacity*sizeof(int), 1); } // filter the servers for(int i = 0; i < NumServers; i++) { int Filtered = 0; if(m_SortHash&FILTER_EMPTY && ((m_SortHash&FILTER_SPECTATORS && m_pServerBrowser->m_ppServerlist[i]->m_Info.m_NumPlayers == 0) || m_pServerBrowser->m_ppServerlist[i]->m_Info.m_NumClients == 0)) Filtered = 1; else if(m_SortHash&FILTER_FULL && ((m_SortHash&FILTER_SPECTATORS && m_pServerBrowser->m_ppServerlist[i]->m_Info.m_NumPlayers == m_pServerBrowser->m_ppServerlist[i]->m_Info.m_MaxPlayers) || m_pServerBrowser->m_ppServerlist[i]->m_Info.m_NumClients == m_pServerBrowser->m_ppServerlist[i]->m_Info.m_MaxClients)) Filtered = 1; else if(m_SortHash&FILTER_PW && m_pServerBrowser->m_ppServerlist[i]->m_Info.m_Flags&FLAG_PASSWORD) Filtered = 1; else if(m_SortHash&FILTER_FAVORITE && !m_pServerBrowser->m_ppServerlist[i]->m_Info.m_Favorite) Filtered = 1; else if(m_SortHash&FILTER_PURE && !(m_pServerBrowser->m_ppServerlist[i]->m_Info.m_Flags&FLAG_PURE)) Filtered = 1; else if(m_SortHash&FILTER_PURE_MAP && !(m_pServerBrowser->m_ppServerlist[i]->m_Info.m_Flags&FLAG_PUREMAP)) Filtered = 1; else if(m_SortHash&FILTER_PING && m_Ping < m_pServerBrowser->m_ppServerlist[i]->m_Info.m_Latency) Filtered = 1; else if(m_SortHash&FILTER_COMPAT_VERSION && str_comp_num(m_pServerBrowser->m_ppServerlist[i]->m_Info.m_aVersion, m_pServerBrowser->m_aNetVersion, 3) != 0) Filtered = 1; else if(m_aServerAddress[0] && !str_find_nocase(m_pServerBrowser->m_ppServerlist[i]->m_Info.m_aAddress, m_aServerAddress)) Filtered = 1; else if(m_SortHash&FILTER_GAMETYPE_STRICT && m_aGametype[0] && str_comp_nocase(m_pServerBrowser->m_ppServerlist[i]->m_Info.m_aGameType, m_aGametype)) Filtered = 1; else if(!(m_SortHash&FILTER_GAMETYPE_STRICT) && m_aGametype[0] && !str_find_nocase(m_pServerBrowser->m_ppServerlist[i]->m_Info.m_aGameType, m_aGametype)) Filtered = 1; else { if(m_SortHash&FILTER_COUNTRY) { Filtered = 1; // match against player country for(int p = 0; p < m_pServerBrowser->m_ppServerlist[i]->m_Info.m_NumClients; p++) { if(m_pServerBrowser->m_ppServerlist[i]->m_Info.m_aClients[p].m_Country == m_Country) { Filtered = 0; break; } } } if(!Filtered && g_Config.m_BrFilterString[0] != 0) { int MatchFound = 0; m_pServerBrowser->m_ppServerlist[i]->m_Info.m_QuickSearchHit = 0; // match against server name if(str_find_nocase(m_pServerBrowser->m_ppServerlist[i]->m_Info.m_aName, g_Config.m_BrFilterString)) { MatchFound = 1; m_pServerBrowser->m_ppServerlist[i]->m_Info.m_QuickSearchHit |= IServerBrowser::QUICK_SERVERNAME; } // match against players for(int p = 0; p < m_pServerBrowser->m_ppServerlist[i]->m_Info.m_NumClients; p++) { if(str_find_nocase(m_pServerBrowser->m_ppServerlist[i]->m_Info.m_aClients[p].m_aName, g_Config.m_BrFilterString) || str_find_nocase(m_pServerBrowser->m_ppServerlist[i]->m_Info.m_aClients[p].m_aClan, g_Config.m_BrFilterString)) { MatchFound = 1; m_pServerBrowser->m_ppServerlist[i]->m_Info.m_QuickSearchHit |= IServerBrowser::QUICK_PLAYER; break; } } // match against map if(str_find_nocase(m_pServerBrowser->m_ppServerlist[i]->m_Info.m_aMap, g_Config.m_BrFilterString)) { MatchFound = 1; m_pServerBrowser->m_ppServerlist[i]->m_Info.m_QuickSearchHit |= IServerBrowser::QUICK_MAPNAME; } if(!MatchFound) Filtered = 1; } } if(Filtered == 0) { // check for friend m_pServerBrowser->m_ppServerlist[i]->m_Info.m_FriendState = IFriends::FRIEND_NO; for(int p = 0; p < m_pServerBrowser->m_ppServerlist[i]->m_Info.m_NumClients; p++) { m_pServerBrowser->m_ppServerlist[i]->m_Info.m_aClients[p].m_FriendState = m_pServerBrowser->m_pFriends->GetFriendState(m_pServerBrowser->m_ppServerlist[i]->m_Info.m_aClients[p].m_aName, m_pServerBrowser->m_ppServerlist[i]->m_Info.m_aClients[p].m_aClan); m_pServerBrowser->m_ppServerlist[i]->m_Info.m_FriendState = max(m_pServerBrowser->m_ppServerlist[i]->m_Info.m_FriendState, m_pServerBrowser->m_ppServerlist[i]->m_Info.m_aClients[p].m_FriendState); } if(!(m_SortHash&FILTER_FRIENDS) || m_pServerBrowser->m_ppServerlist[i]->m_Info.m_FriendState != IFriends::FRIEND_NO) { m_pSortedServerlist[m_NumSortedServers++] = i; m_NumPlayers += m_pServerBrowser->m_ppServerlist[i]->m_Info.m_NumPlayers; } } } } int CServerBrowser::CServerFilter::SortHash() const { int i = g_Config.m_BrSort&0xf; i |= g_Config.m_BrSortOrder<<4; if(m_SortHash&FILTER_EMPTY) i |= 1<<5; if(m_SortHash&FILTER_FULL) i |= 1<<6; if(m_SortHash&FILTER_SPECTATORS) i |= 1<<7; if(m_SortHash&FILTER_FRIENDS) i |= 1<<8; if(m_SortHash&FILTER_PW) i |= 1<<9; if(m_SortHash&FILTER_FAVORITE) i |= 1<<10; if(m_SortHash&FILTER_COMPAT_VERSION) i |= 1<<11; if(m_SortHash&FILTER_PURE) i |= 1<<12; if(m_SortHash&FILTER_PURE_MAP) i |= 1<<13; if(m_SortHash&FILTER_GAMETYPE_STRICT) i |= 1<<14; if(m_SortHash&FILTER_COUNTRY) i |= 1<<15; if(m_SortHash&FILTER_PING) i |= 1<<16; return i; } void CServerBrowser::CServerFilter::Sort() { // create filtered list Filter(); // sort switch(g_Config.m_BrSort) { case IServerBrowser::SORT_NAME: std::stable_sort(m_pSortedServerlist, m_pSortedServerlist+m_NumSortedServers, SortWrap(this, &CServerBrowser::CServerFilter::SortCompareName)); break; case IServerBrowser::SORT_PING: std::stable_sort(m_pSortedServerlist, m_pSortedServerlist+m_NumSortedServers, SortWrap(this, &CServerBrowser::CServerFilter::SortComparePing)); break; case IServerBrowser::SORT_MAP: std::stable_sort(m_pSortedServerlist, m_pSortedServerlist+m_NumSortedServers, SortWrap(this, &CServerBrowser::CServerFilter::SortCompareMap)); break; case IServerBrowser::SORT_NUMPLAYERS: std::stable_sort(m_pSortedServerlist, m_pSortedServerlist+m_NumSortedServers, SortWrap(this, g_Config.m_BrFilterSpectators ? &CServerBrowser::CServerFilter::SortCompareNumPlayers : &CServerBrowser::CServerFilter::SortCompareNumClients)); break; case IServerBrowser::SORT_GAMETYPE: std::stable_sort(m_pSortedServerlist, m_pSortedServerlist+m_NumSortedServers, SortWrap(this, &CServerBrowser::CServerFilter::SortCompareGametype)); } // set indexes /*for(i = 0; i < m_NumSortedServers; i++) m_ppServerlist[m_pSortedServerlist[i]]->m_Info.m_SortedIndex = i;*/ m_SortHash = SortHash(); } void CServerBrowser::RemoveRequest(CServerEntry *pEntry) { if(pEntry->m_pPrevReq || pEntry->m_pNextReq || m_pFirstReqServer == pEntry) { if(pEntry->m_pPrevReq) pEntry->m_pPrevReq->m_pNextReq = pEntry->m_pNextReq; else m_pFirstReqServer = pEntry->m_pNextReq; if(pEntry->m_pNextReq) pEntry->m_pNextReq->m_pPrevReq = pEntry->m_pPrevReq; else m_pLastReqServer = pEntry->m_pPrevReq; pEntry->m_pPrevReq = 0; pEntry->m_pNextReq = 0; m_NumRequests--; } } inline int AddrHash(const NETADDR *pAddr) { if(pAddr->type==NETTYPE_IPV4) return (pAddr->ip[0]+pAddr->ip[1]+pAddr->ip[2]+pAddr->ip[3])&0xFF; else return (pAddr->ip[0]+pAddr->ip[1]+pAddr->ip[2]+pAddr->ip[3]+pAddr->ip[4]+pAddr->ip[5]+pAddr->ip[6]+pAddr->ip[7]+ pAddr->ip[8]+pAddr->ip[9]+pAddr->ip[10]+pAddr->ip[11]+pAddr->ip[12]+pAddr->ip[13]+pAddr->ip[14]+pAddr->ip[15])&0xFF; } CServerBrowser::CServerEntry *CServerBrowser::Find(const NETADDR &Addr) { CServerEntry *pEntry = m_aServerlistIp[AddrHash(&Addr)]; for(; pEntry; pEntry = pEntry->m_pNextIp) { if(net_addr_comp(&pEntry->m_Addr, &Addr) == 0) return pEntry; } return (CServerEntry*)0; } void CServerBrowser::QueueRequest(CServerEntry *pEntry) { // add it to the list of servers that we should request info from pEntry->m_pPrevReq = m_pLastReqServer; if(m_pLastReqServer) m_pLastReqServer->m_pNextReq = pEntry; else m_pFirstReqServer = pEntry; m_pLastReqServer = pEntry; m_NumRequests++; } void CServerBrowser::SetInfo(CServerEntry *pEntry, const CServerInfo &Info) { int Fav = pEntry->m_Info.m_Favorite; pEntry->m_Info = Info; pEntry->m_Info.m_Flags &= FLAG_PASSWORD; if(str_comp(pEntry->m_Info.m_aGameType, "DM") == 0 || str_comp(pEntry->m_Info.m_aGameType, "TDM") == 0 || str_comp(pEntry->m_Info.m_aGameType, "CTF") == 0 || str_comp(pEntry->m_Info.m_aGameType, "SUR") == 0 || str_comp(pEntry->m_Info.m_aGameType, "LMS") == 0) pEntry->m_Info.m_Flags |= FLAG_PURE; if(str_comp(pEntry->m_Info.m_aMap, "dm1") == 0 || str_comp(pEntry->m_Info.m_aMap, "dm2") == 0 || str_comp(pEntry->m_Info.m_aMap, "dm6") == 0 || str_comp(pEntry->m_Info.m_aMap, "dm7") == 0 || str_comp(pEntry->m_Info.m_aMap, "dm8") == 0 || str_comp(pEntry->m_Info.m_aMap, "dm9") == 0 || str_comp(pEntry->m_Info.m_aMap, "ctf1") == 0 || str_comp(pEntry->m_Info.m_aMap, "ctf2") == 0 || str_comp(pEntry->m_Info.m_aMap, "ctf3") == 0 || str_comp(pEntry->m_Info.m_aMap, "ctf4") == 0 || str_comp(pEntry->m_Info.m_aMap, "ctf5") == 0 || str_comp(pEntry->m_Info.m_aMap, "ctf6") == 0 || str_comp(pEntry->m_Info.m_aMap, "ctf7") == 0) pEntry->m_Info.m_Flags |= FLAG_PUREMAP; pEntry->m_Info.m_Favorite = Fav; pEntry->m_Info.m_NetAddr = pEntry->m_Addr; m_NumPlayers += pEntry->m_Info.m_NumPlayers; pEntry->m_GotInfo = 1; } CServerBrowser::CServerEntry *CServerBrowser::Add(const NETADDR &Addr) { // create new pEntry CServerEntry *pEntry = (CServerEntry *)m_ServerlistHeap.Allocate(sizeof(CServerEntry)); mem_zero(pEntry, sizeof(CServerEntry)); // set the info pEntry->m_Addr = Addr; pEntry->m_Info.m_NetAddr = Addr; pEntry->m_Info.m_Latency = 999; net_addr_str(&Addr, pEntry->m_Info.m_aAddress, sizeof(pEntry->m_Info.m_aAddress), true); str_copy(pEntry->m_Info.m_aName, pEntry->m_Info.m_aAddress, sizeof(pEntry->m_Info.m_aName)); str_copy(pEntry->m_Info.m_aHostname, pEntry->m_Info.m_aAddress, sizeof(pEntry->m_Info.m_aHostname)); // check if it's a favorite for(int i = 0; i < m_NumFavoriteServers; i++) { if(m_aFavoriteServers[i].m_State >= FAVSTATE_ADDR && net_addr_comp(&Addr, &m_aFavoriteServers[i].m_Addr) == 0) pEntry->m_Info.m_Favorite = 1; } // add to the hash list int Hash = AddrHash(&Addr); pEntry->m_pNextIp = m_aServerlistIp[Hash]; m_aServerlistIp[Hash] = pEntry; if(m_NumServers == m_NumServerCapacity) { if(m_NumServerCapacity == 0) { // alloc start size m_NumServerCapacity = 1000; m_ppServerlist = (CServerEntry **)mem_alloc(m_NumServerCapacity*sizeof(CServerEntry*), 1); } else { // increase size m_NumServerCapacity += 100; CServerEntry **ppNewlist = (CServerEntry **)mem_alloc(m_NumServerCapacity*sizeof(CServerEntry*), 1); mem_copy(ppNewlist, m_ppServerlist, m_NumServers*sizeof(CServerEntry*)); mem_free(m_ppServerlist); m_ppServerlist = ppNewlist; } } // add to list m_ppServerlist[m_NumServers] = pEntry; pEntry->m_Info.m_ServerIndex = m_NumServers; m_NumServers++; return pEntry; } void CServerBrowser::Set(const NETADDR &Addr, int Type, int Token, const CServerInfo *pInfo) { CServerEntry *pEntry = 0; if(Type == SET_MASTER_ADD) { if(m_ServerlistType != IServerBrowser::TYPE_INTERNET) return; if(!Find(Addr)) { pEntry = Add(Addr); QueueRequest(pEntry); } } /*else if(Type == SET_FAV_ADD) { if(m_ServerlistType != IServerBrowser::TYPE_FAVORITES) return; if(!Find(Addr)) { pEntry = Add(Addr); QueueRequest(pEntry); } }*/ else if(Type == SET_TOKEN) { if(Token != m_CurrentToken) return; pEntry = Find(Addr); if(!pEntry) pEntry = Add(Addr); if(pEntry) { SetInfo(pEntry, *pInfo); if(m_ServerlistType == IServerBrowser::TYPE_LAN) pEntry->m_Info.m_Latency = min(static_cast<int>((time_get()-m_BroadcastTime)*1000/time_freq()), 999); else pEntry->m_Info.m_Latency = min(static_cast<int>((time_get()-pEntry->m_RequestTime)*1000/time_freq()), 999); RemoveRequest(pEntry); } } for(int i = 0; i < m_lFilters.size(); i++) m_lFilters[i].Sort(); } void CServerBrowser::Refresh(int Type) { // clear out everything m_ServerlistHeap.Reset(); m_NumServers = 0; m_NumPlayers = 0; for(int i = 0; i < m_lFilters.size(); i++) { m_lFilters[i].m_NumSortedServers = 0; m_lFilters[i].m_NumPlayers = 0; } mem_zero(m_aServerlistIp, sizeof(m_aServerlistIp)); m_pFirstReqServer = 0; m_pLastReqServer = 0; m_NumRequests = 0; // next token m_CurrentToken = (m_CurrentToken+1)&0xff; // m_ServerlistType = Type; if(Type == IServerBrowser::TYPE_LAN) { unsigned char Buffer[sizeof(SERVERBROWSE_GETINFO)+1]; CNetChunk Packet; int i; mem_copy(Buffer, SERVERBROWSE_GETINFO, sizeof(SERVERBROWSE_GETINFO)); Buffer[sizeof(SERVERBROWSE_GETINFO)] = m_CurrentToken; /* do the broadcast version */ Packet.m_ClientID = -1; mem_zero(&Packet, sizeof(Packet)); Packet.m_Address.type = m_pNetClient->NetType()|NETTYPE_LINK_BROADCAST; Packet.m_Flags = NETSENDFLAG_CONNLESS; Packet.m_DataSize = sizeof(Buffer); Packet.m_pData = Buffer; m_BroadcastTime = time_get(); for(i = 8303; i <= 8310; i++) { Packet.m_Address.port = i; m_pNetClient->Send(&Packet); } if(g_Config.m_Debug) m_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, "client_srvbrowse", "broadcasting for servers"); } else if(Type == IServerBrowser::TYPE_INTERNET) m_NeedRefresh = 1; /*else if(Type == IServerBrowser::TYPE_FAVORITES) { for(int i = 0; i < m_NumFavoriteServers; i++) if(m_aFavoriteServers[i].m_State >= FAVSTATE_ADDR) Set(m_aFavoriteServers[i].m_Addr, SET_FAV_ADD, -1, 0); }*/ } void CServerBrowser::RequestImpl(const NETADDR &Addr, CServerEntry *pEntry) const { unsigned char Buffer[sizeof(SERVERBROWSE_GETINFO)+1]; CNetChunk Packet; if(g_Config.m_Debug) { char aAddrStr[NETADDR_MAXSTRSIZE]; net_addr_str(&Addr, aAddrStr, sizeof(aAddrStr), true); char aBuf[256]; str_format(aBuf, sizeof(aBuf),"requesting server info from %s", aAddrStr); m_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, "client_srvbrowse", aBuf); } mem_copy(Buffer, SERVERBROWSE_GETINFO, sizeof(SERVERBROWSE_GETINFO)); Buffer[sizeof(SERVERBROWSE_GETINFO)] = m_CurrentToken; Packet.m_ClientID = -1; Packet.m_Address = Addr; Packet.m_Flags = NETSENDFLAG_CONNLESS; Packet.m_DataSize = sizeof(Buffer); Packet.m_pData = Buffer; m_pNetClient->Send(&Packet); if(pEntry) pEntry->m_RequestTime = time_get(); } void CServerBrowser::Request(const NETADDR &Addr) const { RequestImpl(Addr, 0); } void CServerBrowser::Update(bool ForceResort) { int64 Timeout = time_freq(); int64 Now = time_get(); int Count; CServerEntry *pEntry, *pNext; // do server list requests if(m_NeedRefresh && !m_pMasterServer->IsRefreshing()) { NETADDR Addr; CNetChunk Packet; int i; m_NeedRefresh = 0; mem_zero(&Packet, sizeof(Packet)); Packet.m_ClientID = -1; Packet.m_Flags = NETSENDFLAG_CONNLESS; Packet.m_DataSize = sizeof(SERVERBROWSE_GETLIST); Packet.m_pData = SERVERBROWSE_GETLIST; for(i = 0; i < IMasterServer::MAX_MASTERSERVERS; i++) { if(!m_pMasterServer->IsValid(i)) continue; Addr = m_pMasterServer->GetAddr(i); Packet.m_Address = Addr; m_pNetClient->Send(&Packet); } if(g_Config.m_Debug) m_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, "client_srvbrowse", "requesting server list"); } // do timeouts pEntry = m_pFirstReqServer; while(1) { if(!pEntry) // no more entries break; pNext = pEntry->m_pNextReq; if(pEntry->m_RequestTime && pEntry->m_RequestTime+Timeout < Now) { // timeout RemoveRequest(pEntry); } pEntry = pNext; } // do timeouts pEntry = m_pFirstReqServer; Count = 0; while(1) { if(!pEntry) // no more entries break; // no more then 10 concurrent requests if(Count == g_Config.m_BrMaxRequests) break; if(pEntry->m_RequestTime == 0) RequestImpl(pEntry->m_Addr, pEntry); Count++; pEntry = pEntry->m_pNextReq; } // update favorites UpdateFavorites(); // check if we need to resort for(int i = 0; i < m_lFilters.size(); i++) { CServerFilter *pFilter = &m_lFilters[i]; if(pFilter->m_SortHash != pFilter->SortHash() || ForceResort) pFilter->Sort(); } } void CServerBrowser::UpdateFavorites() { // check if hostname lookup for favourites is done if(m_FavLookup.m_Active && m_FavLookup.m_HostLookup.m_Job.Status() == CJob::STATE_DONE) { // check if favourite has not been removed in the meanwhile if(m_FavLookup.m_FavoriteIndex != -1) { if(m_FavLookup.m_HostLookup.m_Job.Result() == 0) { CFavoriteServer *pEntry = FindFavoriteByAddr(m_FavLookup.m_HostLookup.m_Addr, 0); if(pEntry) { // address is already in the list -> acquire hostname if existing entry lacks it and drop multiple address entry if(pEntry->m_State != FAVSTATE_HOST) { str_copy(pEntry->m_aHostname, m_aFavoriteServers[m_FavLookup.m_FavoriteIndex].m_aHostname, sizeof(pEntry->m_aHostname)); pEntry->m_State = FAVSTATE_HOST; dbg_msg("test", "fav aquired hostname, %s", m_aFavoriteServers[m_FavLookup.m_FavoriteIndex].m_aHostname); } RemoveFavoriteEntry(m_FavLookup.m_FavoriteIndex); dbg_msg("test", "fav removed multiple entry"); } else { // address wasn't in the list yet -> add it (optional check if hostname matches given address -> drop entry on fail) if(m_aFavoriteServers[m_FavLookup.m_FavoriteIndex].m_State == FAVSTATE_LOOKUP || net_addr_comp(&m_aFavoriteServers[m_NumFavoriteServers].m_Addr, &m_FavLookup.m_HostLookup.m_Addr) == 0) { m_aFavoriteServers[m_FavLookup.m_FavoriteIndex].m_Addr = m_FavLookup.m_HostLookup.m_Addr; m_aFavoriteServers[m_FavLookup.m_FavoriteIndex].m_State = FAVSTATE_HOST; CServerEntry *pEntry = Find(m_aFavoriteServers[m_FavLookup.m_FavoriteIndex].m_Addr); if(pEntry) pEntry->m_Info.m_Favorite = 1; dbg_msg("test", "fav added, %s", m_aFavoriteServers[m_FavLookup.m_FavoriteIndex].m_aHostname); } else { RemoveFavoriteEntry(m_FavLookup.m_FavoriteIndex); dbg_msg("test", "fav removed entry that failed hostname-address check"); } } } else { // hostname lookup failed if(m_aFavoriteServers[m_FavLookup.m_FavoriteIndex].m_State == FAVSTATE_LOOKUP) { m_aFavoriteServers[m_FavLookup.m_FavoriteIndex].m_State = FAVSTATE_INVALID; dbg_msg("test", "fav invalid, %s", m_aFavoriteServers[m_FavLookup.m_FavoriteIndex].m_aHostname); } else { RemoveFavoriteEntry(m_FavLookup.m_FavoriteIndex); dbg_msg("test", "fav removed invalid check-based entry"); } } } m_FavLookup.m_Active = false; } // add hostname lookup for favourites if(m_FavLookup.m_LookupCount > 0 && !m_FavLookup.m_Active) { for(int i = 0; i < m_NumFavoriteServers; i++) { if(m_aFavoriteServers[i].m_State <= FAVSTATE_LOOKUPCHECK) { m_pEngine->HostLookup(&m_FavLookup.m_HostLookup, m_aFavoriteServers[i].m_aHostname, m_pNetClient->NetType()); m_FavLookup.m_FavoriteIndex = i; --m_FavLookup.m_LookupCount; m_FavLookup.m_Active = true; break; } } } } CServerBrowser::CFavoriteServer *CServerBrowser::FindFavoriteByAddr(const NETADDR &Addr, int *Index) { for(int i = 0; i < m_NumFavoriteServers; i++) { if(net_addr_comp(&Addr, &m_aFavoriteServers[i].m_Addr) == 0) { if(Index) *Index = i; return &m_aFavoriteServers[i]; } } return 0; } CServerBrowser::CFavoriteServer *CServerBrowser::FindFavoriteByHostname(const char *pHostname, int *Index) { for(int i = 0; i < m_NumFavoriteServers; i++) { if(str_comp(pHostname, m_aFavoriteServers[i].m_aHostname) == 0) { if(Index) *Index = i; return &m_aFavoriteServers[i]; } } return 0; } void CServerBrowser::RemoveFavoriteEntry(int Index) { mem_move(&m_aFavoriteServers[Index], &m_aFavoriteServers[Index+1], sizeof(CFavoriteServer)*(m_NumFavoriteServers-(Index+1))); m_NumFavoriteServers--; } void CServerBrowser::AddFavoriteEx(const char *pHostname, const NETADDR *pAddr, bool DoCheck) { if(m_NumFavoriteServers == MAX_FAVORITES || FindFavoriteByHostname(pHostname, 0)) return; // check if hostname is a net address string if(net_addr_from_str(&m_aFavoriteServers[m_NumFavoriteServers].m_Addr, pHostname) == 0) { // make sure that we don't already have the server in our list if(FindFavoriteByAddr(m_aFavoriteServers[m_NumFavoriteServers].m_Addr, 0) != 0) return; // check if hostname does not match given address if(DoCheck && net_addr_comp(&m_aFavoriteServers[m_NumFavoriteServers].m_Addr, pAddr) != 0) return; // add the server to the list m_aFavoriteServers[m_NumFavoriteServers].m_State = FAVSTATE_ADDR; CServerEntry *pEntry = Find(m_aFavoriteServers[m_NumFavoriteServers].m_Addr); if(pEntry) pEntry->m_Info.m_Favorite = 1; } else { // prepare for hostname lookup if(DoCheck) { m_aFavoriteServers[m_NumFavoriteServers].m_State = FAVSTATE_LOOKUPCHECK; m_aFavoriteServers[m_NumFavoriteServers].m_Addr = *pAddr; } else m_aFavoriteServers[m_NumFavoriteServers].m_State = FAVSTATE_LOOKUP; ++m_FavLookup.m_LookupCount; } str_copy(m_aFavoriteServers[m_NumFavoriteServers].m_aHostname, pHostname, sizeof(m_aFavoriteServers[m_NumFavoriteServers].m_aHostname)); ++m_NumFavoriteServers; if(g_Config.m_Debug) { char aBuf[256]; str_format(aBuf, sizeof(aBuf), "added fav '%s' (%s)", pHostname); m_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, "client_srvbrowse", aBuf); } // refresh servers in all filters where favorites are filtered for(int i = 0; i < m_lFilters.size(); i++) { CServerFilter *pFilter = &m_lFilters[i]; if(pFilter->m_SortHash&FILTER_FAVORITE) pFilter->Sort(); } } void CServerBrowser::RemoveFavoriteEx(const char *pHostname, const NETADDR *pAddr) { // find favorite entry int Index = 0; CFavoriteServer *pFavEntry = FindFavoriteByHostname(pHostname, &Index); if(pFavEntry == 0 && pAddr) pFavEntry = FindFavoriteByAddr(*pAddr, &Index); if(pFavEntry) { if(pFavEntry->m_State >= FAVSTATE_ADDR) { // invalidate favorite state for server entry CServerEntry *pEntry = Find(pFavEntry->m_Addr); if(pEntry) pEntry->m_Info.m_Favorite = 0; } else if(pFavEntry->m_State <= FAVSTATE_LOOKUPCHECK && m_FavLookup.m_FavoriteIndex == Index) { // skip result on favorite hostname lookup m_FavLookup.m_FavoriteIndex = -1; } // remove favorite RemoveFavoriteEntry(Index); if(m_FavLookup.m_FavoriteIndex > Index) --m_FavLookup.m_FavoriteIndex; } // refresh servers in all filters where favorites are filtered for(int i = 0; i < m_lFilters.size(); i++) { CServerFilter *pFilter = &m_lFilters[i]; if(pFilter->m_SortHash&FILTER_FAVORITE) pFilter->Sort(); } } int CServerBrowser::LoadingProgression() const { if(m_NumServers == 0) return 0; int Servers = m_NumServers; int Loaded = m_NumServers-m_NumRequests; return 100.0f * Loaded/Servers; } void CServerBrowser::ConAddFavorite(IConsole::IResult *pResult, void *pUserData) { CServerBrowser *pSelf = static_cast<CServerBrowser *>(pUserData); pSelf->AddFavoriteEx(pResult->GetString(0), 0, false); } void CServerBrowser::ConRemoveFavorite(IConsole::IResult *pResult, void *pUserData) { CServerBrowser *pSelf = static_cast<CServerBrowser *>(pUserData); pSelf->RemoveFavoriteEx(pResult->GetString(0), 0); } void CServerBrowser::ConfigSaveCallback(IConfig *pConfig, void *pUserData) { CServerBrowser *pSelf = (CServerBrowser *)pUserData; char aBuffer[256]; for(int i = 0; i < pSelf->m_NumFavoriteServers; i++) { str_format(aBuffer, sizeof(aBuffer), "add_favorite %s", pSelf->m_aFavoriteServers[i].m_aHostname); pConfig->WriteLine(aBuffer); } } ================================================ FILE: src/engine/client/serverbrowser.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef ENGINE_CLIENT_SERVERBROWSER_H #define ENGINE_CLIENT_SERVERBROWSER_H #include <base/tl/array.h> #include <engine/serverbrowser.h> class CServerBrowser : public IServerBrowser { public: enum { SET_MASTER_ADD=1, SET_FAV_ADD, SET_TOKEN, }; class CServerEntry { public: NETADDR m_Addr; int64 m_RequestTime; int m_GotInfo; CServerInfo m_Info; CServerEntry *m_pNextIp; // ip hashed list CServerEntry *m_pPrevReq; // request list CServerEntry *m_pNextReq; }; class CServerFilter { public: CServerBrowser *m_pServerBrowser; int m_SortHash; char m_aGametype[32]; char m_aServerAddress[16]; int m_Ping; int m_Country; int m_NumSortedServers; int m_NumSortedServersCapacity; int m_NumPlayers; int *m_pSortedServerlist; ~CServerFilter(); // sorting criterions bool SortCompareName(int Index1, int Index2) const; bool SortCompareMap(int Index1, int Index2) const; bool SortComparePing(int Index1, int Index2) const; bool SortCompareGametype(int Index1, int Index2) const; bool SortCompareNumPlayers(int Index1, int Index2) const; bool SortCompareNumClients(int Index1, int Index2) const; void Filter(); void Sort(); int SortHash() const; }; array<CServerFilter> m_lFilters; int AddFilter(int SortHash, int Ping, int Country, const char* pGametype, const char* pServerAddress); void SetFilter(int Index, int SortHash, int Ping, int Country, const char* pGametype, const char* pServerAddress); void GetFilter(int Index, int *pSortHash, int *pPing, int *pCountry, char* pGametype, char* pServerAddress); void RemoveFilter(int Index); CServerBrowser(); // interface functions void Refresh(int Type); bool IsRefreshing() const { return m_pFirstReqServer != 0; } bool IsRefreshingMasters() const { return m_pMasterServer->IsRefreshing(); } int LoadingProgression() const; int NumServers() const { return m_NumServers; } int NumPlayers() const { return m_NumPlayers; } int NumSortedServers(int Index) const { return m_lFilters[Index].m_NumSortedServers; } int NumSortedPlayers(int Index) const { return m_lFilters[Index].m_NumPlayers; } const CServerInfo *SortedGet(int FilterIndex, int Index) const; const void *GetID(int FilterIndex, int Index) const; bool IsFavorite(const NETADDR &Addr) { return FindFavoriteByAddr(Addr, 0) != 0; } void AddFavorite(const CServerInfo *pEntry) { AddFavoriteEx(pEntry->m_aHostname, &pEntry->m_NetAddr, true); } void RemoveFavorite(const CServerInfo *pEntry) { RemoveFavoriteEx(pEntry->m_aHostname, &pEntry->m_NetAddr); } // void Update(bool ForceResort); void Set(const NETADDR &Addr, int Type, int Token, const CServerInfo *pInfo); void Request(const NETADDR &Addr) const; void SetBaseInfo(class CNetClient *pClient, const char *pNetVersion); private: CNetClient *m_pNetClient; IMasterServer *m_pMasterServer; class IConsole *m_pConsole; class IEngine *m_pEngine; class IFriends *m_pFriends; char m_aNetVersion[128]; CHeap m_ServerlistHeap; // favourite enum { FAVSTATE_LOOKUP=0, FAVSTATE_LOOKUPCHECK, FAVSTATE_INVALID, FAVSTATE_ADDR, FAVSTATE_HOST, MAX_FAVORITES=256, }; struct CFavoriteServer { char m_aHostname[128]; NETADDR m_Addr; int m_State; } m_aFavoriteServers[MAX_FAVORITES]; int m_NumFavoriteServers; struct CFavoriteLookup { class CHostLookup m_HostLookup; int m_FavoriteIndex; int m_LookupCount; bool m_Active; } m_FavLookup; void UpdateFavorites(); CFavoriteServer *FindFavoriteByAddr(const NETADDR &Addr, int *Index); CFavoriteServer *FindFavoriteByHostname(const char *pHostname, int *Index); void RemoveFavoriteEntry(int Index); void AddFavoriteEx(const char *pHostname, const NETADDR *pAddr, bool DoCheck); void RemoveFavoriteEx(const char *pHostname, const NETADDR *Addr); // CServerEntry *m_aServerlistIp[256]; // ip hash list CServerEntry **m_ppServerlist; CServerEntry *m_pFirstReqServer; // request list CServerEntry *m_pLastReqServer; int m_NumRequests; int m_NeedRefresh; int m_NumServers; int m_NumServerCapacity; int m_NumPlayers; // the token is to keep server refresh separated from each other int m_CurrentToken; int m_ServerlistType; int64 m_BroadcastTime; CServerEntry *Find(const NETADDR &Addr); CServerEntry *Add(const NETADDR &Addr); void RemoveRequest(CServerEntry *pEntry); void QueueRequest(CServerEntry *pEntry); void RequestImpl(const NETADDR &Addr, CServerEntry *pEntry) const; void SetInfo(CServerEntry *pEntry, const CServerInfo &Info); static void ConAddFavorite(IConsole::IResult *pResult, void *pUserData); static void ConRemoveFavorite(IConsole::IResult *pResult, void *pUserData); static void ConfigSaveCallback(IConfig *pConfig, void *pUserData); }; #endif ================================================ FILE: src/engine/client/sound.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <base/math.h> #include <base/system.h> #include <engine/graphics.h> #include <engine/storage.h> #include <engine/shared/config.h> #include "SDL.h" #include "sound.h" extern "C" { // wavpack #include <engine/external/wavpack/wavpack.h> } #include <math.h> enum { NUM_SAMPLES = 512, NUM_VOICES = 64, NUM_CHANNELS = 16, }; struct CSample { short *m_pData; int m_NumFrames; int m_Rate; int m_Channels; int m_LoopStart; int m_LoopEnd; int m_PausedAt; }; struct CChannel { int m_Vol; int m_Pan; } ; struct CVoice { CSample *m_pSample; CChannel *m_pChannel; int m_Tick; int m_Vol; // 0 - 255 int m_Flags; int m_X, m_Y; } ; static CSample m_aSamples[NUM_SAMPLES] = { {0} }; static CVoice m_aVoices[NUM_VOICES] = { {0} }; static CChannel m_aChannels[NUM_CHANNELS] = { {255, 0} }; static LOCK m_SoundLock = 0; static int m_CenterX = 0; static int m_CenterY = 0; static int m_MixingRate = 48000; static volatile int m_SoundVolume = 100; static int m_NextVoice = 0; static int *m_pMixBuffer = 0; // buffer only used by the thread callback function static unsigned m_MaxFrames = 0; // TODO: there should be a faster way todo this static short Int2Short(int i) { if(i > 0x7fff) return 0x7fff; else if(i < -0x7fff) return -0x7fff; return i; } static int IntAbs(int i) { if(i<0) return -i; return i; } static void Mix(short *pFinalOut, unsigned Frames) { int MasterVol; mem_zero(m_pMixBuffer, m_MaxFrames*2*sizeof(int)); Frames = min(Frames, m_MaxFrames); // aquire lock while we are mixing lock_wait(m_SoundLock); MasterVol = m_SoundVolume; for(unsigned i = 0; i < NUM_VOICES; i++) { if(m_aVoices[i].m_pSample) { // mix voice CVoice *v = &m_aVoices[i]; int *pOut = m_pMixBuffer; int Step = v->m_pSample->m_Channels; // setup input sources short *pInL = &v->m_pSample->m_pData[v->m_Tick*Step]; short *pInR = &v->m_pSample->m_pData[v->m_Tick*Step+1]; unsigned End = v->m_pSample->m_NumFrames-v->m_Tick; int Rvol = v->m_pChannel->m_Vol; int Lvol = v->m_pChannel->m_Vol; // make sure that we don't go outside the sound data if(Frames < End) End = Frames; // check if we have a mono sound if(v->m_pSample->m_Channels == 1) pInR = pInL; // volume calculation if(v->m_Flags&ISound::FLAG_POS && v->m_pChannel->m_Pan) { // TODO: we should respect the channel panning value const int Range = 1500; // magic value, remove int dx = v->m_X - m_CenterX; int dy = v->m_Y - m_CenterY; int Dist = (int)sqrtf((float)dx*dx+dy*dy); // float here. nasty int p = IntAbs(dx); if(Dist >= 0 && Dist < Range) { // panning if(dx > 0) Lvol = ((Range-p)*Lvol)/Range; else Rvol = ((Range-p)*Rvol)/Range; // falloff Lvol = (Lvol*(Range-Dist))/Range; Rvol = (Rvol*(Range-Dist))/Range; } else { Lvol = 0; Rvol = 0; } } // process all frames for(unsigned s = 0; s < End; s++) { *pOut++ += (*pInL)*Lvol; *pOut++ += (*pInR)*Rvol; pInL += Step; pInR += Step; v->m_Tick++; } // free voice if not used any more if(v->m_Tick == v->m_pSample->m_NumFrames) { if(v->m_Flags&ISound::FLAG_LOOP) v->m_Tick = 0; else v->m_pSample = 0; } } } // release the lock lock_release(m_SoundLock); { // clamp accumulated values // TODO: this seams slow for(unsigned i = 0; i < Frames; i++) { int j = i<<1; int vl = ((m_pMixBuffer[j]*MasterVol)/101)>>8; int vr = ((m_pMixBuffer[j+1]*MasterVol)/101)>>8; pFinalOut[j] = Int2Short(vl); pFinalOut[j+1] = Int2Short(vr); } } #if defined(CONF_ARCH_ENDIAN_BIG) swap_endian(pFinalOut, sizeof(short), Frames * 2); #endif } static void SdlCallback(void *pUnused, Uint8 *pStream, int Len) { (void)pUnused; Mix((short *)pStream, Len/2/2); } int CSound::Init() { m_SoundEnabled = 0; m_pGraphics = Kernel()->RequestInterface<IEngineGraphics>(); m_pStorage = Kernel()->RequestInterface<IStorage>(); SDL_AudioSpec Format; m_SoundLock = lock_create(); if(!g_Config.m_SndEnable) return 0; if(SDL_InitSubSystem(SDL_INIT_AUDIO) < 0) { dbg_msg("gfx", "unable to init SDL audio: %s", SDL_GetError()); return -1; } m_MixingRate = g_Config.m_SndRate; // Set 16-bit stereo audio at 22Khz Format.freq = g_Config.m_SndRate; // ignore_convention Format.format = AUDIO_S16; // ignore_convention Format.channels = 2; // ignore_convention Format.samples = g_Config.m_SndBufferSize; // ignore_convention Format.callback = SdlCallback; // ignore_convention Format.userdata = NULL; // ignore_convention // Open the audio device and start playing sound! if(SDL_OpenAudio(&Format, NULL) < 0) { dbg_msg("client/sound", "unable to open audio: %s", SDL_GetError()); return -1; } else dbg_msg("client/sound", "sound init successful"); m_MaxFrames = g_Config.m_SndBufferSize*2; m_pMixBuffer = (int *)mem_alloc(m_MaxFrames*2*sizeof(int), 1); SDL_PauseAudio(0); m_SoundEnabled = 1; Update(); // update the volume return 0; } int CSound::Update() { // update volume int WantedVolume = g_Config.m_SndVolume; if(!m_pGraphics->WindowActive() && g_Config.m_SndNonactiveMute) WantedVolume = 0; if(WantedVolume != m_SoundVolume) { lock_wait(m_SoundLock); m_SoundVolume = WantedVolume; lock_release(m_SoundLock); } return 0; } int CSound::Shutdown() { SDL_CloseAudio(); SDL_QuitSubSystem(SDL_INIT_AUDIO); lock_destroy(m_SoundLock); if(m_pMixBuffer) { mem_free(m_pMixBuffer); m_pMixBuffer = 0; } return 0; } int CSound::AllocID() { // TODO: linear search, get rid of it for(unsigned SampleID = 0; SampleID < NUM_SAMPLES; SampleID++) { if(m_aSamples[SampleID].m_pData == 0x0) return SampleID; } return -1; } void CSound::RateConvert(int SampleID) { CSample *pSample = &m_aSamples[SampleID]; int NumFrames = 0; short *pNewData = 0; // make sure that we need to convert this sound if(!pSample->m_pData || pSample->m_Rate == m_MixingRate) return; // allocate new data NumFrames = (int)((pSample->m_NumFrames/(float)pSample->m_Rate)*m_MixingRate); pNewData = (short *)mem_alloc(NumFrames*pSample->m_Channels*sizeof(short), 1); for(int i = 0; i < NumFrames; i++) { // resample TODO: this should be done better, like linear atleast float a = i/(float)NumFrames; int f = (int)(a*pSample->m_NumFrames); if(f >= pSample->m_NumFrames) f = pSample->m_NumFrames-1; // set new data if(pSample->m_Channels == 1) pNewData[i] = pSample->m_pData[f]; else if(pSample->m_Channels == 2) { pNewData[i*2] = pSample->m_pData[f*2]; pNewData[i*2+1] = pSample->m_pData[f*2+1]; } } // free old data and apply new mem_free(pSample->m_pData); pSample->m_pData = pNewData; pSample->m_NumFrames = NumFrames; } int CSound::ReadData(void *pBuffer, int Size) { return io_read(ms_File, pBuffer, Size); } ISound::CSampleHandle CSound::LoadWV(const char *pFilename) { CSample *pSample; int SampleID = -1; char aError[100]; WavpackContext *pContext; // don't waste memory on sound when we are stress testing if(g_Config.m_DbgStress) return CSampleHandle(); // no need to load sound when we are running with no sound if(!m_SoundEnabled) return CSampleHandle(); if(!m_pStorage) return CSampleHandle(); ms_File = m_pStorage->OpenFile(pFilename, IOFLAG_READ, IStorage::TYPE_ALL); if(!ms_File) { dbg_msg("sound/wv", "failed to open file. filename='%s'", pFilename); return CSampleHandle(); } SampleID = AllocID(); if(SampleID < 0) { io_close(ms_File); ms_File = 0; return CSampleHandle(); } pSample = &m_aSamples[SampleID]; pContext = WavpackOpenFileInput(ReadData, aError); if (pContext) { int m_aSamples = WavpackGetNumSamples(pContext); int BitsPerSample = WavpackGetBitsPerSample(pContext); unsigned int SampleRate = WavpackGetSampleRate(pContext); int m_aChannels = WavpackGetNumChannels(pContext); int *pData; int *pSrc; short *pDst; int i; pSample->m_Channels = m_aChannels; pSample->m_Rate = SampleRate; if(pSample->m_Channels > 2) { dbg_msg("sound/wv", "file is not mono or stereo. filename='%s'", pFilename); io_close(ms_File); ms_File = 0; return CSampleHandle(); } /* if(snd->rate != 44100) { dbg_msg("sound/wv", "file is %d Hz, not 44100 Hz. filename='%s'", snd->rate, filename); return -1; }*/ if(BitsPerSample != 16) { dbg_msg("sound/wv", "bps is %d, not 16, filname='%s'", BitsPerSample, pFilename); io_close(ms_File); ms_File = 0; return CSampleHandle(); } pData = (int *)mem_alloc(4*m_aSamples*m_aChannels, 1); WavpackUnpackSamples(pContext, pData, m_aSamples); // TODO: check return value pSrc = pData; pSample->m_pData = (short *)mem_alloc(2*m_aSamples*m_aChannels, 1); pDst = pSample->m_pData; for (i = 0; i < m_aSamples*m_aChannels; i++) *pDst++ = (short)*pSrc++; mem_free(pData); pSample->m_NumFrames = m_aSamples; pSample->m_LoopStart = -1; pSample->m_LoopEnd = -1; pSample->m_PausedAt = 0; } else { dbg_msg("sound/wv", "failed to open %s: %s", pFilename, aError); } io_close(ms_File); ms_File = NULL; if(g_Config.m_Debug) dbg_msg("sound/wv", "loaded %s", pFilename); RateConvert(SampleID); return CreateSampleHandle(SampleID); } void CSound::SetListenerPos(float x, float y) { m_CenterX = (int)x; m_CenterY = (int)y; } void CSound::SetChannel(int ChannelID, float Vol, float Pan) { m_aChannels[ChannelID].m_Vol = (int)(Vol*255.0f); m_aChannels[ChannelID].m_Pan = (int)(Pan*255.0f); // TODO: this is only on and off right now } int CSound::Play(int ChannelID, CSampleHandle SampleID, int Flags, float x, float y) { if(!SampleID.IsValid()) return -1; int VoiceID = -1; int i; lock_wait(m_SoundLock); // search for voice for(i = 0; i < NUM_VOICES; i++) { int id = (m_NextVoice + i) % NUM_VOICES; if(!m_aVoices[id].m_pSample) { VoiceID = id; m_NextVoice = id+1; break; } } // voice found, use it if(VoiceID != -1) { m_aVoices[VoiceID].m_pSample = &m_aSamples[SampleID.Id()]; m_aVoices[VoiceID].m_pChannel = &m_aChannels[ChannelID]; if(Flags & FLAG_LOOP) m_aVoices[VoiceID].m_Tick = m_aSamples[SampleID.Id()].m_PausedAt; else m_aVoices[VoiceID].m_Tick = 0; m_aVoices[VoiceID].m_Vol = 255; m_aVoices[VoiceID].m_Flags = Flags; m_aVoices[VoiceID].m_X = (int)x; m_aVoices[VoiceID].m_Y = (int)y; } lock_release(m_SoundLock); return VoiceID; } int CSound::PlayAt(int ChannelID, CSampleHandle SampleID, int Flags, float x, float y) { return Play(ChannelID, SampleID, Flags|ISound::FLAG_POS, x, y); } int CSound::Play(int ChannelID, CSampleHandle SampleID, int Flags) { return Play(ChannelID, SampleID, Flags, 0, 0); } void CSound::Stop(CSampleHandle SampleID) { // TODO: a nice fade out lock_wait(m_SoundLock); CSample *pSample = &m_aSamples[SampleID.Id()]; for(int i = 0; i < NUM_VOICES; i++) { if(m_aVoices[i].m_pSample == pSample) { if(m_aVoices[i].m_Flags & FLAG_LOOP) m_aVoices[i].m_pSample->m_PausedAt = m_aVoices[i].m_Tick; else m_aVoices[i].m_pSample->m_PausedAt = 0; m_aVoices[i].m_pSample = 0; } } lock_release(m_SoundLock); } void CSound::StopAll() { // TODO: a nice fade out lock_wait(m_SoundLock); for(int i = 0; i < NUM_VOICES; i++) { if(m_aVoices[i].m_pSample) { if(m_aVoices[i].m_Flags & FLAG_LOOP) m_aVoices[i].m_pSample->m_PausedAt = m_aVoices[i].m_Tick; else m_aVoices[i].m_pSample->m_PausedAt = 0; } m_aVoices[i].m_pSample = 0; } lock_release(m_SoundLock); } IOHANDLE CSound::ms_File = 0; IEngineSound *CreateEngineSound() { return new CSound; } ================================================ FILE: src/engine/client/sound.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef ENGINE_CLIENT_SOUND_H #define ENGINE_CLIENT_SOUND_H #include <engine/sound.h> class CSound : public IEngineSound { int m_SoundEnabled; public: IEngineGraphics *m_pGraphics; IStorage *m_pStorage; virtual int Init(); int Update(); int Shutdown(); int AllocID(); static void RateConvert(int SampleID); // TODO: Refactor: clean this mess up static IOHANDLE ms_File; static int ReadData(void *pBuffer, int Size); virtual bool IsSoundEnabled() { return m_SoundEnabled != 0; } virtual CSampleHandle LoadWV(const char *pFilename); virtual void SetListenerPos(float x, float y); virtual void SetChannel(int ChannelID, float Vol, float Pan); int Play(int ChannelID, CSampleHandle SampleID, int Flags, float x, float y); virtual int PlayAt(int ChannelID, CSampleHandle SampleID, int Flags, float x, float y); virtual int Play(int ChannelID, CSampleHandle SampleID, int Flags); virtual void Stop(CSampleHandle SampleID); virtual void StopAll(); }; #endif ================================================ FILE: src/engine/client/text.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <base/system.h> #include <base/math.h> #include <engine/graphics.h> #include <engine/textrender.h> #ifdef CONF_FAMILY_WINDOWS #include <windows.h> #endif // ft2 texture #include <ft2build.h> #include FT_FREETYPE_H // TODO: Refactor: clean this up enum { MAX_CHARACTERS = 64, }; static int aFontSizes[] = {8,9,10,11,12,13,14,15,16,17,18,19,20,36,64}; #define NUM_FONT_SIZES (sizeof(aFontSizes)/sizeof(int)) struct CFontChar { int m_ID; // these values are scaled to the pFont size // width * font_size == real_size float m_Width; float m_Height; float m_OffsetX; float m_OffsetY; float m_AdvanceX; float m_aUvs[4]; int64 m_TouchTime; }; struct CFontSizeData { int m_FontSize; FT_Face *m_pFace; IGraphics::CTextureHandle m_aTextures[2]; int m_TextureWidth; int m_TextureHeight; int m_NumXChars; int m_NumYChars; int m_CharMaxWidth; int m_CharMaxHeight; CFontChar m_aCharacters[MAX_CHARACTERS*MAX_CHARACTERS]; int m_CurrentCharacter; }; class CFont { public: char m_aFilename[512]; FT_Face m_FtFace; CFontSizeData m_aSizes[NUM_FONT_SIZES]; }; class CTextRender : public IEngineTextRender { IGraphics *m_pGraphics; IGraphics *Graphics() { return m_pGraphics; } int WordLength(const char *pText) { int s = 1; while(1) { if(*pText == 0) return s-1; if(*pText == '\n' || *pText == '\t' || *pText == ' ') return s; pText++; s++; } } float m_TextR; float m_TextG; float m_TextB; float m_TextA; float m_TextOutlineR; float m_TextOutlineG; float m_TextOutlineB; float m_TextOutlineA; //int m_FontTextureFormat; CFont *m_pDefaultFont; FT_Library m_FTLibrary; int GetFontSizeIndex(int Pixelsize) { for(unsigned i = 0; i < NUM_FONT_SIZES; i++) { if(aFontSizes[i] >= Pixelsize) return i; } return NUM_FONT_SIZES-1; } void Grow(unsigned char *pIn, unsigned char *pOut, int w, int h) { for(int y = 0; y < h; y++) for(int x = 0; x < w; x++) { int c = pIn[y*w+x]; for(int sy = -1; sy <= 1; sy++) for(int sx = -1; sx <= 1; sx++) { int GetX = x+sx; int GetY = y+sy; if (GetX >= 0 && GetY >= 0 && GetX < w && GetY < h) { int Index = GetY*w+GetX; if(pIn[Index] > c) c = pIn[Index]; } } pOut[y*w+x] = c; } } void InitTexture(CFontSizeData *pSizeData, int CharWidth, int CharHeight, int Xchars, int Ychars) { static int FontMemoryUsage = 0; int Width = CharWidth*Xchars; int Height = CharHeight*Ychars; void *pMem = mem_alloc(Width*Height, 1); mem_zero(pMem, Width*Height); for(int i = 0; i < 2; i++) { if(pSizeData->m_aTextures[i].IsValid()) { Graphics()->UnloadTexture(pSizeData->m_aTextures[i]); FontMemoryUsage -= pSizeData->m_TextureWidth*pSizeData->m_TextureHeight; pSizeData->m_aTextures[i] = IGraphics::CTextureHandle(); } pSizeData->m_aTextures[i] = Graphics()->LoadTextureRaw(Width, Height, CImageInfo::FORMAT_ALPHA, pMem, CImageInfo::FORMAT_ALPHA, IGraphics::TEXLOAD_NOMIPMAPS); FontMemoryUsage += Width*Height; } pSizeData->m_NumXChars = Xchars; pSizeData->m_NumYChars = Ychars; pSizeData->m_TextureWidth = Width; pSizeData->m_TextureHeight = Height; pSizeData->m_CurrentCharacter = 0; dbg_msg("", "pFont memory usage: %d", FontMemoryUsage); mem_free(pMem); } int AdjustOutlineThicknessToFontSize(int OutlineThickness, int FontSize) { if(FontSize > 36) OutlineThickness *= 4; else if(FontSize >= 18) OutlineThickness *= 2; return OutlineThickness; } void IncreaseTextureSize(CFontSizeData *pSizeData) { if(pSizeData->m_TextureWidth < pSizeData->m_TextureHeight) pSizeData->m_NumXChars <<= 1; else pSizeData->m_NumYChars <<= 1; InitTexture(pSizeData, pSizeData->m_CharMaxWidth, pSizeData->m_CharMaxHeight, pSizeData->m_NumXChars, pSizeData->m_NumYChars); } // TODO: Refactor: move this into a pFont class void InitIndex(CFont *pFont, int Index) { CFontSizeData *pSizeData = &pFont->m_aSizes[Index]; pSizeData->m_FontSize = aFontSizes[Index]; FT_Set_Pixel_Sizes(pFont->m_FtFace, 0, pSizeData->m_FontSize); int OutlineThickness = AdjustOutlineThicknessToFontSize(1, pSizeData->m_FontSize); { unsigned GlyphIndex; int MaxH = 0; int MaxW = 0; int Charcode = FT_Get_First_Char(pFont->m_FtFace, &GlyphIndex); while(GlyphIndex != 0) { // do stuff FT_Load_Glyph(pFont->m_FtFace, GlyphIndex, FT_LOAD_DEFAULT); if(pFont->m_FtFace->glyph->metrics.width > MaxW) MaxW = pFont->m_FtFace->glyph->metrics.width; // ignore_convention if(pFont->m_FtFace->glyph->metrics.height > MaxH) MaxH = pFont->m_FtFace->glyph->metrics.height; // ignore_convention Charcode = FT_Get_Next_Char(pFont->m_FtFace, Charcode, &GlyphIndex); } MaxW = (MaxW>>6)+2+OutlineThickness*2; MaxH = (MaxH>>6)+2+OutlineThickness*2; for(pSizeData->m_CharMaxWidth = 1; pSizeData->m_CharMaxWidth < MaxW; pSizeData->m_CharMaxWidth <<= 1); for(pSizeData->m_CharMaxHeight = 1; pSizeData->m_CharMaxHeight < MaxH; pSizeData->m_CharMaxHeight <<= 1); } //dbg_msg("pFont", "init size %d, texture size %d %d", pFont->sizes[index].font_size, w, h); //FT_New_Face(m_FTLibrary, "data/fonts/vera.ttf", 0, &pFont->ft_face); InitTexture(pSizeData, pSizeData->m_CharMaxWidth, pSizeData->m_CharMaxHeight, 8, 8); } CFontSizeData *GetSize(CFont *pFont, int Pixelsize) { int Index = GetFontSizeIndex(Pixelsize); if(pFont->m_aSizes[Index].m_FontSize != aFontSizes[Index]) InitIndex(pFont, Index); return &pFont->m_aSizes[Index]; } void UploadGlyph(CFontSizeData *pSizeData, int Texnum, int SlotID, int Chr, const void *pData) { int x = (SlotID%pSizeData->m_NumXChars) * (pSizeData->m_TextureWidth/pSizeData->m_NumXChars); int y = (SlotID/pSizeData->m_NumXChars) * (pSizeData->m_TextureHeight/pSizeData->m_NumYChars); Graphics()->LoadTextureRawSub(pSizeData->m_aTextures[Texnum], x, y, pSizeData->m_TextureWidth/pSizeData->m_NumXChars, pSizeData->m_TextureHeight/pSizeData->m_NumYChars, CImageInfo::FORMAT_ALPHA, pData); /* glBindTexture(GL_TEXTURE_2D, pSizeData->m_aTextures[Texnum]); glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, pSizeData->m_TextureWidth/pSizeData->m_NumXChars, pSizeData->m_TextureHeight/pSizeData->m_NumYChars, m_FontTextureFormat, GL_UNSIGNED_BYTE, pData);*/ } // 32k of data used for rendering glyphs unsigned char ms_aGlyphData[(1024/8) * (1024/8)]; unsigned char ms_aGlyphDataOutlined[(1024/8) * (1024/8)]; int GetSlot(CFontSizeData *pSizeData) { int CharCount = pSizeData->m_NumXChars*pSizeData->m_NumYChars; if(pSizeData->m_CurrentCharacter < CharCount) { int i = pSizeData->m_CurrentCharacter; pSizeData->m_CurrentCharacter++; return i; } // kick out the oldest // TODO: remove this linear search { int Oldest = 0; for(int i = 1; i < CharCount; i++) { if(pSizeData->m_aCharacters[i].m_TouchTime < pSizeData->m_aCharacters[Oldest].m_TouchTime) Oldest = i; } if(time_get()-pSizeData->m_aCharacters[Oldest].m_TouchTime < time_freq() && (pSizeData->m_NumXChars < MAX_CHARACTERS || pSizeData->m_NumYChars < MAX_CHARACTERS)) { IncreaseTextureSize(pSizeData); return GetSlot(pSizeData); } return Oldest; } } int RenderGlyph(CFont *pFont, CFontSizeData *pSizeData, int Chr) { FT_Bitmap *pBitmap; int SlotID = 0; int SlotW = pSizeData->m_TextureWidth / pSizeData->m_NumXChars; int SlotH = pSizeData->m_TextureHeight / pSizeData->m_NumYChars; int SlotSize = SlotW*SlotH; int x = 1; int y = 1; int px, py; FT_Set_Pixel_Sizes(pFont->m_FtFace, 0, pSizeData->m_FontSize); if(FT_Load_Char(pFont->m_FtFace, Chr, FT_LOAD_RENDER|FT_LOAD_NO_BITMAP)) { dbg_msg("pFont", "error loading glyph %d", Chr); return -1; } pBitmap = &pFont->m_FtFace->glyph->bitmap; // ignore_convention // fetch slot SlotID = GetSlot(pSizeData); if(SlotID < 0) return -1; // adjust spacing int OutlineThickness = AdjustOutlineThicknessToFontSize(1, pSizeData->m_FontSize); x += OutlineThickness; y += OutlineThickness; // prepare glyph data mem_zero(ms_aGlyphData, SlotSize); if(pBitmap->pixel_mode == FT_PIXEL_MODE_GRAY) // ignore_convention { for(py = 0; py < pBitmap->rows; py++) // ignore_convention for(px = 0; px < pBitmap->width; px++) // ignore_convention ms_aGlyphData[(py+y)*SlotW+px+x] = pBitmap->buffer[py*pBitmap->pitch+px]; // ignore_convention } else if(pBitmap->pixel_mode == FT_PIXEL_MODE_MONO) // ignore_convention { for(py = 0; py < pBitmap->rows; py++) // ignore_convention for(px = 0; px < pBitmap->width; px++) // ignore_convention { if(pBitmap->buffer[py*pBitmap->pitch+px/8]&(1<<(7-(px%8)))) // ignore_convention ms_aGlyphData[(py+y)*SlotW+px+x] = 255; } } if(0) for(py = 0; py < SlotW; py++) for(px = 0; px < SlotH; px++) ms_aGlyphData[py*SlotW+px] = 255; // upload the glyph UploadGlyph(pSizeData, 0, SlotID, Chr, ms_aGlyphData); if(OutlineThickness == 1) { Grow(ms_aGlyphData, ms_aGlyphDataOutlined, SlotW, SlotH); UploadGlyph(pSizeData, 1, SlotID, Chr, ms_aGlyphDataOutlined); } else { for(int i = OutlineThickness; i > 0; i-=2) { Grow(ms_aGlyphData, ms_aGlyphDataOutlined, SlotW, SlotH); Grow(ms_aGlyphDataOutlined, ms_aGlyphData, SlotW, SlotH); } UploadGlyph(pSizeData, 1, SlotID, Chr, ms_aGlyphData); } // set char info { CFontChar *pFontchr = &pSizeData->m_aCharacters[SlotID]; float Scale = 1.0f/pSizeData->m_FontSize; float Uscale = 1.0f/pSizeData->m_TextureWidth; float Vscale = 1.0f/pSizeData->m_TextureHeight; int Height = pBitmap->rows + OutlineThickness*2 + 2; // ignore_convention int Width = pBitmap->width + OutlineThickness*2 + 2; // ignore_convention pFontchr->m_ID = Chr; pFontchr->m_Height = Height * Scale; pFontchr->m_Width = Width * Scale; pFontchr->m_OffsetX = (pFont->m_FtFace->glyph->bitmap_left-1) * Scale; // ignore_convention pFontchr->m_OffsetY = (pSizeData->m_FontSize - pFont->m_FtFace->glyph->bitmap_top) * Scale; // ignore_convention pFontchr->m_AdvanceX = (pFont->m_FtFace->glyph->advance.x>>6) * Scale; // ignore_convention pFontchr->m_aUvs[0] = (SlotID%pSizeData->m_NumXChars) / (float)(pSizeData->m_NumXChars); pFontchr->m_aUvs[1] = (SlotID/pSizeData->m_NumXChars) / (float)(pSizeData->m_NumYChars); pFontchr->m_aUvs[2] = pFontchr->m_aUvs[0] + Width*Uscale; pFontchr->m_aUvs[3] = pFontchr->m_aUvs[1] + Height*Vscale; } return SlotID; } CFontChar *GetChar(CFont *pFont, CFontSizeData *pSizeData, int Chr) { CFontChar *pFontchr = NULL; // search for the character // TODO: remove this linear search int i; for(i = 0; i < pSizeData->m_CurrentCharacter; i++) { if(pSizeData->m_aCharacters[i].m_ID == Chr) { pFontchr = &pSizeData->m_aCharacters[i]; break; } } // check if we need to render the character if(!pFontchr) { int Index = RenderGlyph(pFont, pSizeData, Chr); if(Index >= 0) pFontchr = &pSizeData->m_aCharacters[Index]; } // touch the character // TODO: don't call time_get here if(pFontchr) pFontchr->m_TouchTime = time_get(); return pFontchr; } // must only be called from the rendering function as the pFont must be set to the correct size void RenderSetup(CFont *pFont, int size) { FT_Set_Pixel_Sizes(pFont->m_FtFace, 0, size); } float Kerning(CFont *pFont, int Left, int Right) { FT_Vector Kerning = {0,0}; FT_Get_Kerning(pFont->m_FtFace, Left, Right, FT_KERNING_DEFAULT, &Kerning); return (Kerning.x>>6); } public: CTextRender() { m_pGraphics = 0; m_TextR = 1.0f; m_TextG = 1.0f; m_TextB = 1.0f; m_TextA = 1.0f; m_TextOutlineR = 0.0f; m_TextOutlineG = 0.0f; m_TextOutlineB = 0.0f; m_TextOutlineA = 0.3f; m_pDefaultFont = 0; // GL_LUMINANCE can be good for debugging //m_FontTextureFormat = GL_ALPHA; } virtual void Init() { m_pGraphics = Kernel()->RequestInterface<IGraphics>(); FT_Init_FreeType(&m_FTLibrary); } virtual CFont *LoadFont(const char *pFilename) { CFont *pFont = (CFont *)mem_alloc(sizeof(CFont), 1); mem_zero(pFont, sizeof(*pFont)); str_copy(pFont->m_aFilename, pFilename, sizeof(pFont->m_aFilename)); if(FT_New_Face(m_FTLibrary, pFont->m_aFilename, 0, &pFont->m_FtFace)) { mem_free(pFont); return NULL; } for(unsigned i = 0; i < NUM_FONT_SIZES; i++) pFont->m_aSizes[i].m_FontSize = -1; dbg_msg("textrender", "loaded pFont from '%s'", pFilename); return pFont; }; virtual void DestroyFont(CFont *pFont) { mem_free(pFont); } virtual void SetDefaultFont(CFont *pFont) { dbg_msg("textrender", "default pFont set %p", pFont); m_pDefaultFont = pFont; } virtual void SetCursor(CTextCursor *pCursor, float x, float y, float FontSize, int Flags) { mem_zero(pCursor, sizeof(*pCursor)); pCursor->m_FontSize = FontSize; pCursor->m_StartX = x; pCursor->m_StartY = y; pCursor->m_X = x; pCursor->m_Y = y; pCursor->m_LineCount = 1; pCursor->m_LineWidth = -1; pCursor->m_Flags = Flags; pCursor->m_CharCount = 0; } virtual void Text(void *pFontSetV, float x, float y, float Size, const char *pText, int MaxWidth) { CTextCursor Cursor; SetCursor(&Cursor, x, y, Size, TEXTFLAG_RENDER); Cursor.m_LineWidth = MaxWidth; TextEx(&Cursor, pText, -1); } virtual float TextWidth(void *pFontSetV, float Size, const char *pText, int Length) { CTextCursor Cursor; SetCursor(&Cursor, 0, 0, Size, 0); TextEx(&Cursor, pText, Length); return Cursor.m_X; } virtual int TextLineCount(void *pFontSetV, float Size, const char *pText, float LineWidth) { CTextCursor Cursor; SetCursor(&Cursor, 0, 0, Size, 0); Cursor.m_LineWidth = LineWidth; TextEx(&Cursor, pText, -1); return Cursor.m_LineCount; } virtual void TextColor(float r, float g, float b, float a) { m_TextR = r; m_TextG = g; m_TextB = b; m_TextA = a; } virtual void TextOutlineColor(float r, float g, float b, float a) { m_TextOutlineR = r; m_TextOutlineG = g; m_TextOutlineB = b; m_TextOutlineA = a; } virtual void TextEx(CTextCursor *pCursor, const char *pText, int Length) { CFont *pFont = pCursor->m_pFont; CFontSizeData *pSizeData = NULL; //dbg_msg("textrender", "rendering text '%s'", text); float ScreenX0, ScreenY0, ScreenX1, ScreenY1; float FakeToScreenX, FakeToScreenY; int ActualX, ActualY; int ActualSize; int i; int GotNewLine = 0; float DrawX = 0.0f, DrawY = 0.0f; int LineCount = 0; float CursorX, CursorY; float Size = pCursor->m_FontSize; // to correct coords, convert to screen coords, round, and convert back Graphics()->GetScreen(&ScreenX0, &ScreenY0, &ScreenX1, &ScreenY1); FakeToScreenX = (Graphics()->ScreenWidth()/(ScreenX1-ScreenX0)); FakeToScreenY = (Graphics()->ScreenHeight()/(ScreenY1-ScreenY0)); ActualX = (int)(pCursor->m_X * FakeToScreenX); ActualY = (int)(pCursor->m_Y * FakeToScreenY); CursorX = ActualX / FakeToScreenX; CursorY = ActualY / FakeToScreenY; // same with size ActualSize = (int)(Size * FakeToScreenY); Size = ActualSize / FakeToScreenY; // fetch pFont data if(!pFont) pFont = m_pDefaultFont; if(!pFont) return; pSizeData = GetSize(pFont, ActualSize); RenderSetup(pFont, ActualSize); float Scale = 1/pSizeData->m_FontSize; // set length if(Length < 0) Length = str_length(pText); // if we don't want to render, we can just skip the first outline pass i = 1; if(pCursor->m_Flags&TEXTFLAG_RENDER) i = 0; for(;i < 2; i++) { const char *pCurrent = (char *)pText; const char *pEnd = pCurrent+Length; DrawX = CursorX; DrawY = CursorY; LineCount = pCursor->m_LineCount; if(pCursor->m_Flags&TEXTFLAG_RENDER) { // TODO: Make this better if (i == 0) Graphics()->TextureSet(pSizeData->m_aTextures[1]); else Graphics()->TextureSet(pSizeData->m_aTextures[0]); Graphics()->QuadsBegin(); if (i == 0) Graphics()->SetColor(m_TextOutlineR, m_TextOutlineG, m_TextOutlineB, m_TextOutlineA*m_TextA); else Graphics()->SetColor(m_TextR, m_TextG, m_TextB, m_TextA); } while(pCurrent < pEnd && (pCursor->m_MaxLines < 1 || LineCount <= pCursor->m_MaxLines)) { int NewLine = 0; const char *pBatchEnd = pEnd; if(pCursor->m_LineWidth > 0 && !(pCursor->m_Flags&TEXTFLAG_STOP_AT_END)) { int Wlen = min(WordLength((char *)pCurrent), (int)(pEnd-pCurrent)); CTextCursor Compare = *pCursor; Compare.m_X = DrawX; Compare.m_Y = DrawY; Compare.m_Flags &= ~TEXTFLAG_RENDER; Compare.m_LineWidth = -1; TextEx(&Compare, pCurrent, Wlen); if(Compare.m_X-DrawX > pCursor->m_LineWidth) { // word can't be fitted in one line, cut it CTextCursor Cutter = *pCursor; Cutter.m_CharCount = 0; Cutter.m_X = DrawX; Cutter.m_Y = DrawY; Cutter.m_Flags &= ~TEXTFLAG_RENDER; Cutter.m_Flags |= TEXTFLAG_STOP_AT_END; TextEx(&Cutter, (const char *)pCurrent, Wlen); Wlen = Cutter.m_CharCount; NewLine = 1; if(Wlen <= 3) // if we can't place 3 chars of the word on this line, take the next Wlen = 0; } else if(Compare.m_X-pCursor->m_StartX > pCursor->m_LineWidth) { NewLine = 1; Wlen = 0; } pBatchEnd = pCurrent + Wlen; } const char *pTmp = pCurrent; int NextCharacter = str_utf8_decode(&pTmp); while(pCurrent < pBatchEnd) { int Character = NextCharacter; pCurrent = pTmp; NextCharacter = str_utf8_decode(&pTmp); if(Character == '\n') { DrawX = pCursor->m_StartX; DrawY += Size; DrawX = (int)(DrawX * FakeToScreenX) / FakeToScreenX; // realign DrawY = (int)(DrawY * FakeToScreenY) / FakeToScreenY; ++LineCount; if(pCursor->m_MaxLines > 0 && LineCount > pCursor->m_MaxLines) break; continue; } CFontChar *pChr = GetChar(pFont, pSizeData, Character); if(pChr) { float Advance = pChr->m_AdvanceX + Kerning(pFont, Character, NextCharacter)*Scale; if(pCursor->m_Flags&TEXTFLAG_STOP_AT_END && DrawX+Advance*Size-pCursor->m_StartX > pCursor->m_LineWidth) { // we hit the end of the line, no more to render or count pCurrent = pEnd; break; } if(pCursor->m_Flags&TEXTFLAG_RENDER) { Graphics()->QuadsSetSubset(pChr->m_aUvs[0], pChr->m_aUvs[1], pChr->m_aUvs[2], pChr->m_aUvs[3]); IGraphics::CQuadItem QuadItem(DrawX+pChr->m_OffsetX*Size, DrawY+pChr->m_OffsetY*Size, pChr->m_Width*Size, pChr->m_Height*Size); Graphics()->QuadsDrawTL(&QuadItem, 1); } DrawX += Advance*Size; pCursor->m_CharCount++; } } if(NewLine) { DrawX = pCursor->m_StartX; DrawY += Size; GotNewLine = 1; DrawX = (int)(DrawX * FakeToScreenX) / FakeToScreenX; // realign DrawY = (int)(DrawY * FakeToScreenY) / FakeToScreenY; ++LineCount; } } if(pCursor->m_Flags&TEXTFLAG_RENDER) Graphics()->QuadsEnd(); } pCursor->m_X = DrawX; pCursor->m_LineCount = LineCount; if(GotNewLine) pCursor->m_Y = DrawY; } }; IEngineTextRender *CreateEngineTextRender() { return new CTextRender; } ================================================ FILE: src/engine/client.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef ENGINE_CLIENT_H #define ENGINE_CLIENT_H #include "kernel.h" #include "message.h" #include "graphics.h" class IClient : public IInterface { MACRO_INTERFACE("client", 0) protected: // quick access to state of the client int m_State; // quick access to time variables int m_PrevGameTick; int m_CurGameTick; float m_GameIntraTick; float m_GameTickTime; int m_CurMenuTick; int64 m_MenuStartTime; int m_PredTick; float m_PredIntraTick; float m_LocalTime; float m_RenderFrameTime; int m_GameTickSpeed; public: class CSnapItem { public: int m_Type; int m_ID; int m_DataSize; }; /* Constants: Client States STATE_OFFLINE - The client is offline. STATE_CONNECTING - The client is trying to connect to a server. STATE_LOADING - The client has connected to a server and is loading resources. STATE_ONLINE - The client is connected to a server and running the game. STATE_DEMOPLAYBACK - The client is playing a demo STATE_QUITING - The client is quiting. */ enum { STATE_OFFLINE=0, STATE_CONNECTING, STATE_LOADING, STATE_ONLINE, STATE_DEMOPLAYBACK, STATE_QUITING, }; // inline int State() const { return m_State; } // tick time access inline int PrevGameTick() const { return m_PrevGameTick; } inline int GameTick() const { return m_CurGameTick; } inline int MenuTick() const { return m_CurMenuTick; } inline int PredGameTick() const { return m_PredTick; } inline float IntraGameTick() const { return m_GameIntraTick; } inline float PredIntraGameTick() const { return m_PredIntraTick; } inline float GameTickTime() const { return m_GameTickTime; } inline int GameTickSpeed() const { return m_GameTickSpeed; } // other time access inline float RenderFrameTime() const { return m_RenderFrameTime; } inline float LocalTime() const { return m_LocalTime; } // actions virtual void Connect(const char *pAddress) = 0; virtual void Disconnect() = 0; virtual void Quit() = 0; virtual const char *DemoPlayer_Play(const char *pFilename, int StorageType) = 0; virtual void DemoRecorder_Start(const char *pFilename, bool WithTimestamp) = 0; virtual void DemoRecorder_HandleAutoStart() = 0; virtual void DemoRecorder_Stop() = 0; virtual void RecordGameMessage(bool State) = 0; virtual void AutoScreenshot_Start() = 0; virtual void ServerBrowserUpdate() = 0; // networking virtual void EnterGame() = 0; // virtual int MapDownloadAmount() = 0; virtual int MapDownloadTotalsize() = 0; // input virtual int *GetInput(int Tick) = 0; // remote console virtual void RconAuth(const char *pUsername, const char *pPassword) = 0; virtual bool RconAuthed() = 0; virtual bool UseTempRconCommands() = 0; virtual void Rcon(const char *pLine) = 0; // server info virtual void GetServerInfo(class CServerInfo *pServerInfo) = 0; // snapshot interface enum { SNAP_CURRENT=0, SNAP_PREV=1 }; // TODO: Refactor: should redo this a bit i think, too many virtual calls virtual int SnapNumItems(int SnapID) = 0; virtual void *SnapFindItem(int SnapID, int Type, int ID) = 0; virtual void *SnapGetItem(int SnapID, int Index, CSnapItem *pItem) = 0; virtual void SnapInvalidateItem(int SnapID, int Index) = 0; virtual void *SnapNewItem(int Type, int ID, int Size) = 0; virtual void SnapSetStaticsize(int ItemType, int Size) = 0; virtual int SendMsg(CMsgPacker *pMsg, int Flags) = 0; template<class T> int SendPackMsg(T *pMsg, int Flags) { CMsgPacker Packer(pMsg->MsgID(), false); if(pMsg->Pack(&Packer)) return -1; return SendMsg(&Packer, Flags); } // virtual const char *ErrorString() = 0; virtual const char *LatestVersion() = 0; virtual bool ConnectionProblems() = 0; virtual bool SoundInitFailed() = 0; virtual IGraphics::CTextureHandle GetDebugFont() = 0; // TODO: remove this function }; class IGameClient : public IInterface { MACRO_INTERFACE("gameclient", 0) protected: public: virtual void OnConsoleInit() = 0; virtual void OnRconLine(const char *pLine) = 0; virtual void OnInit() = 0; virtual void OnNewSnapshot() = 0; virtual void OnDemoRecSnap() = 0; virtual void OnEnterGame() = 0; virtual void OnShutdown() = 0; virtual void OnRender() = 0; virtual void OnStateChange(int NewState, int OldState) = 0; virtual void OnConnected() = 0; virtual void OnMessage(int MsgID, CUnpacker *pUnpacker) = 0; virtual void OnPredict() = 0; virtual void OnActivateEditor() = 0; virtual int OnSnapInput(int *pData) = 0; virtual const char *GetItemName(int Type) = 0; virtual const char *Version() = 0; virtual const char *NetVersion() = 0; }; extern IGameClient *CreateGameClient(); #endif ================================================ FILE: src/engine/config.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef ENGINE_CONFIG_H #define ENGINE_CONFIG_H #include "kernel.h" class IConfig : public IInterface { MACRO_INTERFACE("config", 0) public: typedef void (*SAVECALLBACKFUNC)(IConfig *pConfig, void *pUserData); virtual void Init() = 0; virtual void Reset() = 0; virtual void RestoreStrings() = 0; virtual void Save() = 0; virtual void RegisterCallback(SAVECALLBACKFUNC pfnFunc, void *pUserData) = 0; virtual void WriteLine(const char *pLine) = 0; }; extern IConfig *CreateConfig(); #endif ================================================ FILE: src/engine/console.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef ENGINE_CONSOLE_H #define ENGINE_CONSOLE_H #include "kernel.h" class IConsole : public IInterface { MACRO_INTERFACE("console", 0) public: // TODO: rework/cleanup enum { OUTPUT_LEVEL_STANDARD=0, OUTPUT_LEVEL_ADDINFO, OUTPUT_LEVEL_DEBUG, ACCESS_LEVEL_ADMIN=0, ACCESS_LEVEL_MOD, TEMPCMD_NAME_LENGTH=32, TEMPCMD_HELP_LENGTH=96, TEMPCMD_PARAMS_LENGTH=16, MAX_PRINT_CB=4, }; // TODO: rework this interface to reduce the amount of virtual calls class IResult { protected: unsigned m_NumArgs; public: IResult() { m_NumArgs = 0; } virtual ~IResult() {} virtual int GetInteger(unsigned Index) = 0; virtual float GetFloat(unsigned Index) = 0; virtual const char *GetString(unsigned Index) = 0; int NumArguments() const { return m_NumArgs; } }; class CCommandInfo { protected: int m_AccessLevel; public: CCommandInfo() { m_AccessLevel = ACCESS_LEVEL_ADMIN; } virtual ~CCommandInfo() {} const char *m_pName; const char *m_pHelp; const char *m_pParams; virtual const CCommandInfo *NextCommandInfo(int AccessLevel, int FlagMask) const = 0; int GetAccessLevel() const { return m_AccessLevel; } }; typedef void (*FPrintCallback)(const char *pStr, void *pUser); typedef void (*FPossibleCallback)(const char *pCmd, void *pUser); typedef void (*FCommandCallback)(IResult *pResult, void *pUserData); typedef void (*FChainCommandCallback)(IResult *pResult, void *pUserData, FCommandCallback pfnCallback, void *pCallbackUserData); virtual const CCommandInfo *FirstCommandInfo(int AccessLevel, int Flagmask) const = 0; virtual const CCommandInfo *GetCommandInfo(const char *pName, int FlagMask, bool Temp) = 0; virtual void PossibleCommands(const char *pStr, int FlagMask, bool Temp, FPossibleCallback pfnCallback, void *pUser) = 0; virtual void ParseArguments(int NumArgs, const char **ppArguments) = 0; virtual void Register(const char *pName, const char *pParams, int Flags, FCommandCallback pfnFunc, void *pUser, const char *pHelp) = 0; virtual void RegisterTemp(const char *pName, const char *pParams, int Flags, const char *pHelp) = 0; virtual void DeregisterTemp(const char *pName) = 0; virtual void DeregisterTempAll() = 0; virtual void Chain(const char *pName, FChainCommandCallback pfnChainFunc, void *pUser) = 0; virtual void StoreCommands(bool Store) = 0; virtual bool LineIsValid(const char *pStr) = 0; virtual void ExecuteLine(const char *Sptr) = 0; virtual void ExecuteLineFlag(const char *Sptr, int FlasgMask) = 0; virtual void ExecuteLineStroked(int Stroke, const char *pStr) = 0; virtual void ExecuteFile(const char *pFilename) = 0; virtual int RegisterPrintCallback(int OutputLevel, FPrintCallback pfnPrintCallback, void *pUserData) = 0; virtual void SetPrintOutputLevel(int Index, int OutputLevel) = 0; virtual void Print(int Level, const char *pFrom, const char *pStr) = 0; virtual void SetAccessLevel(int AccessLevel) = 0; }; extern IConsole *CreateConsole(int FlagMask); #endif // FILE_ENGINE_CONSOLE_H ================================================ FILE: src/engine/demo.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef ENGINE_DEMO_H #define ENGINE_DEMO_H #include "kernel.h" enum { MAX_TIMELINE_MARKERS=64 }; struct CDemoHeader { unsigned char m_aMarker[7]; unsigned char m_Version; char m_aNetversion[64]; char m_aMapName[64]; unsigned char m_aMapSize[4]; unsigned char m_aMapCrc[4]; char m_aType[8]; char m_aLength[4]; char m_aTimestamp[20]; char m_aNumTimelineMarkers[4]; char m_aTimelineMarkers[MAX_TIMELINE_MARKERS][4]; }; class IDemoPlayer : public IInterface { MACRO_INTERFACE("demoplayer", 0) public: class CInfo { public: bool m_Paused; float m_Speed; int m_FirstTick; int m_CurrentTick; int m_LastTick; int m_NumTimelineMarkers; int m_aTimelineMarkers[MAX_TIMELINE_MARKERS]; }; enum { DEMOTYPE_INVALID=0, DEMOTYPE_CLIENT, DEMOTYPE_SERVER, }; ~IDemoPlayer() {} virtual void SetSpeed(float Speed) = 0; virtual int SetPos(float Percent) = 0; virtual void Pause() = 0; virtual void Unpause() = 0; virtual const CInfo *BaseInfo() const = 0; virtual void GetDemoName(char *pBuffer, int BufferSize) const = 0; virtual bool GetDemoInfo(class IStorage *pStorage, const char *pFilename, int StorageType, CDemoHeader *pDemoHeader) const = 0; virtual int GetDemoType() const = 0; }; class IDemoRecorder : public IInterface { MACRO_INTERFACE("demorecorder", 0) public: ~IDemoRecorder() {} virtual bool IsRecording() const = 0; virtual int Stop() = 0; virtual int Length() const = 0; }; #endif ================================================ FILE: src/engine/docs/client_time.txt ================================================ Title: Time on the client tick, intratick predtick, predintratick prevtick tick predtick 4 8 14 |---------------------|---------------------| 0 <- intratick -> 1 0 <- ticktime(in s)-> X 0 <- predintratick?-> 1 ================================================ FILE: src/engine/docs/prediction.txt ================================================ Title: Prediction The engine calls <modc_predict> when reprediction is required. This happens usally when new data has arrived from the server. <modc_predict> should to prediction from the current snapshot and current snapshot tick (<client_tick> + 1) upto and including the tick returned by <client_predtick>. Predicted input sent to the server can be retrived by calling <client_get_input> with the corresponding tick that you want the input for. Here is a simple example of how it might look. > void modc_predict() > { > int tick; > prediction_reset(); > > for(tick = client_tick()+1; tick <= client_predtick(); tick++) > { > MY_INPUT *input = (MY_INPUT *)client_get_input(); > if(input) > prediction_apply_input(input); > prediction_tick(); > } > } ================================================ FILE: src/engine/docs/server_op.txt ================================================ Title: Server Operation Section: Init Section: Running Here is an graph over how the server operates on each refresh. (start code) load map init mod while running if map change then load new map shutdown mod <mods_shutdown> reset clients to init state init mod <mods_init> end if if new tick then call <mods_tick> for each client do create snapshot <mods_snap> send snapshot end for end process new network messages end while unload map (end) Section: Reinit Section: Shutdown ================================================ FILE: src/engine/docs/snapshots.txt ================================================ Title: Snapshots Section: Overview Topic: Definitions - *Snapshot*. A is a serialized game state from which a client can render the game from. They are sent from the server at a regular interval and is created specificly for each client in order to reduce bandwidth. - *Delta Snapshot*. A set of data that can be applied to a snapshot in order to create a new snapshot with the updated game state. Topic: Structure A snapshot contains a series of items. Each item have a type, id and data. - *Type*. Type of item. Could be projectile or character for example. - *Id*. A unique id so the client can identify the item between two snapshots. - *Data*. A series of 32-bit integers that contains the per item type specific data. Section: Server Side Topic: Creating Items can be added when <mods_snap> is called using the <snap_new_item> function to insert an item to the snapshot. The server can not inspect the snapshot that is in progress of being created. Section: Client Side Topic: Inspection <modc_newsnapshot> is called when a new snapshot has arrived for processing. <snap_num_items>, <snap_get_item> and <snap_find_item> can be used to inspect the current and previous snapshot. This can be done anywhere while the client is running and not just in the <modc_newsnapshot> function. The client can also call <snap_invalidate_item> if an item contains improper information that could harm the operation of the client. This should however be done in <modc_newsnapshot> to assure that no bad data propagates into the rest of the client. Topic: Rendering DOCTODO Section: In depth Topic: Compression After a snapshot have been created, compression is applyed to reduce the bandwidth. There are several steps taken inorder to reduce the size of the size of the snapshot. - *Delta*. The server looks in a clients backlog of snapshots to find a previous acked snapshot. It then compares the two snapshots and creates a delta snapshot containing the changes from the previous acked snapshot to the new one. - *Variable Integers*. The delta snapshot which is only consisting of 32-bit integers is then encoded into variable integers similar to UTF-8. Each byte has a bit that tells the decoder that it needs one more byte to decode the 32-bit integer. The first byte also contains a bit for telling the sign of the integer. > ESDDDDDD EDDDDDDD EDDDDDDD EDDDDDDD > E = extend > S = sign > D = data bit - *Huffman*. The last step is to compress the buffer with a huffman encoder. It uses a static tree that is weighted towards 0 because it's where most of the data will be because of the delta compression. Topic: Interval The interval for how often a client recives a snapshot changes during the course of the connection. There are three different snapshot rates. - *Init*. 5 snapshots per second. Used when a client is connecting and used until the client has acknowlaged a snapshot. This mechanism is used because the first snapshot because no delta compression can be done. - *Full*. Snapshot for every tick or every even tick depending on server configuration. This is used during normal gameplay and everything is running smooth. - *Recovery*. 1 snapshot each second. A client enters recovery rate when it havn't acknowlaged a snapshot over 1 second. This is to let the client to beable to recover if it has a slow connection. ================================================ FILE: src/engine/editor.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef ENGINE_EDITOR_H #define ENGINE_EDITOR_H #include "kernel.h" class IEditor : public IInterface { MACRO_INTERFACE("editor", 0) public: virtual ~IEditor() {} virtual void Init() = 0; virtual void UpdateAndRender() = 0; virtual bool HasUnsavedData() = 0; }; extern IEditor *CreateEditor(); #endif ================================================ FILE: src/engine/engine.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef ENGINE_ENGINE_H #define ENGINE_ENGINE_H #include "kernel.h" #include <engine/shared/jobs.h> class CHostLookup { public: CJob m_Job; char m_aHostname[128]; int m_Nettype; NETADDR m_Addr; }; class IEngine : public IInterface { MACRO_INTERFACE("engine", 0) protected: class CJobPool m_JobPool; public: virtual void Init() = 0; virtual void InitLogfile() = 0; virtual void HostLookup(CHostLookup *pLookup, const char *pHostname, int Nettype) = 0; virtual void AddJob(CJob *pJob, JOBFUNC pfnFunc, void *pData) = 0; }; extern IEngine *CreateEngine(const char *pAppname); #endif ================================================ FILE: src/engine/external/important.txt ================================================ The source code under this directory are external libraries with their own licences. The source you find here is stripped of unnessesary information. Please visit their websites for more information and official releases. ================================================ FILE: src/engine/external/json-parser/json.c ================================================ /* vim: set et ts=3 sw=3 ft=c: * * Copyright (C) 2012 James McLaughlin et al. All rights reserved. * https://github.com/udp/json-parser * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "json.h" #ifdef _MSC_VER #ifndef _CRT_SECURE_NO_WARNINGS #define _CRT_SECURE_NO_WARNINGS #endif #endif #ifdef __cplusplus const struct _json_value json_value_none; /* zero-d by ctor */ #else const struct _json_value json_value_none = { 0 }; #endif #include <stdlib.h> #include <stdio.h> #include <string.h> #include <ctype.h> #include <math.h> typedef unsigned short json_uchar; static unsigned char hex_value (json_char c) { if (c >= 'A' && c <= 'F') return (c - 'A') + 10; if (c >= 'a' && c <= 'f') return (c - 'a') + 10; if (c >= '0' && c <= '9') return c - '0'; return 0xFF; } typedef struct { json_settings settings; int first_pass; unsigned long used_memory; unsigned int uint_max; unsigned long ulong_max; } json_state; static void * json_alloc (json_state * state, unsigned long size, int zero) { void * mem; if ((state->ulong_max - state->used_memory) < size) return 0; if (state->settings.max_memory && (state->used_memory += size) > state->settings.max_memory) { return 0; } if (! (mem = zero ? calloc (size, 1) : malloc (size))) return 0; return mem; } static int new_value (json_state * state, json_value ** top, json_value ** root, json_value ** alloc, json_type type) { json_value * value; int values_size; if (!state->first_pass) { value = *top = *alloc; *alloc = (*alloc)->_reserved.next_alloc; if (!*root) *root = value; switch (value->type) { case json_array: if (! (value->u.array.values = (json_value **) json_alloc (state, value->u.array.length * sizeof (json_value *), 0)) ) { return 0; } value->u.array.length = 0; break; case json_object: values_size = sizeof (*value->u.object.values) * value->u.object.length; if (! ((*(void **) &value->u.object.values) = json_alloc (state, values_size + ((unsigned long) value->u.object.values), 0)) ) { return 0; } value->_reserved.object_mem = (*(char **) &value->u.object.values) + values_size; value->u.object.length = 0; break; case json_string: if (! (value->u.string.ptr = (json_char *) json_alloc (state, (value->u.string.length + 1) * sizeof (json_char), 0)) ) { return 0; } value->u.string.length = 0; break; default: break; }; return 1; } value = (json_value *) json_alloc (state, sizeof (json_value), 1); if (!value) return 0; if (!*root) *root = value; value->type = type; value->parent = *top; if (*alloc) (*alloc)->_reserved.next_alloc = value; *alloc = *top = value; return 1; } #define e_off \ ((int) (i - cur_line_begin)) #define whitespace \ case '\n': ++ cur_line; cur_line_begin = i; \ case ' ': case '\t': case '\r' #define string_add(b) \ do { if (!state.first_pass) string [string_length] = b; ++ string_length; } while (0); const static long flag_next = 1, flag_reproc = 2, flag_need_comma = 4, flag_seek_value = 8, flag_escaped = 16, flag_string = 32, flag_need_colon = 64, flag_done = 128, flag_num_negative = 256, flag_num_zero = 512, flag_num_e = 1024, flag_num_e_got_sign = 2048, flag_num_e_negative = 4096; json_value * json_parse_ex (json_settings * settings, const json_char * json, char * error_buf) { json_char error [128]; unsigned int cur_line; const json_char * cur_line_begin, * i; json_value * top, * root, * alloc = 0; json_state state; long flags; long num_digits, num_fraction, num_e; error[0] = '\0'; num_digits = num_fraction = num_e = 0; memset (&state, 0, sizeof (json_state)); memcpy (&state.settings, settings, sizeof (json_settings)); memset (&state.uint_max, 0xFF, sizeof (state.uint_max)); memset (&state.ulong_max, 0xFF, sizeof (state.ulong_max)); state.uint_max -= 8; /* limit of how much can be added before next check */ state.ulong_max -= 8; for (state.first_pass = 1; state.first_pass >= 0; -- state.first_pass) { json_uchar uchar; unsigned char uc_b1, uc_b2, uc_b3, uc_b4; json_char * string; unsigned int string_length; top = root = 0; flags = flag_seek_value; string_length = 0; string = 0; cur_line = 1; cur_line_begin = json; for (i = json ;; ++ i) { json_char b = *i; if (flags & flag_done) { if (!b) break; switch (b) { whitespace: continue; default: sprintf (error, "%d:%d: Trailing garbage: `%c`", cur_line, e_off, b); goto e_failed; }; } if (flags & flag_string) { if (!b) { sprintf (error, "Unexpected EOF in string (at %d:%d)", cur_line, e_off); goto e_failed; } if (string_length > state.uint_max) goto e_overflow; if (flags & flag_escaped) { flags &= ~ flag_escaped; switch (b) { case 'b': string_add ('\b'); break; case 'f': string_add ('\f'); break; case 'n': string_add ('\n'); break; case 'r': string_add ('\r'); break; case 't': string_add ('\t'); break; case 'u': if ((uc_b1 = hex_value (*++ i)) == 0xFF || (uc_b2 = hex_value (*++ i)) == 0xFF || (uc_b3 = hex_value (*++ i)) == 0xFF || (uc_b4 = hex_value (*++ i)) == 0xFF) { sprintf (error, "Invalid character value `%c` (at %d:%d)", b, cur_line, e_off); goto e_failed; } uc_b1 = uc_b1 * 16 + uc_b2; uc_b2 = uc_b3 * 16 + uc_b4; uchar = ((json_char) uc_b1) * 256 + uc_b2; if (sizeof (json_char) >= sizeof (json_uchar) || (uc_b1 == 0 && uc_b2 <= 0x7F)) { string_add ((json_char) uchar); break; } if (uchar <= 0x7FF) { if (state.first_pass) string_length += 2; else { string [string_length ++] = 0xC0 | ((uc_b2 & 0xC0) >> 6) | ((uc_b1 & 0x7) << 2); string [string_length ++] = 0x80 | (uc_b2 & 0x3F); } break; } if (state.first_pass) string_length += 3; else { string [string_length ++] = 0xE0 | ((uc_b1 & 0xF0) >> 4); string [string_length ++] = 0x80 | ((uc_b1 & 0xF) << 2) | ((uc_b2 & 0xC0) >> 6); string [string_length ++] = 0x80 | (uc_b2 & 0x3F); } break; default: string_add (b); }; continue; } if (b == '\\') { flags |= flag_escaped; continue; } if (b == '"') { if (!state.first_pass) string [string_length] = 0; flags &= ~ flag_string; string = 0; switch (top->type) { case json_string: top->u.string.length = string_length; flags |= flag_next; break; case json_object: if (state.first_pass) (*(json_char **) &top->u.object.values) += string_length + 1; else { top->u.object.values [top->u.object.length].name = (json_char *) top->_reserved.object_mem; (*(json_char **) &top->_reserved.object_mem) += string_length + 1; } flags |= flag_seek_value | flag_need_colon; continue; default: break; }; } else { string_add (b); continue; } } if (flags & flag_seek_value) { switch (b) { whitespace: continue; case ']': if (top->type == json_array) flags = (flags & ~ (flag_need_comma | flag_seek_value)) | flag_next; else if (!state.settings.settings & json_relaxed_commas) { sprintf (error, "%d:%d: Unexpected ]", cur_line, e_off); goto e_failed; } break; default: if (flags & flag_need_comma) { if (b == ',') { flags &= ~ flag_need_comma; continue; } else { sprintf (error, "%d:%d: Expected , before %c", cur_line, e_off, b); goto e_failed; } } if (flags & flag_need_colon) { if (b == ':') { flags &= ~ flag_need_colon; continue; } else { sprintf (error, "%d:%d: Expected : before %c", cur_line, e_off, b); goto e_failed; } } flags &= ~ flag_seek_value; switch (b) { case '{': if (!new_value (&state, &top, &root, &alloc, json_object)) goto e_alloc_failure; continue; case '[': if (!new_value (&state, &top, &root, &alloc, json_array)) goto e_alloc_failure; flags |= flag_seek_value; continue; case '"': if (!new_value (&state, &top, &root, &alloc, json_string)) goto e_alloc_failure; flags |= flag_string; string = top->u.string.ptr; string_length = 0; continue; case 't': if (*(++ i) != 'r' || *(++ i) != 'u' || *(++ i) != 'e') goto e_unknown_value; if (!new_value (&state, &top, &root, &alloc, json_boolean)) goto e_alloc_failure; top->u.boolean = 1; flags |= flag_next; break; case 'f': if (*(++ i) != 'a' || *(++ i) != 'l' || *(++ i) != 's' || *(++ i) != 'e') goto e_unknown_value; if (!new_value (&state, &top, &root, &alloc, json_boolean)) goto e_alloc_failure; flags |= flag_next; break; case 'n': if (*(++ i) != 'u' || *(++ i) != 'l' || *(++ i) != 'l') goto e_unknown_value; if (!new_value (&state, &top, &root, &alloc, json_null)) goto e_alloc_failure; flags |= flag_next; break; default: if (isdigit (b) || b == '-') { if (!new_value (&state, &top, &root, &alloc, json_integer)) goto e_alloc_failure; if (!state.first_pass) { while (isdigit (b) || b == '+' || b == '-' || b == 'e' || b == 'E' || b == '.') { b = *++ i; } flags |= flag_next | flag_reproc; break; } flags &= ~ (flag_num_negative | flag_num_e | flag_num_e_got_sign | flag_num_e_negative | flag_num_zero); num_digits = 0; num_fraction = 0; num_e = 0; if (b != '-') { flags |= flag_reproc; break; } flags |= flag_num_negative; continue; } else { sprintf (error, "%d:%d: Unexpected %c when seeking value", cur_line, e_off, b); goto e_failed; } }; }; } else { switch (top->type) { case json_object: switch (b) { whitespace: continue; case '"': if (flags & flag_need_comma && (!state.settings.settings & json_relaxed_commas)) { sprintf (error, "%d:%d: Expected , before \"", cur_line, e_off); goto e_failed; } flags |= flag_string; string = (json_char *) top->_reserved.object_mem; string_length = 0; break; case '}': flags = (flags & ~ flag_need_comma) | flag_next; break; case ',': if (flags & flag_need_comma) { flags &= ~ flag_need_comma; break; } default: sprintf (error, "%d:%d: Unexpected `%c` in object", cur_line, e_off, b); goto e_failed; }; break; case json_integer: case json_double: if (isdigit (b)) { ++ num_digits; if (top->type == json_integer || flags & flag_num_e) { if (! (flags & flag_num_e)) { if (flags & flag_num_zero) { sprintf (error, "%d:%d: Unexpected `0` before `%c`", cur_line, e_off, b); goto e_failed; } if (num_digits == 1 && b == '0') flags |= flag_num_zero; } else { flags |= flag_num_e_got_sign; num_e = (num_e * 10) + (b - '0'); continue; } top->u.integer = (top->u.integer * 10) + (b - '0'); continue; } num_fraction = (num_fraction * 10) + (b - '0'); continue; } if (b == '+' || b == '-') { if ( (flags & flag_num_e) && !(flags & flag_num_e_got_sign)) { flags |= flag_num_e_got_sign; if (b == '-') flags |= flag_num_e_negative; continue; } } else if (b == '.' && top->type == json_integer) { if (!num_digits) { sprintf (error, "%d:%d: Expected digit before `.`", cur_line, e_off); goto e_failed; } top->type = json_double; top->u.dbl = top->u.integer; num_digits = 0; continue; } if (! (flags & flag_num_e)) { if (top->type == json_double) { if (!num_digits) { sprintf (error, "%d:%d: Expected digit after `.`", cur_line, e_off); goto e_failed; } top->u.dbl += ((double) num_fraction) / (pow (10, num_digits)); } if (b == 'e' || b == 'E') { flags |= flag_num_e; if (top->type == json_integer) { top->type = json_double; top->u.dbl = top->u.integer; } num_digits = 0; flags &= ~ flag_num_zero; continue; } } else { if (!num_digits) { sprintf (error, "%d:%d: Expected digit after `e`", cur_line, e_off); goto e_failed; } top->u.dbl *= pow (10, flags & flag_num_e_negative ? - num_e : num_e); } if (flags & flag_num_negative) { if (top->type == json_integer) top->u.integer = - top->u.integer; else top->u.dbl = - top->u.dbl; } flags |= flag_next | flag_reproc; break; default: break; }; } if (flags & flag_reproc) { flags &= ~ flag_reproc; -- i; } if (flags & flag_next) { flags = (flags & ~ flag_next) | flag_need_comma; if (!top->parent) { /* root value done */ flags |= flag_done; continue; } if (top->parent->type == json_array) flags |= flag_seek_value; if (!state.first_pass) { json_value * parent = top->parent; switch (parent->type) { case json_object: parent->u.object.values [parent->u.object.length].value = top; break; case json_array: parent->u.array.values [parent->u.array.length] = top; break; default: break; }; } if ( (++ top->parent->u.array.length) > state.uint_max) goto e_overflow; top = top->parent; continue; } } alloc = root; } return root; e_unknown_value: sprintf (error, "%d:%d: Unknown value", cur_line, e_off); goto e_failed; e_alloc_failure: strcpy (error, "Memory allocation failure"); goto e_failed; e_overflow: sprintf (error, "%d:%d: Too long (caught overflow)", cur_line, e_off); goto e_failed; e_failed: if (error_buf) { if (*error) strcpy (error_buf, error); else strcpy (error_buf, "Unknown error"); } if (state.first_pass) alloc = root; while (alloc) { top = alloc->_reserved.next_alloc; free (alloc); alloc = top; } if (!state.first_pass) json_value_free (root); return 0; } json_value * json_parse (const json_char * json) { json_settings settings; memset (&settings, 0, sizeof (json_settings)); return json_parse_ex (&settings, json, 0); } void json_value_free (json_value * value) { json_value * cur_value; if (!value) return; value->parent = 0; while (value) { switch (value->type) { case json_array: if (!value->u.array.length) { free (value->u.array.values); break; } value = value->u.array.values [-- value->u.array.length]; continue; case json_object: if (!value->u.object.length) { free (value->u.object.values); break; } value = value->u.object.values [-- value->u.object.length].value; continue; case json_string: free (value->u.string.ptr); break; default: break; }; cur_value = value; value = value->parent; free (cur_value); } } ================================================ FILE: src/engine/external/json-parser/json.h ================================================ /* vim: set et ts=3 sw=3 ft=c: * * Copyright (C) 2012 James McLaughlin et al. All rights reserved. * https://github.com/udp/json-parser * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef _JSON_H #define _JSON_H #ifndef json_char #define json_char char #endif #ifdef __cplusplus #include <string.h> extern "C" { #endif typedef struct { unsigned long max_memory; int settings; } json_settings; #define json_relaxed_commas 1 typedef enum { json_none, json_object, json_array, json_integer, json_double, json_string, json_boolean, json_null } json_type; extern const struct _json_value json_value_none; typedef struct _json_value { struct _json_value * parent; json_type type; union { int boolean; long integer; double dbl; struct { unsigned int length; json_char * ptr; /* null terminated */ } string; struct { unsigned int length; struct { json_char * name; struct _json_value * value; } * values; } object; struct { unsigned int length; struct _json_value ** values; } array; } u; union { struct _json_value * next_alloc; void * object_mem; } _reserved; /* Some C++ operator sugar */ #ifdef __cplusplus public: inline _json_value () { memset (this, 0, sizeof (_json_value)); } inline const struct _json_value &operator [] (int index) const { if (type != json_array || index < 0 || ((unsigned int) index) >= u.array.length) { return json_value_none; } return *u.array.values [index]; } inline const struct _json_value &operator [] (const char * index) const { if (type != json_object) return json_value_none; for (unsigned int i = 0; i < u.object.length; ++ i) if (!strcmp (u.object.values [i].name, index)) return *u.object.values [i].value; return json_value_none; } inline operator const char * () const { switch (type) { case json_string: return u.string.ptr; default: return ""; }; } inline operator long () const { return u.integer; } inline operator bool () const { return u.boolean != 0; } #endif } json_value; json_value * json_parse (const json_char * json); json_value * json_parse_ex (json_settings * settings, const json_char * json, char * error); void json_value_free (json_value *); #ifdef __cplusplus } /* extern "C" */ #endif #endif ================================================ FILE: src/engine/external/pnglite/VERSION ================================================ 0.1.17 ================================================ FILE: src/engine/external/pnglite/pnglite.c ================================================ /* pnglite.c - pnglite library For conditions of distribution and use, see copyright notice in pnglite.h */ #define DO_CRC_CHECKS 1 #define USE_ZLIB 1 #if USE_ZLIB #include <zlib.h> #else #include "zlite.h" #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include "pnglite.h" static png_alloc_t png_alloc; static png_free_t png_free; static size_t file_read(png_t* png, void* out, size_t size, size_t numel) { size_t result; if(png->read_fun) { result = png->read_fun(out, size, numel, png->user_pointer); } else { if(!out) { result = fseek(png->user_pointer, (long)(size*numel), SEEK_CUR); } else { result = fread(out, size, numel, png->user_pointer); } } return result; } static size_t file_write(png_t* png, void* p, size_t size, size_t numel) { size_t result; if(png->write_fun) { result = png->write_fun(p, size, numel, png->user_pointer); } else { result = fwrite(p, size, numel, png->user_pointer); } return result; } static int file_read_ul(png_t* png, unsigned *out) { unsigned char buf[4]; if(file_read(png, buf, 1, 4) != 4) return PNG_FILE_ERROR; *out = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3]; return PNG_NO_ERROR; } static int file_write_ul(png_t* png, unsigned in) { unsigned char buf[4]; buf[0] = (in>>24) & 0xff; buf[1] = (in>>16) & 0xff; buf[2] = (in>>8) & 0xff; buf[3] = (in) & 0xff; if(file_write(png, buf, 1, 4) != 4) return PNG_FILE_ERROR; return PNG_NO_ERROR; } static unsigned get_ul(unsigned char* buf) { unsigned result; unsigned char foo[4]; memcpy(foo, buf, 4); result = (foo[0]<<24) | (foo[1]<<16) | (foo[2]<<8) | foo[3]; return result; } static unsigned set_ul(unsigned char* buf, unsigned in) { buf[0] = (in>>24) & 0xff; buf[1] = (in>>16) & 0xff; buf[2] = (in>>8) & 0xff; buf[3] = (in) & 0xff; return PNG_NO_ERROR; } int png_init(png_alloc_t pngalloc, png_free_t pngfree) { if(pngalloc) png_alloc = pngalloc; else png_alloc = (png_alloc_t)&malloc; if(pngfree) png_free = pngfree; else png_free = &free; return PNG_NO_ERROR; } static int png_get_bpp(png_t* png) { int bpp; switch(png->color_type) { case PNG_GREYSCALE: bpp = 1; break; case PNG_TRUECOLOR: bpp = 3; break; case PNG_INDEXED: bpp = 1; break; case PNG_GREYSCALE_ALPHA: bpp = 2; break; case PNG_TRUECOLOR_ALPHA: bpp = 4; break; default: return PNG_FILE_ERROR; } bpp *= png->depth/8; return bpp; } static int png_read_ihdr(png_t* png) { int result; unsigned length; #if DO_CRC_CHECKS unsigned orig_crc; unsigned calc_crc; #endif unsigned char ihdr[13+4]; /* length should be 13, make room for type (IHDR) */ file_read_ul(png, &length); if(length != 13) { printf("%d\n", length); return PNG_CRC_ERROR; } if(file_read(png, ihdr, 1, 13+4) != 13+4) return PNG_EOF_ERROR; #if DO_CRC_CHECKS result = file_read_ul(png, &orig_crc); if(result != PNG_NO_ERROR) return result; calc_crc = crc32(0L, 0, 0); calc_crc = crc32(calc_crc, ihdr, 13+4); if(orig_crc != calc_crc) return PNG_CRC_ERROR; #else result = file_read_ul(png); if(result != PNG_NO_ERROR) return result; #endif png->width = get_ul(ihdr+4); png->height = get_ul(ihdr+8); png->depth = ihdr[12]; png->color_type = ihdr[13]; png->compression_method = ihdr[14]; png->filter_method = ihdr[15]; png->interlace_method = ihdr[16]; if(png->color_type == PNG_INDEXED) return PNG_NOT_SUPPORTED; if(png->depth != 8 && png->depth != 16) return PNG_NOT_SUPPORTED; if(png->interlace_method) return PNG_NOT_SUPPORTED; return PNG_NO_ERROR; } static int png_write_ihdr(png_t* png) { unsigned char ihdr[13+4]; unsigned char *p = ihdr; unsigned crc; file_write(png, "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A", 1, 8); file_write_ul(png, 13); *p = 'I'; p++; *p = 'H'; p++; *p = 'D'; p++; *p = 'R'; p++; set_ul(p, png->width); p+=4; set_ul(p, png->height); p+=4; *p = png->depth; p++; *p = png->color_type; p++; *p = 0; p++; *p = 0; p++; *p = 0; p++; file_write(png, ihdr, 1, 13+4); crc = crc32(0L, 0, 0); crc = crc32(crc, ihdr, 13+4); file_write_ul(png, crc); return PNG_NO_ERROR; } void png_print_info(png_t* png) { printf("PNG INFO:\n"); printf("\twidth:\t\t%d\n", png->width); printf("\theight:\t\t%d\n", png->height); printf("\tdepth:\t\t%d\n", png->depth); printf("\tcolor:\t\t"); switch(png->color_type) { case PNG_GREYSCALE: printf("greyscale\n"); break; case PNG_TRUECOLOR: printf("truecolor\n"); break; case PNG_INDEXED: printf("palette\n"); break; case PNG_GREYSCALE_ALPHA: printf("greyscale with alpha\n"); break; case PNG_TRUECOLOR_ALPHA: printf("truecolor with alpha\n"); break; default: printf("unknown, this is not good\n"); break; } printf("\tcompression:\t%s\n", png->compression_method?"unknown, this is not good":"inflate/deflate"); printf("\tfilter:\t\t%s\n", png->filter_method?"unknown, this is not good":"adaptive"); printf("\tinterlace:\t%s\n", png->interlace_method?"interlace":"no interlace"); } int png_open_read(png_t* png, png_read_callback_t read_fun, void* user_pointer) { char header[8]; int result; png->read_fun = read_fun; png->write_fun = 0; png->user_pointer = user_pointer; if(!read_fun && !user_pointer) return PNG_WRONG_ARGUMENTS; if(file_read(png, header, 1, 8) != 8) return PNG_EOF_ERROR; if(memcmp(header, "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A", 8) != 0) return PNG_HEADER_ERROR; result = png_read_ihdr(png); png->bpp = (unsigned char)png_get_bpp(png); if(png->bpp < 0) result = png->bpp; return result; } int png_open_write(png_t* png, png_write_callback_t write_fun, void* user_pointer) { png->write_fun = write_fun; png->read_fun = 0; png->user_pointer = user_pointer; if(!write_fun && !user_pointer) return PNG_WRONG_ARGUMENTS; return PNG_NO_ERROR; } int png_open(png_t* png, png_read_callback_t read_fun, void* user_pointer) { return png_open_read(png, read_fun, user_pointer); } int png_open_file_read(png_t *png, const char* filename) { FILE* fp = fopen(filename, "rb"); if(!fp) return PNG_FILE_ERROR; return png_open_read(png, 0, fp); } int png_open_file_write(png_t *png, const char* filename) { FILE* fp = fopen(filename, "wb"); if(!fp) return PNG_FILE_ERROR; return png_open_write(png, 0, fp); } int png_open_file(png_t *png, const char* filename) { return png_open_file_read(png, filename); } int png_close_file(png_t* png) { fclose(png->user_pointer); return PNG_NO_ERROR; } static int png_init_deflate(png_t* png, unsigned char* data, int datalen) { z_stream *stream; png->zs = png_alloc(sizeof(z_stream)); stream = png->zs; if(!stream) return PNG_MEMORY_ERROR; memset(stream, 0, sizeof(z_stream)); if(deflateInit(stream, Z_DEFAULT_COMPRESSION) != Z_OK) return PNG_ZLIB_ERROR; stream->next_in = data; stream->avail_in = datalen; return PNG_NO_ERROR; } static int png_init_inflate(png_t* png) { #if USE_ZLIB z_stream *stream; png->zs = png_alloc(sizeof(z_stream)); #else zl_stream *stream; png->zs = png_alloc(sizeof(zl_stream)); #endif stream = png->zs; if(!stream) return PNG_MEMORY_ERROR; #if USE_ZLIB memset(stream, 0, sizeof(z_stream)); if(inflateInit(stream) != Z_OK) return PNG_ZLIB_ERROR; #else memset(stream, 0, sizeof(zl_stream)); if(z_inflateInit(stream) != Z_OK) return PNG_ZLIB_ERROR; #endif stream->next_out = png->png_data; stream->avail_out = png->png_datalen; return PNG_NO_ERROR; } static int png_end_deflate(png_t* png) { z_stream *stream = png->zs; if(!stream) return PNG_MEMORY_ERROR; deflateEnd(stream); png_free(png->zs); png->zs = 0; return PNG_NO_ERROR; } static int png_end_inflate(png_t* png) { #if USE_ZLIB z_stream *stream = png->zs; #else zl_stream *stream = png->zs; #endif if(!stream) return PNG_MEMORY_ERROR; #if USE_ZLIB if(inflateEnd(stream) != Z_OK) #else if(z_inflateEnd(stream) != Z_OK) #endif { printf("ZLIB says: %s\n", stream->msg); return PNG_ZLIB_ERROR; } png_free(png->zs); png->zs = 0; return PNG_NO_ERROR; } static int png_inflate(png_t* png, char* data, int len) { int result; #if USE_ZLIB z_stream *stream = png->zs; #else zl_stream *stream = png->zs; #endif if(!stream) return PNG_MEMORY_ERROR; stream->next_in = (unsigned char*)data; stream->avail_in = len; #if USE_ZLIB result = inflate(stream, Z_SYNC_FLUSH); #else result = z_inflate(stream); #endif if(result != Z_STREAM_END && result != Z_OK) { printf("%s\n", stream->msg); return PNG_ZLIB_ERROR; } if(stream->avail_in != 0) return PNG_ZLIB_ERROR; return PNG_NO_ERROR; } static int png_deflate(png_t* png, char* outdata, int outlen, int *outwritten) { int result; z_stream *stream = png->zs; if(!stream) return PNG_MEMORY_ERROR; stream->next_out = (unsigned char*)outdata; stream->avail_out = outlen; result = deflate(stream, Z_SYNC_FLUSH); *outwritten = outlen - stream->avail_out; if(result != Z_STREAM_END && result != Z_OK) { printf("%s\n", stream->msg); return PNG_ZLIB_ERROR; } return result; } static int png_write_idats(png_t* png, unsigned char* data) { unsigned char *chunk; unsigned long written; unsigned long crc; unsigned size = png->width * png->height * png->bpp + png->height; (void)png_init_deflate; (void)png_end_deflate; (void)png_deflate; chunk = png_alloc(size+8); memcpy(chunk, "IDAT", 4); written = size; compress(chunk+4, &written, data, size); crc = crc32(0L, Z_NULL, 0); crc = crc32(crc, chunk, written+4); set_ul(chunk+written+4, crc); file_write_ul(png, written); file_write(png, chunk, 1, written+8); png_free(chunk); file_write_ul(png, 0); file_write(png, "IEND", 1, 4); crc = crc32(0L, (const unsigned char *)"IEND", 4); file_write_ul(png, crc); return PNG_NO_ERROR; } static int png_read_idat(png_t* png, unsigned firstlen) { unsigned type = 0; char *chunk; int result; unsigned length = firstlen; unsigned old_len = length; #if DO_CRC_CHECKS unsigned orig_crc; unsigned calc_crc; #endif chunk = png_alloc(firstlen); if(!chunk) return PNG_MEMORY_ERROR; result = png_init_inflate(png); if(result != PNG_NO_ERROR) { png_end_inflate(png); png_free(chunk); return result; } do { if(file_read(png, chunk, 1, length) != length) { png_end_inflate(png); png_free(chunk); return PNG_FILE_ERROR; } #if DO_CRC_CHECKS calc_crc = crc32(0L, Z_NULL, 0); calc_crc = crc32(calc_crc, (unsigned char*)"IDAT", 4); calc_crc = crc32(calc_crc, (unsigned char*)chunk, length); file_read_ul(png, &orig_crc); if(orig_crc != calc_crc) { result = PNG_CRC_ERROR; break; } #else file_read_ul(png); #endif result = png_inflate(png, chunk, length); if(result != PNG_NO_ERROR) break; file_read_ul(png, &length); if(length > old_len) { png_free(chunk); chunk = png_alloc(length); if(!chunk) { png_end_inflate(png); return PNG_MEMORY_ERROR; } old_len = length; } if(file_read(png, &type, 1, 4) != 4) { result = PNG_FILE_ERROR; break; } }while(type == *(unsigned int*)"IDAT"); if(type == *(unsigned int*)"IEND") result = PNG_DONE; png_free(chunk); png_end_inflate(png); return result; } static int png_process_chunk(png_t* png) { int result = PNG_NO_ERROR; unsigned type; unsigned length; file_read_ul(png, &length); if(file_read(png, &type, 1, 4) != 4) return PNG_FILE_ERROR; if(type == *(unsigned int*)"IDAT") /* if we found an idat, all other idats should be followed with no other chunks in between */ { if(!png->png_data) { png->png_datalen = png->width * png->height * png->bpp + png->height; png->png_data = png_alloc(png->png_datalen); } else return PNG_FILE_ERROR; if(!png->png_data) return PNG_MEMORY_ERROR; return png_read_idat(png, length); } else if(type == *(unsigned int*)"IEND") { return PNG_DONE; } else { file_read(png, 0, 1, length + 4); /* unknown chunk */ } return result; } static void png_filter_sub(int stride, unsigned char* in, unsigned char* out, int len) { int i; unsigned char a = 0; for(i = 0; i < len; i++) { if(i >= stride) a = out[i - stride]; out[i] = in[i] + a; } } static void png_filter_up(int stride, unsigned char* in, unsigned char* out, unsigned char* prev_line, int len) { int i; if(prev_line) { for(i = 0; i < len; i++) out[i] = in[i] + prev_line[i]; } else memcpy(out, in, len); } static void png_filter_average(int stride, unsigned char* in, unsigned char* out, unsigned char* prev_line, int len) { int i; unsigned char a = 0; unsigned char b = 0; unsigned int sum = 0; for(i = 0; i < len; i++) { if(prev_line) b = prev_line[i]; if(i >= stride) a = out[i - stride]; sum = a; sum += b; out[i] = (char)(in[i] + sum/2); } } static unsigned char png_paeth(unsigned char a, unsigned char b, unsigned char c) { int p = (int)a + b - c; int pa = abs(p - a); int pb = abs(p - b); int pc = abs(p - c); int pr; if(pa <= pb && pa <= pc) pr = a; else if(pb <= pc) pr = b; else pr = c; return (char)pr; } static void png_filter_paeth(int stride, unsigned char* in, unsigned char* out, unsigned char* prev_line, int len) { int i; unsigned char a; unsigned char b; unsigned char c; for(i = 0; i < len; i++) { if(prev_line && i >= stride) { a = out[i - stride]; b = prev_line[i]; c = prev_line[i - stride]; } else { if(prev_line) b = prev_line[i]; else b = 0; if(i >= stride) a = out[i - stride]; else a = 0; c = 0; } out[i] = in[i] + png_paeth(a, b, c); } } static int png_filter(png_t* png, unsigned char* data) { return PNG_NO_ERROR; } static int png_unfilter(png_t* png, unsigned char* data) { unsigned i; unsigned pos = 0; unsigned outpos = 0; unsigned char *filtered = png->png_data; int stride = png->bpp; while(pos < png->png_datalen) { unsigned char filter = filtered[pos]; pos++; if(png->depth == 16) { for(i = 0; i < png->width * stride; i+=2) { *(short*)(filtered+pos+i) = (filtered[pos+i] << 8) | filtered[pos+i+1]; } } switch(filter) { case 0: /* none */ memcpy(data+outpos, filtered+pos, png->width * stride); break; case 1: /* sub */ png_filter_sub(stride, filtered+pos, data+outpos, png->width * stride); break; case 2: /* up */ if(outpos) png_filter_up(stride, filtered+pos, data+outpos, data + outpos - (png->width*stride), png->width*stride); else png_filter_up(stride, filtered+pos, data+outpos, 0, png->width*stride); break; case 3: /* average */ if(outpos) png_filter_average(stride, filtered+pos, data+outpos, data + outpos - (png->width*stride), png->width*stride); else png_filter_average(stride, filtered+pos, data+outpos, 0, png->width*stride); break; case 4: /* paeth */ if(outpos) png_filter_paeth(stride, filtered+pos, data+outpos, data + outpos - (png->width*stride), png->width*stride); else png_filter_paeth(stride, filtered+pos, data+outpos, 0, png->width*stride); break; default: return PNG_UNKNOWN_FILTER; } outpos += png->width * stride; pos += png->width * stride; } return PNG_NO_ERROR; } int png_get_data(png_t* png, unsigned char* data) { int result = PNG_NO_ERROR; png->png_data = 0; png->zs = 0; while(result == PNG_NO_ERROR) { result = png_process_chunk(png); } if(result != PNG_DONE) { if(!png->png_data) { png_free(png->png_data); png->png_data = 0; } return result; } result = png_unfilter(png, data); png_free(png->png_data); png->png_data = 0; return result; } int png_set_data(png_t* png, unsigned width, unsigned height, char depth, int color, unsigned char* data) { int i; unsigned char *filtered; png->width = width; png->height = height; png->depth = depth; png->color_type = color; png->bpp = png_get_bpp(png); filtered = png_alloc(width * height * png->bpp + height); for(i = 0; i < png->height; i++) { filtered[i*png->width*png->bpp+i] = 0; memcpy(&filtered[i*png->width*png->bpp+i+1], data + i * png->width*png->bpp, png->width*png->bpp); } png_filter(png, filtered); png_write_ihdr(png); png_write_idats(png, filtered); png_free(filtered); return PNG_NO_ERROR; } char* png_error_string(int error) { switch(error) { case PNG_NO_ERROR: return "No error"; case PNG_FILE_ERROR: return "Unknown file error."; case PNG_HEADER_ERROR: return "No PNG header found. Are you sure this is a PNG?"; case PNG_IO_ERROR: return "Failure while reading file."; case PNG_EOF_ERROR: return "Reached end of file."; case PNG_CRC_ERROR: return "CRC or chunk length error."; case PNG_MEMORY_ERROR: return "Could not allocate memory."; case PNG_ZLIB_ERROR: return "zlib reported an error."; case PNG_UNKNOWN_FILTER: return "Unknown filter method used in scanline."; case PNG_DONE: return "PNG done"; case PNG_NOT_SUPPORTED: return "The PNG is unsupported by pnglite, too bad for you!"; case PNG_WRONG_ARGUMENTS: return "Wrong combination of arguments passed to png_open. You must use either a read_function or supply a file pointer to use."; default: return "Unknown error."; }; } ================================================ FILE: src/engine/external/pnglite/pnglite.h ================================================ /* pnglite.h - Interface for pnglite library Copyright (c) 2007 Daniel Karling This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Daniel Karling daniel.karling@gmail.com */ /* NOTICE: This is a modified version which contains changes that address compiler warnings and increase stability. */ #ifndef _PNGLITE_H_ #define _PNGLITE_H_ #ifdef __cplusplus extern "C"{ #endif /* Enumerations for pnglite. Negative numbers are error codes and 0 and up are okay responses. */ enum { PNG_DONE = 1, PNG_NO_ERROR = 0, PNG_FILE_ERROR = -1, PNG_HEADER_ERROR = -2, PNG_IO_ERROR = -3, PNG_EOF_ERROR = -4, PNG_CRC_ERROR = -5, PNG_MEMORY_ERROR = -6, PNG_ZLIB_ERROR = -7, PNG_UNKNOWN_FILTER = -8, PNG_NOT_SUPPORTED = -9, PNG_WRONG_ARGUMENTS = -10 }; /* The five different kinds of color storage in PNG files. */ enum { PNG_GREYSCALE = 0, PNG_TRUECOLOR = 2, PNG_INDEXED = 3, PNG_GREYSCALE_ALPHA = 4, PNG_TRUECOLOR_ALPHA = 6 }; /* Typedefs for callbacks. */ typedef unsigned (*png_write_callback_t)(void* input, unsigned long size, unsigned long numel, void* user_pointer); typedef unsigned (*png_read_callback_t)(void* output, unsigned long size, unsigned long numel, void* user_pointer); typedef void (*png_free_t)(void* p); typedef void * (*png_alloc_t)(unsigned long s); typedef struct { void* zs; /* pointer to z_stream */ png_read_callback_t read_fun; png_write_callback_t write_fun; void* user_pointer; unsigned char* png_data; unsigned png_datalen; unsigned width; unsigned height; unsigned char depth; unsigned char color_type; unsigned char compression_method; unsigned char filter_method; unsigned char interlace_method; unsigned char bpp; }png_t; /* Function: png_init This function initializes pnglite. The parameters can be used to set your own memory allocation routines following these formats: > void* (*custom_alloc)(unsigned long s) > void (*custom_free)(void* p) Parameters: pngalloc - Pointer to custom allocation routine. If 0 is passed, malloc from libc will be used. pngfree - Pointer to custom free routine. If 0 is passed, free from libc will be used. Returns: Always returns PNG_NO_ERROR. */ int png_init(png_alloc_t pngalloc, png_free_t pngfree); /* Function: png_open_file This function is used to open a png file with the internal file IO system. This function should be used instead of png_open if no custom read function is used. Parameters: png - Empty png_t struct. filename - Filename of the file to be opened. Returns: PNG_NO_ERROR on success, otherwise an error code. */ int png_open_file(png_t *png, const char* filename); int png_open_file_read(png_t *png, const char* filename); int png_open_file_write(png_t *png, const char* filename); /* Function: png_open This function reads or writes a png from/to the specified callback. The callbacks should be of the format: > unsigned long (*png_write_callback_t)(void* input, unsigned long size, unsigned long numel, void* user_pointer); > unsigned long (*png_read_callback_t)(void* output, unsigned long size, unsigned long numel, void* user_pointer). Only one callback has to be specified. The read callback in case of PNG reading, otherwise the write callback. Writing: The callback will be called like fwrite. Reading: The callback will be called each time pnglite needs more data. The callback should read as much data as requested, or return 0. This should always be possible if the PNG is sane. If the output-buffer is a null-pointer the callback should only skip ahead the specified number of elements. If the callback is a null-pointer the user_pointer will be treated as a file pointer (use png_open_file instead). Parameters: png - png_t struct read_fun - Callback function for reading. user_pointer - User pointer to be passed to read_fun. Returns: PNG_NO_ERROR on success, otherwise an error code. */ int png_open(png_t* png, png_read_callback_t read_fun, void* user_pointer); int png_open_read(png_t* png, png_read_callback_t read_fun, void* user_pointer); int png_open_write(png_t* png, png_write_callback_t write_fun, void* user_pointer); /* Function: png_print_info This function prints some info about the opened png file to stdout. Parameters: png - png struct to get info from. */ void png_print_info(png_t* png); /* Function: png_error_string This function translates an error code to a human readable string. Parameters: error - Error code. Returns: Pointer to string. */ char* png_error_string(int error); /* Function: png_get_data This function decodes the opened png file and stores the result in data. data should be big enough to hold the decoded png. Required size will be: > width*height*(bytes per pixel) Parameters: data - Where to store result. Returns: PNG_NO_ERROR on success, otherwise an error code. */ int png_get_data(png_t* png, unsigned char* data); int png_set_data(png_t* png, unsigned width, unsigned height, char depth, int color, unsigned char* data); /* Function: png_close_file Closes an open png file pointer. Should only be used when the png has been opened with png_open_file. Parameters: png - png to close. Returns: PNG_NO_ERROR */ int png_close_file(png_t* png); #ifdef __cplusplus } #endif #endif ================================================ FILE: src/engine/external/wavpack/VERSION ================================================ 4.40 ================================================ FILE: src/engine/external/wavpack/arm.S ================================================ //////////////////////////////////////////////////////////////////////////// // **** WAVPACK **** // // Hybrid Lossless Wavefile Compressor // // Copyright (c) 1998 - 2006 Conifer Software. // // All Rights Reserved. // // Distributed under the BSD Software License (see license.txt) // //////////////////////////////////////////////////////////////////////////// /* This is an assembly optimized version of the following WavPack function: * * void decorr_stereo_pass_cont (struct decorr_pass *dpp, * long *buffer, long sample_count); * * It performs a single pass of stereo decorrelation on the provided buffer. * Note that this version of the function requires that the 8 previous stereo * samples are visible and correct. In other words, it ignores the "samples_*" * fields in the decorr_pass structure and gets the history data directly * from the buffer. It does, however, return the appropriate history samples * to the decorr_pass structure before returning. * * This is written to work on a ARM7TDMI processor. This version only uses the * 32-bit multiply-accumulate instruction and so will overflow with 24-bit * WavPack files. */ .text .align .global decorr_stereo_pass_cont_arm /* * on entry: * * r0 = struct decorr_pass *dpp * r1 = long *buffer * r2 = long sample_count */ decorr_stereo_pass_cont_arm: stmfd sp!, {r4 - r8, r10, r11, lr} mov r5, r0 @ r5 = dpp mov r11, #512 @ r11 = 512 for rounding ldrsh r6, [r0, #2] @ r6 = dpp->delta ldrsh r4, [r0, #4] @ r4 = dpp->weight_A ldrsh r0, [r0, #6] @ r0 = dpp->weight_B cmp r2, #0 @ exit if no samples to process beq common_exit add r7, r1, r2, asl #3 @ r7 = buffer ending position ldrsh r2, [r5, #0] @ r2 = dpp->term cmp r2, #0 bmi minus_term ldr lr, [r1, #-16] @ load 2 sample history from buffer ldr r10, [r1, #-12] @ for terms 2, 17, and 18 ldr r8, [r1, #-8] ldr r3, [r1, #-4] cmp r2, #17 beq term_17_loop cmp r2, #18 beq term_18_loop cmp r2, #2 beq term_2_loop b term_default_loop @ else handle default (1-8, except 2) minus_term: mov r10, #1024 @ r10 = -1024 for weight clipping rsb r10, r10, #0 @ (only used for negative terms) cmn r2, #1 beq term_minus_1 cmn r2, #2 beq term_minus_2 cmn r2, #3 beq term_minus_3 b common_exit /* ****************************************************************************** * Loop to handle term = 17 condition * * r0 = dpp->weight_B r8 = previous left sample * r1 = bptr r9 = * r2 = current sample r10 = second previous left sample * r3 = previous right sample r11 = 512 (for rounding) * r4 = dpp->weight_A ip = current decorrelation value * r5 = dpp sp = * r6 = dpp->delta lr = second previous right sample * r7 = eptr pc = ******************************************************************************* */ term_17_loop: rsbs ip, lr, r8, asl #1 @ decorr value = (2 * prev) - 2nd prev mov lr, r8 @ previous becomes 2nd previous ldr r2, [r1], #4 @ get sample & update pointer mla r8, ip, r4, r11 @ mult decorr value by weight, round, add r8, r2, r8, asr #10 @ shift, and add to new sample strne r8, [r1, #-4] @ if change possible, store sample back cmpne r2, #0 beq .L325 teq ip, r2 @ update weight based on signs submi r4, r4, r6 addpl r4, r4, r6 .L325: rsbs ip, r10, r3, asl #1 @ do same thing for right channel mov r10, r3 ldr r2, [r1], #4 mla r3, ip, r0, r11 add r3, r2, r3, asr #10 strne r3, [r1, #-4] cmpne r2, #0 beq .L329 teq ip, r2 submi r0, r0, r6 addpl r0, r0, r6 .L329: cmp r7, r1 @ loop back if more samples to do bhi term_17_loop b store_1718 @ common exit for terms 17 & 18 /* ****************************************************************************** * Loop to handle term = 18 condition * * r0 = dpp->weight_B r8 = previous left sample * r1 = bptr r9 = * r2 = current sample r10 = second previous left sample * r3 = previous right sample r11 = 512 (for rounding) * r4 = dpp->weight_A ip = decorrelation value * r5 = dpp sp = * r6 = dpp->delta lr = second previous right sample * r7 = eptr pc = ******************************************************************************* */ term_18_loop: sub ip, r8, lr @ decorr value = mov lr, r8 @ ((3 * prev) - 2nd prev) >> 1 adds ip, r8, ip, asr #1 ldr r2, [r1], #4 @ get sample & update pointer mla r8, ip, r4, r11 @ mult decorr value by weight, round, add r8, r2, r8, asr #10 @ shift, and add to new sample strne r8, [r1, #-4] @ if change possible, store sample back cmpne r2, #0 beq .L337 teq ip, r2 @ update weight based on signs submi r4, r4, r6 addpl r4, r4, r6 .L337: sub ip, r3, r10 @ do same thing for right channel mov r10, r3 adds ip, r3, ip, asr #1 ldr r2, [r1], #4 mla r3, ip, r0, r11 add r3, r2, r3, asr #10 strne r3, [r1, #-4] cmpne r2, #0 beq .L341 teq ip, r2 submi r0, r0, r6 addpl r0, r0, r6 .L341: cmp r7, r1 @ loop back if more samples to do bhi term_18_loop /* common exit for terms 17 & 18 */ store_1718: str r3, [r5, #40] @ store sample history into struct str r8, [r5, #8] str r10, [r5, #44] str lr, [r5, #12] b common_exit @ and return /* ****************************************************************************** * Loop to handle term = 2 condition * (note that this case can be handled by the default term handler (1-8), but * this special case is faster because it doesn't have to read memory twice) * * r0 = dpp->weight_B r8 = previous left sample * r1 = bptr r9 = * r2 = current sample r10 = second previous left sample * r3 = previous right sample r11 = 512 (for rounding) * r4 = dpp->weight_A ip = decorrelation value * r5 = dpp sp = * r6 = dpp->delta lr = second previous right sample * r7 = eptr pc = ******************************************************************************* */ term_2_loop: movs ip, lr @ get decorrelation value & test mov lr, r8 @ previous becomes 2nd previous ldr r2, [r1], #4 @ get sample & update pointer mla r8, ip, r4, r11 @ mult decorr value by weight, round, add r8, r2, r8, asr #10 @ shift, and add to new sample strne r8, [r1, #-4] @ if change possible, store sample back cmpne r2, #0 beq .L225 teq ip, r2 @ update weight based on signs submi r4, r4, r6 addpl r4, r4, r6 .L225: movs ip, r10 @ do same thing for right channel mov r10, r3 ldr r2, [r1], #4 mla r3, ip, r0, r11 add r3, r2, r3, asr #10 strne r3, [r1, #-4] cmpne r2, #0 beq .L229 teq ip, r2 submi r0, r0, r6 addpl r0, r0, r6 .L229: cmp r7, r1 @ loop back if more samples to do bhi term_2_loop b default_term_exit @ this exit updates all dpp->samples /* ****************************************************************************** * Loop to handle default term condition * * r0 = dpp->weight_B r8 = result accumulator * r1 = bptr r9 = * r2 = dpp->term r10 = * r3 = decorrelation value r11 = 512 (for rounding) * r4 = dpp->weight_A ip = current sample * r5 = dpp sp = * r6 = dpp->delta lr = * r7 = eptr pc = ******************************************************************************* */ term_default_loop: ldr ip, [r1] @ get original sample ldr r3, [r1, -r2, asl #3] @ get decorrelation value based on term mla r8, r3, r4, r11 @ mult decorr value by weight, round, add r8, ip, r8, asr #10 @ shift and add to new sample str r8, [r1], #4 @ store update sample cmp r3, #0 cmpne ip, #0 beq .L350 teq ip, r3 @ update weight based on signs submi r4, r4, r6 addpl r4, r4, r6 .L350: ldr ip, [r1] @ do the same thing for right channel ldr r3, [r1, -r2, asl #3] mla r8, r3, r0, r11 add r8, ip, r8, asr #10 str r8, [r1], #4 cmp r3, #0 cmpne ip, #0 beq .L354 teq ip, r3 submi r0, r0, r6 addpl r0, r0, r6 .L354: cmp r7, r1 @ loop back if more samples to do bhi term_default_loop /* * This exit is used by terms 1-8 to store the previous 8 samples into the decorr * structure (even if they are not all used for the given term) */ default_term_exit: ldrsh r3, [r5, #0] sub ip, r3, #1 mov lr, #7 .L358: and r3, ip, #7 add r3, r5, r3, asl #2 ldr r2, [r1, #-4] str r2, [r3, #40] ldr r2, [r1, #-8]! str r2, [r3, #8] sub ip, ip, #1 sub lr, lr, #1 cmn lr, #1 bne .L358 b common_exit /* ****************************************************************************** * Loop to handle term = -1 condition * * r0 = dpp->weight_B r8 = * r1 = bptr r9 = * r2 = intermediate result r10 = -1024 (for clipping) * r3 = previous right sample r11 = 512 (for rounding) * r4 = dpp->weight_A ip = current sample * r5 = dpp sp = * r6 = dpp->delta lr = updated left sample * r7 = eptr pc = ******************************************************************************* */ term_minus_1: ldr r3, [r1, #-4] term_minus_1_loop: ldr ip, [r1] @ for left channel the decorrelation value mla r2, r3, r4, r11 @ is the previous right sample (in r3) add lr, ip, r2, asr #10 str lr, [r1], #8 cmp r3, #0 cmpne ip, #0 beq .L361 teq ip, r3 @ update weight based on signs submi r4, r4, r6 addpl r4, r4, r6 cmp r4, #1024 movgt r4, #1024 cmp r4, r10 movlt r4, r10 .L361: ldr r2, [r1, #-4] @ for right channel the decorrelation value mla r3, lr, r0, r11 @ is the just updated right sample (in lr) add r3, r2, r3, asr #10 str r3, [r1, #-4] cmp lr, #0 cmpne r2, #0 beq .L369 teq r2, lr submi r0, r0, r6 addpl r0, r0, r6 cmp r0, #1024 @ then clip weight to +/-1024 movgt r0, #1024 cmp r0, r10 movlt r0, r10 .L369: cmp r7, r1 @ loop back if more samples to do bhi term_minus_1_loop str r3, [r5, #8] @ else store right sample and exit b common_exit /* ****************************************************************************** * Loop to handle term = -2 condition * (note that the channels are processed in the reverse order here) * * r0 = dpp->weight_B r8 = * r1 = bptr r9 = * r2 = intermediate result r10 = -1024 (for clipping) * r3 = previous left sample r11 = 512 (for rounding) * r4 = dpp->weight_A ip = current sample * r5 = dpp sp = * r6 = dpp->delta lr = updated right sample * r7 = eptr pc = ******************************************************************************* */ term_minus_2: ldr r3, [r1, #-8] term_minus_2_loop: ldr ip, [r1, #4] @ for right channel the decorrelation value mla r2, r3, r0, r11 @ is the previous left sample (in r3) add lr, ip, r2, asr #10 str lr, [r1, #4] cmp r3, #0 cmpne ip, #0 beq .L380 teq ip, r3 @ update weight based on signs submi r0, r0, r6 addpl r0, r0, r6 cmp r0, #1024 @ then clip weight to +/-1024 movgt r0, #1024 cmp r0, r10 movlt r0, r10 .L380: ldr r2, [r1, #0] @ for left channel the decorrelation value mla r3, lr, r4, r11 @ is the just updated left sample (in lr) add r3, r2, r3, asr #10 str r3, [r1], #8 cmp lr, #0 cmpne r2, #0 beq .L388 teq r2, lr submi r4, r4, r6 addpl r4, r4, r6 cmp r4, #1024 movgt r4, #1024 cmp r4, r10 movlt r4, r10 .L388: cmp r7, r1 @ loop back if more samples to do bhi term_minus_2_loop str r3, [r5, #40] @ else store left channel and exit b common_exit /* ****************************************************************************** * Loop to handle term = -3 condition * * r0 = dpp->weight_B r8 = previous left sample * r1 = bptr r9 = * r2 = current left sample r10 = -1024 (for clipping) * r3 = previous right sample r11 = 512 (for rounding) * r4 = dpp->weight_A ip = intermediate result * r5 = dpp sp = * r6 = dpp->delta lr = * r7 = eptr pc = ******************************************************************************* */ term_minus_3: ldr r3, [r1, #-4] @ load previous samples ldr r8, [r1, #-8] term_minus_3_loop: ldr ip, [r1] mla r2, r3, r4, r11 add r2, ip, r2, asr #10 str r2, [r1], #4 cmp r3, #0 cmpne ip, #0 beq .L399 teq ip, r3 @ update weight based on signs submi r4, r4, r6 addpl r4, r4, r6 cmp r4, #1024 @ then clip weight to +/-1024 movgt r4, #1024 cmp r4, r10 movlt r4, r10 .L399: movs ip, r8 @ ip = previous left we use now mov r8, r2 @ r8 = current left we use next time ldr r2, [r1], #4 mla r3, ip, r0, r11 add r3, r2, r3, asr #10 strne r3, [r1, #-4] cmpne r2, #0 beq .L407 teq ip, r2 submi r0, r0, r6 addpl r0, r0, r6 cmp r0, #1024 movgt r0, #1024 cmp r0, r10 movlt r0, r10 .L407: cmp r7, r1 @ loop back if more samples to do bhi term_minus_3_loop str r3, [r5, #8] @ else store previous samples & exit str r8, [r5, #40] /* * Before finally exiting we must store weights back for next time */ common_exit: strh r4, [r5, #4] strh r0, [r5, #6] ldmfd sp!, {r4 - r8, r10, r11, pc} ================================================ FILE: src/engine/external/wavpack/arml.S ================================================ //////////////////////////////////////////////////////////////////////////// // **** WAVPACK **** // // Hybrid Lossless Wavefile Compressor // // Copyright (c) 1998 - 2006 Conifer Software. // // All Rights Reserved. // // Distributed under the BSD Software License (see license.txt) // //////////////////////////////////////////////////////////////////////////// /* This is an assembly optimized version of the following WavPack function: * * void decorr_stereo_pass_cont (struct decorr_pass *dpp, * long *buffer, long sample_count); * * It performs a single pass of stereo decorrelation on the provided buffer. * Note that this version of the function requires that the 8 previous stereo * samples are visible and correct. In other words, it ignores the "samples_*" * fields in the decorr_pass structure and gets the history data directly * from the buffer. It does, however, return the appropriate history samples * to the decorr_pass structure before returning. * * This is written to work on a ARM7TDMI processor. This version uses the * 64-bit multiply-accumulate instruction and so can be used with all * WavPack files. However, for optimum performance with 16-bit WavPack * files, there is a faster version that only uses the 32-bit MLA * instruction. */ .text .align .global decorr_stereo_pass_cont_arml /* * on entry: * * r0 = struct decorr_pass *dpp * r1 = long *buffer * r2 = long sample_count */ decorr_stereo_pass_cont_arml: stmfd sp!, {r4 - r8, r10, r11, lr} mov r5, r0 @ r5 = dpp mov r11, #512 @ r11 = 512 for rounding ldrsh r6, [r0, #2] @ r6 = dpp->delta ldrsh r4, [r0, #4] @ r4 = dpp->weight_A ldrsh r0, [r0, #6] @ r0 = dpp->weight_B cmp r2, #0 @ exit if no samples to process beq common_exit mov r0, r0, asl #18 @ for 64-bit math we use weights << 18 mov r4, r4, asl #18 mov r6, r6, asl #18 add r7, r1, r2, asl #3 @ r7 = buffer ending position ldrsh r2, [r5, #0] @ r2 = dpp->term cmp r2, #0 blt minus_term ldr lr, [r1, #-16] @ load 2 sample history from buffer ldr r10, [r1, #-12] @ for terms 2, 17, and 18 ldr r8, [r1, #-8] ldr r3, [r1, #-4] cmp r2, #18 beq term_18_loop mov lr, lr, asl #4 mov r10, r10, asl #4 cmp r2, #2 beq term_2_loop cmp r2, #17 beq term_17_loop b term_default_loop minus_term: mov r10, #(1024 << 18) @ r10 = -1024 << 18 for weight clipping rsb r10, r10, #0 @ (only used for negative terms) cmn r2, #1 beq term_minus_1 cmn r2, #2 beq term_minus_2 cmn r2, #3 beq term_minus_3 b common_exit /* ****************************************************************************** * Loop to handle term = 17 condition * * r0 = dpp->weight_B r8 = previous left sample * r1 = bptr r9 = * r2 = current sample r10 = second previous left sample << 4 * r3 = previous right sample r11 = lo accumulator (for rounding) * r4 = dpp->weight_A ip = current decorrelation value * r5 = dpp sp = * r6 = dpp->delta lr = second previous right sample << 4 * r7 = eptr pc = ******************************************************************************* */ term_17_loop: rsbs ip, lr, r8, asl #5 @ decorr value = (2 * prev) - 2nd prev mov lr, r8, asl #4 @ previous becomes 2nd previous ldr r2, [r1], #4 @ get sample & update pointer mov r11, #0x80000000 mov r8, r2 smlalne r11, r8, r4, ip strne r8, [r1, #-4] @ if change possible, store sample back cmpne r2, #0 beq .L325 teq ip, r2 @ update weight based on signs submi r4, r4, r6 addpl r4, r4, r6 .L325: rsbs ip, r10, r3, asl #5 @ do same thing for right channel mov r10, r3, asl #4 ldr r2, [r1], #4 mov r11, #0x80000000 mov r3, r2 smlalne r11, r3, r0, ip strne r3, [r1, #-4] cmpne r2, #0 beq .L329 teq ip, r2 submi r0, r0, r6 addpl r0, r0, r6 .L329: cmp r7, r1 @ loop back if more samples to do bhi term_17_loop mov lr, lr, asr #4 mov r10, r10, asr #4 b store_1718 @ common exit for terms 17 & 18 /* ****************************************************************************** * Loop to handle term = 18 condition * * r0 = dpp->weight_B r8 = previous left sample * r1 = bptr r9 = * r2 = current sample r10 = second previous left sample * r3 = previous right sample r11 = lo accumulator (for rounding) * r4 = dpp->weight_A ip = decorrelation value * r5 = dpp sp = * r6 = dpp->delta lr = second previous right sample * r7 = eptr pc = ******************************************************************************* */ term_18_loop: rsb ip, lr, r8 @ decorr value = mov lr, r8 @ ((3 * prev) - 2nd prev) >> 1 add ip, lr, ip, asr #1 movs ip, ip, asl #4 ldr r2, [r1], #4 @ get sample & update pointer mov r11, #0x80000000 mov r8, r2 smlalne r11, r8, r4, ip strne r8, [r1, #-4] @ if change possible, store sample back cmpne r2, #0 beq .L337 teq ip, r2 @ update weight based on signs submi r4, r4, r6 addpl r4, r4, r6 .L337: rsb ip, r10, r3 @ do same thing for right channel mov r10, r3 add ip, r10, ip, asr #1 movs ip, ip, asl #4 ldr r2, [r1], #4 mov r11, #0x80000000 mov r3, r2 smlalne r11, r3, r0, ip strne r3, [r1, #-4] cmpne r2, #0 beq .L341 teq ip, r2 submi r0, r0, r6 addpl r0, r0, r6 .L341: cmp r7, r1 @ loop back if more samples to do bhi term_18_loop /* common exit for terms 17 & 18 */ store_1718: str r3, [r5, #40] @ store sample history into struct str r8, [r5, #8] str r10, [r5, #44] str lr, [r5, #12] b common_exit @ and return /* ****************************************************************************** * Loop to handle term = 2 condition * (note that this case can be handled by the default term handler (1-8), but * this special case is faster because it doesn't have to read memory twice) * * r0 = dpp->weight_B r8 = previous left sample * r1 = bptr r9 = * r2 = current sample r10 = second previous left sample << 4 * r3 = previous right sample r11 = lo accumulator (for rounding) * r4 = dpp->weight_A ip = decorrelation value * r5 = dpp sp = * r6 = dpp->delta lr = second previous right sample << 4 * r7 = eptr pc = ******************************************************************************* */ term_2_loop: movs ip, lr @ get decorrelation value & test ldr r2, [r1], #4 @ get sample & update pointer mov lr, r8, asl #4 @ previous becomes 2nd previous mov r11, #0x80000000 mov r8, r2 smlalne r11, r8, r4, ip strne r8, [r1, #-4] @ if change possible, store sample back cmpne r2, #0 beq .L225 teq ip, r2 @ update weight based on signs submi r4, r4, r6 addpl r4, r4, r6 .L225: movs ip, r10 @ do same thing for right channel ldr r2, [r1], #4 mov r10, r3, asl #4 mov r11, #0x80000000 mov r3, r2 smlalne r11, r3, r0, ip strne r3, [r1, #-4] cmpne r2, #0 beq .L229 teq ip, r2 submi r0, r0, r6 addpl r0, r0, r6 .L229: cmp r7, r1 @ loop back if more samples to do bhi term_2_loop b default_term_exit @ this exit updates all dpp->samples /* ****************************************************************************** * Loop to handle default term condition * * r0 = dpp->weight_B r8 = result accumulator * r1 = bptr r9 = * r2 = dpp->term r10 = * r3 = decorrelation value r11 = lo accumulator (for rounding) * r4 = dpp->weight_A ip = current sample * r5 = dpp sp = * r6 = dpp->delta lr = * r7 = eptr pc = ******************************************************************************* */ term_default_loop: ldr r3, [r1, -r2, asl #3] @ get decorrelation value based on term ldr ip, [r1], #4 @ get original sample and bump ptr movs r3, r3, asl #4 mov r11, #0x80000000 mov r8, ip smlalne r11, r8, r4, r3 strne r8, [r1, #-4] @ if possibly changed, store updated sample cmpne ip, #0 beq .L350 teq ip, r3 @ update weight based on signs submi r4, r4, r6 addpl r4, r4, r6 .L350: ldr r3, [r1, -r2, asl #3] @ do the same thing for right channel ldr ip, [r1], #4 movs r3, r3, asl #4 mov r11, #0x80000000 mov r8, ip smlalne r11, r8, r0, r3 strne r8, [r1, #-4] cmpne ip, #0 beq .L354 teq ip, r3 submi r0, r0, r6 addpl r0, r0, r6 .L354: cmp r7, r1 @ loop back if more samples to do bhi term_default_loop /* * This exit is used by terms 1-8 to store the previous 8 samples into the decorr * structure (even if they are not all used for the given term) */ default_term_exit: ldrsh r3, [r5, #0] sub ip, r3, #1 mov lr, #7 .L358: and r3, ip, #7 add r3, r5, r3, asl #2 ldr r2, [r1, #-4] str r2, [r3, #40] ldr r2, [r1, #-8]! str r2, [r3, #8] sub ip, ip, #1 sub lr, lr, #1 cmn lr, #1 bne .L358 b common_exit /* ****************************************************************************** * Loop to handle term = -1 condition * * r0 = dpp->weight_B r8 = * r1 = bptr r9 = * r2 = intermediate result r10 = -1024 (for clipping) * r3 = previous right sample r11 = lo accumulator (for rounding) * r4 = dpp->weight_A ip = current sample * r5 = dpp sp = * r6 = dpp->delta lr = updated left sample * r7 = eptr pc = ******************************************************************************* */ term_minus_1: ldr r3, [r1, #-4] term_minus_1_loop: ldr ip, [r1], #8 @ for left channel the decorrelation value movs r3, r3, asl #4 @ is the previous right sample (in r3) mov r11, #0x80000000 mov lr, ip smlalne r11, lr, r4, r3 strne lr, [r1, #-8] cmpne ip, #0 beq .L361 teq ip, r3 @ update weight based on signs submi r4, r4, r6 addpl r4, r4, r6 cmp r4, #(1024 << 18) movgt r4, #(1024 << 18) cmp r4, r10 movlt r4, r10 .L361: ldr r2, [r1, #-4] @ for right channel the decorrelation value movs lr, lr, asl #4 mov r11, #0x80000000 mov r3, r2 smlalne r11, r3, r0, lr strne r3, [r1, #-4] cmpne r2, #0 beq .L369 teq r2, lr submi r0, r0, r6 addpl r0, r0, r6 cmp r0, #(1024 << 18) @ then clip weight to +/-1024 movgt r0, #(1024 << 18) cmp r0, r10 movlt r0, r10 .L369: cmp r7, r1 @ loop back if more samples to do bhi term_minus_1_loop str r3, [r5, #8] @ else store right sample and exit b common_exit /* ****************************************************************************** * Loop to handle term = -2 condition * (note that the channels are processed in the reverse order here) * * r0 = dpp->weight_B r8 = * r1 = bptr r9 = * r2 = intermediate result r10 = -1024 (for clipping) * r3 = previous left sample r11 = lo accumulator (for rounding) * r4 = dpp->weight_A ip = current sample * r5 = dpp sp = * r6 = dpp->delta lr = updated right sample * r7 = eptr pc = ******************************************************************************* */ term_minus_2: ldr r3, [r1, #-8] term_minus_2_loop: ldr ip, [r1, #4] @ for right channel the decorrelation value movs r3, r3, asl #4 @ is the previous left sample (in r3) mov r11, #0x80000000 mov lr, ip smlalne r11, lr, r0, r3 strne lr, [r1, #4] cmpne ip, #0 beq .L380 teq ip, r3 @ update weight based on signs submi r0, r0, r6 addpl r0, r0, r6 cmp r0, #(1024 << 18) @ then clip weight to +/-1024 movgt r0, #(1024 << 18) cmp r0, r10 movlt r0, r10 .L380: ldr r2, [r1], #8 @ for left channel the decorrelation value movs lr, lr, asl #4 mov r11, #0x80000000 mov r3, r2 smlalne r11, r3, r4, lr strne r3, [r1, #-8] cmpne r2, #0 beq .L388 teq r2, lr submi r4, r4, r6 addpl r4, r4, r6 cmp r4, #(1024 << 18) movgt r4, #(1024 << 18) cmp r4, r10 movlt r4, r10 .L388: cmp r7, r1 @ loop back if more samples to do bhi term_minus_2_loop str r3, [r5, #40] @ else store left channel and exit b common_exit /* ****************************************************************************** * Loop to handle term = -3 condition * * r0 = dpp->weight_B r8 = previous left sample * r1 = bptr r9 = * r2 = current left sample r10 = -1024 (for clipping) * r3 = previous right sample r11 = lo accumulator (for rounding) * r4 = dpp->weight_A ip = intermediate result * r5 = dpp sp = * r6 = dpp->delta lr = * r7 = eptr pc = ******************************************************************************* */ term_minus_3: ldr r3, [r1, #-4] @ load previous samples ldr r8, [r1, #-8] term_minus_3_loop: ldr ip, [r1], #4 movs r3, r3, asl #4 mov r11, #0x80000000 mov r2, ip smlalne r11, r2, r4, r3 strne r2, [r1, #-4] cmpne ip, #0 beq .L399 teq ip, r3 @ update weight based on signs submi r4, r4, r6 addpl r4, r4, r6 cmp r4, #(1024 << 18) @ then clip weight to +/-1024 movgt r4, #(1024 << 18) cmp r4, r10 movlt r4, r10 .L399: movs ip, r8, asl #4 @ ip = previous left we use now mov r8, r2 @ r8 = current left we use next time ldr r2, [r1], #4 mov r11, #0x80000000 mov r3, r2 smlalne r11, r3, r0, ip strne r3, [r1, #-4] cmpne r2, #0 beq .L407 teq ip, r2 submi r0, r0, r6 addpl r0, r0, r6 cmp r0, #(1024 << 18) movgt r0, #(1024 << 18) cmp r0, r10 movlt r0, r10 .L407: cmp r7, r1 @ loop back if more samples to do bhi term_minus_3_loop str r3, [r5, #8] @ else store previous samples & exit str r8, [r5, #40] /* * Before finally exiting we must store weights back for next time */ common_exit: mov r0, r0, asr #18 @ restore weights to real magnitude mov r4, r4, asr #18 strh r4, [r5, #4] strh r0, [r5, #6] ldmfd sp!, {r4 - r8, r10, r11, pc} ================================================ FILE: src/engine/external/wavpack/bits.c ================================================ //////////////////////////////////////////////////////////////////////////// // **** WAVPACK **** // // Hybrid Lossless Wavefile Compressor // // Copyright (c) 1998 - 2006 Conifer Software. // // All Rights Reserved. // // Distributed under the BSD Software License (see license.txt) // //////////////////////////////////////////////////////////////////////////// // bits.c // This module provides utilities to support the BitStream structure which is // used to read and write all WavPack audio data streams. It also contains a // wrapper for the stream I/O functions and a set of functions dealing with // endian-ness, both for enhancing portability. Finally, a debug wrapper for // the malloc() system is provided. #include "wavpack.h" #include <string.h> #include <ctype.h> ////////////////////////// Bitstream functions //////////////////////////////// // Open the specified BitStream and associate with the specified buffer. static void bs_read (Bitstream *bs); void bs_open_read (Bitstream *bs, uchar *buffer_start, uchar *buffer_end, read_stream file, uint32_t file_bytes) { CLEAR (*bs); bs->buf = buffer_start; bs->end = buffer_end; if (file) { bs->ptr = bs->end - 1; bs->file_bytes = file_bytes; bs->file = file; } else bs->ptr = bs->buf - 1; bs->wrap = bs_read; } // This function is only called from the getbit() and getbits() macros when // the BitStream has been exhausted and more data is required. Sinve these // bistreams no longer access files, this function simple sets an error and // resets the buffer. static void bs_read (Bitstream *bs) { if (bs->file && bs->file_bytes) { uint32_t bytes_read, bytes_to_read = bs->end - bs->buf; if (bytes_to_read > bs->file_bytes) bytes_to_read = bs->file_bytes; bytes_read = bs->file (bs->buf, bytes_to_read); if (bytes_read) { bs->end = bs->buf + bytes_read; bs->file_bytes -= bytes_read; } else { memset (bs->buf, -1, bs->end - bs->buf); bs->error = 1; } } else bs->error = 1; if (bs->error) memset (bs->buf, -1, bs->end - bs->buf); bs->ptr = bs->buf; } /////////////////////// Endian Correction Routines //////////////////////////// void little_endian_to_native (void *data, char *format) { uchar *cp = (uchar *) data; int32_t temp; while (*format) { switch (*format) { case 'L': temp = cp [0] + ((int32_t) cp [1] << 8) + ((int32_t) cp [2] << 16) + ((int32_t) cp [3] << 24); * (int32_t *) cp = temp; cp += 4; break; case 'S': temp = cp [0] + (cp [1] << 8); * (short *) cp = (short) temp; cp += 2; break; default: if (isdigit (*format)) cp += *format - '0'; break; } format++; } } void native_to_little_endian (void *data, char *format) { uchar *cp = (uchar *) data; int32_t temp; while (*format) { switch (*format) { case 'L': temp = * (int32_t *) cp; *cp++ = (uchar) temp; *cp++ = (uchar) (temp >> 8); *cp++ = (uchar) (temp >> 16); *cp++ = (uchar) (temp >> 24); break; case 'S': temp = * (short *) cp; *cp++ = (uchar) temp; *cp++ = (uchar) (temp >> 8); break; default: if (isdigit (*format)) cp += *format - '0'; break; } format++; } } ================================================ FILE: src/engine/external/wavpack/coldfire.S ================================================ //////////////////////////////////////////////////////////////////////////// // **** WAVPACK **** // // Hybrid Lossless Wavefile Compressor // // Copyright (c) 1998 - 2006 Conifer Software. // // All Rights Reserved. // // Distributed under the BSD Software License (see license.txt) // //////////////////////////////////////////////////////////////////////////// /* This is an assembly optimized version of the following WavPack function: * * void decorr_stereo_pass_cont (struct decorr_pass *dpp, * long *buffer, long sample_count); * * It performs a single pass of stereo decorrelation on the provided buffer. * Note that this version of the function requires that the 8 previous stereo * samples are visible and correct. In other words, it ignores the "samples_*" * fields in the decorr_pass structure and gets the history data directly * from the buffer. It does, however, return the appropriate history samples * to the decorr_pass structure before returning. * * This is written to work on a MCF5249 processor, or any processor based on * the ColdFire V2 core with an EMAC unit. The EMAC is perfectly suited for * the "apply_weight" function of WavPack decorrelation because it provides * the requires 40-bit product. The fractional rounding mode of the EMAC is not * configurable and uses "round to even" while WavPack uses "round to larger", * so the rounding has to be done manually. */ .text .align 2 .global decorr_stereo_pass_cont_mcf5249 decorr_stereo_pass_cont_mcf5249: lea (-44, %sp), %sp movem.l %d2-%d7/%a2-%a6, (%sp) move.l 44+4(%sp), %a2 | a2 = dpp-> move.l 44+8(%sp), %a1 | a1 = bptr move.w 2(%a2), %a3 | a3 = dpp->delta move.w 4(%a2), %d3 | d3 = dpp->weight_A (sign extended) ext.l %d3 move.w 6(%a2), %d4 | d4 = dpp->weight_B (sign extended) ext.l %d4 move.l 44+12(%sp), %d0 | d0 = sample_count jbeq return_only | if zero, nothing to do lsl.l #3, %d0 | d5 = bptr + (sample_count * 8) move.l %d0, %d5 add.l %a1, %d5 moveq.l #17, %d0 | left shift weights & delta 17 places asl.l %d0, %d3 asl.l %d0, %d4 move.l %a3, %d1 asl.l %d0, %d1 move.l %d1, %a3 moveq.l #0x20, %d6 move.l %d6, %macsr | set fractional mode for MAC move.l #0, %acc1 | acc1 = 0x00 0000 80 (for rounding) move.l #0x800000, %accext01 move.l #1024<<17, %d6 | d6 & d7 are weight clipping limits move.l #-1024<<17, %d7 | (only used by negative terms) move.w (%a2), %d0 | d0 = term ext.l %d0 cmp.l #17, %d0 jbeq term_17 | term = 17 cmp.l #18, %d0 jbeq term_18 | term = 18 addq.l #1, %d0 jbeq term_minus_1 | term = -1 addq.l #1, %d0 jbeq term_minus_2 | term = -2 addq.l #1, %d0 jbeq term_minus_3 | term = -3 jbra term_default | default term = 1 - 8 |------------------------------------------------------------------------------ | Loop to handle term = 17 condition | | a0 = d0 = (2 * bptr [-1]) - bptr [-2] | a1 = bptr d1 = initial bptr [0] | a2 = dpp-> d2 = updated bptr [0] | a3 = dpp->delta << 17 d3 = dpp->weight_A << 17 | a4 = d4 = dpp->weight_B << 17 | a5 = d5 = eptr | macsr = 0x20 acc1 = 0x00 0000 80 |------------------------------------------------------------------------------ term_17: move.l -8(%a1), %d0 | d0 = 2 * bptr [-1] - bptr [-2] add.l %d0, %d0 sub.l -16(%a1), %d0 beq .L251 | if zero, skip calculation move.l %acc1, %acc0 asl.l #4, %d0 | acc0 = acc1 + (d0 << 4) * weight_A mac.l %d0, %d3, %acc0 move.l (%a1), %d1 beq .L255 eor.l %d1, %d0 | else compare signs bge .L256 | if same, add delta to weight sub.l %a3, %d3 | else subtract delta from weight sub.l %a3, %d3 | subtract again instead of branch .L256: add.l %a3, %d3 | add delta to weight .L255: move.l %acc0, %d2 | d2 = rounded product add.l %d1, %d2 | update bptr [0] and store move.l %d2, (%a1)+ .L253: move.l -8(%a1), %d0 | d0 = 2 * bptr [-1] - bptr [-2] add.l %d0, %d0 sub.l -16(%a1), %d0 beq .L257 | if zero, skip calculations move.l %acc1, %acc0 asl.l #4, %d0 | acc0 = acc1 + (d0 << 4) * weight_B mac.l %d0, %d4, %acc0 move.l (%a1), %d1 beq .L254 eor.l %d1, %d0 | else compare signs bge .L259 | if same, add delta to weight sub.l %a3, %d4 | else subtract delta from weight sub.l %a3, %d4 | subtract again instead of branch .L259: add.l %a3, %d4 | add delta to weight .L254: move.l %acc0, %d2 | d2 = rounded product add.l %d1, %d2 | update bptr [0] and store move.l %d2, (%a1)+ .L252: cmp.l %a1, %d5 | loop if bptr < eptr jbhi term_17 bra term_17_18_finish | exit through common path .L251: addq.l #4, %a1 | update point and jump back into loop bra .L253 .L257: addq.l #4, %a1 | update point and jump back into loop bra .L252 |------------------------------------------------------------------------------ | Loop to handle term = 18 condition | | a0 = d0 = ((3 * bptr [-1]) - bptr [-2]) >> 1 | a1 = bptr d1 = initial bptr [0] | a2 = dpp-> d2 = updated bptr [0] | a3 = dpp->delta << 17 d3 = dpp->weight_A << 17 | a4 = d4 = dpp->weight_B << 17 | a5 = d5 = eptr | macsr = 0x20 acc1 = 0x00 0000 80 |------------------------------------------------------------------------------ term_18: move.l -8(%a1), %a0 | d0 = (3 * bptr [-1] - bptr [-2]) >> 1 lea (%a0,%a0.l*2), %a0 move.l %a0, %d0 sub.l -16(%a1), %d0 asr.l #1, %d0 beq .L260 move.l %acc1, %acc0 asl.l #4, %d0 | acc0 = acc1 + (d0 << 4) * weight_A mac.l %d0, %d3, %acc0 move.l (%a1), %d1 beq .L266 eor.l %d1, %d0 | else compare signs bge .L267 | if same, add delta to weight sub.l %a3, %d3 | else subtract delta from weight sub.l %a3, %d3 | subtract again instead of branch .L267: add.l %a3, %d3 | add delta to weight .L266: move.l %acc0, %d2 | d2 = rounded product add.l %d1, %d2 | add applied weight to bptr [0], store move.l %d2, (%a1)+ .L268: move.l -8(%a1), %a0 | d0 = (3 * bptr [-1] - bptr [-2]) >> 1 lea (%a0,%a0.l*2), %a0 move.l %a0, %d0 sub.l -16(%a1), %d0 asr.l #1, %d0 beq .L261 move.l %acc1, %acc0 asl.l #4, %d0 | acc0 = acc1 + (d0 << 4) * weight_B mac.l %d0, %d4, %acc0 move.l (%a1), %d1 beq .L265 eor.l %d1, %d0 | else compare signs bge .L270 | if same, add delta to weight sub.l %a3, %d4 | else subtract delta from weight sub.l %a3, %d4 | subtract again instead of branch .L270: add.l %a3, %d4 | add delta to weight .L265: move.l %acc0, %d2 | d2 = rounded product add.l %d1, %d2 | add applied weight to bptr [0], store move.l %d2, (%a1)+ .L269: cmp.l %a1, %d5 | loop if bptr < eptr jbhi term_18 bra term_17_18_finish | exit through common path .L260: addq.l #4, %a1 | bump pointer and jump back into loop bra .L268 .L261: addq.l #4, %a1 | bump pointer and jump back into loop bra .L269 term_17_18_finish: move.l -4(%a1), 40(%a2) | restore dpp->samples_A [0-1], B [0-1] move.l -8(%a1), 8(%a2) move.l -12(%a1), 44(%a2) move.l -16(%a1), 12(%a2) jbra finish_up |------------------------------------------------------------------------------ | Loop to handle default terms (i.e. 1 - 8) | | a0 = tptr d0 = tptr [0] | a1 = bptr d1 = initial bptr [0] | a2 = dpp-> d2 = updated bptr [0] | a3 = dpp->delta << 17 d3 = dpp->weight_A << 17 | a4 = d4 = dpp->weight_B << 17 | a5 = d5 = eptr | macsr = 0x20 acc1 = 0x00 0000 80 |------------------------------------------------------------------------------ term_default: move.w (%a2), %d0 | a0 = a1 - (dpp->term * 8) ext.l %d0 lsl.l #3, %d0 move.l %a1, %a0 sub.l %d0, %a0 term_default_loop: move.l (%a0)+, %d0 | d0 = tptr [0], skip ahead if zero beq .L271 move.l %acc1, %acc0 asl.l #4, %d0 | acc0 = acc1 + (d0 << 4) * weight_A mac.l %d0, %d3, %acc0 move.l (%a1), %d1 beq .L277 eor.l %d1, %d0 | else compare signs bge .L278 | if same, add delta to weight sub.l %a3, %d3 | else subtract delta from weight sub.l %a3, %d3 | subtract again instead of branch .L278: add.l %a3, %d3 | add delta to weight .L277: move.l %acc0, %d2 | d2 = rounded product add.l %d1, %d2 | add applied weight to bptr [0], store move.l %d2, (%a1)+ .L275: move.l (%a0)+, %d0 | d0 = tptr [0], skip ahead if zero beq .L272 move.l %acc1, %acc0 asl.l #4, %d0 | acc0 = acc1 + (d0 << 4) * weight_B mac.l %d0, %d4, %acc0 move.l (%a1), %d1 beq .L276 eor.l %d1, %d0 | else compare signs bge .L281 | if same, add delta to weight sub.l %a3, %d4 | else subtract delta from weight sub.l %a3, %d4 | subtract again instead of branch .L281: add.l %a3, %d4 | add delta to weight .L276: move.l %acc0, %d2 | d2 = rounded product add.l %d1, %d2 | add applied weight to bptr [0], store move.l %d2, (%a1)+ .L274: cmp.l %a1, %d5 | loop back if bptr < eptr jbhi term_default_loop move.w (%a2), %d0 | d0 = term - 1 moveq.l #8, %d1 | d1 = loop counter .L323: subq.l #1, %d0 | back up & mask index and.l #7, %d0 move.l -(%a1), 40(%a2,%d0.l*4) | store dpp->samples_B [d0] move.l -(%a1), 8(%a2,%d0.l*4) | store dpp->samples_A [d0] subq.l #1, %d1 | loop on count jbne .L323 jbra finish_up .L271: addq.l #4, %a1 | bump pointer and jump back into loop bra .L275 .L272: addq.l #4, %a1 | bump pointer and jump back into loop bra .L274 |------------------------------------------------------------------------------ | Loop to handle term = -1 condition | | a0 = d0 = decorrelation sample | a1 = bptr d1 = initial bptr [0] | a2 = dpp-> d2 = updated bptr [0] | a3 = dpp->delta << 17 d3 = dpp->weight_A << 17 | a4 = d4 = dpp->weight_B << 17 | a5 = d5 = eptr | a6 = d6 = 1024 << 17 | a7 = d7 = -1024 << 17 | macsr = 0x20 acc1 = 0x00 0000 80 |------------------------------------------------------------------------------ term_minus_1: move.l -4(%a1), %d0 | d0 = bptr [-1] beq .L402 move.l %acc1, %acc0 asl.l #4, %d0 | acc0 = acc1 + ((d0 << 4) * weight_A) mac.l %d0, %d3, %acc0 move.l (%a1), %d1 beq .L405 eor.l %d1, %d0 | else compare signs bge .L404 | if same, add delta to weight sub.l %a3, %d3 | else subtract delta from weight cmp.l %d7, %d3 | check for negative clip limit bge .L405 move.l %d7, %d3 bra .L405 .L404: add.l %a3, %d3 | add delta to weight cmp.l %d6, %d3 | check for positive clip limit ble .L405 move.l %d6, %d3 .L405: move.l %acc0, %d0 | d2 = rounded product add.l %d1, %d0 | add applied weight to bptr [0], store move.l %d0, (%a1)+ beq .L401 .L410: move.l %acc1, %acc0 asl.l #4, %d0 | acc0 = acc1 + ((d0 << 4) * weight_B) mac.l %d0, %d4, %acc0 move.l (%a1), %d1 beq .L403 eor.l %d1, %d0 | else compare signs bge .L407 | if same, add delta to weight sub.l %a3, %d4 | else subtract delta from weight cmp.l %d7, %d4 | check for negative clip limit bge .L403 move.l %d7, %d4 bra .L403 .L407: add.l %a3, %d4 | add delta to weight cmp.l %d6, %d4 | check for positive clip limit ble .L403 move.l %d6, %d4 .L403: move.l %acc0, %d2 | d2 = rounded product add.l %d1, %d2 | add applied weight to bptr [1], store move.l %d2, (%a1)+ .L411: cmp.l %a1, %d5 | loop back if bptr < eptr jbhi term_minus_1 move.l -4(%a1), 8(%a2) | dpp->samples_A [0] = bptr [-1] jbra finish_up .L402: move.l (%a1)+, %d0 bne .L410 .L401: addq.l #4, %a1 bra .L411 |------------------------------------------------------------------------------ | Loop to handle term = -2 condition | | a0 = d0 = decorrelation sample | a1 = bptr d1 = initial bptr [0] | a2 = dpp-> d2 = updated bptr [0] | a3 = dpp->delta << 17 d3 = dpp->weight_A << 17 | a4 = d4 = dpp->weight_B << 17 | a5 = d5 = eptr | a6 = d6 = 1024 << 17 | a7 = d7 = -1024 << 17 | macsr = 0x20 acc1 = 0x00 0000 80 |------------------------------------------------------------------------------ term_minus_2: move.l -8(%a1), %d0 | d0 = bptr [-2] beq .L511 move.l %acc1, %acc0 asl.l #4, %d0 | acc0 = acc1 + ((d0 << 4) * weight_B) mac.l %d0, %d4, %acc0 move.l 4(%a1), %d1 beq .L505 eor.l %d1, %d0 | else compare signs bge .L504 | if same, add delta to weight sub.l %a3, %d4 | else subtract delta from weight cmp.l %d7, %d4 | ckeck for negative clip limit bge .L505 move.l %d7, %d4 bra .L505 .L504: add.l %a3, %d4 | add delta to weight cmp.l %d6, %d4 | check for positive clip limit ble .L505 move.l %d6, %d4 .L505: move.l %acc0, %d0 | d2 = rounded product add.l %d1, %d0 | add applied weight to bptr [0], store move.l %d0, 4(%a1) beq .L512 .L510: move.l %acc1, %acc0 asl.l #4, %d0 | acc0 = acc1 + ((d0 << 4) * weight_A) mac.l %d0, %d3, %acc0 move.l (%a1), %d1 beq .L503 eor.l %d1, %d0 | else compare signs bge .L507 | if same, add delta to weight sub.l %a3, %d3 | else subtract delta from weight cmp.l %d7, %d3 | check for negative clip limit bge .L503 move.l %d7, %d3 bra .L503 .L507: add.l %a3, %d3 | add delta to weight cmp.l %d6, %d3 | check for negative clip limit ble .L503 move.l %d6, %d3 .L503: move.l %acc0, %d2 | d2 = rounded product add.l %d1, %d2 | add applied weight to bptr [1], store move.l %d2, (%a1) .L512: addq.l #8, %a1 cmp.l %a1, %d5 | loop if bptr < eptr jbhi term_minus_2 move.l -8(%a1), 40(%a2) | dpp->samples_B [0] = bptr [-4] jbra finish_up .L511: move.l 4(%a1), %d0 beq .L512 bra .L510 |------------------------------------------------------------------------------ | Loop to handle term = -3 condition | | a0 = d0 = decorrelation sample | a1 = bptr d1 = initial bptr [0] | a2 = dpp-> d2 = updated bptr [0] | a3 = dpp->delta << 17 d3 = dpp->weight_A << 17 | a4 = d4 = dpp->weight_B << 17 | a5 = d5 = eptr | a6 = d6 = 1024 << 17 | a7 = d7 = -1024 << 17 | macsr = 0x20 acc1 = 0x00 0000 80 |------------------------------------------------------------------------------ term_minus_3: move.l -4(%a1), %d0 | d0 = bptr [-1] beq .L301 move.l %acc1, %acc0 asl.l #4, %d0 | acc0 = acc1 + ((d0 << 4) * weight_A) mac.l %d0, %d3, %acc0 move.l (%a1), %d1 beq .L320 eor.l %d1, %d0 | else compare signs bge .L319 | if same, add delta to weight sub.l %a3, %d3 | else subtract delta from weight cmp.l %d7, %d3 | check for negative clip limit bge .L320 move.l %d7, %d3 bra .L320 .L319: add.l %a3, %d3 | add delta to weight cmp.l %d6, %d3 | check for positive clip limit ble .L320 move.l %d6, %d3 .L320: move.l %acc0, %d2 | d2 = rounded product add.l %d1, %d2 | add applied weight to bptr [0], store move.l %d2, (%a1)+ .L330: move.l -12(%a1), %d0 | d0 = bptr [-2] beq .L302 move.l %acc1, %acc0 asl.l #4, %d0 | acc0 = acc1 + ((d0 << 4) * weight_B) mac.l %d0, %d4, %acc0 move.l (%a1), %d1 beq .L318 eor.l %d1, %d0 | else compare signs bge .L322 | if same, add delta to weight sub.l %a3, %d4 | else subtract delta from weight cmp.l %d7, %d4 | check for negative clip limit bge .L318 move.l %d7, %d4 bra .L318 .L322: add.l %a3, %d4 | add delta to weight cmp.l %d6, %d4 | check for positive clip limit ble .L318 move.l %d6, %d4 .L318: move.l %acc0, %d2 | d2 = rounded product add.l %d1, %d2 | add applied weight to bptr [1], store move.l %d2, (%a1)+ .L331: cmp.l %a1, %d5 | bptr, eptr jbhi term_minus_3 move.l -4(%a1), 8(%a2) | dpp->samples_A [0] = bptr [-1] move.l -8(%a1), 40(%a2) | dpp->samples_B [0] = bptr [-2] jbra finish_up .L301: addq.l #4, %a1 bra .L330 .L302: addq.l #4, %a1 bra .L331 | finish and return finish_up: moveq.l #17, %d0 asr.l %d0, %d3 asr.l %d0, %d4 move.w %d3, 4(%a2) | weight_A, dpp->weight_A move.w %d4, 6(%a2) | weight_B, dpp->weight_B clr.l %d0 | clear up EMAC move.l %d0, %acc0 move.l %d0, %acc1 return_only: movem.l (%sp), %d2-%d7/%a2-%a6 lea (44,%sp), %sp rts ================================================ FILE: src/engine/external/wavpack/float.c ================================================ //////////////////////////////////////////////////////////////////////////// // **** WAVPACK **** // // Hybrid Lossless Wavefile Compressor // // Copyright (c) 1998 - 2006 Conifer Software. // // All Rights Reserved. // // Distributed under the BSD Software License (see license.txt) // //////////////////////////////////////////////////////////////////////////// // float.c #include "wavpack.h" int read_float_info (WavpackStream *wps, WavpackMetadata *wpmd) { int bytecnt = wpmd->byte_length; char *byteptr = wpmd->data; if (bytecnt != 4) return FALSE; wps->float_flags = *byteptr++; wps->float_shift = *byteptr++; wps->float_max_exp = *byteptr++; wps->float_norm_exp = *byteptr; return TRUE; } void float_values (WavpackStream *wps, int32_t *values, int32_t num_values) { int shift = wps->float_max_exp - wps->float_norm_exp + wps->float_shift; if (shift > 32) shift = 32; else if (shift < -32) shift = -32; while (num_values--) { if (shift > 0) *values <<= shift; else if (shift < 0) *values >>= -shift; if (*values > 8388607L) *values = 8388607L; else if (*values < -8388608L) *values = -8388608L; values++; } } ================================================ FILE: src/engine/external/wavpack/license.txt ================================================ Copyright (c) 1998 - 2006 Conifer Software All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Conifer Software nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ================================================ FILE: src/engine/external/wavpack/metadata.c ================================================ //////////////////////////////////////////////////////////////////////////// // **** WAVPACK **** // // Hybrid Lossless Wavefile Compressor // // Copyright (c) 1998 - 2006 Conifer Software. // // All Rights Reserved. // // Distributed under the BSD Software License (see license.txt) // //////////////////////////////////////////////////////////////////////////// // metadata.c // This module handles the metadata structure introduced in WavPack 4.0 #include "wavpack.h" int read_metadata_buff (WavpackContext *wpc, WavpackMetadata *wpmd) { uchar tchar; if (!wpc->infile (&wpmd->id, 1) || !wpc->infile (&tchar, 1)) return FALSE; wpmd->byte_length = tchar << 1; if (wpmd->id & ID_LARGE) { wpmd->id &= ~ID_LARGE; if (!wpc->infile (&tchar, 1)) return FALSE; wpmd->byte_length += (int32_t) tchar << 9; if (!wpc->infile (&tchar, 1)) return FALSE; wpmd->byte_length += (int32_t) tchar << 17; } if (wpmd->id & ID_ODD_SIZE) { wpmd->id &= ~ID_ODD_SIZE; wpmd->byte_length--; } if (wpmd->byte_length && wpmd->byte_length <= sizeof (wpc->read_buffer)) { uint32_t bytes_to_read = wpmd->byte_length + (wpmd->byte_length & 1); if (wpc->infile (wpc->read_buffer, bytes_to_read) != (int32_t) bytes_to_read) { wpmd->data = NULL; return FALSE; } wpmd->data = wpc->read_buffer; } else wpmd->data = NULL; return TRUE; } int process_metadata (WavpackContext *wpc, WavpackMetadata *wpmd) { WavpackStream *wps = &wpc->stream; switch (wpmd->id) { case ID_DUMMY: return TRUE; case ID_DECORR_TERMS: return read_decorr_terms (wps, wpmd); case ID_DECORR_WEIGHTS: return read_decorr_weights (wps, wpmd); case ID_DECORR_SAMPLES: return read_decorr_samples (wps, wpmd); case ID_ENTROPY_VARS: return read_entropy_vars (wps, wpmd); case ID_HYBRID_PROFILE: return read_hybrid_profile (wps, wpmd); case ID_FLOAT_INFO: return read_float_info (wps, wpmd); case ID_INT32_INFO: return read_int32_info (wps, wpmd); case ID_CHANNEL_INFO: return read_channel_info (wpc, wpmd); case ID_CONFIG_BLOCK: return read_config_info (wpc, wpmd); case ID_WV_BITSTREAM: return init_wv_bitstream (wpc, wpmd); case ID_SHAPING_WEIGHTS: case ID_WVC_BITSTREAM: case ID_WVX_BITSTREAM: return TRUE; default: return (wpmd->id & ID_OPTIONAL_DATA) ? TRUE : FALSE; } } ================================================ FILE: src/engine/external/wavpack/readme.txt ================================================ //////////////////////////////////////////////////////////////////////////// // **** WAVPACK **** // // Hybrid Lossless Wavefile Compressor // // Copyright (c) 1998 - 2006 Conifer Software. // // All Rights Reserved. // // Distributed under the BSD Software License (see license.txt) // //////////////////////////////////////////////////////////////////////////// This package contains a tiny version of the WavPack 4.40 decoder that might be used in a "resource limited" CPU environment or form the basis for a hardware decoding implementation. It is packaged with a demo command-line program that accepts a WavPack audio file on stdin and outputs a RIFF wav file to stdout. The program is standard C, and a win32 executable is included which was compiled under MS Visual C++ 6.0 using this command: cl /O1 /DWIN32 wvfilter.c wputils.c unpack.c float.c metadata.c words.c bits.c WavPack data is read with a stream reading callback. No direct seeking is provided for, but it is possible to start decoding anywhere in a WavPack stream. In this case, WavPack will be able to provide the sample-accurate position when it synchs with the data and begins decoding. The WIN32 macro is used for Windows to force the stdin and stdout streams to be binary mode. Compared to the previous version, this library has been optimized somewhat for improved performance in exchange for slightly larger code size. The library also now includes hand-optimized assembly language versions of the decorrelation functions for both the ColdFire (w/EMAC) and ARM processors. For demonstration purposes this uses a single static copy of the WavpackContext structure, so obviously it cannot be used for more than one file at a time. Also, this decoder will not handle "correction" files, plays only the first two channels of multi-channel files, and is limited in resolution in some large integer or floating point files (but always provides at least 24 bits of resolution). It also will not accept WavPack files from before version 4.0. The previous version of this library would handle float files by returning 32-bit floating-point data (even though no floating point math was used). Because this library would normally be used for simply playing WavPack files where lossless performance (beyond 24-bits) is not relevant, I have changed this behavior. Now, these files will generate clipped 24-bit data. The MODE_FLOAT flag will still be returned by WavpackGetMode(), but the BitsPerSample and BytesPerSample queries will be 24 and 3, respectfully. What this means is that an application that can handle 24-bit data will now be able to handle floating point data (assuming that the MODE_FLOAT flag is ignored). To make this code viable on the greatest number of hardware platforms, the following are true: speed is about 5x realtime on an AMD K6 300 MHz ("high" mode 16/44 stereo; normal mode is about twice that fast) no floating-point math required; just 32b * 32b = 32b int multiply large data areas are static and less than 4K total executable code and tables are less than 40K no malloc / free usage To maintain compatibility on various platforms, the following conventions are used: a "char" must be exactly 8-bits a "short" must be exactly 16-bits an "int" must be at least 16-bits, but may be larger the "long" type is not used to avoid problems with 64-bit compilers Questions or comments should be directed to david@wavpack.com ================================================ FILE: src/engine/external/wavpack/unpack.c ================================================ //////////////////////////////////////////////////////////////////////////// // **** WAVPACK **** // // Hybrid Lossless Wavefile Compressor // // Copyright (c) 1998 - 2006 Conifer Software. // // All Rights Reserved. // // Distributed under the BSD Software License (see license.txt) // //////////////////////////////////////////////////////////////////////////// // unpack.c // This module actually handles the decompression of the audio data, except // for the entropy decoding which is handled by the words.c module. For // maximum efficiency, the conversion is isolated to tight loops that handle // an entire buffer. #include "wavpack.h" #include <stdlib.h> #include <string.h> #define LOSSY_MUTE ///////////////////////////// executable code //////////////////////////////// // This function initializes everything required to unpack a WavPack block // and must be called before unpack_samples() is called to obtain audio data. // It is assumed that the WavpackHeader has been read into the wps->wphdr // (in the current WavpackStream). This is where all the metadata blocks are // scanned up to the one containing the audio bitstream. int unpack_init (WavpackContext *wpc) { WavpackStream *wps = &wpc->stream; WavpackMetadata wpmd; if (wps->wphdr.block_samples && wps->wphdr.block_index != (uint32_t) -1) wps->sample_index = wps->wphdr.block_index; wps->mute_error = FALSE; wps->crc = 0xffffffff; CLEAR (wps->wvbits); CLEAR (wps->decorr_passes); CLEAR (wps->w); while (read_metadata_buff (wpc, &wpmd)) { if (!process_metadata (wpc, &wpmd)) { strcpy (wpc->error_message, "invalid metadata!"); return FALSE; } if (wpmd.id == ID_WV_BITSTREAM) break; } if (wps->wphdr.block_samples && !bs_is_open (&wps->wvbits)) { strcpy (wpc->error_message, "invalid WavPack file!"); return FALSE; } if (wps->wphdr.block_samples) { if ((wps->wphdr.flags & INT32_DATA) && wps->int32_sent_bits) wpc->lossy_blocks = TRUE; if ((wps->wphdr.flags & FLOAT_DATA) && wps->float_flags & (FLOAT_EXCEPTIONS | FLOAT_ZEROS_SENT | FLOAT_SHIFT_SENT | FLOAT_SHIFT_SAME)) wpc->lossy_blocks = TRUE; } return TRUE; } // This function initialzes the main bitstream for audio samples, which must // be in the "wv" file. int init_wv_bitstream (WavpackContext *wpc, WavpackMetadata *wpmd) { WavpackStream *wps = &wpc->stream; if (wpmd->data) bs_open_read (&wps->wvbits, wpmd->data, (unsigned char *) wpmd->data + wpmd->byte_length, NULL, 0); else if (wpmd->byte_length) bs_open_read (&wps->wvbits, wpc->read_buffer, wpc->read_buffer + sizeof (wpc->read_buffer), wpc->infile, wpmd->byte_length + (wpmd->byte_length & 1)); return TRUE; } // Read decorrelation terms from specified metadata block into the // decorr_passes array. The terms range from -3 to 8, plus 17 & 18; // other values are reserved and generate errors for now. The delta // ranges from 0 to 7 with all values valid. Note that the terms are // stored in the opposite order in the decorr_passes array compared // to packing. int read_decorr_terms (WavpackStream *wps, WavpackMetadata *wpmd) { int termcnt = wpmd->byte_length; uchar *byteptr = wpmd->data; struct decorr_pass *dpp; if (termcnt > MAX_NTERMS) return FALSE; wps->num_terms = termcnt; for (dpp = wps->decorr_passes + termcnt - 1; termcnt--; dpp--) { dpp->term = (int)(*byteptr & 0x1f) - 5; dpp->delta = (*byteptr++ >> 5) & 0x7; if (!dpp->term || dpp->term < -3 || (dpp->term > MAX_TERM && dpp->term < 17) || dpp->term > 18) return FALSE; } return TRUE; } // Read decorrelation weights from specified metadata block into the // decorr_passes array. The weights range +/-1024, but are rounded and // truncated to fit in signed chars for metadata storage. Weights are // separate for the two channels and are specified from the "last" term // (first during encode). Unspecified weights are set to zero. int read_decorr_weights (WavpackStream *wps, WavpackMetadata *wpmd) { int termcnt = wpmd->byte_length, tcount; signed char *byteptr = wpmd->data; struct decorr_pass *dpp; if (!(wps->wphdr.flags & MONO_DATA)) termcnt /= 2; if (termcnt > wps->num_terms) return FALSE; for (tcount = wps->num_terms, dpp = wps->decorr_passes; tcount--; dpp++) dpp->weight_A = dpp->weight_B = 0; while (--dpp >= wps->decorr_passes && termcnt--) { dpp->weight_A = restore_weight (*byteptr++); if (!(wps->wphdr.flags & MONO_DATA)) dpp->weight_B = restore_weight (*byteptr++); } return TRUE; } // Read decorrelation samples from specified metadata block into the // decorr_passes array. The samples are signed 32-bit values, but are // converted to signed log2 values for storage in metadata. Values are // stored for both channels and are specified from the "last" term // (first during encode) with unspecified samples set to zero. The // number of samples stored varies with the actual term value, so // those must obviously come first in the metadata. int read_decorr_samples (WavpackStream *wps, WavpackMetadata *wpmd) { uchar *byteptr = wpmd->data; uchar *endptr = byteptr + wpmd->byte_length; struct decorr_pass *dpp; int tcount; for (tcount = wps->num_terms, dpp = wps->decorr_passes; tcount--; dpp++) { CLEAR (dpp->samples_A); CLEAR (dpp->samples_B); } if (wps->wphdr.version == 0x402 && (wps->wphdr.flags & HYBRID_FLAG)) { byteptr += 2; if (!(wps->wphdr.flags & MONO_DATA)) byteptr += 2; } while (dpp-- > wps->decorr_passes && byteptr < endptr) if (dpp->term > MAX_TERM) { dpp->samples_A [0] = exp2s ((short)(byteptr [0] + (byteptr [1] << 8))); dpp->samples_A [1] = exp2s ((short)(byteptr [2] + (byteptr [3] << 8))); byteptr += 4; if (!(wps->wphdr.flags & MONO_DATA)) { dpp->samples_B [0] = exp2s ((short)(byteptr [0] + (byteptr [1] << 8))); dpp->samples_B [1] = exp2s ((short)(byteptr [2] + (byteptr [3] << 8))); byteptr += 4; } } else if (dpp->term < 0) { dpp->samples_A [0] = exp2s ((short)(byteptr [0] + (byteptr [1] << 8))); dpp->samples_B [0] = exp2s ((short)(byteptr [2] + (byteptr [3] << 8))); byteptr += 4; } else { int m = 0, cnt = dpp->term; while (cnt--) { dpp->samples_A [m] = exp2s ((short)(byteptr [0] + (byteptr [1] << 8))); byteptr += 2; if (!(wps->wphdr.flags & MONO_DATA)) { dpp->samples_B [m] = exp2s ((short)(byteptr [0] + (byteptr [1] << 8))); byteptr += 2; } m++; } } return byteptr == endptr; } // Read the int32 data from the specified metadata into the specified stream. // This data is used for integer data that has more than 24 bits of magnitude // or, in some cases, used to eliminate redundant bits from any audio stream. int read_int32_info (WavpackStream *wps, WavpackMetadata *wpmd) { int bytecnt = wpmd->byte_length; char *byteptr = wpmd->data; if (bytecnt != 4) return FALSE; wps->int32_sent_bits = *byteptr++; wps->int32_zeros = *byteptr++; wps->int32_ones = *byteptr++; wps->int32_dups = *byteptr; return TRUE; } // Read multichannel information from metadata. The first byte is the total // number of channels and the following bytes represent the channel_mask // as described for Microsoft WAVEFORMATEX. int read_channel_info (WavpackContext *wpc, WavpackMetadata *wpmd) { int bytecnt = wpmd->byte_length, shift = 0; char *byteptr = wpmd->data; uint32_t mask = 0; if (!bytecnt || bytecnt > 5) return FALSE; wpc->config.num_channels = *byteptr++; while (--bytecnt) { mask |= (uint32_t) *byteptr++ << shift; shift += 8; } wpc->config.channel_mask = mask; return TRUE; } // Read configuration information from metadata. int read_config_info (WavpackContext *wpc, WavpackMetadata *wpmd) { int bytecnt = wpmd->byte_length; uchar *byteptr = wpmd->data; if (bytecnt >= 3) { wpc->config.flags &= 0xff; wpc->config.flags |= (int32_t) *byteptr++ << 8; wpc->config.flags |= (int32_t) *byteptr++ << 16; wpc->config.flags |= (int32_t) *byteptr << 24; } return TRUE; } // This monster actually unpacks the WavPack bitstream(s) into the specified // buffer as 32-bit integers or floats (depending on orignal data). Lossy // samples will be clipped to their original limits (i.e. 8-bit samples are // clipped to -128/+127) but are still returned in int32_ts. It is up to the // caller to potentially reformat this for the final output including any // multichannel distribution, block alignment or endian compensation. The // function unpack_init() must have been called and the entire WavPack block // must still be visible (although wps->blockbuff will not be accessed again). // For maximum clarity, the function is broken up into segments that handle // various modes. This makes for a few extra infrequent flag checks, but // makes the code easier to follow because the nesting does not become so // deep. For maximum efficiency, the conversion is isolated to tight loops // that handle an entire buffer. The function returns the total number of // samples unpacked, which can be less than the number requested if an error // occurs or the end of the block is reached. #if defined(CPU_COLDFIRE) && !defined(SIMULATOR) extern void decorr_stereo_pass_cont_mcf5249 (struct decorr_pass *dpp, int32_t *buffer, int32_t sample_count); #elif defined(CPU_ARM) && !defined(SIMULATOR) extern void decorr_stereo_pass_cont_arm (struct decorr_pass *dpp, int32_t *buffer, int32_t sample_count); extern void decorr_stereo_pass_cont_arml (struct decorr_pass *dpp, int32_t *buffer, int32_t sample_count); #else static void decorr_stereo_pass_cont (struct decorr_pass *dpp, int32_t *buffer, int32_t sample_count); #endif static void decorr_mono_pass (struct decorr_pass *dpp, int32_t *buffer, int32_t sample_count); static void decorr_stereo_pass (struct decorr_pass *dpp, int32_t *buffer, int32_t sample_count); static void fixup_samples (WavpackStream *wps, int32_t *buffer, uint32_t sample_count); int32_t unpack_samples (WavpackContext *wpc, int32_t *buffer, uint32_t sample_count) { WavpackStream *wps = &wpc->stream; uint32_t flags = wps->wphdr.flags, crc = wps->crc, i; int32_t mute_limit = (1L << ((flags & MAG_MASK) >> MAG_LSB)) + 2; struct decorr_pass *dpp; int32_t *bptr, *eptr; int tcount; if (wps->sample_index + sample_count > wps->wphdr.block_index + wps->wphdr.block_samples) sample_count = wps->wphdr.block_index + wps->wphdr.block_samples - wps->sample_index; if (wps->mute_error) { memset (buffer, 0, sample_count * (flags & MONO_FLAG ? 4 : 8)); wps->sample_index += sample_count; return sample_count; } if (flags & HYBRID_FLAG) mute_limit *= 2; ///////////////////// handle version 4 mono data ///////////////////////// if (flags & MONO_DATA) { eptr = buffer + sample_count; i = get_words (buffer, sample_count, flags, &wps->w, &wps->wvbits); for (tcount = wps->num_terms, dpp = wps->decorr_passes; tcount--; dpp++) decorr_mono_pass (dpp, buffer, sample_count); for (bptr = buffer; bptr < eptr; ++bptr) { if (labs (bptr [0]) > mute_limit) { i = bptr - buffer; break; } crc = crc * 3 + bptr [0]; } } //////////////////// handle version 4 stereo data //////////////////////// else { eptr = buffer + (sample_count * 2); i = get_words (buffer, sample_count, flags, &wps->w, &wps->wvbits); if (sample_count < 16) for (tcount = wps->num_terms, dpp = wps->decorr_passes; tcount--; dpp++) decorr_stereo_pass (dpp, buffer, sample_count); else for (tcount = wps->num_terms, dpp = wps->decorr_passes; tcount--; dpp++) { decorr_stereo_pass (dpp, buffer, 8); #if defined(CPU_COLDFIRE) && !defined(SIMULATOR) decorr_stereo_pass_cont_mcf5249 (dpp, buffer + 16, sample_count - 8); #elif defined(CPU_ARM) && !defined(SIMULATOR) if (((flags & MAG_MASK) >> MAG_LSB) > 15) decorr_stereo_pass_cont_arml (dpp, buffer + 16, sample_count - 8); else decorr_stereo_pass_cont_arm (dpp, buffer + 16, sample_count - 8); #else decorr_stereo_pass_cont (dpp, buffer + 16, sample_count - 8); #endif } if (flags & JOINT_STEREO) for (bptr = buffer; bptr < eptr; bptr += 2) { bptr [0] += (bptr [1] -= (bptr [0] >> 1)); if (labs (bptr [0]) > mute_limit || labs (bptr [1]) > mute_limit) { i = (bptr - buffer) / 2; break; } crc = (crc * 3 + bptr [0]) * 3 + bptr [1]; } else for (bptr = buffer; bptr < eptr; bptr += 2) { if (labs (bptr [0]) > mute_limit || labs (bptr [1]) > mute_limit) { i = (bptr - buffer) / 2; break; } crc = (crc * 3 + bptr [0]) * 3 + bptr [1]; } } if (i != sample_count) { memset (buffer, 0, sample_count * (flags & MONO_FLAG ? 4 : 8)); wps->mute_error = TRUE; i = sample_count; } fixup_samples (wps, buffer, i); if (flags & FALSE_STEREO) { int32_t *dptr = buffer + i * 2; int32_t *sptr = buffer + i; int32_t c = i; while (c--) { *--dptr = *--sptr; *--dptr = *sptr; } } wps->sample_index += i; wps->crc = crc; return i; } static void decorr_stereo_pass (struct decorr_pass *dpp, int32_t *buffer, int32_t sample_count) { int32_t delta = dpp->delta, weight_A = dpp->weight_A, weight_B = dpp->weight_B; int32_t *bptr, *eptr = buffer + (sample_count * 2), sam_A, sam_B; int m, k; switch (dpp->term) { case 17: for (bptr = buffer; bptr < eptr; bptr += 2) { sam_A = 2 * dpp->samples_A [0] - dpp->samples_A [1]; dpp->samples_A [1] = dpp->samples_A [0]; dpp->samples_A [0] = apply_weight (weight_A, sam_A) + bptr [0]; update_weight (weight_A, delta, sam_A, bptr [0]); bptr [0] = dpp->samples_A [0]; sam_A = 2 * dpp->samples_B [0] - dpp->samples_B [1]; dpp->samples_B [1] = dpp->samples_B [0]; dpp->samples_B [0] = apply_weight (weight_B, sam_A) + bptr [1]; update_weight (weight_B, delta, sam_A, bptr [1]); bptr [1] = dpp->samples_B [0]; } break; case 18: for (bptr = buffer; bptr < eptr; bptr += 2) { sam_A = (3 * dpp->samples_A [0] - dpp->samples_A [1]) >> 1; dpp->samples_A [1] = dpp->samples_A [0]; dpp->samples_A [0] = apply_weight (weight_A, sam_A) + bptr [0]; update_weight (weight_A, delta, sam_A, bptr [0]); bptr [0] = dpp->samples_A [0]; sam_A = (3 * dpp->samples_B [0] - dpp->samples_B [1]) >> 1; dpp->samples_B [1] = dpp->samples_B [0]; dpp->samples_B [0] = apply_weight (weight_B, sam_A) + bptr [1]; update_weight (weight_B, delta, sam_A, bptr [1]); bptr [1] = dpp->samples_B [0]; } break; default: for (m = 0, k = dpp->term & (MAX_TERM - 1), bptr = buffer; bptr < eptr; bptr += 2) { sam_A = dpp->samples_A [m]; dpp->samples_A [k] = apply_weight (weight_A, sam_A) + bptr [0]; update_weight (weight_A, delta, sam_A, bptr [0]); bptr [0] = dpp->samples_A [k]; sam_A = dpp->samples_B [m]; dpp->samples_B [k] = apply_weight (weight_B, sam_A) + bptr [1]; update_weight (weight_B, delta, sam_A, bptr [1]); bptr [1] = dpp->samples_B [k]; m = (m + 1) & (MAX_TERM - 1); k = (k + 1) & (MAX_TERM - 1); } if (m) { int32_t temp_samples [MAX_TERM]; memcpy (temp_samples, dpp->samples_A, sizeof (dpp->samples_A)); for (k = 0; k < MAX_TERM; k++, m++) dpp->samples_A [k] = temp_samples [m & (MAX_TERM - 1)]; memcpy (temp_samples, dpp->samples_B, sizeof (dpp->samples_B)); for (k = 0; k < MAX_TERM; k++, m++) dpp->samples_B [k] = temp_samples [m & (MAX_TERM - 1)]; } break; case -1: for (bptr = buffer; bptr < eptr; bptr += 2) { sam_A = bptr [0] + apply_weight (weight_A, dpp->samples_A [0]); update_weight_clip (weight_A, delta, dpp->samples_A [0], bptr [0]); bptr [0] = sam_A; dpp->samples_A [0] = bptr [1] + apply_weight (weight_B, sam_A); update_weight_clip (weight_B, delta, sam_A, bptr [1]); bptr [1] = dpp->samples_A [0]; } break; case -2: for (bptr = buffer; bptr < eptr; bptr += 2) { sam_B = bptr [1] + apply_weight (weight_B, dpp->samples_B [0]); update_weight_clip (weight_B, delta, dpp->samples_B [0], bptr [1]); bptr [1] = sam_B; dpp->samples_B [0] = bptr [0] + apply_weight (weight_A, sam_B); update_weight_clip (weight_A, delta, sam_B, bptr [0]); bptr [0] = dpp->samples_B [0]; } break; case -3: for (bptr = buffer; bptr < eptr; bptr += 2) { sam_A = bptr [0] + apply_weight (weight_A, dpp->samples_A [0]); update_weight_clip (weight_A, delta, dpp->samples_A [0], bptr [0]); sam_B = bptr [1] + apply_weight (weight_B, dpp->samples_B [0]); update_weight_clip (weight_B, delta, dpp->samples_B [0], bptr [1]); bptr [0] = dpp->samples_B [0] = sam_A; bptr [1] = dpp->samples_A [0] = sam_B; } break; } dpp->weight_A = weight_A; dpp->weight_B = weight_B; } #if (!defined(CPU_COLDFIRE) && !defined(CPU_ARM)) || defined(SIMULATOR) static void decorr_stereo_pass_cont (struct decorr_pass *dpp, int32_t *buffer, int32_t sample_count) { int32_t delta = dpp->delta, weight_A = dpp->weight_A, weight_B = dpp->weight_B; int32_t *bptr, *tptr, *eptr = buffer + (sample_count * 2), sam_A, sam_B; int k, i; switch (dpp->term) { case 17: for (bptr = buffer; bptr < eptr; bptr += 2) { sam_A = 2 * bptr [-2] - bptr [-4]; bptr [0] = apply_weight (weight_A, sam_A) + (sam_B = bptr [0]); update_weight (weight_A, delta, sam_A, sam_B); sam_A = 2 * bptr [-1] - bptr [-3]; bptr [1] = apply_weight (weight_B, sam_A) + (sam_B = bptr [1]); update_weight (weight_B, delta, sam_A, sam_B); } dpp->samples_B [0] = bptr [-1]; dpp->samples_A [0] = bptr [-2]; dpp->samples_B [1] = bptr [-3]; dpp->samples_A [1] = bptr [-4]; break; case 18: for (bptr = buffer; bptr < eptr; bptr += 2) { sam_A = (3 * bptr [-2] - bptr [-4]) >> 1; bptr [0] = apply_weight (weight_A, sam_A) + (sam_B = bptr [0]); update_weight (weight_A, delta, sam_A, sam_B); sam_A = (3 * bptr [-1] - bptr [-3]) >> 1; bptr [1] = apply_weight (weight_B, sam_A) + (sam_B = bptr [1]); update_weight (weight_B, delta, sam_A, sam_B); } dpp->samples_B [0] = bptr [-1]; dpp->samples_A [0] = bptr [-2]; dpp->samples_B [1] = bptr [-3]; dpp->samples_A [1] = bptr [-4]; break; default: for (bptr = buffer, tptr = buffer - (dpp->term * 2); bptr < eptr; bptr += 2, tptr += 2) { bptr [0] = apply_weight (weight_A, tptr [0]) + (sam_A = bptr [0]); update_weight (weight_A, delta, tptr [0], sam_A); bptr [1] = apply_weight (weight_B, tptr [1]) + (sam_A = bptr [1]); update_weight (weight_B, delta, tptr [1], sam_A); } for (k = dpp->term - 1, i = 8; i--; k--) { dpp->samples_B [k & (MAX_TERM - 1)] = *--bptr; dpp->samples_A [k & (MAX_TERM - 1)] = *--bptr; } break; case -1: for (bptr = buffer; bptr < eptr; bptr += 2) { bptr [0] = apply_weight (weight_A, bptr [-1]) + (sam_A = bptr [0]); update_weight_clip (weight_A, delta, bptr [-1], sam_A); bptr [1] = apply_weight (weight_B, bptr [0]) + (sam_A = bptr [1]); update_weight_clip (weight_B, delta, bptr [0], sam_A); } dpp->samples_A [0] = bptr [-1]; break; case -2: for (bptr = buffer; bptr < eptr; bptr += 2) { bptr [1] = apply_weight (weight_B, bptr [-2]) + (sam_A = bptr [1]); update_weight_clip (weight_B, delta, bptr [-2], sam_A); bptr [0] = apply_weight (weight_A, bptr [1]) + (sam_A = bptr [0]); update_weight_clip (weight_A, delta, bptr [1], sam_A); } dpp->samples_B [0] = bptr [-2]; break; case -3: for (bptr = buffer; bptr < eptr; bptr += 2) { bptr [0] = apply_weight (weight_A, bptr [-1]) + (sam_A = bptr [0]); update_weight_clip (weight_A, delta, bptr [-1], sam_A); bptr [1] = apply_weight (weight_B, bptr [-2]) + (sam_A = bptr [1]); update_weight_clip (weight_B, delta, bptr [-2], sam_A); } dpp->samples_A [0] = bptr [-1]; dpp->samples_B [0] = bptr [-2]; break; } dpp->weight_A = weight_A; dpp->weight_B = weight_B; } #endif static void decorr_mono_pass (struct decorr_pass *dpp, int32_t *buffer, int32_t sample_count) { int32_t delta = dpp->delta, weight_A = dpp->weight_A; int32_t *bptr, *eptr = buffer + sample_count, sam_A; int m, k; switch (dpp->term) { case 17: for (bptr = buffer; bptr < eptr; bptr++) { sam_A = 2 * dpp->samples_A [0] - dpp->samples_A [1]; dpp->samples_A [1] = dpp->samples_A [0]; dpp->samples_A [0] = apply_weight (weight_A, sam_A) + bptr [0]; update_weight (weight_A, delta, sam_A, bptr [0]); bptr [0] = dpp->samples_A [0]; } break; case 18: for (bptr = buffer; bptr < eptr; bptr++) { sam_A = (3 * dpp->samples_A [0] - dpp->samples_A [1]) >> 1; dpp->samples_A [1] = dpp->samples_A [0]; dpp->samples_A [0] = apply_weight (weight_A, sam_A) + bptr [0]; update_weight (weight_A, delta, sam_A, bptr [0]); bptr [0] = dpp->samples_A [0]; } break; default: for (m = 0, k = dpp->term & (MAX_TERM - 1), bptr = buffer; bptr < eptr; bptr++) { sam_A = dpp->samples_A [m]; dpp->samples_A [k] = apply_weight (weight_A, sam_A) + bptr [0]; update_weight (weight_A, delta, sam_A, bptr [0]); bptr [0] = dpp->samples_A [k]; m = (m + 1) & (MAX_TERM - 1); k = (k + 1) & (MAX_TERM - 1); } if (m) { int32_t temp_samples [MAX_TERM]; memcpy (temp_samples, dpp->samples_A, sizeof (dpp->samples_A)); for (k = 0; k < MAX_TERM; k++, m++) dpp->samples_A [k] = temp_samples [m & (MAX_TERM - 1)]; } break; } dpp->weight_A = weight_A; } // This is a helper function for unpack_samples() that applies several final // operations. First, if the data is 32-bit float data, then that conversion // is done in the float.c module (whether lossy or lossless) and we return. // Otherwise, if the extended integer data applies, then that operation is // executed first. If the unpacked data is lossy (and not corrected) then // it is clipped and shifted in a single operation. Otherwise, if it's // lossless then the last step is to apply the final shift (if any). static void fixup_samples (WavpackStream *wps, int32_t *buffer, uint32_t sample_count) { uint32_t flags = wps->wphdr.flags; int shift = (flags & SHIFT_MASK) >> SHIFT_LSB; if (flags & FLOAT_DATA) { float_values (wps, buffer, (flags & MONO_FLAG) ? sample_count : sample_count * 2); return; } if (flags & INT32_DATA) { uint32_t count = (flags & MONO_FLAG) ? sample_count : sample_count * 2; int sent_bits = wps->int32_sent_bits, zeros = wps->int32_zeros; int ones = wps->int32_ones, dups = wps->int32_dups; int32_t *dptr = buffer; if (!(flags & HYBRID_FLAG) && !sent_bits && (zeros + ones + dups)) while (count--) { if (zeros) *dptr <<= zeros; else if (ones) *dptr = ((*dptr + 1) << ones) - 1; else if (dups) *dptr = ((*dptr + (*dptr & 1)) << dups) - (*dptr & 1); dptr++; } else shift += zeros + sent_bits + ones + dups; } if (flags & HYBRID_FLAG) { int32_t min_value, max_value, min_shifted, max_shifted; switch (flags & BYTES_STORED) { case 0: min_shifted = (min_value = -128 >> shift) << shift; max_shifted = (max_value = 127 >> shift) << shift; break; case 1: min_shifted = (min_value = -32768 >> shift) << shift; max_shifted = (max_value = 32767 >> shift) << shift; break; case 2: min_shifted = (min_value = -8388608 >> shift) << shift; max_shifted = (max_value = 8388607 >> shift) << shift; break; case 3: default: min_shifted = (min_value = (int32_t) 0x80000000 >> shift) << shift; max_shifted = (max_value = (int32_t) 0x7FFFFFFF >> shift) << shift; break; } if (!(flags & MONO_FLAG)) sample_count *= 2; while (sample_count--) { if (*buffer < min_value) *buffer++ = min_shifted; else if (*buffer > max_value) *buffer++ = max_shifted; else *buffer++ <<= shift; } } else if (shift) { if (!(flags & MONO_FLAG)) sample_count *= 2; while (sample_count--) *buffer++ <<= shift; } } // This function checks the crc value(s) for an unpacked block, returning the // number of actual crc errors detected for the block. The block must be // completely unpacked before this test is valid. For losslessly unpacked // blocks of float or extended integer data the extended crc is also checked. // Note that WavPack's crc is not a CCITT approved polynomial algorithm, but // is a much simpler method that is virtually as robust for real world data. int check_crc_error (WavpackContext *wpc) { WavpackStream *wps = &wpc->stream; int result = 0; if (wps->crc != wps->wphdr.crc) ++result; return result; } ================================================ FILE: src/engine/external/wavpack/wavpack.h ================================================ /*////////////////////////////////////////////////////////////////////////// */ /* **** WAVPACK **** // */ /* Hybrid Lossless Wavefile Compressor // */ /* Copyright (c) 1998 - 2004 Conifer Software. // */ /* All Rights Reserved. // */ /* Distributed under the BSD Software License (see license.txt) // */ /*////////////////////////////////////////////////////////////////////////// */ /* wavpack.h */ #include <sys/types.h> /* This header file contains all the definitions required by WavPack. */ #ifdef __BORLANDC__ typedef unsigned long uint32_t; typedef long int32_t; #elif defined(_WIN32) && !defined(__MINGW32__) #include <stdlib.h> typedef unsigned __int64 uint64_t; typedef unsigned __int32 uint32_t; typedef __int64 int64_t; typedef __int32 int32_t; #else #include <inttypes.h> #endif typedef unsigned char uchar; #if !defined(__GNUC__) || defined(WIN32) typedef unsigned short ushort; typedef unsigned int uint; #endif #include <stdio.h> #define FALSE 0 #define TRUE 1 /*//////////////////////////// WavPack Header ///////////////////////////////// */ /* Note that this is the ONLY structure that is written to (or read from) */ /* WavPack 4.0 files, and is the preamble to every block in both the .wv */ /* and .wvc files. */ typedef struct { char ckID [4]; uint32_t ckSize; short version; uchar track_no, index_no; uint32_t total_samples, block_index, block_samples, flags, crc; } WavpackHeader; #define WavpackHeaderFormat "4LS2LLLLL" /* or-values for "flags" */ #define BYTES_STORED 3 /* 1-4 bytes/sample */ #define MONO_FLAG 4 /* not stereo */ #define HYBRID_FLAG 8 /* hybrid mode */ #define JOINT_STEREO 0x10 /* joint stereo */ #define CROSS_DECORR 0x20 /* no-delay cross decorrelation */ #define HYBRID_SHAPE 0x40 /* noise shape (hybrid mode only) */ #define FLOAT_DATA 0x80 /* ieee 32-bit floating point data */ #define INT32_DATA 0x100 /* special extended int handling */ #define HYBRID_BITRATE 0x200 /* bitrate noise (hybrid mode only) */ #define HYBRID_BALANCE 0x400 /* balance noise (hybrid stereo mode only) */ #define INITIAL_BLOCK 0x800 /* initial block of multichannel segment */ #define FINAL_BLOCK 0x1000 /* final block of multichannel segment */ #define SHIFT_LSB 13 #define SHIFT_MASK (0x1fL << SHIFT_LSB) #define MAG_LSB 18 #define MAG_MASK (0x1fL << MAG_LSB) #define SRATE_LSB 23 #define SRATE_MASK (0xfL << SRATE_LSB) #define FALSE_STEREO 0x40000000 /* block is stereo, but data is mono */ #define IGNORED_FLAGS 0x18000000 /* reserved, but ignore if encountered */ #define NEW_SHAPING 0x20000000 /* use IIR filter for negative shaping */ #define UNKNOWN_FLAGS 0x80000000 /* also reserved, but refuse decode if */ /* encountered */ #define MONO_DATA (MONO_FLAG | FALSE_STEREO) #define MIN_STREAM_VERS 0x402 /* lowest stream version we'll decode */ #define MAX_STREAM_VERS 0x410 /* highest stream version we'll decode */ /*////////////////////////// WavPack Metadata ///////////////////////////////// */ /* This is an internal representation of metadata. */ typedef struct { int32_t byte_length; void *data; uchar id; } WavpackMetadata; #define ID_OPTIONAL_DATA 0x20 #define ID_ODD_SIZE 0x40 #define ID_LARGE 0x80 #define ID_DUMMY 0x0 #define ID_ENCODER_INFO 0x1 #define ID_DECORR_TERMS 0x2 #define ID_DECORR_WEIGHTS 0x3 #define ID_DECORR_SAMPLES 0x4 #define ID_ENTROPY_VARS 0x5 #define ID_HYBRID_PROFILE 0x6 #define ID_SHAPING_WEIGHTS 0x7 #define ID_FLOAT_INFO 0x8 #define ID_INT32_INFO 0x9 #define ID_WV_BITSTREAM 0xa #define ID_WVC_BITSTREAM 0xb #define ID_WVX_BITSTREAM 0xc #define ID_CHANNEL_INFO 0xd #define ID_RIFF_HEADER (ID_OPTIONAL_DATA | 0x1) #define ID_RIFF_TRAILER (ID_OPTIONAL_DATA | 0x2) #define ID_REPLAY_GAIN (ID_OPTIONAL_DATA | 0x3) #define ID_CUESHEET (ID_OPTIONAL_DATA | 0x4) #define ID_CONFIG_BLOCK (ID_OPTIONAL_DATA | 0x5) #define ID_MD5_CHECKSUM (ID_OPTIONAL_DATA | 0x6) /*/////////////////////// WavPack Configuration /////////////////////////////// */ /* This internal structure is used during encode to provide configuration to */ /* the encoding engine and during decoding to provide fle information back to */ /* the higher level functions. Not all fields are used in both modes. */ typedef struct { int bits_per_sample, bytes_per_sample; int num_channels, float_norm_exp; uint32_t flags, sample_rate, channel_mask; } WavpackConfig; #define CONFIG_BYTES_STORED 3 /* 1-4 bytes/sample */ #define CONFIG_MONO_FLAG 4 /* not stereo */ #define CONFIG_HYBRID_FLAG 8 /* hybrid mode */ #define CONFIG_JOINT_STEREO 0x10 /* joint stereo */ #define CONFIG_CROSS_DECORR 0x20 /* no-delay cross decorrelation */ #define CONFIG_HYBRID_SHAPE 0x40 /* noise shape (hybrid mode only) */ #define CONFIG_FLOAT_DATA 0x80 /* ieee 32-bit floating point data */ #define CONFIG_FAST_FLAG 0x200 /* fast mode */ #define CONFIG_HIGH_FLAG 0x800 /* high quality mode */ #define CONFIG_VERY_HIGH_FLAG 0x1000 /* very high */ #define CONFIG_BITRATE_KBPS 0x2000 /* bitrate is kbps, not bits / sample */ #define CONFIG_AUTO_SHAPING 0x4000 /* automatic noise shaping */ #define CONFIG_SHAPE_OVERRIDE 0x8000 /* shaping mode specified */ #define CONFIG_JOINT_OVERRIDE 0x10000 /* joint-stereo mode specified */ #define CONFIG_CREATE_EXE 0x40000 /* create executable */ #define CONFIG_CREATE_WVC 0x80000 /* create correction file */ #define CONFIG_OPTIMIZE_WVC 0x100000 /* maximize bybrid compression */ #define CONFIG_CALC_NOISE 0x800000 /* calc noise in hybrid mode */ #define CONFIG_LOSSY_MODE 0x1000000 /* obsolete (for information) */ #define CONFIG_EXTRA_MODE 0x2000000 /* extra processing mode */ #define CONFIG_SKIP_WVX 0x4000000 /* no wvx stream w/ floats & big ints */ #define CONFIG_MD5_CHECKSUM 0x8000000 /* compute & store MD5 signature */ #define CONFIG_OPTIMIZE_MONO 0x80000000 /* optimize for mono streams posing as stereo */ /*////////////////////////////// WavPack Stream /////////////////////////////// */ /* This internal structure contains everything required to handle a WavPack */ /* "stream", which is defined as a stereo or mono stream of audio samples. For */ /* multichannel audio several of these would be required. Each stream contains */ /* pointers to hold a complete allocated block of WavPack data, although it's */ /* possible to decode WavPack blocks without buffering an entire block. */ typedef int32_t (*read_stream)(void *, int32_t); typedef struct bs { uchar *buf, *end, *ptr; void (*wrap)(struct bs *bs); uint32_t file_bytes, sr; int error, bc; read_stream file; } Bitstream; #define MAX_NTERMS 16 #define MAX_TERM 8 struct decorr_pass { short term, delta, weight_A, weight_B; int32_t samples_A [MAX_TERM], samples_B [MAX_TERM]; }; struct entropy_data { uint32_t median [3], slow_level, error_limit; }; struct words_data { uint32_t bitrate_delta [2], bitrate_acc [2]; uint32_t pend_data, holding_one, zeros_acc; int holding_zero, pend_count; struct entropy_data c [2]; }; typedef struct { WavpackHeader wphdr; Bitstream wvbits; struct words_data w; int num_terms, mute_error; uint32_t sample_index, crc; uchar int32_sent_bits, int32_zeros, int32_ones, int32_dups; uchar float_flags, float_shift, float_max_exp, float_norm_exp; struct decorr_pass decorr_passes [MAX_NTERMS]; } WavpackStream; /* flags for float_flags: */ #define FLOAT_SHIFT_ONES 1 /* bits left-shifted into float = '1' */ #define FLOAT_SHIFT_SAME 2 /* bits left-shifted into float are the same */ #define FLOAT_SHIFT_SENT 4 /* bits shifted into float are sent literally */ #define FLOAT_ZEROS_SENT 8 /* "zeros" are not all real zeros */ #define FLOAT_NEG_ZEROS 0x10 /* contains negative zeros */ #define FLOAT_EXCEPTIONS 0x20 /* contains exceptions (inf, nan, etc.) */ /*///////////////////////////// WavPack Context /////////////////////////////// */ /* This internal structure holds everything required to encode or decode WavPack */ /* files. It is recommended that direct access to this structure be minimized */ /* and the provided utilities used instead. */ typedef struct { WavpackConfig config; WavpackStream stream; uchar read_buffer [1024]; char error_message [80]; read_stream infile; uint32_t total_samples, crc_errors, first_flags; int open_flags, norm_offset, reduced_channels, lossy_blocks; } WavpackContext; /*////////////////////// function prototypes and macros ////////////////////// */ #define CLEAR(destin) memset (&destin, 0, sizeof (destin)); /* bits.c */ void bs_open_read (Bitstream *bs, uchar *buffer_start, uchar *buffer_end, read_stream file, uint32_t file_bytes); #define bs_is_open(bs) ((bs)->ptr != NULL) #define getbit(bs) ( \ (((bs)->bc) ? \ ((bs)->bc--, (bs)->sr & 1) : \ (((++((bs)->ptr) != (bs)->end) ? (void) 0 : (bs)->wrap (bs)), (bs)->bc = 7, ((bs)->sr = *((bs)->ptr)) & 1) \ ) ? \ ((bs)->sr >>= 1, 1) : \ ((bs)->sr >>= 1, 0) \ ) #define getbits(value, nbits, bs) { \ while ((nbits) > (bs)->bc) { \ if (++((bs)->ptr) == (bs)->end) (bs)->wrap (bs); \ (bs)->sr |= (int32_t)*((bs)->ptr) << (bs)->bc; \ (bs)->bc += 8; \ } \ *(value) = (bs)->sr; \ if ((bs)->bc > 32) { \ (bs)->bc -= (nbits); \ (bs)->sr = *((bs)->ptr) >> (8 - (bs)->bc); \ } \ else { \ (bs)->bc -= (nbits); \ (bs)->sr >>= (nbits); \ } \ } void little_endian_to_native (void *data, char *format); void native_to_little_endian (void *data, char *format); /* These macros implement the weight application and update operations */ /* that are at the heart of the decorrelation loops. Note that when there */ /* are several alternative versions of the same macro (marked with PERFCOND) */ /* then the versions are functionally equivalent with respect to WavPack */ /* decoding and the user should choose the one that provides the best */ /* performance. This may be easier to check when NOT using the assembly */ /* language optimizations. */ #if 1 /* PERFCOND */ #define apply_weight_i(weight, sample) ((weight * sample + 512) >> 10) #else #define apply_weight_i(weight, sample) ((((weight * sample) >> 8) + 2) >> 2) #endif #define apply_weight_f(weight, sample) (((((sample & 0xffffL) * weight) >> 9) + \ (((sample & ~0xffffL) >> 9) * weight) + 1) >> 1) #if 1 /* PERFCOND */ #define apply_weight(weight, sample) (sample != (short) sample ? \ apply_weight_f (weight, sample) : apply_weight_i (weight, sample)) #else #define apply_weight(weight, sample) ((int32_t)((weight * (int64_t) sample + 512) >> 10)) #endif #if 0 /* PERFCOND */ #define update_weight(weight, delta, source, result) \ if (source && result) { int32_t s = (int32_t) (source ^ result) >> 31; weight = (delta ^ s) + (weight - s); } #elif 1 #define update_weight(weight, delta, source, result) \ if (source && result) weight += (((source ^ result) >> 30) | 1) * delta #else #define update_weight(weight, delta, source, result) \ if (source && result) (source ^ result) < 0 ? (weight -= delta) : (weight += delta) #endif #define update_weight_clip(weight, delta, source, result) \ if (source && result && ((source ^ result) < 0 ? (weight -= delta) < -1024 : (weight += delta) > 1024)) \ weight = weight < 0 ? -1024 : 1024 /* unpack.c */ int unpack_init (WavpackContext *wpc); int init_wv_bitstream (WavpackContext *wpc, WavpackMetadata *wpmd); int read_decorr_terms (WavpackStream *wps, WavpackMetadata *wpmd); int read_decorr_weights (WavpackStream *wps, WavpackMetadata *wpmd); int read_decorr_samples (WavpackStream *wps, WavpackMetadata *wpmd); int read_float_info (WavpackStream *wps, WavpackMetadata *wpmd); int read_int32_info (WavpackStream *wps, WavpackMetadata *wpmd); int read_channel_info (WavpackContext *wpc, WavpackMetadata *wpmd); int read_config_info (WavpackContext *wpc, WavpackMetadata *wpmd); int32_t unpack_samples (WavpackContext *wpc, int32_t *buffer, uint32_t sample_count); int check_crc_error (WavpackContext *wpc); /* metadata.c stuff */ int read_metadata_buff (WavpackContext *wpc, WavpackMetadata *wpmd); int process_metadata (WavpackContext *wpc, WavpackMetadata *wpmd); /* words.c stuff */ int read_entropy_vars (WavpackStream *wps, WavpackMetadata *wpmd); int read_hybrid_profile (WavpackStream *wps, WavpackMetadata *wpmd); int32_t get_words (int32_t *buffer, int nsamples, uint32_t flags, struct words_data *w, Bitstream *bs); int32_t exp2s (int log); int restore_weight (signed char weight); #define WORD_EOF (1L << 31) /* float.c */ int read_float_info (WavpackStream *wps, WavpackMetadata *wpmd); void float_values (WavpackStream *wps, int32_t *values, int32_t num_values); /* wputils.c */ WavpackContext *WavpackOpenFileInput (read_stream infile, char *error); int WavpackGetMode (WavpackContext *wpc); #define MODE_WVC 0x1 #define MODE_LOSSLESS 0x2 #define MODE_HYBRID 0x4 #define MODE_FLOAT 0x8 #define MODE_VALID_TAG 0x10 #define MODE_HIGH 0x20 #define MODE_FAST 0x40 uint32_t WavpackUnpackSamples (WavpackContext *wpc, int32_t *buffer, uint32_t samples); uint32_t WavpackGetNumSamples (WavpackContext *wpc); uint32_t WavpackGetSampleIndex (WavpackContext *wpc); int WavpackGetNumErrors (WavpackContext *wpc); int WavpackLossyBlocks (WavpackContext *wpc); uint32_t WavpackGetSampleRate (WavpackContext *wpc); int WavpackGetBitsPerSample (WavpackContext *wpc); int WavpackGetBytesPerSample (WavpackContext *wpc); int WavpackGetNumChannels (WavpackContext *wpc); int WavpackGetReducedChannels (WavpackContext *wpc); ================================================ FILE: src/engine/external/wavpack/words.c ================================================ //////////////////////////////////////////////////////////////////////////// // **** WAVPACK **** // // Hybrid Lossless Wavefile Compressor // // Copyright (c) 1998 - 2006 Conifer Software. // // All Rights Reserved. // // Distributed under the BSD Software License (see license.txt) // //////////////////////////////////////////////////////////////////////////// // words.c // This module provides entropy word encoding and decoding functions using // a variation on the Rice method. This was introduced in version 3.93 // because it allows splitting the data into a "lossy" stream and a // "correction" stream in a very efficient manner and is therefore ideal // for the "hybrid" mode. For 4.0, the efficiency of this method was // significantly improved by moving away from the normal Rice restriction of // using powers of two for the modulus divisions and now the method can be // used for both hybrid and pure lossless encoding. // Samples are divided by median probabilities at 5/7 (71.43%), 10/49 (20.41%), // and 20/343 (5.83%). Each zone has 3.5 times fewer samples than the // previous. Using standard Rice coding on this data would result in 1.4 // bits per sample average (not counting sign bit). However, there is a // very simple encoding that is over 99% efficient with this data and // results in about 1.22 bits per sample. #include "wavpack.h" #include <string.h> //////////////////////////////// local macros ///////////////////////////////// #define LIMIT_ONES 16 // maximum consecutive 1s sent for "div" data // these control the time constant "slow_level" which is used for hybrid mode // that controls bitrate as a function of residual level (HYBRID_BITRATE). #define SLS 8 #define SLO ((1 << (SLS - 1))) // these control the time constant of the 3 median level breakpoints #define DIV0 128 // 5/7 of samples #define DIV1 64 // 10/49 of samples #define DIV2 32 // 20/343 of samples // this macro retrieves the specified median breakpoint (without frac; min = 1) #define GET_MED(med) (((c->median [med]) >> 4) + 1) // These macros update the specified median breakpoints. Note that the median // is incremented when the sample is higher than the median, else decremented. // They are designed so that the median will never drop below 1 and the value // is essentially stationary if there are 2 increments for every 5 decrements. #define INC_MED0() (c->median [0] += ((c->median [0] + DIV0) / DIV0) * 5) #define DEC_MED0() (c->median [0] -= ((c->median [0] + (DIV0-2)) / DIV0) * 2) #define INC_MED1() (c->median [1] += ((c->median [1] + DIV1) / DIV1) * 5) #define DEC_MED1() (c->median [1] -= ((c->median [1] + (DIV1-2)) / DIV1) * 2) #define INC_MED2() (c->median [2] += ((c->median [2] + DIV2) / DIV2) * 5) #define DEC_MED2() (c->median [2] -= ((c->median [2] + (DIV2-2)) / DIV2) * 2) #define count_bits(av) ( \ (av) < (1 << 8) ? nbits_table [av] : \ ( \ (av) < (1L << 16) ? nbits_table [(av) >> 8] + 8 : \ ((av) < (1L << 24) ? nbits_table [(av) >> 16] + 16 : nbits_table [(av) >> 24] + 24) \ ) \ ) ///////////////////////////// local table storage //////////////////////////// const char nbits_table [] = { 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, // 0 - 15 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, // 16 - 31 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, // 32 - 47 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, // 48 - 63 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, // 64 - 79 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, // 80 - 95 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, // 96 - 111 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, // 112 - 127 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, // 128 - 143 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, // 144 - 159 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, // 160 - 175 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, // 176 - 191 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, // 192 - 207 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, // 208 - 223 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, // 224 - 239 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 // 240 - 255 }; static const uchar log2_table [] = { 0x00, 0x01, 0x03, 0x04, 0x06, 0x07, 0x09, 0x0a, 0x0b, 0x0d, 0x0e, 0x10, 0x11, 0x12, 0x14, 0x15, 0x16, 0x18, 0x19, 0x1a, 0x1c, 0x1d, 0x1e, 0x20, 0x21, 0x22, 0x24, 0x25, 0x26, 0x28, 0x29, 0x2a, 0x2c, 0x2d, 0x2e, 0x2f, 0x31, 0x32, 0x33, 0x34, 0x36, 0x37, 0x38, 0x39, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x41, 0x42, 0x43, 0x44, 0x45, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5c, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62, 0x63, 0x64, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe4, 0xe5, 0xe6, 0xe7, 0xe7, 0xe8, 0xe9, 0xea, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xee, 0xef, 0xf0, 0xf1, 0xf1, 0xf2, 0xf3, 0xf4, 0xf4, 0xf5, 0xf6, 0xf7, 0xf7, 0xf8, 0xf9, 0xf9, 0xfa, 0xfb, 0xfc, 0xfc, 0xfd, 0xfe, 0xff, 0xff }; static const uchar exp2_table [] = { 0x00, 0x01, 0x01, 0x02, 0x03, 0x03, 0x04, 0x05, 0x06, 0x06, 0x07, 0x08, 0x08, 0x09, 0x0a, 0x0b, 0x0b, 0x0c, 0x0d, 0x0e, 0x0e, 0x0f, 0x10, 0x10, 0x11, 0x12, 0x13, 0x13, 0x14, 0x15, 0x16, 0x16, 0x17, 0x18, 0x19, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1d, 0x1e, 0x1f, 0x20, 0x20, 0x21, 0x22, 0x23, 0x24, 0x24, 0x25, 0x26, 0x27, 0x28, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5e, 0x5f, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc8, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf, 0xd0, 0xd2, 0xd3, 0xd4, 0xd6, 0xd7, 0xd8, 0xd9, 0xdb, 0xdc, 0xdd, 0xde, 0xe0, 0xe1, 0xe2, 0xe4, 0xe5, 0xe6, 0xe8, 0xe9, 0xea, 0xec, 0xed, 0xee, 0xf0, 0xf1, 0xf2, 0xf4, 0xf5, 0xf6, 0xf8, 0xf9, 0xfa, 0xfc, 0xfd, 0xff }; static const char ones_count_table [] = { 0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5, 0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,6, 0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5, 0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,7, 0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5, 0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,6, 0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5, 0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,8 }; ///////////////////////////// executable code //////////////////////////////// void init_words (WavpackStream *wps) { CLEAR (wps->w); } static int mylog2 (uint32_t avalue); // Read the median log2 values from the specifed metadata structure, convert // them back to 32-bit unsigned values and store them. If length is not // exactly correct then we flag and return an error. int read_entropy_vars (WavpackStream *wps, WavpackMetadata *wpmd) { uchar *byteptr = wpmd->data; if (wpmd->byte_length != ((wps->wphdr.flags & MONO_DATA) ? 6 : 12)) return FALSE; wps->w.c [0].median [0] = exp2s (byteptr [0] + (byteptr [1] << 8)); wps->w.c [0].median [1] = exp2s (byteptr [2] + (byteptr [3] << 8)); wps->w.c [0].median [2] = exp2s (byteptr [4] + (byteptr [5] << 8)); if (!(wps->wphdr.flags & MONO_DATA)) { wps->w.c [1].median [0] = exp2s (byteptr [6] + (byteptr [7] << 8)); wps->w.c [1].median [1] = exp2s (byteptr [8] + (byteptr [9] << 8)); wps->w.c [1].median [2] = exp2s (byteptr [10] + (byteptr [11] << 8)); } return TRUE; } // Read the hybrid related values from the specifed metadata structure, convert // them back to their internal formats and store them. The extended profile // stuff is not implemented yet, so return an error if we get more data than // we know what to do with. int read_hybrid_profile (WavpackStream *wps, WavpackMetadata *wpmd) { uchar *byteptr = wpmd->data; uchar *endptr = byteptr + wpmd->byte_length; if (wps->wphdr.flags & HYBRID_BITRATE) { wps->w.c [0].slow_level = exp2s (byteptr [0] + (byteptr [1] << 8)); byteptr += 2; if (!(wps->wphdr.flags & MONO_DATA)) { wps->w.c [1].slow_level = exp2s (byteptr [0] + (byteptr [1] << 8)); byteptr += 2; } } wps->w.bitrate_acc [0] = (int32_t)(byteptr [0] + (byteptr [1] << 8)) << 16; byteptr += 2; if (!(wps->wphdr.flags & MONO_DATA)) { wps->w.bitrate_acc [1] = (int32_t)(byteptr [0] + (byteptr [1] << 8)) << 16; byteptr += 2; } if (byteptr < endptr) { wps->w.bitrate_delta [0] = exp2s ((short)(byteptr [0] + (byteptr [1] << 8))); byteptr += 2; if (!(wps->wphdr.flags & MONO_DATA)) { wps->w.bitrate_delta [1] = exp2s ((short)(byteptr [0] + (byteptr [1] << 8))); byteptr += 2; } if (byteptr < endptr) return FALSE; } else wps->w.bitrate_delta [0] = wps->w.bitrate_delta [1] = 0; return TRUE; } // This function is called during both encoding and decoding of hybrid data to // update the "error_limit" variable which determines the maximum sample error // allowed in the main bitstream. In the HYBRID_BITRATE mode (which is the only // currently implemented) this is calculated from the slow_level values and the // bitrate accumulators. Note that the bitrate accumulators can be changing. void update_error_limit (struct words_data *w, uint32_t flags) { int bitrate_0 = (w->bitrate_acc [0] += w->bitrate_delta [0]) >> 16; if (flags & MONO_DATA) { if (flags & HYBRID_BITRATE) { int slow_log_0 = (w->c [0].slow_level + SLO) >> SLS; if (slow_log_0 - bitrate_0 > -0x100) w->c [0].error_limit = exp2s (slow_log_0 - bitrate_0 + 0x100); else w->c [0].error_limit = 0; } else w->c [0].error_limit = exp2s (bitrate_0); } else { int bitrate_1 = (w->bitrate_acc [1] += w->bitrate_delta [1]) >> 16; if (flags & HYBRID_BITRATE) { int slow_log_0 = (w->c [0].slow_level + SLO) >> SLS; int slow_log_1 = (w->c [1].slow_level + SLO) >> SLS; if (flags & HYBRID_BALANCE) { int balance = (slow_log_1 - slow_log_0 + bitrate_1 + 1) >> 1; if (balance > bitrate_0) { bitrate_1 = bitrate_0 * 2; bitrate_0 = 0; } else if (-balance > bitrate_0) { bitrate_0 = bitrate_0 * 2; bitrate_1 = 0; } else { bitrate_1 = bitrate_0 + balance; bitrate_0 = bitrate_0 - balance; } } if (slow_log_0 - bitrate_0 > -0x100) w->c [0].error_limit = exp2s (slow_log_0 - bitrate_0 + 0x100); else w->c [0].error_limit = 0; if (slow_log_1 - bitrate_1 > -0x100) w->c [1].error_limit = exp2s (slow_log_1 - bitrate_1 + 0x100); else w->c [1].error_limit = 0; } else { w->c [0].error_limit = exp2s (bitrate_0); w->c [1].error_limit = exp2s (bitrate_1); } } } static uint32_t read_code (Bitstream *bs, uint32_t maxcode); // Read the next word from the bitstream "wvbits" and return the value. This // function can be used for hybrid or lossless streams, but since an // optimized version is available for lossless this function would normally // be used for hybrid only. If a hybrid lossless stream is being read then // the "correction" offset is written at the specified pointer. A return value // of WORD_EOF indicates that the end of the bitstream was reached (all 1s) or // some other error occurred. int32_t get_words (int32_t *buffer, int nsamples, uint32_t flags, struct words_data *w, Bitstream *bs) { register struct entropy_data *c = w->c; int csamples; if (!(flags & MONO_DATA)) nsamples *= 2; for (csamples = 0; csamples < nsamples; ++csamples) { uint32_t ones_count, low, mid, high; if (!(flags & MONO_DATA)) c = w->c + (csamples & 1); if (!(w->c [0].median [0] & ~1) && !w->holding_zero && !w->holding_one && !(w->c [1].median [0] & ~1)) { uint32_t mask; int cbits; if (w->zeros_acc) { if (--w->zeros_acc) { c->slow_level -= (c->slow_level + SLO) >> SLS; *buffer++ = 0; continue; } } else { for (cbits = 0; cbits < 33 && getbit (bs); ++cbits); if (cbits == 33) break; if (cbits < 2) w->zeros_acc = cbits; else { for (mask = 1, w->zeros_acc = 0; --cbits; mask <<= 1) if (getbit (bs)) w->zeros_acc |= mask; w->zeros_acc |= mask; } if (w->zeros_acc) { c->slow_level -= (c->slow_level + SLO) >> SLS; CLEAR (w->c [0].median); CLEAR (w->c [1].median); *buffer++ = 0; continue; } } } if (w->holding_zero) ones_count = w->holding_zero = 0; else { int next8; if (bs->bc < 8) { if (++(bs->ptr) == bs->end) bs->wrap (bs); next8 = (bs->sr |= *(bs->ptr) << bs->bc) & 0xff; bs->bc += 8; } else next8 = bs->sr & 0xff; if (next8 == 0xff) { bs->bc -= 8; bs->sr >>= 8; for (ones_count = 8; ones_count < (LIMIT_ONES + 1) && getbit (bs); ++ones_count); if (ones_count == (LIMIT_ONES + 1)) break; if (ones_count == LIMIT_ONES) { uint32_t mask; int cbits; for (cbits = 0; cbits < 33 && getbit (bs); ++cbits); if (cbits == 33) break; if (cbits < 2) ones_count = cbits; else { for (mask = 1, ones_count = 0; --cbits; mask <<= 1) if (getbit (bs)) ones_count |= mask; ones_count |= mask; } ones_count += LIMIT_ONES; } } else { bs->bc -= (ones_count = ones_count_table [next8]) + 1; bs->sr >>= ones_count + 1; } if (w->holding_one) { w->holding_one = ones_count & 1; ones_count = (ones_count >> 1) + 1; } else { w->holding_one = ones_count & 1; ones_count >>= 1; } w->holding_zero = ~w->holding_one & 1; } if ((flags & HYBRID_FLAG) && ((flags & MONO_DATA) || !(csamples & 1))) update_error_limit (w, flags); if (ones_count == 0) { low = 0; high = GET_MED (0) - 1; DEC_MED0 (); } else { low = GET_MED (0); INC_MED0 (); if (ones_count == 1) { high = low + GET_MED (1) - 1; DEC_MED1 (); } else { low += GET_MED (1); INC_MED1 (); if (ones_count == 2) { high = low + GET_MED (2) - 1; DEC_MED2 (); } else { low += (ones_count - 2) * GET_MED (2); high = low + GET_MED (2) - 1; INC_MED2 (); } } } mid = (high + low + 1) >> 1; if (!c->error_limit) mid = read_code (bs, high - low) + low; else while (high - low > c->error_limit) { if (getbit (bs)) mid = (high + (low = mid) + 1) >> 1; else mid = ((high = mid - 1) + low + 1) >> 1; } *buffer++ = getbit (bs) ? ~mid : mid; if (flags & HYBRID_BITRATE) c->slow_level = c->slow_level - ((c->slow_level + SLO) >> SLS) + mylog2 (mid); } return (flags & MONO_DATA) ? csamples : (csamples / 2); } // Read a single unsigned value from the specified bitstream with a value // from 0 to maxcode. If there are exactly a power of two number of possible // codes then this will read a fixed number of bits; otherwise it reads the // minimum number of bits and then determines whether another bit is needed // to define the code. static uint32_t read_code (Bitstream *bs, uint32_t maxcode) { int bitcount = count_bits (maxcode); uint32_t extras = (1L << bitcount) - maxcode - 1, code; if (!bitcount) return 0; getbits (&code, bitcount - 1, bs); code &= (1L << (bitcount - 1)) - 1; if (code >= extras) { code = (code << 1) - extras; if (getbit (bs)) ++code; } return code; } // The concept of a base 2 logarithm is used in many parts of WavPack. It is // a way of sufficiently accurately representing 32-bit signed and unsigned // values storing only 16 bits (actually fewer). It is also used in the hybrid // mode for quickly comparing the relative magnitude of large values (i.e. // division) and providing smooth exponentials using only addition. // These are not strict logarithms in that they become linear around zero and // can therefore represent both zero and negative values. They have 8 bits // of precision and in "roundtrip" conversions the total error never exceeds 1 // part in 225 except for the cases of +/-115 and +/-195 (which error by 1). // This function returns the log2 for the specified 32-bit unsigned value. // The maximum value allowed is about 0xff800000 and returns 8447. static int mylog2 (uint32_t avalue) { int dbits; if ((avalue += avalue >> 9) < (1 << 8)) { dbits = nbits_table [avalue]; return (dbits << 8) + log2_table [(avalue << (9 - dbits)) & 0xff]; } else { if (avalue < (1L << 16)) dbits = nbits_table [avalue >> 8] + 8; else if (avalue < (1L << 24)) dbits = nbits_table [avalue >> 16] + 16; else dbits = nbits_table [avalue >> 24] + 24; return (dbits << 8) + log2_table [(avalue >> (dbits - 9)) & 0xff]; } } // This function returns the log2 for the specified 32-bit signed value. // All input values are valid and the return values are in the range of // +/- 8192. int log2s (int32_t value) { return (value < 0) ? -mylog2 (-value) : mylog2 (value); } // This function returns the original integer represented by the supplied // logarithm (at least within the provided accuracy). The log is signed, // but since a full 32-bit value is returned this can be used for unsigned // conversions as well (i.e. the input range is -8192 to +8447). int32_t exp2s (int log) { uint32_t value; if (log < 0) return -exp2s (-log); value = exp2_table [log & 0xff] | 0x100; if ((log >>= 8) <= 9) return value >> (9 - log); else return value << (log - 9); } // These two functions convert internal weights (which are normally +/-1024) // to and from an 8-bit signed character version for storage in metadata. The // weights are clipped here in the case that they are outside that range. int restore_weight (signed char weight) { int result; if ((result = (int) weight << 3) > 0) result += (result + 64) >> 7; return result; } ================================================ FILE: src/engine/external/wavpack/wputils.c ================================================ //////////////////////////////////////////////////////////////////////////// // **** WAVPACK **** // // Hybrid Lossless Wavefile Compressor // // Copyright (c) 1998 - 2006 Conifer Software. // // All Rights Reserved. // // Distributed under the BSD Software License (see license.txt) // //////////////////////////////////////////////////////////////////////////// // wputils.c // This module provides a high-level interface for decoding WavPack 4.0 audio // streams and files. WavPack data is read with a stream reading callback. No // direct seeking is provided for, but it is possible to start decoding // anywhere in a WavPack stream. In this case, WavPack will be able to provide // the sample-accurate position when it synchs with the data and begins // decoding. #include "wavpack.h" #include <string.h> ///////////////////////////// local table storage //////////////////////////// const uint32_t sample_rates [] = { 6000, 8000, 9600, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000, 64000, 88200, 96000, 192000 }; ///////////////////////////// executable code //////////////////////////////// static uint32_t read_next_header (read_stream infile, WavpackHeader *wphdr); // This function reads data from the specified stream in search of a valid // WavPack 4.0 audio block. If this fails in 1 megabyte (or an invalid or // unsupported WavPack block is encountered) then an appropriate message is // copied to "error" and NULL is returned, otherwise a pointer to a // WavpackContext structure is returned (which is used to call all other // functions in this module). This can be initiated at the beginning of a // WavPack file, or anywhere inside a WavPack file. To determine the exact // position within the file use WavpackGetSampleIndex(). For demonstration // purposes this uses a single static copy of the WavpackContext structure, // so obviously it cannot be used for more than one file at a time. Also, // this function will not handle "correction" files, plays only the first // two channels of multi-channel files, and is limited in resolution in some // large integer or floating point files (but always provides at least 24 bits // of resolution). static WavpackContext wpc; WavpackContext *WavpackOpenFileInput (read_stream infile, char *error) { WavpackStream *wps = &wpc.stream; uint32_t bcount; CLEAR (wpc); wpc.infile = infile; wpc.total_samples = (uint32_t) -1; wpc.norm_offset = 0; wpc.open_flags = 0; // open the source file for reading and store the size while (!wps->wphdr.block_samples) { bcount = read_next_header (wpc.infile, &wps->wphdr); if (bcount == (uint32_t) -1) { strcpy (error, "not compatible with this version of WavPack file!"); return NULL; } if (wps->wphdr.block_samples && wps->wphdr.total_samples != (uint32_t) -1) wpc.total_samples = wps->wphdr.total_samples; if (!unpack_init (&wpc)) { strcpy (error, wpc.error_message [0] ? wpc.error_message : "not compatible with this version of WavPack file!"); return NULL; } } wpc.config.flags &= ~0xff; wpc.config.flags |= wps->wphdr.flags & 0xff; wpc.config.bytes_per_sample = (wps->wphdr.flags & BYTES_STORED) + 1; wpc.config.float_norm_exp = wps->float_norm_exp; wpc.config.bits_per_sample = (wpc.config.bytes_per_sample * 8) - ((wps->wphdr.flags & SHIFT_MASK) >> SHIFT_LSB); if (wpc.config.flags & FLOAT_DATA) { wpc.config.bytes_per_sample = 3; wpc.config.bits_per_sample = 24; } if (!wpc.config.sample_rate) { if (!wps || !wps->wphdr.block_samples || (wps->wphdr.flags & SRATE_MASK) == SRATE_MASK) wpc.config.sample_rate = 44100; else wpc.config.sample_rate = sample_rates [(wps->wphdr.flags & SRATE_MASK) >> SRATE_LSB]; } if (!wpc.config.num_channels) { wpc.config.num_channels = (wps->wphdr.flags & MONO_FLAG) ? 1 : 2; wpc.config.channel_mask = 0x5 - wpc.config.num_channels; } if (!(wps->wphdr.flags & FINAL_BLOCK)) wpc.reduced_channels = (wps->wphdr.flags & MONO_FLAG) ? 1 : 2; return &wpc; } // This function obtains general information about an open file and returns // a mask with the following bit values: // MODE_LOSSLESS: file is lossless (pure lossless only) // MODE_HYBRID: file is hybrid mode (lossy part only) // MODE_FLOAT: audio data is 32-bit ieee floating point (but will provided // in 24-bit integers for convenience) // MODE_HIGH: file was created in "high" mode (information only) // MODE_FAST: file was created in "fast" mode (information only) int WavpackGetMode (WavpackContext *wpc) { int mode = 0; if (wpc) { if (wpc->config.flags & CONFIG_HYBRID_FLAG) mode |= MODE_HYBRID; else if (!(wpc->config.flags & CONFIG_LOSSY_MODE)) mode |= MODE_LOSSLESS; if (wpc->lossy_blocks) mode &= ~MODE_LOSSLESS; if (wpc->config.flags & CONFIG_FLOAT_DATA) mode |= MODE_FLOAT; if (wpc->config.flags & CONFIG_HIGH_FLAG) mode |= MODE_HIGH; if (wpc->config.flags & CONFIG_FAST_FLAG) mode |= MODE_FAST; } return mode; } // Unpack the specified number of samples from the current file position. // Note that "samples" here refers to "complete" samples, which would be // 2 longs for stereo files. The audio data is returned right-justified in // 32-bit longs in the endian mode native to the executing processor. So, // if the original data was 16-bit, then the values returned would be // +/-32k. Floating point data will be returned as 24-bit integers (and may // also be clipped). The actual number of samples unpacked is returned, // which should be equal to the number requested unless the end of fle is // encountered or an error occurs. uint32_t WavpackUnpackSamples (WavpackContext *wpc, int32_t *buffer, uint32_t samples) { WavpackStream *wps = &wpc->stream; uint32_t bcount, samples_unpacked = 0, samples_to_unpack; int num_channels = wpc->config.num_channels; while (samples) { if (!wps->wphdr.block_samples || !(wps->wphdr.flags & INITIAL_BLOCK) || wps->sample_index >= wps->wphdr.block_index + wps->wphdr.block_samples) { bcount = read_next_header (wpc->infile, &wps->wphdr); if (bcount == (uint32_t) -1) break; if (!wps->wphdr.block_samples || wps->sample_index == wps->wphdr.block_index) if (!unpack_init (wpc)) break; } if (!wps->wphdr.block_samples || !(wps->wphdr.flags & INITIAL_BLOCK) || wps->sample_index >= wps->wphdr.block_index + wps->wphdr.block_samples) continue; if (wps->sample_index < wps->wphdr.block_index) { samples_to_unpack = wps->wphdr.block_index - wps->sample_index; if (samples_to_unpack > samples) samples_to_unpack = samples; wps->sample_index += samples_to_unpack; samples_unpacked += samples_to_unpack; samples -= samples_to_unpack; if (wpc->reduced_channels) samples_to_unpack *= wpc->reduced_channels; else samples_to_unpack *= num_channels; while (samples_to_unpack--) *buffer++ = 0; continue; } samples_to_unpack = wps->wphdr.block_index + wps->wphdr.block_samples - wps->sample_index; if (samples_to_unpack > samples) samples_to_unpack = samples; unpack_samples (wpc, buffer, samples_to_unpack); if (wpc->reduced_channels) buffer += samples_to_unpack * wpc->reduced_channels; else buffer += samples_to_unpack * num_channels; samples_unpacked += samples_to_unpack; samples -= samples_to_unpack; if (wps->sample_index == wps->wphdr.block_index + wps->wphdr.block_samples) { if (check_crc_error (wpc)) wpc->crc_errors++; } if (wps->sample_index == wpc->total_samples) break; } return samples_unpacked; } // Get total number of samples contained in the WavPack file, or -1 if unknown uint32_t WavpackGetNumSamples (WavpackContext *wpc) { return wpc ? wpc->total_samples : (uint32_t) -1; } // Get the current sample index position, or -1 if unknown uint32_t WavpackGetSampleIndex (WavpackContext *wpc) { if (wpc) return wpc->stream.sample_index; return (uint32_t) -1; } // Get the number of errors encountered so far int WavpackGetNumErrors (WavpackContext *wpc) { return wpc ? wpc->crc_errors : 0; } // return TRUE if any uncorrected lossy blocks were actually written or read int WavpackLossyBlocks (WavpackContext *wpc) { return wpc ? wpc->lossy_blocks : 0; } // Returns the sample rate of the specified WavPack file uint32_t WavpackGetSampleRate (WavpackContext *wpc) { return wpc ? wpc->config.sample_rate : 44100; } // Returns the number of channels of the specified WavPack file. Note that // this is the actual number of channels contained in the file, but this // version can only decode the first two. int WavpackGetNumChannels (WavpackContext *wpc) { return wpc ? wpc->config.num_channels : 2; } // Returns the actual number of valid bits per sample contained in the // original file, which may or may not be a multiple of 8. Floating data // always has 32 bits, integers may be from 1 to 32 bits each. When this // value is not a multiple of 8, then the "extra" bits are located in the // LSBs of the results. That is, values are right justified when unpacked // into longs, but are left justified in the number of bytes used by the // original data. int WavpackGetBitsPerSample (WavpackContext *wpc) { return wpc ? wpc->config.bits_per_sample : 16; } // Returns the number of bytes used for each sample (1 to 4) in the original // file. This is required information for the user of this module because the // audio data is returned in the LOWER bytes of the long buffer and must be // left-shifted 8, 16, or 24 bits if normalized longs are required. int WavpackGetBytesPerSample (WavpackContext *wpc) { return wpc ? wpc->config.bytes_per_sample : 2; } // This function will return the actual number of channels decoded from the // file (which may or may not be less than the actual number of channels, but // will always be 1 or 2). Normally, this will be the front left and right // channels of a multi-channel file. int WavpackGetReducedChannels (WavpackContext *wpc) { if (wpc) return wpc->reduced_channels ? wpc->reduced_channels : wpc->config.num_channels; else return 2; } // Read from current file position until a valid 32-byte WavPack 4.0 header is // found and read into the specified pointer. The number of bytes skipped is // returned. If no WavPack header is found within 1 meg, then a -1 is returned // to indicate the error. No additional bytes are read past the header and it // is returned in the processor's native endian mode. Seeking is not required. static uint32_t read_next_header (read_stream infile, WavpackHeader *wphdr) { char buffer [sizeof (*wphdr)], *sp = buffer + sizeof (*wphdr), *ep = sp; uint32_t bytes_skipped = 0; int bleft; while (1) { if (sp < ep) { bleft = ep - sp; memcpy (buffer, sp, bleft); } else bleft = 0; if (infile (buffer + bleft, sizeof (*wphdr) - bleft) != (int32_t) sizeof (*wphdr) - bleft) return -1; sp = buffer; if (*sp++ == 'w' && *sp == 'v' && *++sp == 'p' && *++sp == 'k' && !(*++sp & 1) && sp [2] < 16 && !sp [3] && sp [5] == 4 && sp [4] >= (MIN_STREAM_VERS & 0xff) && sp [4] <= (MAX_STREAM_VERS & 0xff)) { memcpy (wphdr, buffer, sizeof (*wphdr)); little_endian_to_native (wphdr, WavpackHeaderFormat); return bytes_skipped; } while (sp < ep && *sp != 'w') sp++; if ((bytes_skipped += sp - buffer) > 1048576L) return -1; } } ================================================ FILE: src/engine/external/wavpack/wvfilter.c.no_compile ================================================ //////////////////////////////////////////////////////////////////////////// // **** WAVPACK **** // // Hybrid Lossless Wavefile Compressor // // Copyright (c) 1998 - 2006 Conifer Software. // // All Rights Reserved. // // Distributed under the BSD Software License (see license.txt) // //////////////////////////////////////////////////////////////////////////// // wv_filter.c // This is the main module for the demonstration WavPack command-line // decoder filter. It uses the tiny "hardware" version of the decoder and // accepts WavPack files on stdin and outputs a standard MS wav file to // stdout. Note that this involves converting the data to little-endian // (if the executing processor is not), possibly packing the data into // fewer bytes per sample, and generating an appropriate riff wav header. // Note that this is NOT the copy of the RIFF header that might be stored // in the file, and any additional RIFF information and tags are lost. // See wputils.c for further limitations. #include "wavpack.h" #if defined(WIN32) #include <io.h> #include <fcntl.h> #endif #include <string.h> // These structures are used to place a wav riff header at the beginning of // the output. typedef struct { char ckID [4]; uint32_t ckSize; char formType [4]; } RiffChunkHeader; typedef struct { char ckID [4]; uint32_t ckSize; } ChunkHeader; #define ChunkHeaderFormat "4L" typedef struct { ushort FormatTag, NumChannels; uint32_t SampleRate, BytesPerSecond; ushort BlockAlign, BitsPerSample; } WaveHeader; #define WaveHeaderFormat "SSLLSS" static uchar *format_samples (int bps, uchar *dst, int32_t *src, uint32_t samcnt); static int32_t read_bytes (void *buff, int32_t bcount); static int32_t temp_buffer [256]; int main () { ChunkHeader FormatChunkHeader, DataChunkHeader; RiffChunkHeader RiffChunkHeader; WaveHeader WaveHeader; uint32_t total_unpacked_samples = 0, total_samples; int num_channels, bps; WavpackContext *wpc; char error [80]; #if defined(WIN32) setmode (fileno (stdin), O_BINARY); setmode (fileno (stdout), O_BINARY); #endif wpc = WavpackOpenFileInput (read_bytes, error); if (!wpc) { fputs (error, stderr); fputs ("\n", stderr); return 1; } num_channels = WavpackGetReducedChannels (wpc); total_samples = WavpackGetNumSamples (wpc); bps = WavpackGetBytesPerSample (wpc); strncpy (RiffChunkHeader.ckID, "RIFF", sizeof (RiffChunkHeader.ckID)); RiffChunkHeader.ckSize = total_samples * num_channels * bps + sizeof (ChunkHeader) * 2 + sizeof (WaveHeader) + 4; strncpy (RiffChunkHeader.formType, "WAVE", sizeof (RiffChunkHeader.formType)); strncpy (FormatChunkHeader.ckID, "fmt ", sizeof (FormatChunkHeader.ckID)); FormatChunkHeader.ckSize = sizeof (WaveHeader); WaveHeader.FormatTag = 1; WaveHeader.NumChannels = num_channels; WaveHeader.SampleRate = WavpackGetSampleRate (wpc); WaveHeader.BlockAlign = num_channels * bps; WaveHeader.BytesPerSecond = WaveHeader.SampleRate * WaveHeader.BlockAlign; WaveHeader.BitsPerSample = WavpackGetBitsPerSample (wpc); strncpy (DataChunkHeader.ckID, "data", sizeof (DataChunkHeader.ckID)); DataChunkHeader.ckSize = total_samples * num_channels * bps; native_to_little_endian (&RiffChunkHeader, ChunkHeaderFormat); native_to_little_endian (&FormatChunkHeader, ChunkHeaderFormat); native_to_little_endian (&WaveHeader, WaveHeaderFormat); native_to_little_endian (&DataChunkHeader, ChunkHeaderFormat); if (!fwrite (&RiffChunkHeader, sizeof (RiffChunkHeader), 1, stdout) || !fwrite (&FormatChunkHeader, sizeof (FormatChunkHeader), 1, stdout) || !fwrite (&WaveHeader, sizeof (WaveHeader), 1, stdout) || !fwrite (&DataChunkHeader, sizeof (DataChunkHeader), 1, stdout)) { fputs ("can't write .WAV data, disk probably full!\n", stderr); return 1; } while (1) { uint32_t samples_unpacked; samples_unpacked = WavpackUnpackSamples (wpc, temp_buffer, 256 / num_channels); total_unpacked_samples += samples_unpacked; if (samples_unpacked) { format_samples (bps, (uchar *) temp_buffer, temp_buffer, samples_unpacked *= num_channels); if (fwrite (temp_buffer, bps, samples_unpacked, stdout) != samples_unpacked) { fputs ("can't write .WAV data, disk probably full!\n", stderr); return 1; } } if (!samples_unpacked) break; } fflush (stdout); if (WavpackGetNumSamples (wpc) != (uint32_t) -1 && total_unpacked_samples != WavpackGetNumSamples (wpc)) { fputs ("incorrect number of samples!\n", stderr); return 1; } if (WavpackGetNumErrors (wpc)) { fputs ("crc errors detected!\n", stderr); return 1; } return 0; } static int32_t read_bytes (void *buff, int32_t bcount) { return fread (buff, 1, bcount, stdin); } // Reformat samples from longs in processor's native endian mode to // little-endian data with (possibly) less than 4 bytes / sample. static uchar *format_samples (int bps, uchar *dst, int32_t *src, uint32_t samcnt) { int32_t temp; switch (bps) { case 1: while (samcnt--) *dst++ = *src++ + 128; break; case 2: while (samcnt--) { *dst++ = (uchar)(temp = *src++); *dst++ = (uchar)(temp >> 8); } break; case 3: while (samcnt--) { *dst++ = (uchar)(temp = *src++); *dst++ = (uchar)(temp >> 8); *dst++ = (uchar)(temp >> 16); } break; case 4: while (samcnt--) { *dst++ = (uchar)(temp = *src++); *dst++ = (uchar)(temp >> 8); *dst++ = (uchar)(temp >> 16); *dst++ = (uchar)(temp >> 24); } break; } return dst; } ================================================ FILE: src/engine/external/zlib/VERSION ================================================ 1.2.5 ================================================ FILE: src/engine/external/zlib/adler32.c ================================================ /* adler32.c -- compute the Adler-32 checksum of a data stream * Copyright (C) 1995-2007 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ /* @(#) $Id$ */ #include "zutil.h" #define local static local uLong adler32_combine_(uLong adler1, uLong adler2, z_off64_t len2); #define BASE 65521UL /* largest prime smaller than 65536 */ #define NMAX 5552 /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */ #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;} #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1); #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2); #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4); #define DO16(buf) DO8(buf,0); DO8(buf,8); /* use NO_DIVIDE if your processor does not do division in hardware */ #ifdef NO_DIVIDE # define MOD(a) \ do { \ if (a >= (BASE << 16)) a -= (BASE << 16); \ if (a >= (BASE << 15)) a -= (BASE << 15); \ if (a >= (BASE << 14)) a -= (BASE << 14); \ if (a >= (BASE << 13)) a -= (BASE << 13); \ if (a >= (BASE << 12)) a -= (BASE << 12); \ if (a >= (BASE << 11)) a -= (BASE << 11); \ if (a >= (BASE << 10)) a -= (BASE << 10); \ if (a >= (BASE << 9)) a -= (BASE << 9); \ if (a >= (BASE << 8)) a -= (BASE << 8); \ if (a >= (BASE << 7)) a -= (BASE << 7); \ if (a >= (BASE << 6)) a -= (BASE << 6); \ if (a >= (BASE << 5)) a -= (BASE << 5); \ if (a >= (BASE << 4)) a -= (BASE << 4); \ if (a >= (BASE << 3)) a -= (BASE << 3); \ if (a >= (BASE << 2)) a -= (BASE << 2); \ if (a >= (BASE << 1)) a -= (BASE << 1); \ if (a >= BASE) a -= BASE; \ } while (0) # define MOD4(a) \ do { \ if (a >= (BASE << 4)) a -= (BASE << 4); \ if (a >= (BASE << 3)) a -= (BASE << 3); \ if (a >= (BASE << 2)) a -= (BASE << 2); \ if (a >= (BASE << 1)) a -= (BASE << 1); \ if (a >= BASE) a -= BASE; \ } while (0) #else # define MOD(a) a %= BASE # define MOD4(a) a %= BASE #endif /* ========================================================================= */ uLong ZEXPORT adler32(adler, buf, len) uLong adler; const Bytef *buf; uInt len; { unsigned long sum2; unsigned n; /* split Adler-32 into component sums */ sum2 = (adler >> 16) & 0xffff; adler &= 0xffff; /* in case user likes doing a byte at a time, keep it fast */ if (len == 1) { adler += buf[0]; if (adler >= BASE) adler -= BASE; sum2 += adler; if (sum2 >= BASE) sum2 -= BASE; return adler | (sum2 << 16); } /* initial Adler-32 value (deferred check for len == 1 speed) */ if (buf == Z_NULL) return 1L; /* in case short lengths are provided, keep it somewhat fast */ if (len < 16) { while (len--) { adler += *buf++; sum2 += adler; } if (adler >= BASE) adler -= BASE; MOD4(sum2); /* only added so many BASE's */ return adler | (sum2 << 16); } /* do length NMAX blocks -- requires just one modulo operation */ while (len >= NMAX) { len -= NMAX; n = NMAX / 16; /* NMAX is divisible by 16 */ do { DO16(buf); /* 16 sums unrolled */ buf += 16; } while (--n); MOD(adler); MOD(sum2); } /* do remaining bytes (less than NMAX, still just one modulo) */ if (len) { /* avoid modulos if none remaining */ while (len >= 16) { len -= 16; DO16(buf); buf += 16; } while (len--) { adler += *buf++; sum2 += adler; } MOD(adler); MOD(sum2); } /* return recombined sums */ return adler | (sum2 << 16); } /* ========================================================================= */ local uLong adler32_combine_(adler1, adler2, len2) uLong adler1; uLong adler2; z_off64_t len2; { unsigned long sum1; unsigned long sum2; unsigned rem; /* the derivation of this formula is left as an exercise for the reader */ rem = (unsigned)(len2 % BASE); sum1 = adler1 & 0xffff; sum2 = rem * sum1; MOD(sum2); sum1 += (adler2 & 0xffff) + BASE - 1; sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem; if (sum1 >= BASE) sum1 -= BASE; if (sum1 >= BASE) sum1 -= BASE; if (sum2 >= (BASE << 1)) sum2 -= (BASE << 1); if (sum2 >= BASE) sum2 -= BASE; return sum1 | (sum2 << 16); } /* ========================================================================= */ uLong ZEXPORT adler32_combine(adler1, adler2, len2) uLong adler1; uLong adler2; z_off_t len2; { return adler32_combine_(adler1, adler2, len2); } uLong ZEXPORT adler32_combine64(adler1, adler2, len2) uLong adler1; uLong adler2; z_off64_t len2; { return adler32_combine_(adler1, adler2, len2); } ================================================ FILE: src/engine/external/zlib/compress.c ================================================ /* compress.c -- compress a memory buffer * Copyright (C) 1995-2005 Jean-loup Gailly. * For conditions of distribution and use, see copyright notice in zlib.h */ /* @(#) $Id$ */ #define ZLIB_INTERNAL #include "zlib.h" /* =========================================================================== Compresses the source buffer into the destination buffer. The level parameter has the same meaning as in deflateInit. sourceLen is the byte length of the source buffer. Upon entry, destLen is the total size of the destination buffer, which must be at least 0.1% larger than sourceLen plus 12 bytes. Upon exit, destLen is the actual size of the compressed buffer. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if there was not enough room in the output buffer, Z_STREAM_ERROR if the level parameter is invalid. */ int ZEXPORT compress2 (dest, destLen, source, sourceLen, level) Bytef *dest; uLongf *destLen; const Bytef *source; uLong sourceLen; int level; { z_stream stream; int err; stream.next_in = (Bytef*)source; stream.avail_in = (uInt)sourceLen; #ifdef MAXSEG_64K /* Check for source > 64K on 16-bit machine: */ if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR; #endif stream.next_out = dest; stream.avail_out = (uInt)*destLen; if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR; stream.zalloc = (alloc_func)0; stream.zfree = (free_func)0; stream.opaque = (voidpf)0; err = deflateInit(&stream, level); if (err != Z_OK) return err; err = deflate(&stream, Z_FINISH); if (err != Z_STREAM_END) { deflateEnd(&stream); return err == Z_OK ? Z_BUF_ERROR : err; } *destLen = stream.total_out; err = deflateEnd(&stream); return err; } /* =========================================================================== */ int ZEXPORT compress (dest, destLen, source, sourceLen) Bytef *dest; uLongf *destLen; const Bytef *source; uLong sourceLen; { return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION); } /* =========================================================================== If the default memLevel or windowBits for deflateInit() is changed, then this function needs to be updated. */ uLong ZEXPORT compressBound (sourceLen) uLong sourceLen; { return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + (sourceLen >> 25) + 13; } ================================================ FILE: src/engine/external/zlib/crc32.c ================================================ /* crc32.c -- compute the CRC-32 of a data stream * Copyright (C) 1995-2006, 2010 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h * * Thanks to Rodney Brown <rbrown64@csc.com.au> for his contribution of faster * CRC methods: exclusive-oring 32 bits of data at a time, and pre-computing * tables for updating the shift register in one step with three exclusive-ors * instead of four steps with four exclusive-ors. This results in about a * factor of two increase in speed on a Power PC G4 (PPC7455) using gcc -O3. */ /* @(#) $Id$ */ /* Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore protection on the static variables used to control the first-use generation of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should first call get_crc_table() to initialize the tables before allowing more than one thread to use crc32(). */ #ifdef MAKECRCH # include <stdio.h> # ifndef DYNAMIC_CRC_TABLE # define DYNAMIC_CRC_TABLE # endif /* !DYNAMIC_CRC_TABLE */ #endif /* MAKECRCH */ #include "zutil.h" /* for STDC and FAR definitions */ #define local static /* Find a four-byte integer type for crc32_little() and crc32_big(). */ #ifndef NOBYFOUR # ifdef STDC /* need ANSI C limits.h to determine sizes */ # include <limits.h> # define BYFOUR # if (UINT_MAX == 0xffffffffUL) typedef unsigned int u4; # else # if (ULONG_MAX == 0xffffffffUL) typedef unsigned long u4; # else # if (USHRT_MAX == 0xffffffffUL) typedef unsigned short u4; # else # undef BYFOUR /* can't find a four-byte integer type! */ # endif # endif # endif # endif /* STDC */ #endif /* !NOBYFOUR */ /* Definitions for doing the crc four data bytes at a time. */ #ifdef BYFOUR # define REV(w) ((((w)>>24)&0xff)+(((w)>>8)&0xff00)+ \ (((w)&0xff00)<<8)+(((w)&0xff)<<24)) local unsigned long crc32_little OF((unsigned long, const unsigned char FAR *, unsigned)); local unsigned long crc32_big OF((unsigned long, const unsigned char FAR *, unsigned)); # define TBLS 8 #else # define TBLS 1 #endif /* BYFOUR */ /* Local functions for crc concatenation */ local unsigned long gf2_matrix_times OF((unsigned long *mat, unsigned long vec)); local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat)); local uLong crc32_combine_(uLong crc1, uLong crc2, z_off64_t len2); #ifdef DYNAMIC_CRC_TABLE local volatile int crc_table_empty = 1; local unsigned long FAR crc_table[TBLS][256]; local void make_crc_table OF((void)); #ifdef MAKECRCH local void write_table OF((FILE *, const unsigned long FAR *)); #endif /* MAKECRCH */ /* Generate tables for a byte-wise 32-bit CRC calculation on the polynomial: x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1. Polynomials over GF(2) are represented in binary, one bit per coefficient, with the lowest powers in the most significant bit. Then adding polynomials is just exclusive-or, and multiplying a polynomial by x is a right shift by one. If we call the above polynomial p, and represent a byte as the polynomial q, also with the lowest power in the most significant bit (so the byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p, where a mod b means the remainder after dividing a by b. This calculation is done using the shift-register method of multiplying and taking the remainder. The register is initialized to zero, and for each incoming bit, x^32 is added mod p to the register if the bit is a one (where x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by x (which is shifting right by one and adding x^32 mod p if the bit shifted out is a one). We start with the highest power (least significant bit) of q and repeat for all eight bits of q. The first table is simply the CRC of all possible eight bit values. This is all the information needed to generate CRCs on data a byte at a time for all combinations of CRC register values and incoming bytes. The remaining tables allow for word-at-a-time CRC calculation for both big-endian and little- endian machines, where a word is four bytes. */ local void make_crc_table() { unsigned long c; int n, k; unsigned long poly; /* polynomial exclusive-or pattern */ /* terms of polynomial defining this crc (except x^32): */ static volatile int first = 1; /* flag to limit concurrent making */ static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26}; /* See if another task is already doing this (not thread-safe, but better than nothing -- significantly reduces duration of vulnerability in case the advice about DYNAMIC_CRC_TABLE is ignored) */ if (first) { first = 0; /* make exclusive-or pattern from polynomial (0xedb88320UL) */ poly = 0UL; for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++) poly |= 1UL << (31 - p[n]); /* generate a crc for every 8-bit value */ for (n = 0; n < 256; n++) { c = (unsigned long)n; for (k = 0; k < 8; k++) c = c & 1 ? poly ^ (c >> 1) : c >> 1; crc_table[0][n] = c; } #ifdef BYFOUR /* generate crc for each value followed by one, two, and three zeros, and then the byte reversal of those as well as the first table */ for (n = 0; n < 256; n++) { c = crc_table[0][n]; crc_table[4][n] = REV(c); for (k = 1; k < 4; k++) { c = crc_table[0][c & 0xff] ^ (c >> 8); crc_table[k][n] = c; crc_table[k + 4][n] = REV(c); } } #endif /* BYFOUR */ crc_table_empty = 0; } else { /* not first */ /* wait for the other guy to finish (not efficient, but rare) */ while (crc_table_empty) ; } #ifdef MAKECRCH /* write out CRC tables to crc32.h */ { FILE *out; out = fopen("crc32.h", "w"); if (out == NULL) return; fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n"); fprintf(out, " * Generated automatically by crc32.c\n */\n\n"); fprintf(out, "local const unsigned long FAR "); fprintf(out, "crc_table[TBLS][256] =\n{\n {\n"); write_table(out, crc_table[0]); # ifdef BYFOUR fprintf(out, "#ifdef BYFOUR\n"); for (k = 1; k < 8; k++) { fprintf(out, " },\n {\n"); write_table(out, crc_table[k]); } fprintf(out, "#endif\n"); # endif /* BYFOUR */ fprintf(out, " }\n};\n"); fclose(out); } #endif /* MAKECRCH */ } #ifdef MAKECRCH local void write_table(out, table) FILE *out; const unsigned long FAR *table; { int n; for (n = 0; n < 256; n++) fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n], n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", ")); } #endif /* MAKECRCH */ #else /* !DYNAMIC_CRC_TABLE */ /* ======================================================================== * Tables of CRC-32s of all single-byte values, made by make_crc_table(). */ #include "crc32.h" #endif /* DYNAMIC_CRC_TABLE */ /* ========================================================================= * This function can be used by asm versions of crc32() */ const unsigned long FAR * ZEXPORT get_crc_table() { #ifdef DYNAMIC_CRC_TABLE if (crc_table_empty) make_crc_table(); #endif /* DYNAMIC_CRC_TABLE */ return (const unsigned long FAR *)crc_table; } /* ========================================================================= */ #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8) #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1 /* ========================================================================= */ unsigned long ZEXPORT crc32(crc, buf, len) unsigned long crc; const unsigned char FAR *buf; uInt len; { if (buf == Z_NULL) return 0UL; #ifdef DYNAMIC_CRC_TABLE if (crc_table_empty) make_crc_table(); #endif /* DYNAMIC_CRC_TABLE */ #ifdef BYFOUR if (sizeof(void *) == sizeof(ptrdiff_t)) { u4 endian; endian = 1; if (*((unsigned char *)(&endian))) return crc32_little(crc, buf, len); else return crc32_big(crc, buf, len); } #endif /* BYFOUR */ crc = crc ^ 0xffffffffUL; while (len >= 8) { DO8; len -= 8; } if (len) do { DO1; } while (--len); return crc ^ 0xffffffffUL; } #ifdef BYFOUR /* ========================================================================= */ #define DOLIT4 c ^= *buf4++; \ c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \ crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24] #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4 /* ========================================================================= */ local unsigned long crc32_little(crc, buf, len) unsigned long crc; const unsigned char FAR *buf; unsigned len; { register u4 c; register const u4 FAR *buf4; c = (u4)crc; c = ~c; while (len && ((ptrdiff_t)buf & 3)) { c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8); len--; } buf4 = (const u4 FAR *)(const void FAR *)buf; while (len >= 32) { DOLIT32; len -= 32; } while (len >= 4) { DOLIT4; len -= 4; } buf = (const unsigned char FAR *)buf4; if (len) do { c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8); } while (--len); c = ~c; return (unsigned long)c; } /* ========================================================================= */ #define DOBIG4 c ^= *++buf4; \ c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \ crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24] #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4 /* ========================================================================= */ local unsigned long crc32_big(crc, buf, len) unsigned long crc; const unsigned char FAR *buf; unsigned len; { register u4 c; register const u4 FAR *buf4; c = REV((u4)crc); c = ~c; while (len && ((ptrdiff_t)buf & 3)) { c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); len--; } buf4 = (const u4 FAR *)(const void FAR *)buf; buf4--; while (len >= 32) { DOBIG32; len -= 32; } while (len >= 4) { DOBIG4; len -= 4; } buf4++; buf = (const unsigned char FAR *)buf4; if (len) do { c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); } while (--len); c = ~c; return (unsigned long)(REV(c)); } #endif /* BYFOUR */ #define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */ /* ========================================================================= */ local unsigned long gf2_matrix_times(mat, vec) unsigned long *mat; unsigned long vec; { unsigned long sum; sum = 0; while (vec) { if (vec & 1) sum ^= *mat; vec >>= 1; mat++; } return sum; } /* ========================================================================= */ local void gf2_matrix_square(square, mat) unsigned long *square; unsigned long *mat; { int n; for (n = 0; n < GF2_DIM; n++) square[n] = gf2_matrix_times(mat, mat[n]); } /* ========================================================================= */ local uLong crc32_combine_(crc1, crc2, len2) uLong crc1; uLong crc2; z_off64_t len2; { int n; unsigned long row; unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */ unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */ /* degenerate case (also disallow negative lengths) */ if (len2 <= 0) return crc1; /* put operator for one zero bit in odd */ odd[0] = 0xedb88320UL; /* CRC-32 polynomial */ row = 1; for (n = 1; n < GF2_DIM; n++) { odd[n] = row; row <<= 1; } /* put operator for two zero bits in even */ gf2_matrix_square(even, odd); /* put operator for four zero bits in odd */ gf2_matrix_square(odd, even); /* apply len2 zeros to crc1 (first square will put the operator for one zero byte, eight zero bits, in even) */ do { /* apply zeros operator for this bit of len2 */ gf2_matrix_square(even, odd); if (len2 & 1) crc1 = gf2_matrix_times(even, crc1); len2 >>= 1; /* if no more bits set, then done */ if (len2 == 0) break; /* another iteration of the loop with odd and even swapped */ gf2_matrix_square(odd, even); if (len2 & 1) crc1 = gf2_matrix_times(odd, crc1); len2 >>= 1; /* if no more bits set, then done */ } while (len2 != 0); /* return combined crc */ crc1 ^= crc2; return crc1; } /* ========================================================================= */ uLong ZEXPORT crc32_combine(crc1, crc2, len2) uLong crc1; uLong crc2; z_off_t len2; { return crc32_combine_(crc1, crc2, len2); } uLong ZEXPORT crc32_combine64(crc1, crc2, len2) uLong crc1; uLong crc2; z_off64_t len2; { return crc32_combine_(crc1, crc2, len2); } ================================================ FILE: src/engine/external/zlib/crc32.h ================================================ /* crc32.h -- tables for rapid CRC calculation * Generated automatically by crc32.c */ local const unsigned long FAR crc_table[TBLS][256] = { { 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL, 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL, 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL, 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL, 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL, 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL, 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL, 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL, 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL, 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL, 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL, 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL, 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL, 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL, 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL, 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL, 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL, 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL, 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL, 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL, 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL, 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL, 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL, 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL, 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL, 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL, 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL, 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL, 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL, 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL, 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL, 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL, 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL, 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL, 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL, 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL, 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL, 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL, 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL, 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL, 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL, 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL, 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL, 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL, 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL, 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL, 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL, 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL, 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL, 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL, 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL, 0x2d02ef8dUL #ifdef BYFOUR }, { 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL, 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL, 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL, 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL, 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL, 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL, 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL, 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL, 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL, 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL, 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL, 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL, 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL, 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL, 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL, 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL, 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL, 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL, 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL, 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL, 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL, 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL, 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL, 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL, 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL, 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL, 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL, 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL, 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL, 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL, 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL, 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL, 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL, 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL, 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL, 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL, 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL, 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL, 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL, 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL, 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL, 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL, 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL, 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL, 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL, 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL, 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL, 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL, 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL, 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL, 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL, 0x9324fd72UL }, { 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL, 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL, 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL, 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL, 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL, 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL, 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL, 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL, 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL, 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL, 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL, 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL, 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL, 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL, 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL, 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL, 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL, 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL, 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL, 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL, 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL, 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL, 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL, 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL, 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL, 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL, 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL, 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL, 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL, 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL, 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL, 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL, 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL, 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL, 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL, 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL, 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL, 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL, 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL, 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL, 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL, 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL, 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL, 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL, 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL, 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL, 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL, 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL, 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL, 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL, 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL, 0xbe9834edUL }, { 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL, 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL, 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL, 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL, 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL, 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL, 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL, 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL, 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL, 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL, 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL, 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL, 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL, 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL, 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL, 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL, 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL, 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL, 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL, 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL, 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL, 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL, 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL, 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL, 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL, 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL, 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL, 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL, 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL, 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL, 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL, 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL, 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL, 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL, 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL, 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL, 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL, 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL, 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL, 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL, 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL, 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL, 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL, 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL, 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL, 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL, 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL, 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL, 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL, 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL, 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL, 0xde0506f1UL }, { 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL, 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL, 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL, 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL, 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL, 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL, 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL, 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL, 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL, 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL, 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL, 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL, 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL, 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL, 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL, 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL, 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL, 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL, 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL, 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL, 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL, 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL, 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL, 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL, 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL, 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL, 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL, 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL, 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL, 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL, 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL, 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL, 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL, 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL, 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL, 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL, 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL, 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL, 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL, 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL, 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL, 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL, 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL, 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL, 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL, 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL, 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL, 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL, 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL, 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL, 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL, 0x8def022dUL }, { 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL, 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL, 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL, 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL, 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL, 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL, 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL, 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL, 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL, 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL, 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL, 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL, 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL, 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL, 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL, 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL, 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL, 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL, 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL, 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL, 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL, 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL, 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL, 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL, 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL, 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL, 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL, 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL, 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL, 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL, 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL, 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL, 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL, 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL, 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL, 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL, 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL, 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL, 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL, 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL, 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL, 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL, 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL, 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL, 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL, 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL, 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL, 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL, 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL, 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL, 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL, 0x72fd2493UL }, { 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL, 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL, 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL, 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL, 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL, 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL, 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL, 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL, 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL, 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL, 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL, 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL, 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL, 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL, 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL, 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL, 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL, 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL, 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL, 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL, 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL, 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL, 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL, 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL, 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL, 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL, 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL, 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL, 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL, 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL, 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL, 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL, 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL, 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL, 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL, 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL, 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL, 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL, 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL, 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL, 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL, 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL, 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL, 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL, 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL, 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL, 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL, 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL, 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL, 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL, 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL, 0xed3498beUL }, { 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL, 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL, 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL, 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL, 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL, 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL, 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL, 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL, 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL, 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL, 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL, 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL, 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL, 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL, 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL, 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL, 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL, 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL, 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL, 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL, 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL, 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL, 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL, 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL, 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL, 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL, 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL, 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL, 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL, 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL, 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL, 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL, 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL, 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL, 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL, 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL, 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL, 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL, 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL, 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL, 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL, 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL, 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL, 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL, 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL, 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL, 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL, 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL, 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL, 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL, 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL, 0xf10605deUL #endif } }; ================================================ FILE: src/engine/external/zlib/deflate.c ================================================ /* deflate.c -- compress data using the deflation algorithm * Copyright (C) 1995-2010 Jean-loup Gailly and Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ /* * ALGORITHM * * The "deflation" process depends on being able to identify portions * of the input text which are identical to earlier input (within a * sliding window trailing behind the input currently being processed). * * The most straightforward technique turns out to be the fastest for * most input files: try all possible matches and select the longest. * The key feature of this algorithm is that insertions into the string * dictionary are very simple and thus fast, and deletions are avoided * completely. Insertions are performed at each input character, whereas * string matches are performed only when the previous match ends. So it * is preferable to spend more time in matches to allow very fast string * insertions and avoid deletions. The matching algorithm for small * strings is inspired from that of Rabin & Karp. A brute force approach * is used to find longer strings when a small match has been found. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze * (by Leonid Broukhis). * A previous version of this file used a more sophisticated algorithm * (by Fiala and Greene) which is guaranteed to run in linear amortized * time, but has a larger average cost, uses more memory and is patented. * However the F&G algorithm may be faster for some highly redundant * files if the parameter max_chain_length (described below) is too large. * * ACKNOWLEDGEMENTS * * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and * I found it in 'freeze' written by Leonid Broukhis. * Thanks to many people for bug reports and testing. * * REFERENCES * * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification". * Available in http://www.ietf.org/rfc/rfc1951.txt * * A description of the Rabin and Karp algorithm is given in the book * "Algorithms" by R. Sedgewick, Addison-Wesley, p252. * * Fiala,E.R., and Greene,D.H. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595 * */ /* @(#) $Id$ */ #include "deflate.h" const char deflate_copyright[] = " deflate 1.2.5 Copyright 1995-2010 Jean-loup Gailly and Mark Adler "; /* If you use the zlib library in a product, an acknowledgment is welcome in the documentation of your product. If for some reason you cannot include such an acknowledgment, I would appreciate that you keep this copyright string in the executable of your product. */ /* =========================================================================== * Function prototypes. */ typedef enum { need_more, /* block not completed, need more input or more output */ block_done, /* block flush performed */ finish_started, /* finish started, need only more output at next deflate */ finish_done /* finish done, accept no more input or output */ } block_state; typedef block_state (*compress_func) OF((deflate_state *s, int flush)); /* Compression function. Returns the block state after the call. */ local void fill_window OF((deflate_state *s)); local block_state deflate_stored OF((deflate_state *s, int flush)); local block_state deflate_fast OF((deflate_state *s, int flush)); #ifndef FASTEST local block_state deflate_slow OF((deflate_state *s, int flush)); #endif local block_state deflate_rle OF((deflate_state *s, int flush)); local block_state deflate_huff OF((deflate_state *s, int flush)); local void lm_init OF((deflate_state *s)); local void putShortMSB OF((deflate_state *s, uInt b)); local void flush_pending OF((z_streamp strm)); local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size)); #ifdef ASMV void match_init OF((void)); /* asm code initialization */ uInt longest_match OF((deflate_state *s, IPos cur_match)); #else local uInt longest_match OF((deflate_state *s, IPos cur_match)); #endif #ifdef DEBUG local void check_match OF((deflate_state *s, IPos start, IPos match, int length)); #endif /* =========================================================================== * Local data */ #define NIL 0 /* Tail of hash chains */ #ifndef TOO_FAR # define TOO_FAR 4096 #endif /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */ /* Values for max_lazy_match, good_match and max_chain_length, depending on * the desired pack level (0..9). The values given below have been tuned to * exclude worst case performance for pathological files. Better values may be * found for specific files. */ typedef struct config_s { ush good_length; /* reduce lazy search above this match length */ ush max_lazy; /* do not perform lazy search above this match length */ ush nice_length; /* quit search above this match length */ ush max_chain; compress_func func; } config; #ifdef FASTEST local const config configuration_table[2] = { /* good lazy nice chain */ /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */ /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */ #else local const config configuration_table[10] = { /* good lazy nice chain */ /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */ /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */ /* 2 */ {4, 5, 16, 8, deflate_fast}, /* 3 */ {4, 6, 32, 32, deflate_fast}, /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */ /* 5 */ {8, 16, 32, 32, deflate_slow}, /* 6 */ {8, 16, 128, 128, deflate_slow}, /* 7 */ {8, 32, 128, 256, deflate_slow}, /* 8 */ {32, 128, 258, 1024, deflate_slow}, /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */ #endif /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4 * For deflate_fast() (levels <= 3) good is ignored and lazy has a different * meaning. */ #define EQUAL 0 /* result of memcmp for equal strings */ #ifndef NO_DUMMY_DECL struct static_tree_desc_s {int dummy;}; /* for buggy compilers */ #endif /* =========================================================================== * Update a hash value with the given input byte * IN assertion: all calls to to UPDATE_HASH are made with consecutive * input characters, so that a running hash key can be computed from the * previous key instead of complete recalculation each time. */ #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask) /* =========================================================================== * Insert string str in the dictionary and set match_head to the previous head * of the hash chain (the most recent string with same hash key). Return * the previous length of the hash chain. * If this file is compiled with -DFASTEST, the compression level is forced * to 1, and no hash chains are maintained. * IN assertion: all calls to to INSERT_STRING are made with consecutive * input characters and the first MIN_MATCH bytes of str are valid * (except for the last MIN_MATCH-1 bytes of the input file). */ #ifdef FASTEST #define INSERT_STRING(s, str, match_head) \ (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ match_head = s->head[s->ins_h], \ s->head[s->ins_h] = (Pos)(str)) #else #define INSERT_STRING(s, str, match_head) \ (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \ s->head[s->ins_h] = (Pos)(str)) #endif /* =========================================================================== * Initialize the hash table (avoiding 64K overflow for 16 bit systems). * prev[] will be initialized on the fly. */ #define CLEAR_HASH(s) \ s->head[s->hash_size-1] = NIL; \ zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head)); /* ========================================================================= */ int ZEXPORT deflateInit_(strm, level, version, stream_size) z_streamp strm; int level; const char *version; int stream_size; { return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, version, stream_size); /* To do: ignore strm->next_in if we use it as window */ } /* ========================================================================= */ int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, version, stream_size) z_streamp strm; int level; int method; int windowBits; int memLevel; int strategy; const char *version; int stream_size; { deflate_state *s; int wrap = 1; static const char my_version[] = ZLIB_VERSION; ushf *overlay; /* We overlay pending_buf and d_buf+l_buf. This works since the average * output size for (length,distance) codes is <= 24 bits. */ if (version == Z_NULL || version[0] != my_version[0] || stream_size != sizeof(z_stream)) { return Z_VERSION_ERROR; } if (strm == Z_NULL) return Z_STREAM_ERROR; strm->msg = Z_NULL; if (strm->zalloc == (alloc_func)0) { strm->zalloc = zcalloc; strm->opaque = (voidpf)0; } if (strm->zfree == (free_func)0) strm->zfree = zcfree; #ifdef FASTEST if (level != 0) level = 1; #else if (level == Z_DEFAULT_COMPRESSION) level = 6; #endif if (windowBits < 0) { /* suppress zlib wrapper */ wrap = 0; windowBits = -windowBits; } #ifdef GZIP else if (windowBits > 15) { wrap = 2; /* write gzip wrapper instead */ windowBits -= 16; } #endif if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED || windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) { return Z_STREAM_ERROR; } if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */ s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state)); if (s == Z_NULL) return Z_MEM_ERROR; strm->state = (struct internal_state FAR *)s; s->strm = strm; s->wrap = wrap; s->gzhead = Z_NULL; s->w_bits = windowBits; s->w_size = 1 << s->w_bits; s->w_mask = s->w_size - 1; s->hash_bits = memLevel + 7; s->hash_size = 1 << s->hash_bits; s->hash_mask = s->hash_size - 1; s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH); s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte)); s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos)); s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos)); s->high_water = 0; /* nothing written to s->window yet */ s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); s->pending_buf = (uchf *) overlay; s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L); if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL || s->pending_buf == Z_NULL) { s->status = FINISH_STATE; strm->msg = (char*)ERR_MSG(Z_MEM_ERROR); deflateEnd (strm); return Z_MEM_ERROR; } s->d_buf = overlay + s->lit_bufsize/sizeof(ush); s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; s->level = level; s->strategy = strategy; s->method = (Byte)method; return deflateReset(strm); } /* ========================================================================= */ int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength) z_streamp strm; const Bytef *dictionary; uInt dictLength; { deflate_state *s; uInt length = dictLength; uInt n; IPos hash_head = 0; if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL || strm->state->wrap == 2 || (strm->state->wrap == 1 && strm->state->status != INIT_STATE)) return Z_STREAM_ERROR; s = strm->state; if (s->wrap) strm->adler = adler32(strm->adler, dictionary, dictLength); if (length < MIN_MATCH) return Z_OK; if (length > s->w_size) { length = s->w_size; dictionary += dictLength - length; /* use the tail of the dictionary */ } zmemcpy(s->window, dictionary, length); s->strstart = length; s->block_start = (long)length; /* Insert all strings in the hash table (except for the last two bytes). * s->lookahead stays null, so s->ins_h will be recomputed at the next * call of fill_window. */ s->ins_h = s->window[0]; UPDATE_HASH(s, s->ins_h, s->window[1]); for (n = 0; n <= length - MIN_MATCH; n++) { INSERT_STRING(s, n, hash_head); } if (hash_head) hash_head = 0; /* to make compiler happy */ return Z_OK; } /* ========================================================================= */ int ZEXPORT deflateReset (strm) z_streamp strm; { deflate_state *s; if (strm == Z_NULL || strm->state == Z_NULL || strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) { return Z_STREAM_ERROR; } strm->total_in = strm->total_out = 0; strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */ strm->data_type = Z_UNKNOWN; s = (deflate_state *)strm->state; s->pending = 0; s->pending_out = s->pending_buf; if (s->wrap < 0) { s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */ } s->status = s->wrap ? INIT_STATE : BUSY_STATE; strm->adler = #ifdef GZIP s->wrap == 2 ? crc32(0L, Z_NULL, 0) : #endif adler32(0L, Z_NULL, 0); s->last_flush = Z_NO_FLUSH; _tr_init(s); lm_init(s); return Z_OK; } /* ========================================================================= */ int ZEXPORT deflateSetHeader (strm, head) z_streamp strm; gz_headerp head; { if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; if (strm->state->wrap != 2) return Z_STREAM_ERROR; strm->state->gzhead = head; return Z_OK; } /* ========================================================================= */ int ZEXPORT deflatePrime (strm, bits, value) z_streamp strm; int bits; int value; { if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; strm->state->bi_valid = bits; strm->state->bi_buf = (ush)(value & ((1 << bits) - 1)); return Z_OK; } /* ========================================================================= */ int ZEXPORT deflateParams(strm, level, strategy) z_streamp strm; int level; int strategy; { deflate_state *s; compress_func func; int err = Z_OK; if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; s = strm->state; #ifdef FASTEST if (level != 0) level = 1; #else if (level == Z_DEFAULT_COMPRESSION) level = 6; #endif if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) { return Z_STREAM_ERROR; } func = configuration_table[s->level].func; if ((strategy != s->strategy || func != configuration_table[level].func) && strm->total_in != 0) { /* Flush the last buffer: */ err = deflate(strm, Z_BLOCK); } if (s->level != level) { s->level = level; s->max_lazy_match = configuration_table[level].max_lazy; s->good_match = configuration_table[level].good_length; s->nice_match = configuration_table[level].nice_length; s->max_chain_length = configuration_table[level].max_chain; } s->strategy = strategy; return err; } /* ========================================================================= */ int ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain) z_streamp strm; int good_length; int max_lazy; int nice_length; int max_chain; { deflate_state *s; if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; s = strm->state; s->good_match = good_length; s->max_lazy_match = max_lazy; s->nice_match = nice_length; s->max_chain_length = max_chain; return Z_OK; } /* ========================================================================= * For the default windowBits of 15 and memLevel of 8, this function returns * a close to exact, as well as small, upper bound on the compressed size. * They are coded as constants here for a reason--if the #define's are * changed, then this function needs to be changed as well. The return * value for 15 and 8 only works for those exact settings. * * For any setting other than those defaults for windowBits and memLevel, * the value returned is a conservative worst case for the maximum expansion * resulting from using fixed blocks instead of stored blocks, which deflate * can emit on compressed data for some combinations of the parameters. * * This function could be more sophisticated to provide closer upper bounds for * every combination of windowBits and memLevel. But even the conservative * upper bound of about 14% expansion does not seem onerous for output buffer * allocation. */ uLong ZEXPORT deflateBound(strm, sourceLen) z_streamp strm; uLong sourceLen; { deflate_state *s; uLong complen, wraplen; Bytef *str; /* conservative upper bound for compressed data */ complen = sourceLen + ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 5; /* if can't get parameters, return conservative bound plus zlib wrapper */ if (strm == Z_NULL || strm->state == Z_NULL) return complen + 6; /* compute wrapper length */ s = strm->state; switch (s->wrap) { case 0: /* raw deflate */ wraplen = 0; break; case 1: /* zlib wrapper */ wraplen = 6 + (s->strstart ? 4 : 0); break; case 2: /* gzip wrapper */ wraplen = 18; if (s->gzhead != Z_NULL) { /* user-supplied gzip header */ if (s->gzhead->extra != Z_NULL) wraplen += 2 + s->gzhead->extra_len; str = s->gzhead->name; if (str != Z_NULL) do { wraplen++; } while (*str++); str = s->gzhead->comment; if (str != Z_NULL) do { wraplen++; } while (*str++); if (s->gzhead->hcrc) wraplen += 2; } break; default: /* for compiler happiness */ wraplen = 6; } /* if not default parameters, return conservative bound */ if (s->w_bits != 15 || s->hash_bits != 8 + 7) return complen + wraplen; /* default settings: return tight bound for that case */ return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + (sourceLen >> 25) + 13 - 6 + wraplen; } /* ========================================================================= * Put a short in the pending buffer. The 16-bit value is put in MSB order. * IN assertion: the stream state is correct and there is enough room in * pending_buf. */ local void putShortMSB (s, b) deflate_state *s; uInt b; { put_byte(s, (Byte)(b >> 8)); put_byte(s, (Byte)(b & 0xff)); } /* ========================================================================= * Flush as much pending output as possible. All deflate() output goes * through this function so some applications may wish to modify it * to avoid allocating a large strm->next_out buffer and copying into it. * (See also read_buf()). */ local void flush_pending(strm) z_streamp strm; { unsigned len = strm->state->pending; if (len > strm->avail_out) len = strm->avail_out; if (len == 0) return; zmemcpy(strm->next_out, strm->state->pending_out, len); strm->next_out += len; strm->state->pending_out += len; strm->total_out += len; strm->avail_out -= len; strm->state->pending -= len; if (strm->state->pending == 0) { strm->state->pending_out = strm->state->pending_buf; } } /* ========================================================================= */ int ZEXPORT deflate (strm, flush) z_streamp strm; int flush; { int old_flush; /* value of flush param for previous deflate call */ deflate_state *s; if (strm == Z_NULL || strm->state == Z_NULL || flush > Z_BLOCK || flush < 0) { return Z_STREAM_ERROR; } s = strm->state; if (strm->next_out == Z_NULL || (strm->next_in == Z_NULL && strm->avail_in != 0) || (s->status == FINISH_STATE && flush != Z_FINISH)) { ERR_RETURN(strm, Z_STREAM_ERROR); } if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR); s->strm = strm; /* just in case */ old_flush = s->last_flush; s->last_flush = flush; /* Write the header */ if (s->status == INIT_STATE) { #ifdef GZIP if (s->wrap == 2) { strm->adler = crc32(0L, Z_NULL, 0); put_byte(s, 31); put_byte(s, 139); put_byte(s, 8); if (s->gzhead == Z_NULL) { put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, s->level == 9 ? 2 : (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? 4 : 0)); put_byte(s, OS_CODE); s->status = BUSY_STATE; } else { put_byte(s, (s->gzhead->text ? 1 : 0) + (s->gzhead->hcrc ? 2 : 0) + (s->gzhead->extra == Z_NULL ? 0 : 4) + (s->gzhead->name == Z_NULL ? 0 : 8) + (s->gzhead->comment == Z_NULL ? 0 : 16) ); put_byte(s, (Byte)(s->gzhead->time & 0xff)); put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff)); put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff)); put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff)); put_byte(s, s->level == 9 ? 2 : (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? 4 : 0)); put_byte(s, s->gzhead->os & 0xff); if (s->gzhead->extra != Z_NULL) { put_byte(s, s->gzhead->extra_len & 0xff); put_byte(s, (s->gzhead->extra_len >> 8) & 0xff); } if (s->gzhead->hcrc) strm->adler = crc32(strm->adler, s->pending_buf, s->pending); s->gzindex = 0; s->status = EXTRA_STATE; } } else #endif { uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8; uInt level_flags; if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2) level_flags = 0; else if (s->level < 6) level_flags = 1; else if (s->level == 6) level_flags = 2; else level_flags = 3; header |= (level_flags << 6); if (s->strstart != 0) header |= PRESET_DICT; header += 31 - (header % 31); s->status = BUSY_STATE; putShortMSB(s, header); /* Save the adler32 of the preset dictionary: */ if (s->strstart != 0) { putShortMSB(s, (uInt)(strm->adler >> 16)); putShortMSB(s, (uInt)(strm->adler & 0xffff)); } strm->adler = adler32(0L, Z_NULL, 0); } } #ifdef GZIP if (s->status == EXTRA_STATE) { if (s->gzhead->extra != Z_NULL) { uInt beg = s->pending; /* start of bytes to update crc */ while (s->gzindex < (s->gzhead->extra_len & 0xffff)) { if (s->pending == s->pending_buf_size) { if (s->gzhead->hcrc && s->pending > beg) strm->adler = crc32(strm->adler, s->pending_buf + beg, s->pending - beg); flush_pending(strm); beg = s->pending; if (s->pending == s->pending_buf_size) break; } put_byte(s, s->gzhead->extra[s->gzindex]); s->gzindex++; } if (s->gzhead->hcrc && s->pending > beg) strm->adler = crc32(strm->adler, s->pending_buf + beg, s->pending - beg); if (s->gzindex == s->gzhead->extra_len) { s->gzindex = 0; s->status = NAME_STATE; } } else s->status = NAME_STATE; } if (s->status == NAME_STATE) { if (s->gzhead->name != Z_NULL) { uInt beg = s->pending; /* start of bytes to update crc */ int val; do { if (s->pending == s->pending_buf_size) { if (s->gzhead->hcrc && s->pending > beg) strm->adler = crc32(strm->adler, s->pending_buf + beg, s->pending - beg); flush_pending(strm); beg = s->pending; if (s->pending == s->pending_buf_size) { val = 1; break; } } val = s->gzhead->name[s->gzindex++]; put_byte(s, val); } while (val != 0); if (s->gzhead->hcrc && s->pending > beg) strm->adler = crc32(strm->adler, s->pending_buf + beg, s->pending - beg); if (val == 0) { s->gzindex = 0; s->status = COMMENT_STATE; } } else s->status = COMMENT_STATE; } if (s->status == COMMENT_STATE) { if (s->gzhead->comment != Z_NULL) { uInt beg = s->pending; /* start of bytes to update crc */ int val; do { if (s->pending == s->pending_buf_size) { if (s->gzhead->hcrc && s->pending > beg) strm->adler = crc32(strm->adler, s->pending_buf + beg, s->pending - beg); flush_pending(strm); beg = s->pending; if (s->pending == s->pending_buf_size) { val = 1; break; } } val = s->gzhead->comment[s->gzindex++]; put_byte(s, val); } while (val != 0); if (s->gzhead->hcrc && s->pending > beg) strm->adler = crc32(strm->adler, s->pending_buf + beg, s->pending - beg); if (val == 0) s->status = HCRC_STATE; } else s->status = HCRC_STATE; } if (s->status == HCRC_STATE) { if (s->gzhead->hcrc) { if (s->pending + 2 > s->pending_buf_size) flush_pending(strm); if (s->pending + 2 <= s->pending_buf_size) { put_byte(s, (Byte)(strm->adler & 0xff)); put_byte(s, (Byte)((strm->adler >> 8) & 0xff)); strm->adler = crc32(0L, Z_NULL, 0); s->status = BUSY_STATE; } } else s->status = BUSY_STATE; } #endif /* Flush as much pending output as possible */ if (s->pending != 0) { flush_pending(strm); if (strm->avail_out == 0) { /* Since avail_out is 0, deflate will be called again with * more output space, but possibly with both pending and * avail_in equal to zero. There won't be anything to do, * but this is not an error situation so make sure we * return OK instead of BUF_ERROR at next call of deflate: */ s->last_flush = -1; return Z_OK; } /* Make sure there is something to do and avoid duplicate consecutive * flushes. For repeated and useless calls with Z_FINISH, we keep * returning Z_STREAM_END instead of Z_BUF_ERROR. */ } else if (strm->avail_in == 0 && flush <= old_flush && flush != Z_FINISH) { ERR_RETURN(strm, Z_BUF_ERROR); } /* User must not provide more input after the first FINISH: */ if (s->status == FINISH_STATE && strm->avail_in != 0) { ERR_RETURN(strm, Z_BUF_ERROR); } /* Start a new block or continue the current one. */ if (strm->avail_in != 0 || s->lookahead != 0 || (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) { block_state bstate; bstate = s->strategy == Z_HUFFMAN_ONLY ? deflate_huff(s, flush) : (s->strategy == Z_RLE ? deflate_rle(s, flush) : (*(configuration_table[s->level].func))(s, flush)); if (bstate == finish_started || bstate == finish_done) { s->status = FINISH_STATE; } if (bstate == need_more || bstate == finish_started) { if (strm->avail_out == 0) { s->last_flush = -1; /* avoid BUF_ERROR next call, see above */ } return Z_OK; /* If flush != Z_NO_FLUSH && avail_out == 0, the next call * of deflate should use the same flush parameter to make sure * that the flush is complete. So we don't have to output an * empty block here, this will be done at next call. This also * ensures that for a very small output buffer, we emit at most * one empty block. */ } if (bstate == block_done) { if (flush == Z_PARTIAL_FLUSH) { _tr_align(s); } else if (flush != Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ _tr_stored_block(s, (char*)0, 0L, 0); /* For a full flush, this empty block will be recognized * as a special marker by inflate_sync(). */ if (flush == Z_FULL_FLUSH) { CLEAR_HASH(s); /* forget history */ if (s->lookahead == 0) { s->strstart = 0; s->block_start = 0L; } } } flush_pending(strm); if (strm->avail_out == 0) { s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */ return Z_OK; } } } Assert(strm->avail_out > 0, "bug2"); if (flush != Z_FINISH) return Z_OK; if (s->wrap <= 0) return Z_STREAM_END; /* Write the trailer */ #ifdef GZIP if (s->wrap == 2) { put_byte(s, (Byte)(strm->adler & 0xff)); put_byte(s, (Byte)((strm->adler >> 8) & 0xff)); put_byte(s, (Byte)((strm->adler >> 16) & 0xff)); put_byte(s, (Byte)((strm->adler >> 24) & 0xff)); put_byte(s, (Byte)(strm->total_in & 0xff)); put_byte(s, (Byte)((strm->total_in >> 8) & 0xff)); put_byte(s, (Byte)((strm->total_in >> 16) & 0xff)); put_byte(s, (Byte)((strm->total_in >> 24) & 0xff)); } else #endif { putShortMSB(s, (uInt)(strm->adler >> 16)); putShortMSB(s, (uInt)(strm->adler & 0xffff)); } flush_pending(strm); /* If avail_out is zero, the application will call deflate again * to flush the rest. */ if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */ return s->pending != 0 ? Z_OK : Z_STREAM_END; } /* ========================================================================= */ int ZEXPORT deflateEnd (strm) z_streamp strm; { int status; if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; status = strm->state->status; if (status != INIT_STATE && status != EXTRA_STATE && status != NAME_STATE && status != COMMENT_STATE && status != HCRC_STATE && status != BUSY_STATE && status != FINISH_STATE) { return Z_STREAM_ERROR; } /* Deallocate in reverse order of allocations: */ TRY_FREE(strm, strm->state->pending_buf); TRY_FREE(strm, strm->state->head); TRY_FREE(strm, strm->state->prev); TRY_FREE(strm, strm->state->window); ZFREE(strm, strm->state); strm->state = Z_NULL; return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK; } /* ========================================================================= * Copy the source state to the destination state. * To simplify the source, this is not supported for 16-bit MSDOS (which * doesn't have enough memory anyway to duplicate compression states). */ int ZEXPORT deflateCopy (dest, source) z_streamp dest; z_streamp source; { #ifdef MAXSEG_64K return Z_STREAM_ERROR; #else deflate_state *ds; deflate_state *ss; ushf *overlay; if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) { return Z_STREAM_ERROR; } ss = source->state; zmemcpy(dest, source, sizeof(z_stream)); ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state)); if (ds == Z_NULL) return Z_MEM_ERROR; dest->state = (struct internal_state FAR *) ds; zmemcpy(ds, ss, sizeof(deflate_state)); ds->strm = dest; ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte)); ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos)); ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos)); overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2); ds->pending_buf = (uchf *) overlay; if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL || ds->pending_buf == Z_NULL) { deflateEnd (dest); return Z_MEM_ERROR; } /* following zmemcpy do not work for 16-bit MSDOS */ zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte)); zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos)); zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos)); zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size); ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf); ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush); ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize; ds->l_desc.dyn_tree = ds->dyn_ltree; ds->d_desc.dyn_tree = ds->dyn_dtree; ds->bl_desc.dyn_tree = ds->bl_tree; return Z_OK; #endif /* MAXSEG_64K */ } /* =========================================================================== * Read a new buffer from the current input stream, update the adler32 * and total number of bytes read. All deflate() input goes through * this function so some applications may wish to modify it to avoid * allocating a large strm->next_in buffer and copying from it. * (See also flush_pending()). */ local int read_buf(strm, buf, size) z_streamp strm; Bytef *buf; unsigned size; { unsigned len = strm->avail_in; if (len > size) len = size; if (len == 0) return 0; strm->avail_in -= len; if (strm->state->wrap == 1) { strm->adler = adler32(strm->adler, strm->next_in, len); } #ifdef GZIP else if (strm->state->wrap == 2) { strm->adler = crc32(strm->adler, strm->next_in, len); } #endif zmemcpy(buf, strm->next_in, len); strm->next_in += len; strm->total_in += len; return (int)len; } /* =========================================================================== * Initialize the "longest match" routines for a new zlib stream */ local void lm_init (s) deflate_state *s; { s->window_size = (ulg)2L*s->w_size; CLEAR_HASH(s); /* Set the default configuration parameters: */ s->max_lazy_match = configuration_table[s->level].max_lazy; s->good_match = configuration_table[s->level].good_length; s->nice_match = configuration_table[s->level].nice_length; s->max_chain_length = configuration_table[s->level].max_chain; s->strstart = 0; s->block_start = 0L; s->lookahead = 0; s->match_length = s->prev_length = MIN_MATCH-1; s->match_available = 0; s->ins_h = 0; #ifndef FASTEST #ifdef ASMV match_init(); /* initialize the asm code */ #endif #endif } #ifndef FASTEST /* =========================================================================== * Set match_start to the longest match starting at the given string and * return its length. Matches shorter or equal to prev_length are discarded, * in which case the result is equal to prev_length and match_start is * garbage. * IN assertions: cur_match is the head of the hash chain for the current * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 * OUT assertion: the match length is not greater than s->lookahead. */ #ifndef ASMV /* For 80x86 and 680x0, an optimized version will be provided in match.asm or * match.S. The code will be functionally equivalent. */ local uInt longest_match(s, cur_match) deflate_state *s; IPos cur_match; /* current match */ { unsigned chain_length = s->max_chain_length;/* max hash chain length */ register Bytef *scan = s->window + s->strstart; /* current string */ register Bytef *match; /* matched string */ register int len; /* length of current match */ int best_len = s->prev_length; /* best match length so far */ int nice_match = s->nice_match; /* stop if match long enough */ IPos limit = s->strstart > (IPos)MAX_DIST(s) ? s->strstart - (IPos)MAX_DIST(s) : NIL; /* Stop when cur_match becomes <= limit. To simplify the code, * we prevent matches with the string of window index 0. */ Posf *prev = s->prev; uInt wmask = s->w_mask; #ifdef UNALIGNED_OK /* Compare two bytes at a time. Note: this is not always beneficial. * Try with and without -DUNALIGNED_OK to check. */ register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1; register ush scan_start = *(ushf*)scan; register ush scan_end = *(ushf*)(scan+best_len-1); #else register Bytef *strend = s->window + s->strstart + MAX_MATCH; register Byte scan_end1 = scan[best_len-1]; register Byte scan_end = scan[best_len]; #endif /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. * It is easy to get rid of this optimization if necessary. */ Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); /* Do not waste too much time if we already have a good match: */ if (s->prev_length >= s->good_match) { chain_length >>= 2; } /* Do not look for matches beyond the end of the input. This is necessary * to make deflate deterministic. */ if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead; Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); do { Assert(cur_match < s->strstart, "no future"); match = s->window + cur_match; /* Skip to next match if the match length cannot increase * or if the match length is less than 2. Note that the checks below * for insufficient lookahead only occur occasionally for performance * reasons. Therefore uninitialized memory will be accessed, and * conditional jumps will be made that depend on those values. * However the length of the match is limited to the lookahead, so * the output of deflate is not affected by the uninitialized values. */ #if (defined(UNALIGNED_OK) && MAX_MATCH == 258) /* This code assumes sizeof(unsigned short) == 2. Do not use * UNALIGNED_OK if your compiler uses a different size. */ if (*(ushf*)(match+best_len-1) != scan_end || *(ushf*)match != scan_start) continue; /* It is not necessary to compare scan[2] and match[2] since they are * always equal when the other bytes match, given that the hash keys * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at * strstart+3, +5, ... up to strstart+257. We check for insufficient * lookahead only every 4th comparison; the 128th check will be made * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is * necessary to put more guard bytes at the end of the window, or * to check more often for insufficient lookahead. */ Assert(scan[2] == match[2], "scan[2]?"); scan++, match++; do { } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) && *(ushf*)(scan+=2) == *(ushf*)(match+=2) && *(ushf*)(scan+=2) == *(ushf*)(match+=2) && *(ushf*)(scan+=2) == *(ushf*)(match+=2) && scan < strend); /* The funny "do {}" generates better code on most compilers */ /* Here, scan <= window+strstart+257 */ Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); if (*scan == *match) scan++; len = (MAX_MATCH - 1) - (int)(strend-scan); scan = strend - (MAX_MATCH-1); #else /* UNALIGNED_OK */ if (match[best_len] != scan_end || match[best_len-1] != scan_end1 || *match != *scan || *++match != scan[1]) continue; /* The check at best_len-1 can be removed because it will be made * again later. (This heuristic is not always a win.) * It is not necessary to compare scan[2] and match[2] since they * are always equal when the other bytes match, given that * the hash keys are equal and that HASH_BITS >= 8. */ scan += 2, match++; Assert(*scan == *match, "match[2]?"); /* We check for insufficient lookahead only every 8th comparison; * the 256th check will be made at strstart+258. */ do { } while (*++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && scan < strend); Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); len = MAX_MATCH - (int)(strend - scan); scan = strend - MAX_MATCH; #endif /* UNALIGNED_OK */ if (len > best_len) { s->match_start = cur_match; best_len = len; if (len >= nice_match) break; #ifdef UNALIGNED_OK scan_end = *(ushf*)(scan+best_len-1); #else scan_end1 = scan[best_len-1]; scan_end = scan[best_len]; #endif } } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length != 0); if ((uInt)best_len <= s->lookahead) return (uInt)best_len; return s->lookahead; } #endif /* ASMV */ #else /* FASTEST */ /* --------------------------------------------------------------------------- * Optimized version for FASTEST only */ local uInt longest_match(s, cur_match) deflate_state *s; IPos cur_match; /* current match */ { register Bytef *scan = s->window + s->strstart; /* current string */ register Bytef *match; /* matched string */ register int len; /* length of current match */ register Bytef *strend = s->window + s->strstart + MAX_MATCH; /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. * It is easy to get rid of this optimization if necessary. */ Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); Assert(cur_match < s->strstart, "no future"); match = s->window + cur_match; /* Return failure if the match length is less than 2: */ if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1; /* The check at best_len-1 can be removed because it will be made * again later. (This heuristic is not always a win.) * It is not necessary to compare scan[2] and match[2] since they * are always equal when the other bytes match, given that * the hash keys are equal and that HASH_BITS >= 8. */ scan += 2, match += 2; Assert(*scan == *match, "match[2]?"); /* We check for insufficient lookahead only every 8th comparison; * the 256th check will be made at strstart+258. */ do { } while (*++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match && scan < strend); Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); len = MAX_MATCH - (int)(strend - scan); if (len < MIN_MATCH) return MIN_MATCH - 1; s->match_start = cur_match; return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead; } #endif /* FASTEST */ #ifdef DEBUG /* =========================================================================== * Check that the match at match_start is indeed a match. */ local void check_match(s, start, match, length) deflate_state *s; IPos start, match; int length; { /* check that the match is indeed a match */ if (zmemcmp(s->window + match, s->window + start, length) != EQUAL) { fprintf(stderr, " start %u, match %u, length %d\n", start, match, length); do { fprintf(stderr, "%c%c", s->window[match++], s->window[start++]); } while (--length != 0); z_error("invalid match"); } if (z_verbose > 1) { fprintf(stderr,"\\[%d,%d]", start-match, length); do { putc(s->window[start++], stderr); } while (--length != 0); } } #else # define check_match(s, start, match, length) #endif /* DEBUG */ /* =========================================================================== * Fill the window when the lookahead becomes insufficient. * Updates strstart and lookahead. * * IN assertion: lookahead < MIN_LOOKAHEAD * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD * At least one byte has been read, or avail_in == 0; reads are * performed for at least two bytes (required for the zip translate_eol * option -- not supported here). */ local void fill_window(s) deflate_state *s; { register unsigned n, m; register Posf *p; unsigned more; /* Amount of free space at the end of the window. */ uInt wsize = s->w_size; do { more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart); /* Deal with !@#$% 64K limit: */ if (sizeof(int) <= 2) { if (more == 0 && s->strstart == 0 && s->lookahead == 0) { more = wsize; } else if (more == (unsigned)(-1)) { /* Very unlikely, but possible on 16 bit machine if * strstart == 0 && lookahead == 1 (input done a byte at time) */ more--; } } /* If the window is almost full and there is insufficient lookahead, * move the upper half to the lower one to make room in the upper half. */ if (s->strstart >= wsize+MAX_DIST(s)) { zmemcpy(s->window, s->window+wsize, (unsigned)wsize); s->match_start -= wsize; s->strstart -= wsize; /* we now have strstart >= MAX_DIST */ s->block_start -= (long) wsize; /* Slide the hash table (could be avoided with 32 bit values at the expense of memory usage). We slide even when level == 0 to keep the hash table consistent if we switch back to level > 0 later. (Using level 0 permanently is not an optimal usage of zlib, so we don't care about this pathological case.) */ n = s->hash_size; p = &s->head[n]; do { m = *--p; *p = (Pos)(m >= wsize ? m-wsize : NIL); } while (--n); n = wsize; #ifndef FASTEST p = &s->prev[n]; do { m = *--p; *p = (Pos)(m >= wsize ? m-wsize : NIL); /* If n is not on any hash chain, prev[n] is garbage but * its value will never be used. */ } while (--n); #endif more += wsize; } if (s->strm->avail_in == 0) return; /* If there was no sliding: * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && * more == window_size - lookahead - strstart * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) * => more >= window_size - 2*WSIZE + 2 * In the BIG_MEM or MMAP case (not yet supported), * window_size == input_size + MIN_LOOKAHEAD && * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. * Otherwise, window_size == 2*WSIZE so more >= 2. * If there was sliding, more >= WSIZE. So in all cases, more >= 2. */ Assert(more >= 2, "more < 2"); n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more); s->lookahead += n; /* Initialize the hash value now that we have some input: */ if (s->lookahead >= MIN_MATCH) { s->ins_h = s->window[s->strstart]; UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]); #if MIN_MATCH != 3 Call UPDATE_HASH() MIN_MATCH-3 more times #endif } /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, * but this is not important since only literal bytes will be emitted. */ } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0); /* If the WIN_INIT bytes after the end of the current data have never been * written, then zero those bytes in order to avoid memory check reports of * the use of uninitialized (or uninitialised as Julian writes) bytes by * the longest match routines. Update the high water mark for the next * time through here. WIN_INIT is set to MAX_MATCH since the longest match * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. */ if (s->high_water < s->window_size) { ulg curr = s->strstart + (ulg)(s->lookahead); ulg init; if (s->high_water < curr) { /* Previous high water mark below current data -- zero WIN_INIT * bytes or up to end of window, whichever is less. */ init = s->window_size - curr; if (init > WIN_INIT) init = WIN_INIT; zmemzero(s->window + curr, (unsigned)init); s->high_water = curr + init; } else if (s->high_water < (ulg)curr + WIN_INIT) { /* High water mark at or above current data, but below current data * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up * to end of window, whichever is less. */ init = (ulg)curr + WIN_INIT - s->high_water; if (init > s->window_size - s->high_water) init = s->window_size - s->high_water; zmemzero(s->window + s->high_water, (unsigned)init); s->high_water += init; } } } /* =========================================================================== * Flush the current block, with given end-of-file flag. * IN assertion: strstart is set to the end of the current match. */ #define FLUSH_BLOCK_ONLY(s, last) { \ _tr_flush_block(s, (s->block_start >= 0L ? \ (charf *)&s->window[(unsigned)s->block_start] : \ (charf *)Z_NULL), \ (ulg)((long)s->strstart - s->block_start), \ (last)); \ s->block_start = s->strstart; \ flush_pending(s->strm); \ Tracev((stderr,"[FLUSH]")); \ } /* Same but force premature exit if necessary. */ #define FLUSH_BLOCK(s, last) { \ FLUSH_BLOCK_ONLY(s, last); \ if (s->strm->avail_out == 0) return (last) ? finish_started : need_more; \ } /* =========================================================================== * Copy without compression as much as possible from the input stream, return * the current block state. * This function does not insert new strings in the dictionary since * uncompressible data is probably not useful. This function is used * only for the level=0 compression option. * NOTE: this function should be optimized to avoid extra copying from * window to pending_buf. */ local block_state deflate_stored(s, flush) deflate_state *s; int flush; { /* Stored blocks are limited to 0xffff bytes, pending_buf is limited * to pending_buf_size, and each stored block has a 5 byte header: */ ulg max_block_size = 0xffff; ulg max_start; if (max_block_size > s->pending_buf_size - 5) { max_block_size = s->pending_buf_size - 5; } /* Copy as much as possible from input to output: */ for (;;) { /* Fill the window as much as possible: */ if (s->lookahead <= 1) { Assert(s->strstart < s->w_size+MAX_DIST(s) || s->block_start >= (long)s->w_size, "slide too late"); fill_window(s); if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more; if (s->lookahead == 0) break; /* flush the current block */ } Assert(s->block_start >= 0L, "block gone"); s->strstart += s->lookahead; s->lookahead = 0; /* Emit a stored block if pending_buf will be full: */ max_start = s->block_start + max_block_size; if (s->strstart == 0 || (ulg)s->strstart >= max_start) { /* strstart == 0 is possible when wraparound on 16-bit machine */ s->lookahead = (uInt)(s->strstart - max_start); s->strstart = (uInt)max_start; FLUSH_BLOCK(s, 0); } /* Flush if we may have to slide, otherwise block_start may become * negative and the data will be gone: */ if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) { FLUSH_BLOCK(s, 0); } } FLUSH_BLOCK(s, flush == Z_FINISH); return flush == Z_FINISH ? finish_done : block_done; } /* =========================================================================== * Compress as much as possible from the input stream, return the current * block state. * This function does not perform lazy evaluation of matches and inserts * new strings in the dictionary only for unmatched strings or for short * matches. It is used only for the fast compression options. */ local block_state deflate_fast(s, flush) deflate_state *s; int flush; { IPos hash_head; /* head of the hash chain */ int bflush; /* set if current block must be flushed */ for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the next match, plus MIN_MATCH bytes to insert the * string following the next match. */ if (s->lookahead < MIN_LOOKAHEAD) { fill_window(s); if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { return need_more; } if (s->lookahead == 0) break; /* flush the current block */ } /* Insert the string window[strstart .. strstart+2] in the * dictionary, and set hash_head to the head of the hash chain: */ hash_head = NIL; if (s->lookahead >= MIN_MATCH) { INSERT_STRING(s, s->strstart, hash_head); } /* Find the longest match, discarding those <= prev_length. * At this point we have always match_length < MIN_MATCH */ if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) { /* To simplify the code, we prevent matches with the string * of window index 0 (in particular we have to avoid a match * of the string with itself at the start of the input file). */ s->match_length = longest_match (s, hash_head); /* longest_match() sets match_start */ } if (s->match_length >= MIN_MATCH) { check_match(s, s->strstart, s->match_start, s->match_length); _tr_tally_dist(s, s->strstart - s->match_start, s->match_length - MIN_MATCH, bflush); s->lookahead -= s->match_length; /* Insert new strings in the hash table only if the match length * is not too large. This saves time but degrades compression. */ #ifndef FASTEST if (s->match_length <= s->max_insert_length && s->lookahead >= MIN_MATCH) { s->match_length--; /* string at strstart already in table */ do { s->strstart++; INSERT_STRING(s, s->strstart, hash_head); /* strstart never exceeds WSIZE-MAX_MATCH, so there are * always MIN_MATCH bytes ahead. */ } while (--s->match_length != 0); s->strstart++; } else #endif { s->strstart += s->match_length; s->match_length = 0; s->ins_h = s->window[s->strstart]; UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]); #if MIN_MATCH != 3 Call UPDATE_HASH() MIN_MATCH-3 more times #endif /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not * matter since it will be recomputed at next deflate call. */ } } else { /* No match, output a literal byte */ Tracevv((stderr,"%c", s->window[s->strstart])); _tr_tally_lit (s, s->window[s->strstart], bflush); s->lookahead--; s->strstart++; } if (bflush) FLUSH_BLOCK(s, 0); } FLUSH_BLOCK(s, flush == Z_FINISH); return flush == Z_FINISH ? finish_done : block_done; } #ifndef FASTEST /* =========================================================================== * Same as above, but achieves better compression. We use a lazy * evaluation for matches: a match is finally adopted only if there is * no better match at the next window position. */ local block_state deflate_slow(s, flush) deflate_state *s; int flush; { IPos hash_head; /* head of hash chain */ int bflush; /* set if current block must be flushed */ /* Process the input block. */ for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the next match, plus MIN_MATCH bytes to insert the * string following the next match. */ if (s->lookahead < MIN_LOOKAHEAD) { fill_window(s); if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { return need_more; } if (s->lookahead == 0) break; /* flush the current block */ } /* Insert the string window[strstart .. strstart+2] in the * dictionary, and set hash_head to the head of the hash chain: */ hash_head = NIL; if (s->lookahead >= MIN_MATCH) { INSERT_STRING(s, s->strstart, hash_head); } /* Find the longest match, discarding those <= prev_length. */ s->prev_length = s->match_length, s->prev_match = s->match_start; s->match_length = MIN_MATCH-1; if (hash_head != NIL && s->prev_length < s->max_lazy_match && s->strstart - hash_head <= MAX_DIST(s)) { /* To simplify the code, we prevent matches with the string * of window index 0 (in particular we have to avoid a match * of the string with itself at the start of the input file). */ s->match_length = longest_match (s, hash_head); /* longest_match() sets match_start */ if (s->match_length <= 5 && (s->strategy == Z_FILTERED #if TOO_FAR <= 32767 || (s->match_length == MIN_MATCH && s->strstart - s->match_start > TOO_FAR) #endif )) { /* If prev_match is also MIN_MATCH, match_start is garbage * but we will ignore the current match anyway. */ s->match_length = MIN_MATCH-1; } } /* If there was a match at the previous step and the current * match is not better, output the previous match: */ if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) { uInt max_insert = s->strstart + s->lookahead - MIN_MATCH; /* Do not insert strings in hash table beyond this. */ check_match(s, s->strstart-1, s->prev_match, s->prev_length); _tr_tally_dist(s, s->strstart -1 - s->prev_match, s->prev_length - MIN_MATCH, bflush); /* Insert in hash table all strings up to the end of the match. * strstart-1 and strstart are already inserted. If there is not * enough lookahead, the last two strings are not inserted in * the hash table. */ s->lookahead -= s->prev_length-1; s->prev_length -= 2; do { if (++s->strstart <= max_insert) { INSERT_STRING(s, s->strstart, hash_head); } } while (--s->prev_length != 0); s->match_available = 0; s->match_length = MIN_MATCH-1; s->strstart++; if (bflush) FLUSH_BLOCK(s, 0); } else if (s->match_available) { /* If there was no match at the previous position, output a * single literal. If there was a match but the current match * is longer, truncate the previous match to a single literal. */ Tracevv((stderr,"%c", s->window[s->strstart-1])); _tr_tally_lit(s, s->window[s->strstart-1], bflush); if (bflush) { FLUSH_BLOCK_ONLY(s, 0); } s->strstart++; s->lookahead--; if (s->strm->avail_out == 0) return need_more; } else { /* There is no previous match to compare with, wait for * the next step to decide. */ s->match_available = 1; s->strstart++; s->lookahead--; } } Assert (flush != Z_NO_FLUSH, "no flush?"); if (s->match_available) { Tracevv((stderr,"%c", s->window[s->strstart-1])); _tr_tally_lit(s, s->window[s->strstart-1], bflush); s->match_available = 0; } FLUSH_BLOCK(s, flush == Z_FINISH); return flush == Z_FINISH ? finish_done : block_done; } #endif /* FASTEST */ /* =========================================================================== * For Z_RLE, simply look for runs of bytes, generate matches only of distance * one. Do not maintain a hash table. (It will be regenerated if this run of * deflate switches away from Z_RLE.) */ local block_state deflate_rle(s, flush) deflate_state *s; int flush; { int bflush; /* set if current block must be flushed */ uInt prev; /* byte at distance one to match */ Bytef *scan, *strend; /* scan goes up to strend for length of run */ for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the longest encodable run. */ if (s->lookahead < MAX_MATCH) { fill_window(s); if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) { return need_more; } if (s->lookahead == 0) break; /* flush the current block */ } /* See how many times the previous byte repeats */ s->match_length = 0; if (s->lookahead >= MIN_MATCH && s->strstart > 0) { scan = s->window + s->strstart - 1; prev = *scan; if (prev == *++scan && prev == *++scan && prev == *++scan) { strend = s->window + s->strstart + MAX_MATCH; do { } while (prev == *++scan && prev == *++scan && prev == *++scan && prev == *++scan && prev == *++scan && prev == *++scan && prev == *++scan && prev == *++scan && scan < strend); s->match_length = MAX_MATCH - (int)(strend - scan); if (s->match_length > s->lookahead) s->match_length = s->lookahead; } } /* Emit match if have run of MIN_MATCH or longer, else emit literal */ if (s->match_length >= MIN_MATCH) { check_match(s, s->strstart, s->strstart - 1, s->match_length); _tr_tally_dist(s, 1, s->match_length - MIN_MATCH, bflush); s->lookahead -= s->match_length; s->strstart += s->match_length; s->match_length = 0; } else { /* No match, output a literal byte */ Tracevv((stderr,"%c", s->window[s->strstart])); _tr_tally_lit (s, s->window[s->strstart], bflush); s->lookahead--; s->strstart++; } if (bflush) FLUSH_BLOCK(s, 0); } FLUSH_BLOCK(s, flush == Z_FINISH); return flush == Z_FINISH ? finish_done : block_done; } /* =========================================================================== * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. * (It will be regenerated if this run of deflate switches away from Huffman.) */ local block_state deflate_huff(s, flush) deflate_state *s; int flush; { int bflush; /* set if current block must be flushed */ for (;;) { /* Make sure that we have a literal to write. */ if (s->lookahead == 0) { fill_window(s); if (s->lookahead == 0) { if (flush == Z_NO_FLUSH) return need_more; break; /* flush the current block */ } } /* Output a literal byte */ s->match_length = 0; Tracevv((stderr,"%c", s->window[s->strstart])); _tr_tally_lit (s, s->window[s->strstart], bflush); s->lookahead--; s->strstart++; if (bflush) FLUSH_BLOCK(s, 0); } FLUSH_BLOCK(s, flush == Z_FINISH); return flush == Z_FINISH ? finish_done : block_done; } ================================================ FILE: src/engine/external/zlib/deflate.h ================================================ /* deflate.h -- internal compression state * Copyright (C) 1995-2010 Jean-loup Gailly * For conditions of distribution and use, see copyright notice in zlib.h */ /* WARNING: this file should *not* be used by applications. It is part of the implementation of the compression library and is subject to change. Applications should only use zlib.h. */ /* @(#) $Id$ */ #ifndef DEFLATE_H #define DEFLATE_H #include "zutil.h" /* define NO_GZIP when compiling if you want to disable gzip header and trailer creation by deflate(). NO_GZIP would be used to avoid linking in the crc code when it is not needed. For shared libraries, gzip encoding should be left enabled. */ #ifndef NO_GZIP # define GZIP #endif /* =========================================================================== * Internal compression state. */ #define LENGTH_CODES 29 /* number of length codes, not counting the special END_BLOCK code */ #define LITERALS 256 /* number of literal bytes 0..255 */ #define L_CODES (LITERALS+1+LENGTH_CODES) /* number of Literal or Length codes, including the END_BLOCK code */ #define D_CODES 30 /* number of distance codes */ #define BL_CODES 19 /* number of codes used to transfer the bit lengths */ #define HEAP_SIZE (2*L_CODES+1) /* maximum heap size */ #define MAX_BITS 15 /* All codes must not exceed MAX_BITS bits */ #define INIT_STATE 42 #define EXTRA_STATE 69 #define NAME_STATE 73 #define COMMENT_STATE 91 #define HCRC_STATE 103 #define BUSY_STATE 113 #define FINISH_STATE 666 /* Stream status */ /* Data structure describing a single value and its code string. */ typedef struct ct_data_s { union { ush freq; /* frequency count */ ush code; /* bit string */ } fc; union { ush dad; /* father node in Huffman tree */ ush len; /* length of bit string */ } dl; } FAR ct_data; #define Freq fc.freq #define Code fc.code #define Dad dl.dad #define Len dl.len typedef struct static_tree_desc_s static_tree_desc; typedef struct tree_desc_s { ct_data *dyn_tree; /* the dynamic tree */ int max_code; /* largest code with non zero frequency */ static_tree_desc *stat_desc; /* the corresponding static tree */ } FAR tree_desc; typedef ush Pos; typedef Pos FAR Posf; typedef unsigned IPos; /* A Pos is an index in the character window. We use short instead of int to * save space in the various tables. IPos is used only for parameter passing. */ typedef struct internal_state { z_streamp strm; /* pointer back to this zlib stream */ int status; /* as the name implies */ Bytef *pending_buf; /* output still pending */ ulg pending_buf_size; /* size of pending_buf */ Bytef *pending_out; /* next pending byte to output to the stream */ uInt pending; /* nb of bytes in the pending buffer */ int wrap; /* bit 0 true for zlib, bit 1 true for gzip */ gz_headerp gzhead; /* gzip header information to write */ uInt gzindex; /* where in extra, name, or comment */ Byte method; /* STORED (for zip only) or DEFLATED */ int last_flush; /* value of flush param for previous deflate call */ /* used by deflate.c: */ uInt w_size; /* LZ77 window size (32K by default) */ uInt w_bits; /* log2(w_size) (8..16) */ uInt w_mask; /* w_size - 1 */ Bytef *window; /* Sliding window. Input bytes are read into the second half of the window, * and move to the first half later to keep a dictionary of at least wSize * bytes. With this organization, matches are limited to a distance of * wSize-MAX_MATCH bytes, but this ensures that IO is always * performed with a length multiple of the block size. Also, it limits * the window size to 64K, which is quite useful on MSDOS. * To do: use the user input buffer as sliding window. */ ulg window_size; /* Actual size of window: 2*wSize, except when the user input buffer * is directly used as sliding window. */ Posf *prev; /* Link to older string with same hash index. To limit the size of this * array to 64K, this link is maintained only for the last 32K strings. * An index in this array is thus a window index modulo 32K. */ Posf *head; /* Heads of the hash chains or NIL. */ uInt ins_h; /* hash index of string to be inserted */ uInt hash_size; /* number of elements in hash table */ uInt hash_bits; /* log2(hash_size) */ uInt hash_mask; /* hash_size-1 */ uInt hash_shift; /* Number of bits by which ins_h must be shifted at each input * step. It must be such that after MIN_MATCH steps, the oldest * byte no longer takes part in the hash key, that is: * hash_shift * MIN_MATCH >= hash_bits */ long block_start; /* Window position at the beginning of the current output block. Gets * negative when the window is moved backwards. */ uInt match_length; /* length of best match */ IPos prev_match; /* previous match */ int match_available; /* set if previous match exists */ uInt strstart; /* start of string to insert */ uInt match_start; /* start of matching string */ uInt lookahead; /* number of valid bytes ahead in window */ uInt prev_length; /* Length of the best match at previous step. Matches not greater than this * are discarded. This is used in the lazy match evaluation. */ uInt max_chain_length; /* To speed up deflation, hash chains are never searched beyond this * length. A higher limit improves compression ratio but degrades the * speed. */ uInt max_lazy_match; /* Attempt to find a better match only when the current match is strictly * smaller than this value. This mechanism is used only for compression * levels >= 4. */ # define max_insert_length max_lazy_match /* Insert new strings in the hash table only if the match length is not * greater than this length. This saves time but degrades compression. * max_insert_length is used only for compression levels <= 3. */ int level; /* compression level (1..9) */ int strategy; /* favor or force Huffman coding*/ uInt good_match; /* Use a faster search when the previous match is longer than this */ int nice_match; /* Stop searching when current match exceeds this */ /* used by trees.c: */ /* Didn't use ct_data typedef below to supress compiler warning */ struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ struct tree_desc_s l_desc; /* desc. for literal tree */ struct tree_desc_s d_desc; /* desc. for distance tree */ struct tree_desc_s bl_desc; /* desc. for bit length tree */ ush bl_count[MAX_BITS+1]; /* number of codes at each bit length for an optimal tree */ int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ int heap_len; /* number of elements in the heap */ int heap_max; /* element of largest frequency */ /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. * The same heap array is used to build all trees. */ uch depth[2*L_CODES+1]; /* Depth of each subtree used as tie breaker for trees of equal frequency */ uchf *l_buf; /* buffer for literals or lengths */ uInt lit_bufsize; /* Size of match buffer for literals/lengths. There are 4 reasons for * limiting lit_bufsize to 64K: * - frequencies can be kept in 16 bit counters * - if compression is not successful for the first block, all input * data is still in the window so we can still emit a stored block even * when input comes from standard input. (This can also be done for * all blocks if lit_bufsize is not greater than 32K.) * - if compression is not successful for a file smaller than 64K, we can * even emit a stored file instead of a stored block (saving 5 bytes). * This is applicable only for zip (not gzip or zlib). * - creating new Huffman trees less frequently may not provide fast * adaptation to changes in the input data statistics. (Take for * example a binary file with poorly compressible code followed by * a highly compressible string table.) Smaller buffer sizes give * fast adaptation but have of course the overhead of transmitting * trees more frequently. * - I can't count above 4 */ uInt last_lit; /* running index in l_buf */ ushf *d_buf; /* Buffer for distances. To simplify the code, d_buf and l_buf have * the same number of elements. To use different lengths, an extra flag * array would be necessary. */ ulg opt_len; /* bit length of current block with optimal trees */ ulg static_len; /* bit length of current block with static trees */ uInt matches; /* number of string matches in current block */ int last_eob_len; /* bit length of EOB code for last block */ #ifdef DEBUG ulg compressed_len; /* total bit length of compressed file mod 2^32 */ ulg bits_sent; /* bit length of compressed data sent mod 2^32 */ #endif ush bi_buf; /* Output buffer. bits are inserted starting at the bottom (least * significant bits). */ int bi_valid; /* Number of valid bits in bi_buf. All bits above the last valid bit * are always zero. */ ulg high_water; /* High water mark offset in window for initialized bytes -- bytes above * this are set to zero in order to avoid memory check warnings when * longest match routines access bytes past the input. This is then * updated to the new high water mark. */ } FAR deflate_state; /* Output a byte on the stream. * IN assertion: there is enough room in pending_buf. */ #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);} #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1) /* Minimum amount of lookahead, except at the end of the input file. * See deflate.c for comments about the MIN_MATCH+1. */ #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD) /* In order to simplify the code, particularly on 16 bit machines, match * distances are limited to MAX_DIST instead of WSIZE. */ #define WIN_INIT MAX_MATCH /* Number of bytes after end of data in window to initialize in order to avoid memory checker errors from longest match routines */ /* in trees.c */ void ZLIB_INTERNAL _tr_init OF((deflate_state *s)); int ZLIB_INTERNAL _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc)); void ZLIB_INTERNAL _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len, int last)); void ZLIB_INTERNAL _tr_align OF((deflate_state *s)); void ZLIB_INTERNAL _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len, int last)); #define d_code(dist) \ ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)]) /* Mapping from a distance to a distance code. dist is the distance - 1 and * must not have side effects. _dist_code[256] and _dist_code[257] are never * used. */ #ifndef DEBUG /* Inline versions of _tr_tally for speed: */ #if defined(GEN_TREES_H) || !defined(STDC) extern uch ZLIB_INTERNAL _length_code[]; extern uch ZLIB_INTERNAL _dist_code[]; #else extern const uch ZLIB_INTERNAL _length_code[]; extern const uch ZLIB_INTERNAL _dist_code[]; #endif # define _tr_tally_lit(s, c, flush) \ { uch cc = (c); \ s->d_buf[s->last_lit] = 0; \ s->l_buf[s->last_lit++] = cc; \ s->dyn_ltree[cc].Freq++; \ flush = (s->last_lit == s->lit_bufsize-1); \ } # define _tr_tally_dist(s, distance, length, flush) \ { uch len = (length); \ ush dist = (distance); \ s->d_buf[s->last_lit] = dist; \ s->l_buf[s->last_lit++] = len; \ dist--; \ s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \ s->dyn_dtree[d_code(dist)].Freq++; \ flush = (s->last_lit == s->lit_bufsize-1); \ } #else # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c) # define _tr_tally_dist(s, distance, length, flush) \ flush = _tr_tally(s, distance, length) #endif #endif /* DEFLATE_H */ ================================================ FILE: src/engine/external/zlib/infback.c ================================================ /* infback.c -- inflate using a call-back interface * Copyright (C) 1995-2009 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ /* This code is largely copied from inflate.c. Normally either infback.o or inflate.o would be linked into an application--not both. The interface with inffast.c is retained so that optimized assembler-coded versions of inflate_fast() can be used with either inflate.c or infback.c. */ #include "zutil.h" #include "inftrees.h" #include "inflate.h" #include "inffast.h" /* function prototypes */ local void fixedtables OF((struct inflate_state FAR *state)); /* strm provides memory allocation functions in zalloc and zfree, or Z_NULL to use the library memory allocation functions. windowBits is in the range 8..15, and window is a user-supplied window and output buffer that is 2**windowBits bytes. */ int ZEXPORT inflateBackInit_(strm, windowBits, window, version, stream_size) z_streamp strm; int windowBits; unsigned char FAR *window; const char *version; int stream_size; { struct inflate_state FAR *state; if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || stream_size != (int)(sizeof(z_stream))) return Z_VERSION_ERROR; if (strm == Z_NULL || window == Z_NULL || windowBits < 8 || windowBits > 15) return Z_STREAM_ERROR; strm->msg = Z_NULL; /* in case we return an error */ if (strm->zalloc == (alloc_func)0) { strm->zalloc = zcalloc; strm->opaque = (voidpf)0; } if (strm->zfree == (free_func)0) strm->zfree = zcfree; state = (struct inflate_state FAR *)ZALLOC(strm, 1, sizeof(struct inflate_state)); if (state == Z_NULL) return Z_MEM_ERROR; Tracev((stderr, "inflate: allocated\n")); strm->state = (struct internal_state FAR *)state; state->dmax = 32768U; state->wbits = windowBits; state->wsize = 1U << windowBits; state->window = window; state->wnext = 0; state->whave = 0; return Z_OK; } /* Return state with length and distance decoding tables and index sizes set to fixed code decoding. Normally this returns fixed tables from inffixed.h. If BUILDFIXED is defined, then instead this routine builds the tables the first time it's called, and returns those tables the first time and thereafter. This reduces the size of the code by about 2K bytes, in exchange for a little execution time. However, BUILDFIXED should not be used for threaded applications, since the rewriting of the tables and virgin may not be thread-safe. */ local void fixedtables(state) struct inflate_state FAR *state; { #ifdef BUILDFIXED static int virgin = 1; static code *lenfix, *distfix; static code fixed[544]; /* build fixed huffman tables if first call (may not be thread safe) */ if (virgin) { unsigned sym, bits; static code *next; /* literal/length table */ sym = 0; while (sym < 144) state->lens[sym++] = 8; while (sym < 256) state->lens[sym++] = 9; while (sym < 280) state->lens[sym++] = 7; while (sym < 288) state->lens[sym++] = 8; next = fixed; lenfix = next; bits = 9; inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work); /* distance table */ sym = 0; while (sym < 32) state->lens[sym++] = 5; distfix = next; bits = 5; inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work); /* do this just once */ virgin = 0; } #else /* !BUILDFIXED */ # include "inffixed.h" #endif /* BUILDFIXED */ state->lencode = lenfix; state->lenbits = 9; state->distcode = distfix; state->distbits = 5; } /* Macros for inflateBack(): */ /* Load returned state from inflate_fast() */ #define LOAD() \ do { \ put = strm->next_out; \ left = strm->avail_out; \ next = strm->next_in; \ have = strm->avail_in; \ hold = state->hold; \ bits = state->bits; \ } while (0) /* Set state from registers for inflate_fast() */ #define RESTORE() \ do { \ strm->next_out = put; \ strm->avail_out = left; \ strm->next_in = next; \ strm->avail_in = have; \ state->hold = hold; \ state->bits = bits; \ } while (0) /* Clear the input bit accumulator */ #define INITBITS() \ do { \ hold = 0; \ bits = 0; \ } while (0) /* Assure that some input is available. If input is requested, but denied, then return a Z_BUF_ERROR from inflateBack(). */ #define PULL() \ do { \ if (have == 0) { \ have = in(in_desc, &next); \ if (have == 0) { \ next = Z_NULL; \ ret = Z_BUF_ERROR; \ goto inf_leave; \ } \ } \ } while (0) /* Get a byte of input into the bit accumulator, or return from inflateBack() with an error if there is no input available. */ #define PULLBYTE() \ do { \ PULL(); \ have--; \ hold += (unsigned long)(*next++) << bits; \ bits += 8; \ } while (0) /* Assure that there are at least n bits in the bit accumulator. If there is not enough available input to do that, then return from inflateBack() with an error. */ #define NEEDBITS(n) \ do { \ while (bits < (unsigned)(n)) \ PULLBYTE(); \ } while (0) /* Return the low n bits of the bit accumulator (n < 16) */ #define BITS(n) \ ((unsigned)hold & ((1U << (n)) - 1)) /* Remove n bits from the bit accumulator */ #define DROPBITS(n) \ do { \ hold >>= (n); \ bits -= (unsigned)(n); \ } while (0) /* Remove zero to seven bits as needed to go to a byte boundary */ #define BYTEBITS() \ do { \ hold >>= bits & 7; \ bits -= bits & 7; \ } while (0) /* Assure that some output space is available, by writing out the window if it's full. If the write fails, return from inflateBack() with a Z_BUF_ERROR. */ #define ROOM() \ do { \ if (left == 0) { \ put = state->window; \ left = state->wsize; \ state->whave = left; \ if (out(out_desc, put, left)) { \ ret = Z_BUF_ERROR; \ goto inf_leave; \ } \ } \ } while (0) /* strm provides the memory allocation functions and window buffer on input, and provides information on the unused input on return. For Z_DATA_ERROR returns, strm will also provide an error message. in() and out() are the call-back input and output functions. When inflateBack() needs more input, it calls in(). When inflateBack() has filled the window with output, or when it completes with data in the window, it calls out() to write out the data. The application must not change the provided input until in() is called again or inflateBack() returns. The application must not change the window/output buffer until inflateBack() returns. in() and out() are called with a descriptor parameter provided in the inflateBack() call. This parameter can be a structure that provides the information required to do the read or write, as well as accumulated information on the input and output such as totals and check values. in() should return zero on failure. out() should return non-zero on failure. If either in() or out() fails, than inflateBack() returns a Z_BUF_ERROR. strm->next_in can be checked for Z_NULL to see whether it was in() or out() that caused in the error. Otherwise, inflateBack() returns Z_STREAM_END on success, Z_DATA_ERROR for an deflate format error, or Z_MEM_ERROR if it could not allocate memory for the state. inflateBack() can also return Z_STREAM_ERROR if the input parameters are not correct, i.e. strm is Z_NULL or the state was not initialized. */ int ZEXPORT inflateBack(strm, in, in_desc, out, out_desc) z_streamp strm; in_func in; void FAR *in_desc; out_func out; void FAR *out_desc; { struct inflate_state FAR *state; unsigned char FAR *next; /* next input */ unsigned char FAR *put; /* next output */ unsigned have, left; /* available input and output */ unsigned long hold; /* bit buffer */ unsigned bits; /* bits in bit buffer */ unsigned copy; /* number of stored or match bytes to copy */ unsigned char FAR *from; /* where to copy match bytes from */ code here; /* current decoding table entry */ code last; /* parent table entry */ unsigned len; /* length to copy for repeats, bits to drop */ int ret; /* return code */ static const unsigned short order[19] = /* permutation of code lengths */ {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; /* Check that the strm exists and that the state was initialized */ if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; /* Reset the state */ strm->msg = Z_NULL; state->mode = TYPE; state->last = 0; state->whave = 0; next = strm->next_in; have = next != Z_NULL ? strm->avail_in : 0; hold = 0; bits = 0; put = state->window; left = state->wsize; /* Inflate until end of block marked as last */ for (;;) switch (state->mode) { case TYPE: /* determine and dispatch block type */ if (state->last) { BYTEBITS(); state->mode = DONE; break; } NEEDBITS(3); state->last = BITS(1); DROPBITS(1); switch (BITS(2)) { case 0: /* stored block */ Tracev((stderr, "inflate: stored block%s\n", state->last ? " (last)" : "")); state->mode = STORED; break; case 1: /* fixed block */ fixedtables(state); Tracev((stderr, "inflate: fixed codes block%s\n", state->last ? " (last)" : "")); state->mode = LEN; /* decode codes */ break; case 2: /* dynamic block */ Tracev((stderr, "inflate: dynamic codes block%s\n", state->last ? " (last)" : "")); state->mode = TABLE; break; case 3: strm->msg = (char *)"invalid block type"; state->mode = BAD; } DROPBITS(2); break; case STORED: /* get and verify stored block length */ BYTEBITS(); /* go to byte boundary */ NEEDBITS(32); if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) { strm->msg = (char *)"invalid stored block lengths"; state->mode = BAD; break; } state->length = (unsigned)hold & 0xffff; Tracev((stderr, "inflate: stored length %u\n", state->length)); INITBITS(); /* copy stored block from input to output */ while (state->length != 0) { copy = state->length; PULL(); ROOM(); if (copy > have) copy = have; if (copy > left) copy = left; zmemcpy(put, next, copy); have -= copy; next += copy; left -= copy; put += copy; state->length -= copy; } Tracev((stderr, "inflate: stored end\n")); state->mode = TYPE; break; case TABLE: /* get dynamic table entries descriptor */ NEEDBITS(14); state->nlen = BITS(5) + 257; DROPBITS(5); state->ndist = BITS(5) + 1; DROPBITS(5); state->ncode = BITS(4) + 4; DROPBITS(4); #ifndef PKZIP_BUG_WORKAROUND if (state->nlen > 286 || state->ndist > 30) { strm->msg = (char *)"too many length or distance symbols"; state->mode = BAD; break; } #endif Tracev((stderr, "inflate: table sizes ok\n")); /* get code length code lengths (not a typo) */ state->have = 0; while (state->have < state->ncode) { NEEDBITS(3); state->lens[order[state->have++]] = (unsigned short)BITS(3); DROPBITS(3); } while (state->have < 19) state->lens[order[state->have++]] = 0; state->next = state->codes; state->lencode = (code const FAR *)(state->next); state->lenbits = 7; ret = inflate_table(CODES, state->lens, 19, &(state->next), &(state->lenbits), state->work); if (ret) { strm->msg = (char *)"invalid code lengths set"; state->mode = BAD; break; } Tracev((stderr, "inflate: code lengths ok\n")); /* get length and distance code code lengths */ state->have = 0; while (state->have < state->nlen + state->ndist) { for (;;) { here = state->lencode[BITS(state->lenbits)]; if ((unsigned)(here.bits) <= bits) break; PULLBYTE(); } if (here.val < 16) { NEEDBITS(here.bits); DROPBITS(here.bits); state->lens[state->have++] = here.val; } else { if (here.val == 16) { NEEDBITS(here.bits + 2); DROPBITS(here.bits); if (state->have == 0) { strm->msg = (char *)"invalid bit length repeat"; state->mode = BAD; break; } len = (unsigned)(state->lens[state->have - 1]); copy = 3 + BITS(2); DROPBITS(2); } else if (here.val == 17) { NEEDBITS(here.bits + 3); DROPBITS(here.bits); len = 0; copy = 3 + BITS(3); DROPBITS(3); } else { NEEDBITS(here.bits + 7); DROPBITS(here.bits); len = 0; copy = 11 + BITS(7); DROPBITS(7); } if (state->have + copy > state->nlen + state->ndist) { strm->msg = (char *)"invalid bit length repeat"; state->mode = BAD; break; } while (copy--) state->lens[state->have++] = (unsigned short)len; } } /* handle error breaks in while */ if (state->mode == BAD) break; /* check for end-of-block code (better have one) */ if (state->lens[256] == 0) { strm->msg = (char *)"invalid code -- missing end-of-block"; state->mode = BAD; break; } /* build code tables -- note: do not change the lenbits or distbits values here (9 and 6) without reading the comments in inftrees.h concerning the ENOUGH constants, which depend on those values */ state->next = state->codes; state->lencode = (code const FAR *)(state->next); state->lenbits = 9; ret = inflate_table(LENS, state->lens, state->nlen, &(state->next), &(state->lenbits), state->work); if (ret) { strm->msg = (char *)"invalid literal/lengths set"; state->mode = BAD; break; } state->distcode = (code const FAR *)(state->next); state->distbits = 6; ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist, &(state->next), &(state->distbits), state->work); if (ret) { strm->msg = (char *)"invalid distances set"; state->mode = BAD; break; } Tracev((stderr, "inflate: codes ok\n")); state->mode = LEN; case LEN: /* use inflate_fast() if we have enough input and output */ if (have >= 6 && left >= 258) { RESTORE(); if (state->whave < state->wsize) state->whave = state->wsize - left; inflate_fast(strm, state->wsize); LOAD(); break; } /* get a literal, length, or end-of-block code */ for (;;) { here = state->lencode[BITS(state->lenbits)]; if ((unsigned)(here.bits) <= bits) break; PULLBYTE(); } if (here.op && (here.op & 0xf0) == 0) { last = here; for (;;) { here = state->lencode[last.val + (BITS(last.bits + last.op) >> last.bits)]; if ((unsigned)(last.bits + here.bits) <= bits) break; PULLBYTE(); } DROPBITS(last.bits); } DROPBITS(here.bits); state->length = (unsigned)here.val; /* process literal */ if (here.op == 0) { Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? "inflate: literal '%c'\n" : "inflate: literal 0x%02x\n", here.val)); ROOM(); *put++ = (unsigned char)(state->length); left--; state->mode = LEN; break; } /* process end of block */ if (here.op & 32) { Tracevv((stderr, "inflate: end of block\n")); state->mode = TYPE; break; } /* invalid code */ if (here.op & 64) { strm->msg = (char *)"invalid literal/length code"; state->mode = BAD; break; } /* length code -- get extra bits, if any */ state->extra = (unsigned)(here.op) & 15; if (state->extra != 0) { NEEDBITS(state->extra); state->length += BITS(state->extra); DROPBITS(state->extra); } Tracevv((stderr, "inflate: length %u\n", state->length)); /* get distance code */ for (;;) { here = state->distcode[BITS(state->distbits)]; if ((unsigned)(here.bits) <= bits) break; PULLBYTE(); } if ((here.op & 0xf0) == 0) { last = here; for (;;) { here = state->distcode[last.val + (BITS(last.bits + last.op) >> last.bits)]; if ((unsigned)(last.bits + here.bits) <= bits) break; PULLBYTE(); } DROPBITS(last.bits); } DROPBITS(here.bits); if (here.op & 64) { strm->msg = (char *)"invalid distance code"; state->mode = BAD; break; } state->offset = (unsigned)here.val; /* get distance extra bits, if any */ state->extra = (unsigned)(here.op) & 15; if (state->extra != 0) { NEEDBITS(state->extra); state->offset += BITS(state->extra); DROPBITS(state->extra); } if (state->offset > state->wsize - (state->whave < state->wsize ? left : 0)) { strm->msg = (char *)"invalid distance too far back"; state->mode = BAD; break; } Tracevv((stderr, "inflate: distance %u\n", state->offset)); /* copy match from window to output */ do { ROOM(); copy = state->wsize - state->offset; if (copy < left) { from = put + copy; copy = left - copy; } else { from = put - state->offset; copy = left; } if (copy > state->length) copy = state->length; state->length -= copy; left -= copy; do { *put++ = *from++; } while (--copy); } while (state->length != 0); break; case DONE: /* inflate stream terminated properly -- write leftover output */ ret = Z_STREAM_END; if (left < state->wsize) { if (out(out_desc, state->window, state->wsize - left)) ret = Z_BUF_ERROR; } goto inf_leave; case BAD: ret = Z_DATA_ERROR; goto inf_leave; default: /* can't happen, but makes compilers happy */ ret = Z_STREAM_ERROR; goto inf_leave; } /* Return unused input */ inf_leave: strm->next_in = next; strm->avail_in = have; return ret; } int ZEXPORT inflateBackEnd(strm) z_streamp strm; { if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0) return Z_STREAM_ERROR; ZFREE(strm, strm->state); strm->state = Z_NULL; Tracev((stderr, "inflate: end\n")); return Z_OK; } ================================================ FILE: src/engine/external/zlib/inffast.c ================================================ /* inffast.c -- fast decoding * Copyright (C) 1995-2008, 2010 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ #include "zutil.h" #include "inftrees.h" #include "inflate.h" #include "inffast.h" #ifndef ASMINF /* Allow machine dependent optimization for post-increment or pre-increment. Based on testing to date, Pre-increment preferred for: - PowerPC G3 (Adler) - MIPS R5000 (Randers-Pehrson) Post-increment preferred for: - none No measurable difference: - Pentium III (Anderson) - M68060 (Nikl) */ #ifdef POSTINC # define OFF 0 # define PUP(a) *(a)++ #else # define OFF 1 # define PUP(a) *++(a) #endif /* Decode literal, length, and distance codes and write out the resulting literal and match bytes until either not enough input or output is available, an end-of-block is encountered, or a data error is encountered. When large enough input and output buffers are supplied to inflate(), for example, a 16K input buffer and a 64K output buffer, more than 95% of the inflate execution time is spent in this routine. Entry assumptions: state->mode == LEN strm->avail_in >= 6 strm->avail_out >= 258 start >= strm->avail_out state->bits < 8 On return, state->mode is one of: LEN -- ran out of enough output space or enough available input TYPE -- reached end of block code, inflate() to interpret next block BAD -- error in block data Notes: - The maximum input bits used by a length/distance pair is 15 bits for the length code, 5 bits for the length extra, 15 bits for the distance code, and 13 bits for the distance extra. This totals 48 bits, or six bytes. Therefore if strm->avail_in >= 6, then there is enough input to avoid checking for available input while decoding. - The maximum bytes that a single length/distance pair can output is 258 bytes, which is the maximum length that can be coded. inflate_fast() requires strm->avail_out >= 258 for each loop to avoid checking for output space. */ void ZLIB_INTERNAL inflate_fast(strm, start) z_streamp strm; unsigned start; /* inflate()'s starting value for strm->avail_out */ { struct inflate_state FAR *state; unsigned char FAR *in; /* local strm->next_in */ unsigned char FAR *last; /* while in < last, enough input available */ unsigned char FAR *out; /* local strm->next_out */ unsigned char FAR *beg; /* inflate()'s initial strm->next_out */ unsigned char FAR *end; /* while out < end, enough space available */ #ifdef INFLATE_STRICT unsigned dmax; /* maximum distance from zlib header */ #endif unsigned wsize; /* window size or zero if not using window */ unsigned whave; /* valid bytes in the window */ unsigned wnext; /* window write index */ unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */ unsigned long hold; /* local strm->hold */ unsigned bits; /* local strm->bits */ code const FAR *lcode; /* local strm->lencode */ code const FAR *dcode; /* local strm->distcode */ unsigned lmask; /* mask for first level of length codes */ unsigned dmask; /* mask for first level of distance codes */ code here; /* retrieved table entry */ unsigned op; /* code bits, operation, extra bits, or */ /* window position, window bytes to copy */ unsigned len; /* match length, unused bytes */ unsigned dist; /* match distance */ unsigned char FAR *from; /* where to copy match from */ /* copy state to local variables */ state = (struct inflate_state FAR *)strm->state; in = strm->next_in - OFF; last = in + (strm->avail_in - 5); out = strm->next_out - OFF; beg = out - (start - strm->avail_out); end = out + (strm->avail_out - 257); #ifdef INFLATE_STRICT dmax = state->dmax; #endif wsize = state->wsize; whave = state->whave; wnext = state->wnext; window = state->window; hold = state->hold; bits = state->bits; lcode = state->lencode; dcode = state->distcode; lmask = (1U << state->lenbits) - 1; dmask = (1U << state->distbits) - 1; /* decode literals and length/distances until end-of-block or not enough input data or output space */ do { if (bits < 15) { hold += (unsigned long)(PUP(in)) << bits; bits += 8; hold += (unsigned long)(PUP(in)) << bits; bits += 8; } here = lcode[hold & lmask]; dolen: op = (unsigned)(here.bits); hold >>= op; bits -= op; op = (unsigned)(here.op); if (op == 0) { /* literal */ Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? "inflate: literal '%c'\n" : "inflate: literal 0x%02x\n", here.val)); PUP(out) = (unsigned char)(here.val); } else if (op & 16) { /* length base */ len = (unsigned)(here.val); op &= 15; /* number of extra bits */ if (op) { if (bits < op) { hold += (unsigned long)(PUP(in)) << bits; bits += 8; } len += (unsigned)hold & ((1U << op) - 1); hold >>= op; bits -= op; } Tracevv((stderr, "inflate: length %u\n", len)); if (bits < 15) { hold += (unsigned long)(PUP(in)) << bits; bits += 8; hold += (unsigned long)(PUP(in)) << bits; bits += 8; } here = dcode[hold & dmask]; dodist: op = (unsigned)(here.bits); hold >>= op; bits -= op; op = (unsigned)(here.op); if (op & 16) { /* distance base */ dist = (unsigned)(here.val); op &= 15; /* number of extra bits */ if (bits < op) { hold += (unsigned long)(PUP(in)) << bits; bits += 8; if (bits < op) { hold += (unsigned long)(PUP(in)) << bits; bits += 8; } } dist += (unsigned)hold & ((1U << op) - 1); #ifdef INFLATE_STRICT if (dist > dmax) { strm->msg = (char *)"invalid distance too far back"; state->mode = BAD; break; } #endif hold >>= op; bits -= op; Tracevv((stderr, "inflate: distance %u\n", dist)); op = (unsigned)(out - beg); /* max distance in output */ if (dist > op) { /* see if copy from window */ op = dist - op; /* distance back in window */ if (op > whave) { if (state->sane) { strm->msg = (char *)"invalid distance too far back"; state->mode = BAD; break; } #ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR if (len <= op - whave) { do { PUP(out) = 0; } while (--len); continue; } len -= op - whave; do { PUP(out) = 0; } while (--op > whave); if (op == 0) { from = out - dist; do { PUP(out) = PUP(from); } while (--len); continue; } #endif } from = window - OFF; if (wnext == 0) { /* very common case */ from += wsize - op; if (op < len) { /* some from window */ len -= op; do { PUP(out) = PUP(from); } while (--op); from = out - dist; /* rest from output */ } } else if (wnext < op) { /* wrap around window */ from += wsize + wnext - op; op -= wnext; if (op < len) { /* some from end of window */ len -= op; do { PUP(out) = PUP(from); } while (--op); from = window - OFF; if (wnext < len) { /* some from start of window */ op = wnext; len -= op; do { PUP(out) = PUP(from); } while (--op); from = out - dist; /* rest from output */ } } } else { /* contiguous in window */ from += wnext - op; if (op < len) { /* some from window */ len -= op; do { PUP(out) = PUP(from); } while (--op); from = out - dist; /* rest from output */ } } while (len > 2) { PUP(out) = PUP(from); PUP(out) = PUP(from); PUP(out) = PUP(from); len -= 3; } if (len) { PUP(out) = PUP(from); if (len > 1) PUP(out) = PUP(from); } } else { from = out - dist; /* copy direct from output */ do { /* minimum length is three */ PUP(out) = PUP(from); PUP(out) = PUP(from); PUP(out) = PUP(from); len -= 3; } while (len > 2); if (len) { PUP(out) = PUP(from); if (len > 1) PUP(out) = PUP(from); } } } else if ((op & 64) == 0) { /* 2nd level distance code */ here = dcode[here.val + (hold & ((1U << op) - 1))]; goto dodist; } else { strm->msg = (char *)"invalid distance code"; state->mode = BAD; break; } } else if ((op & 64) == 0) { /* 2nd level length code */ here = lcode[here.val + (hold & ((1U << op) - 1))]; goto dolen; } else if (op & 32) { /* end-of-block */ Tracevv((stderr, "inflate: end of block\n")); state->mode = TYPE; break; } else { strm->msg = (char *)"invalid literal/length code"; state->mode = BAD; break; } } while (in < last && out < end); /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ len = bits >> 3; in -= len; bits -= len << 3; hold &= (1U << bits) - 1; /* update state and return */ strm->next_in = in + OFF; strm->next_out = out + OFF; strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last)); strm->avail_out = (unsigned)(out < end ? 257 + (end - out) : 257 - (out - end)); state->hold = hold; state->bits = bits; return; } /* inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe): - Using bit fields for code structure - Different op definition to avoid & for extra bits (do & for table bits) - Three separate decoding do-loops for direct, window, and wnext == 0 - Special case for distance > 1 copies to do overlapped load and store copy - Explicit branch predictions (based on measured branch probabilities) - Deferring match copy and interspersed it with decoding subsequent codes - Swapping literal/length else - Swapping window/direct else - Larger unrolled copy loops (three is about right) - Moving len -= 3 statement into middle of loop */ #endif /* !ASMINF */ ================================================ FILE: src/engine/external/zlib/inffast.h ================================================ /* inffast.h -- header to use inffast.c * Copyright (C) 1995-2003, 2010 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ /* WARNING: this file should *not* be used by applications. It is part of the implementation of the compression library and is subject to change. Applications should only use zlib.h. */ void ZLIB_INTERNAL inflate_fast OF((z_streamp strm, unsigned start)); ================================================ FILE: src/engine/external/zlib/inffixed.h ================================================ /* inffixed.h -- table for decoding fixed codes * Generated automatically by makefixed(). */ /* WARNING: this file should *not* be used by applications. It is part of the implementation of the compression library and is subject to change. Applications should only use zlib.h. */ static const code lenfix[512] = { {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48}, {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128}, {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59}, {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176}, {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20}, {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100}, {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8}, {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216}, {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76}, {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114}, {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2}, {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148}, {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42}, {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86}, {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15}, {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236}, {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62}, {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142}, {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31}, {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162}, {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25}, {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105}, {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4}, {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202}, {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69}, {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125}, {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13}, {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195}, {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35}, {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91}, {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19}, {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246}, {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55}, {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135}, {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99}, {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190}, {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16}, {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96}, {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6}, {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209}, {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72}, {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116}, {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4}, {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153}, {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44}, {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82}, {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11}, {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229}, {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58}, {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138}, {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51}, {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173}, {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30}, {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110}, {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0}, {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195}, {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65}, {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121}, {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9}, {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258}, {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37}, {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93}, {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23}, {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251}, {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51}, {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131}, {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67}, {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183}, {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23}, {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103}, {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9}, {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223}, {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79}, {0,9,255} }; static const code distfix[32] = { {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025}, {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193}, {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385}, {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577}, {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073}, {22,5,193},{64,5,0} }; ================================================ FILE: src/engine/external/zlib/inflate.c ================================================ /* inflate.c -- zlib decompression * Copyright (C) 1995-2010 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ /* * Change history: * * 1.2.beta0 24 Nov 2002 * - First version -- complete rewrite of inflate to simplify code, avoid * creation of window when not needed, minimize use of window when it is * needed, make inffast.c even faster, implement gzip decoding, and to * improve code readability and style over the previous zlib inflate code * * 1.2.beta1 25 Nov 2002 * - Use pointers for available input and output checking in inffast.c * - Remove input and output counters in inffast.c * - Change inffast.c entry and loop from avail_in >= 7 to >= 6 * - Remove unnecessary second byte pull from length extra in inffast.c * - Unroll direct copy to three copies per loop in inffast.c * * 1.2.beta2 4 Dec 2002 * - Change external routine names to reduce potential conflicts * - Correct filename to inffixed.h for fixed tables in inflate.c * - Make hbuf[] unsigned char to match parameter type in inflate.c * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset) * to avoid negation problem on Alphas (64 bit) in inflate.c * * 1.2.beta3 22 Dec 2002 * - Add comments on state->bits assertion in inffast.c * - Add comments on op field in inftrees.h * - Fix bug in reuse of allocated window after inflateReset() * - Remove bit fields--back to byte structure for speed * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths * - Change post-increments to pre-increments in inflate_fast(), PPC biased? * - Add compile time option, POSTINC, to use post-increments instead (Intel?) * - Make MATCH copy in inflate() much faster for when inflate_fast() not used * - Use local copies of stream next and avail values, as well as local bit * buffer and bit count in inflate()--for speed when inflate_fast() not used * * 1.2.beta4 1 Jan 2003 * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings * - Move a comment on output buffer sizes from inffast.c to inflate.c * - Add comments in inffast.c to introduce the inflate_fast() routine * - Rearrange window copies in inflate_fast() for speed and simplification * - Unroll last copy for window match in inflate_fast() * - Use local copies of window variables in inflate_fast() for speed * - Pull out common wnext == 0 case for speed in inflate_fast() * - Make op and len in inflate_fast() unsigned for consistency * - Add FAR to lcode and dcode declarations in inflate_fast() * - Simplified bad distance check in inflate_fast() * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new * source file infback.c to provide a call-back interface to inflate for * programs like gzip and unzip -- uses window as output buffer to avoid * window copying * * 1.2.beta5 1 Jan 2003 * - Improved inflateBack() interface to allow the caller to provide initial * input in strm. * - Fixed stored blocks bug in inflateBack() * * 1.2.beta6 4 Jan 2003 * - Added comments in inffast.c on effectiveness of POSTINC * - Typecasting all around to reduce compiler warnings * - Changed loops from while (1) or do {} while (1) to for (;;), again to * make compilers happy * - Changed type of window in inflateBackInit() to unsigned char * * * 1.2.beta7 27 Jan 2003 * - Changed many types to unsigned or unsigned short to avoid warnings * - Added inflateCopy() function * * 1.2.0 9 Mar 2003 * - Changed inflateBack() interface to provide separate opaque descriptors * for the in() and out() functions * - Changed inflateBack() argument and in_func typedef to swap the length * and buffer address return values for the input function * - Check next_in and next_out for Z_NULL on entry to inflate() * * The history for versions after 1.2.0 are in ChangeLog in zlib distribution. */ #include "zutil.h" #include "inftrees.h" #include "inflate.h" #include "inffast.h" #ifdef MAKEFIXED # ifndef BUILDFIXED # define BUILDFIXED # endif #endif /* function prototypes */ local void fixedtables OF((struct inflate_state FAR *state)); local int updatewindow OF((z_streamp strm, unsigned out)); #ifdef BUILDFIXED void makefixed OF((void)); #endif local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf, unsigned len)); int ZEXPORT inflateReset(strm) z_streamp strm; { struct inflate_state FAR *state; if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; strm->total_in = strm->total_out = state->total = 0; strm->msg = Z_NULL; strm->adler = 1; /* to support ill-conceived Java test suite */ state->mode = HEAD; state->last = 0; state->havedict = 0; state->dmax = 32768U; state->head = Z_NULL; state->wsize = 0; state->whave = 0; state->wnext = 0; state->hold = 0; state->bits = 0; state->lencode = state->distcode = state->next = state->codes; state->sane = 1; state->back = -1; Tracev((stderr, "inflate: reset\n")); return Z_OK; } int ZEXPORT inflateReset2(strm, windowBits) z_streamp strm; int windowBits; { int wrap; struct inflate_state FAR *state; /* get the state */ if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; /* extract wrap request from windowBits parameter */ if (windowBits < 0) { wrap = 0; windowBits = -windowBits; } else { wrap = (windowBits >> 4) + 1; #ifdef GUNZIP if (windowBits < 48) windowBits &= 15; #endif } /* set number of window bits, free window if different */ if (windowBits && (windowBits < 8 || windowBits > 15)) return Z_STREAM_ERROR; if (state->window != Z_NULL && state->wbits != (unsigned)windowBits) { ZFREE(strm, state->window); state->window = Z_NULL; } /* update state and reset the rest of it */ state->wrap = wrap; state->wbits = (unsigned)windowBits; return inflateReset(strm); } int ZEXPORT inflateInit2_(strm, windowBits, version, stream_size) z_streamp strm; int windowBits; const char *version; int stream_size; { int ret; struct inflate_state FAR *state; if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || stream_size != (int)(sizeof(z_stream))) return Z_VERSION_ERROR; if (strm == Z_NULL) return Z_STREAM_ERROR; strm->msg = Z_NULL; /* in case we return an error */ if (strm->zalloc == (alloc_func)0) { strm->zalloc = zcalloc; strm->opaque = (voidpf)0; } if (strm->zfree == (free_func)0) strm->zfree = zcfree; state = (struct inflate_state FAR *) ZALLOC(strm, 1, sizeof(struct inflate_state)); if (state == Z_NULL) return Z_MEM_ERROR; Tracev((stderr, "inflate: allocated\n")); strm->state = (struct internal_state FAR *)state; state->window = Z_NULL; ret = inflateReset2(strm, windowBits); if (ret != Z_OK) { ZFREE(strm, state); strm->state = Z_NULL; } return ret; } int ZEXPORT inflateInit_(strm, version, stream_size) z_streamp strm; const char *version; int stream_size; { return inflateInit2_(strm, DEF_WBITS, version, stream_size); } int ZEXPORT inflatePrime(strm, bits, value) z_streamp strm; int bits; int value; { struct inflate_state FAR *state; if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; if (bits < 0) { state->hold = 0; state->bits = 0; return Z_OK; } if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR; value &= (1L << bits) - 1; state->hold += value << state->bits; state->bits += bits; return Z_OK; } /* Return state with length and distance decoding tables and index sizes set to fixed code decoding. Normally this returns fixed tables from inffixed.h. If BUILDFIXED is defined, then instead this routine builds the tables the first time it's called, and returns those tables the first time and thereafter. This reduces the size of the code by about 2K bytes, in exchange for a little execution time. However, BUILDFIXED should not be used for threaded applications, since the rewriting of the tables and virgin may not be thread-safe. */ local void fixedtables(state) struct inflate_state FAR *state; { #ifdef BUILDFIXED static int virgin = 1; static code *lenfix, *distfix; static code fixed[544]; /* build fixed huffman tables if first call (may not be thread safe) */ if (virgin) { unsigned sym, bits; static code *next; /* literal/length table */ sym = 0; while (sym < 144) state->lens[sym++] = 8; while (sym < 256) state->lens[sym++] = 9; while (sym < 280) state->lens[sym++] = 7; while (sym < 288) state->lens[sym++] = 8; next = fixed; lenfix = next; bits = 9; inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work); /* distance table */ sym = 0; while (sym < 32) state->lens[sym++] = 5; distfix = next; bits = 5; inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work); /* do this just once */ virgin = 0; } #else /* !BUILDFIXED */ # include "inffixed.h" #endif /* BUILDFIXED */ state->lencode = lenfix; state->lenbits = 9; state->distcode = distfix; state->distbits = 5; } #ifdef MAKEFIXED #include <stdio.h> /* Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also defines BUILDFIXED, so the tables are built on the fly. makefixed() writes those tables to stdout, which would be piped to inffixed.h. A small program can simply call makefixed to do this: void makefixed(void); int main(void) { makefixed(); return 0; } Then that can be linked with zlib built with MAKEFIXED defined and run: a.out > inffixed.h */ void makefixed() { unsigned low, size; struct inflate_state state; fixedtables(&state); puts(" /* inffixed.h -- table for decoding fixed codes"); puts(" * Generated automatically by makefixed()."); puts(" */"); puts(""); puts(" /* WARNING: this file should *not* be used by applications."); puts(" It is part of the implementation of this library and is"); puts(" subject to change. Applications should only use zlib.h."); puts(" */"); puts(""); size = 1U << 9; printf(" static const code lenfix[%u] = {", size); low = 0; for (;;) { if ((low % 7) == 0) printf("\n "); printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits, state.lencode[low].val); if (++low == size) break; putchar(','); } puts("\n };"); size = 1U << 5; printf("\n static const code distfix[%u] = {", size); low = 0; for (;;) { if ((low % 6) == 0) printf("\n "); printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits, state.distcode[low].val); if (++low == size) break; putchar(','); } puts("\n };"); } #endif /* MAKEFIXED */ /* Update the window with the last wsize (normally 32K) bytes written before returning. If window does not exist yet, create it. This is only called when a window is already in use, or when output has been written during this inflate call, but the end of the deflate stream has not been reached yet. It is also called to create a window for dictionary data when a dictionary is loaded. Providing output buffers larger than 32K to inflate() should provide a speed advantage, since only the last 32K of output is copied to the sliding window upon return from inflate(), and since all distances after the first 32K of output will fall in the output data, making match copies simpler and faster. The advantage may be dependent on the size of the processor's data caches. */ local int updatewindow(strm, out) z_streamp strm; unsigned out; { struct inflate_state FAR *state; unsigned copy, dist; state = (struct inflate_state FAR *)strm->state; /* if it hasn't been done already, allocate space for the window */ if (state->window == Z_NULL) { state->window = (unsigned char FAR *) ZALLOC(strm, 1U << state->wbits, sizeof(unsigned char)); if (state->window == Z_NULL) return 1; } /* if window not in use yet, initialize */ if (state->wsize == 0) { state->wsize = 1U << state->wbits; state->wnext = 0; state->whave = 0; } /* copy state->wsize or less output bytes into the circular window */ copy = out - strm->avail_out; if (copy >= state->wsize) { zmemcpy(state->window, strm->next_out - state->wsize, state->wsize); state->wnext = 0; state->whave = state->wsize; } else { dist = state->wsize - state->wnext; if (dist > copy) dist = copy; zmemcpy(state->window + state->wnext, strm->next_out - copy, dist); copy -= dist; if (copy) { zmemcpy(state->window, strm->next_out - copy, copy); state->wnext = copy; state->whave = state->wsize; } else { state->wnext += dist; if (state->wnext == state->wsize) state->wnext = 0; if (state->whave < state->wsize) state->whave += dist; } } return 0; } /* Macros for inflate(): */ /* check function to use adler32() for zlib or crc32() for gzip */ #ifdef GUNZIP # define UPDATE(check, buf, len) \ (state->flags ? crc32(check, buf, len) : adler32(check, buf, len)) #else # define UPDATE(check, buf, len) adler32(check, buf, len) #endif /* check macros for header crc */ #ifdef GUNZIP # define CRC2(check, word) \ do { \ hbuf[0] = (unsigned char)(word); \ hbuf[1] = (unsigned char)((word) >> 8); \ check = crc32(check, hbuf, 2); \ } while (0) # define CRC4(check, word) \ do { \ hbuf[0] = (unsigned char)(word); \ hbuf[1] = (unsigned char)((word) >> 8); \ hbuf[2] = (unsigned char)((word) >> 16); \ hbuf[3] = (unsigned char)((word) >> 24); \ check = crc32(check, hbuf, 4); \ } while (0) #endif /* Load registers with state in inflate() for speed */ #define LOAD() \ do { \ put = strm->next_out; \ left = strm->avail_out; \ next = strm->next_in; \ have = strm->avail_in; \ hold = state->hold; \ bits = state->bits; \ } while (0) /* Restore state from registers in inflate() */ #define RESTORE() \ do { \ strm->next_out = put; \ strm->avail_out = left; \ strm->next_in = next; \ strm->avail_in = have; \ state->hold = hold; \ state->bits = bits; \ } while (0) /* Clear the input bit accumulator */ #define INITBITS() \ do { \ hold = 0; \ bits = 0; \ } while (0) /* Get a byte of input into the bit accumulator, or return from inflate() if there is no input available. */ #define PULLBYTE() \ do { \ if (have == 0) goto inf_leave; \ have--; \ hold += (unsigned long)(*next++) << bits; \ bits += 8; \ } while (0) /* Assure that there are at least n bits in the bit accumulator. If there is not enough available input to do that, then return from inflate(). */ #define NEEDBITS(n) \ do { \ while (bits < (unsigned)(n)) \ PULLBYTE(); \ } while (0) /* Return the low n bits of the bit accumulator (n < 16) */ #define BITS(n) \ ((unsigned)hold & ((1U << (n)) - 1)) /* Remove n bits from the bit accumulator */ #define DROPBITS(n) \ do { \ hold >>= (n); \ bits -= (unsigned)(n); \ } while (0) /* Remove zero to seven bits as needed to go to a byte boundary */ #define BYTEBITS() \ do { \ hold >>= bits & 7; \ bits -= bits & 7; \ } while (0) /* Reverse the bytes in a 32-bit value */ #define REVERSE(q) \ ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \ (((q) & 0xff00) << 8) + (((q) & 0xff) << 24)) /* inflate() uses a state machine to process as much input data and generate as much output data as possible before returning. The state machine is structured roughly as follows: for (;;) switch (state) { ... case STATEn: if (not enough input data or output space to make progress) return; ... make progress ... state = STATEm; break; ... } so when inflate() is called again, the same case is attempted again, and if the appropriate resources are provided, the machine proceeds to the next state. The NEEDBITS() macro is usually the way the state evaluates whether it can proceed or should return. NEEDBITS() does the return if the requested bits are not available. The typical use of the BITS macros is: NEEDBITS(n); ... do something with BITS(n) ... DROPBITS(n); where NEEDBITS(n) either returns from inflate() if there isn't enough input left to load n bits into the accumulator, or it continues. BITS(n) gives the low n bits in the accumulator. When done, DROPBITS(n) drops the low n bits off the accumulator. INITBITS() clears the accumulator and sets the number of available bits to zero. BYTEBITS() discards just enough bits to put the accumulator on a byte boundary. After BYTEBITS() and a NEEDBITS(8), then BITS(8) would return the next byte in the stream. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return if there is no input available. The decoding of variable length codes uses PULLBYTE() directly in order to pull just enough bytes to decode the next code, and no more. Some states loop until they get enough input, making sure that enough state information is maintained to continue the loop where it left off if NEEDBITS() returns in the loop. For example, want, need, and keep would all have to actually be part of the saved state in case NEEDBITS() returns: case STATEw: while (want < need) { NEEDBITS(n); keep[want++] = BITS(n); DROPBITS(n); } state = STATEx; case STATEx: As shown above, if the next state is also the next case, then the break is omitted. A state may also return if there is not enough output space available to complete that state. Those states are copying stored data, writing a literal byte, and copying a matching string. When returning, a "goto inf_leave" is used to update the total counters, update the check value, and determine whether any progress has been made during that inflate() call in order to return the proper return code. Progress is defined as a change in either strm->avail_in or strm->avail_out. When there is a window, goto inf_leave will update the window with the last output written. If a goto inf_leave occurs in the middle of decompression and there is no window currently, goto inf_leave will create one and copy output to the window for the next call of inflate(). In this implementation, the flush parameter of inflate() only affects the return code (per zlib.h). inflate() always writes as much as possible to strm->next_out, given the space available and the provided input--the effect documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers the allocation of and copying into a sliding window until necessary, which provides the effect documented in zlib.h for Z_FINISH when the entire input stream available. So the only thing the flush parameter actually does is: when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it will return Z_BUF_ERROR if it has not reached the end of the stream. */ int ZEXPORT inflate(strm, flush) z_streamp strm; int flush; { struct inflate_state FAR *state; unsigned char FAR *next; /* next input */ unsigned char FAR *put; /* next output */ unsigned have, left; /* available input and output */ unsigned long hold; /* bit buffer */ unsigned bits; /* bits in bit buffer */ unsigned in, out; /* save starting available input and output */ unsigned copy; /* number of stored or match bytes to copy */ unsigned char FAR *from; /* where to copy match bytes from */ code here; /* current decoding table entry */ code last; /* parent table entry */ unsigned len; /* length to copy for repeats, bits to drop */ int ret; /* return code */ #ifdef GUNZIP unsigned char hbuf[4]; /* buffer for gzip header crc calculation */ #endif static const unsigned short order[19] = /* permutation of code lengths */ {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL || (strm->next_in == Z_NULL && strm->avail_in != 0)) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */ LOAD(); in = have; out = left; ret = Z_OK; for (;;) switch (state->mode) { case HEAD: if (state->wrap == 0) { state->mode = TYPEDO; break; } NEEDBITS(16); #ifdef GUNZIP if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */ state->check = crc32(0L, Z_NULL, 0); CRC2(state->check, hold); INITBITS(); state->mode = FLAGS; break; } state->flags = 0; /* expect zlib header */ if (state->head != Z_NULL) state->head->done = -1; if (!(state->wrap & 1) || /* check if zlib header allowed */ #else if ( #endif ((BITS(8) << 8) + (hold >> 8)) % 31) { strm->msg = (char *)"incorrect header check"; state->mode = BAD; break; } if (BITS(4) != Z_DEFLATED) { strm->msg = (char *)"unknown compression method"; state->mode = BAD; break; } DROPBITS(4); len = BITS(4) + 8; if (state->wbits == 0) state->wbits = len; else if (len > state->wbits) { strm->msg = (char *)"invalid window size"; state->mode = BAD; break; } state->dmax = 1U << len; Tracev((stderr, "inflate: zlib header ok\n")); strm->adler = state->check = adler32(0L, Z_NULL, 0); state->mode = hold & 0x200 ? DICTID : TYPE; INITBITS(); break; #ifdef GUNZIP case FLAGS: NEEDBITS(16); state->flags = (int)(hold); if ((state->flags & 0xff) != Z_DEFLATED) { strm->msg = (char *)"unknown compression method"; state->mode = BAD; break; } if (state->flags & 0xe000) { strm->msg = (char *)"unknown header flags set"; state->mode = BAD; break; } if (state->head != Z_NULL) state->head->text = (int)((hold >> 8) & 1); if (state->flags & 0x0200) CRC2(state->check, hold); INITBITS(); state->mode = TIME; case TIME: NEEDBITS(32); if (state->head != Z_NULL) state->head->time = hold; if (state->flags & 0x0200) CRC4(state->check, hold); INITBITS(); state->mode = OS; case OS: NEEDBITS(16); if (state->head != Z_NULL) { state->head->xflags = (int)(hold & 0xff); state->head->os = (int)(hold >> 8); } if (state->flags & 0x0200) CRC2(state->check, hold); INITBITS(); state->mode = EXLEN; case EXLEN: if (state->flags & 0x0400) { NEEDBITS(16); state->length = (unsigned)(hold); if (state->head != Z_NULL) state->head->extra_len = (unsigned)hold; if (state->flags & 0x0200) CRC2(state->check, hold); INITBITS(); } else if (state->head != Z_NULL) state->head->extra = Z_NULL; state->mode = EXTRA; case EXTRA: if (state->flags & 0x0400) { copy = state->length; if (copy > have) copy = have; if (copy) { if (state->head != Z_NULL && state->head->extra != Z_NULL) { len = state->head->extra_len - state->length; zmemcpy(state->head->extra + len, next, len + copy > state->head->extra_max ? state->head->extra_max - len : copy); } if (state->flags & 0x0200) state->check = crc32(state->check, next, copy); have -= copy; next += copy; state->length -= copy; } if (state->length) goto inf_leave; } state->length = 0; state->mode = NAME; case NAME: if (state->flags & 0x0800) { if (have == 0) goto inf_leave; copy = 0; do { len = (unsigned)(next[copy++]); if (state->head != Z_NULL && state->head->name != Z_NULL && state->length < state->head->name_max) state->head->name[state->length++] = len; } while (len && copy < have); if (state->flags & 0x0200) state->check = crc32(state->check, next, copy); have -= copy; next += copy; if (len) goto inf_leave; } else if (state->head != Z_NULL) state->head->name = Z_NULL; state->length = 0; state->mode = COMMENT; case COMMENT: if (state->flags & 0x1000) { if (have == 0) goto inf_leave; copy = 0; do { len = (unsigned)(next[copy++]); if (state->head != Z_NULL && state->head->comment != Z_NULL && state->length < state->head->comm_max) state->head->comment[state->length++] = len; } while (len && copy < have); if (state->flags & 0x0200) state->check = crc32(state->check, next, copy); have -= copy; next += copy; if (len) goto inf_leave; } else if (state->head != Z_NULL) state->head->comment = Z_NULL; state->mode = HCRC; case HCRC: if (state->flags & 0x0200) { NEEDBITS(16); if (hold != (state->check & 0xffff)) { strm->msg = (char *)"header crc mismatch"; state->mode = BAD; break; } INITBITS(); } if (state->head != Z_NULL) { state->head->hcrc = (int)((state->flags >> 9) & 1); state->head->done = 1; } strm->adler = state->check = crc32(0L, Z_NULL, 0); state->mode = TYPE; break; #endif case DICTID: NEEDBITS(32); strm->adler = state->check = REVERSE(hold); INITBITS(); state->mode = DICT; case DICT: if (state->havedict == 0) { RESTORE(); return Z_NEED_DICT; } strm->adler = state->check = adler32(0L, Z_NULL, 0); state->mode = TYPE; case TYPE: if (flush == Z_BLOCK || flush == Z_TREES) goto inf_leave; case TYPEDO: if (state->last) { BYTEBITS(); state->mode = CHECK; break; } NEEDBITS(3); state->last = BITS(1); DROPBITS(1); switch (BITS(2)) { case 0: /* stored block */ Tracev((stderr, "inflate: stored block%s\n", state->last ? " (last)" : "")); state->mode = STORED; break; case 1: /* fixed block */ fixedtables(state); Tracev((stderr, "inflate: fixed codes block%s\n", state->last ? " (last)" : "")); state->mode = LEN_; /* decode codes */ if (flush == Z_TREES) { DROPBITS(2); goto inf_leave; } break; case 2: /* dynamic block */ Tracev((stderr, "inflate: dynamic codes block%s\n", state->last ? " (last)" : "")); state->mode = TABLE; break; case 3: strm->msg = (char *)"invalid block type"; state->mode = BAD; } DROPBITS(2); break; case STORED: BYTEBITS(); /* go to byte boundary */ NEEDBITS(32); if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) { strm->msg = (char *)"invalid stored block lengths"; state->mode = BAD; break; } state->length = (unsigned)hold & 0xffff; Tracev((stderr, "inflate: stored length %u\n", state->length)); INITBITS(); state->mode = COPY_; if (flush == Z_TREES) goto inf_leave; case COPY_: state->mode = COPY; case COPY: copy = state->length; if (copy) { if (copy > have) copy = have; if (copy > left) copy = left; if (copy == 0) goto inf_leave; zmemcpy(put, next, copy); have -= copy; next += copy; left -= copy; put += copy; state->length -= copy; break; } Tracev((stderr, "inflate: stored end\n")); state->mode = TYPE; break; case TABLE: NEEDBITS(14); state->nlen = BITS(5) + 257; DROPBITS(5); state->ndist = BITS(5) + 1; DROPBITS(5); state->ncode = BITS(4) + 4; DROPBITS(4); #ifndef PKZIP_BUG_WORKAROUND if (state->nlen > 286 || state->ndist > 30) { strm->msg = (char *)"too many length or distance symbols"; state->mode = BAD; break; } #endif Tracev((stderr, "inflate: table sizes ok\n")); state->have = 0; state->mode = LENLENS; case LENLENS: while (state->have < state->ncode) { NEEDBITS(3); state->lens[order[state->have++]] = (unsigned short)BITS(3); DROPBITS(3); } while (state->have < 19) state->lens[order[state->have++]] = 0; state->next = state->codes; state->lencode = (code const FAR *)(state->next); state->lenbits = 7; ret = inflate_table(CODES, state->lens, 19, &(state->next), &(state->lenbits), state->work); if (ret) { strm->msg = (char *)"invalid code lengths set"; state->mode = BAD; break; } Tracev((stderr, "inflate: code lengths ok\n")); state->have = 0; state->mode = CODELENS; case CODELENS: while (state->have < state->nlen + state->ndist) { for (;;) { here = state->lencode[BITS(state->lenbits)]; if ((unsigned)(here.bits) <= bits) break; PULLBYTE(); } if (here.val < 16) { NEEDBITS(here.bits); DROPBITS(here.bits); state->lens[state->have++] = here.val; } else { if (here.val == 16) { NEEDBITS(here.bits + 2); DROPBITS(here.bits); if (state->have == 0) { strm->msg = (char *)"invalid bit length repeat"; state->mode = BAD; break; } len = state->lens[state->have - 1]; copy = 3 + BITS(2); DROPBITS(2); } else if (here.val == 17) { NEEDBITS(here.bits + 3); DROPBITS(here.bits); len = 0; copy = 3 + BITS(3); DROPBITS(3); } else { NEEDBITS(here.bits + 7); DROPBITS(here.bits); len = 0; copy = 11 + BITS(7); DROPBITS(7); } if (state->have + copy > state->nlen + state->ndist) { strm->msg = (char *)"invalid bit length repeat"; state->mode = BAD; break; } while (copy--) state->lens[state->have++] = (unsigned short)len; } } /* handle error breaks in while */ if (state->mode == BAD) break; /* check for end-of-block code (better have one) */ if (state->lens[256] == 0) { strm->msg = (char *)"invalid code -- missing end-of-block"; state->mode = BAD; break; } /* build code tables -- note: do not change the lenbits or distbits values here (9 and 6) without reading the comments in inftrees.h concerning the ENOUGH constants, which depend on those values */ state->next = state->codes; state->lencode = (code const FAR *)(state->next); state->lenbits = 9; ret = inflate_table(LENS, state->lens, state->nlen, &(state->next), &(state->lenbits), state->work); if (ret) { strm->msg = (char *)"invalid literal/lengths set"; state->mode = BAD; break; } state->distcode = (code const FAR *)(state->next); state->distbits = 6; ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist, &(state->next), &(state->distbits), state->work); if (ret) { strm->msg = (char *)"invalid distances set"; state->mode = BAD; break; } Tracev((stderr, "inflate: codes ok\n")); state->mode = LEN_; if (flush == Z_TREES) goto inf_leave; case LEN_: state->mode = LEN; case LEN: if (have >= 6 && left >= 258) { RESTORE(); inflate_fast(strm, out); LOAD(); if (state->mode == TYPE) state->back = -1; break; } state->back = 0; for (;;) { here = state->lencode[BITS(state->lenbits)]; if ((unsigned)(here.bits) <= bits) break; PULLBYTE(); } if (here.op && (here.op & 0xf0) == 0) { last = here; for (;;) { here = state->lencode[last.val + (BITS(last.bits + last.op) >> last.bits)]; if ((unsigned)(last.bits + here.bits) <= bits) break; PULLBYTE(); } DROPBITS(last.bits); state->back += last.bits; } DROPBITS(here.bits); state->back += here.bits; state->length = (unsigned)here.val; if ((int)(here.op) == 0) { Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? "inflate: literal '%c'\n" : "inflate: literal 0x%02x\n", here.val)); state->mode = LIT; break; } if (here.op & 32) { Tracevv((stderr, "inflate: end of block\n")); state->back = -1; state->mode = TYPE; break; } if (here.op & 64) { strm->msg = (char *)"invalid literal/length code"; state->mode = BAD; break; } state->extra = (unsigned)(here.op) & 15; state->mode = LENEXT; case LENEXT: if (state->extra) { NEEDBITS(state->extra); state->length += BITS(state->extra); DROPBITS(state->extra); state->back += state->extra; } Tracevv((stderr, "inflate: length %u\n", state->length)); state->was = state->length; state->mode = DIST; case DIST: for (;;) { here = state->distcode[BITS(state->distbits)]; if ((unsigned)(here.bits) <= bits) break; PULLBYTE(); } if ((here.op & 0xf0) == 0) { last = here; for (;;) { here = state->distcode[last.val + (BITS(last.bits + last.op) >> last.bits)]; if ((unsigned)(last.bits + here.bits) <= bits) break; PULLBYTE(); } DROPBITS(last.bits); state->back += last.bits; } DROPBITS(here.bits); state->back += here.bits; if (here.op & 64) { strm->msg = (char *)"invalid distance code"; state->mode = BAD; break; } state->offset = (unsigned)here.val; state->extra = (unsigned)(here.op) & 15; state->mode = DISTEXT; case DISTEXT: if (state->extra) { NEEDBITS(state->extra); state->offset += BITS(state->extra); DROPBITS(state->extra); state->back += state->extra; } #ifdef INFLATE_STRICT if (state->offset > state->dmax) { strm->msg = (char *)"invalid distance too far back"; state->mode = BAD; break; } #endif Tracevv((stderr, "inflate: distance %u\n", state->offset)); state->mode = MATCH; case MATCH: if (left == 0) goto inf_leave; copy = out - left; if (state->offset > copy) { /* copy from window */ copy = state->offset - copy; if (copy > state->whave) { if (state->sane) { strm->msg = (char *)"invalid distance too far back"; state->mode = BAD; break; } #ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR Trace((stderr, "inflate.c too far\n")); copy -= state->whave; if (copy > state->length) copy = state->length; if (copy > left) copy = left; left -= copy; state->length -= copy; do { *put++ = 0; } while (--copy); if (state->length == 0) state->mode = LEN; break; #endif } if (copy > state->wnext) { copy -= state->wnext; from = state->window + (state->wsize - copy); } else from = state->window + (state->wnext - copy); if (copy > state->length) copy = state->length; } else { /* copy from output */ from = put - state->offset; copy = state->length; } if (copy > left) copy = left; left -= copy; state->length -= copy; do { *put++ = *from++; } while (--copy); if (state->length == 0) state->mode = LEN; break; case LIT: if (left == 0) goto inf_leave; *put++ = (unsigned char)(state->length); left--; state->mode = LEN; break; case CHECK: if (state->wrap) { NEEDBITS(32); out -= left; strm->total_out += out; state->total += out; if (out) strm->adler = state->check = UPDATE(state->check, put - out, out); out = left; if (( #ifdef GUNZIP state->flags ? hold : #endif REVERSE(hold)) != state->check) { strm->msg = (char *)"incorrect data check"; state->mode = BAD; break; } INITBITS(); Tracev((stderr, "inflate: check matches trailer\n")); } #ifdef GUNZIP state->mode = LENGTH; case LENGTH: if (state->wrap && state->flags) { NEEDBITS(32); if (hold != (state->total & 0xffffffffUL)) { strm->msg = (char *)"incorrect length check"; state->mode = BAD; break; } INITBITS(); Tracev((stderr, "inflate: length matches trailer\n")); } #endif state->mode = DONE; case DONE: ret = Z_STREAM_END; goto inf_leave; case BAD: ret = Z_DATA_ERROR; goto inf_leave; case MEM: return Z_MEM_ERROR; case SYNC: default: return Z_STREAM_ERROR; } /* Return from inflate(), updating the total counts and the check value. If there was no progress during the inflate() call, return a buffer error. Call updatewindow() to create and/or update the window state. Note: a memory error from inflate() is non-recoverable. */ inf_leave: RESTORE(); if (state->wsize || (state->mode < CHECK && out != strm->avail_out)) if (updatewindow(strm, out)) { state->mode = MEM; return Z_MEM_ERROR; } in -= strm->avail_in; out -= strm->avail_out; strm->total_in += in; strm->total_out += out; state->total += out; if (state->wrap && out) strm->adler = state->check = UPDATE(state->check, strm->next_out - out, out); strm->data_type = state->bits + (state->last ? 64 : 0) + (state->mode == TYPE ? 128 : 0) + (state->mode == LEN_ || state->mode == COPY_ ? 256 : 0); if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK) ret = Z_BUF_ERROR; return ret; } int ZEXPORT inflateEnd(strm) z_streamp strm; { struct inflate_state FAR *state; if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; if (state->window != Z_NULL) ZFREE(strm, state->window); ZFREE(strm, strm->state); strm->state = Z_NULL; Tracev((stderr, "inflate: end\n")); return Z_OK; } int ZEXPORT inflateSetDictionary(strm, dictionary, dictLength) z_streamp strm; const Bytef *dictionary; uInt dictLength; { struct inflate_state FAR *state; unsigned long id; /* check state */ if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; if (state->wrap != 0 && state->mode != DICT) return Z_STREAM_ERROR; /* check for correct dictionary id */ if (state->mode == DICT) { id = adler32(0L, Z_NULL, 0); id = adler32(id, dictionary, dictLength); if (id != state->check) return Z_DATA_ERROR; } /* copy dictionary to window */ if (updatewindow(strm, strm->avail_out)) { state->mode = MEM; return Z_MEM_ERROR; } if (dictLength > state->wsize) { zmemcpy(state->window, dictionary + dictLength - state->wsize, state->wsize); state->whave = state->wsize; } else { zmemcpy(state->window + state->wsize - dictLength, dictionary, dictLength); state->whave = dictLength; } state->havedict = 1; Tracev((stderr, "inflate: dictionary set\n")); return Z_OK; } int ZEXPORT inflateGetHeader(strm, head) z_streamp strm; gz_headerp head; { struct inflate_state FAR *state; /* check state */ if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; if ((state->wrap & 2) == 0) return Z_STREAM_ERROR; /* save header structure */ state->head = head; head->done = 0; return Z_OK; } /* Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found or when out of input. When called, *have is the number of pattern bytes found in order so far, in 0..3. On return *have is updated to the new state. If on return *have equals four, then the pattern was found and the return value is how many bytes were read including the last byte of the pattern. If *have is less than four, then the pattern has not been found yet and the return value is len. In the latter case, syncsearch() can be called again with more data and the *have state. *have is initialized to zero for the first call. */ local unsigned syncsearch(have, buf, len) unsigned FAR *have; unsigned char FAR *buf; unsigned len; { unsigned got; unsigned next; got = *have; next = 0; while (next < len && got < 4) { if ((int)(buf[next]) == (got < 2 ? 0 : 0xff)) got++; else if (buf[next]) got = 0; else got = 4 - got; next++; } *have = got; return next; } int ZEXPORT inflateSync(strm) z_streamp strm; { unsigned len; /* number of bytes to look at or looked at */ unsigned long in, out; /* temporary to save total_in and total_out */ unsigned char buf[4]; /* to restore bit buffer to byte string */ struct inflate_state FAR *state; /* check parameters */ if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR; /* if first time, start search in bit buffer */ if (state->mode != SYNC) { state->mode = SYNC; state->hold <<= state->bits & 7; state->bits -= state->bits & 7; len = 0; while (state->bits >= 8) { buf[len++] = (unsigned char)(state->hold); state->hold >>= 8; state->bits -= 8; } state->have = 0; syncsearch(&(state->have), buf, len); } /* search available input */ len = syncsearch(&(state->have), strm->next_in, strm->avail_in); strm->avail_in -= len; strm->next_in += len; strm->total_in += len; /* return no joy or set up to restart inflate() on a new block */ if (state->have != 4) return Z_DATA_ERROR; in = strm->total_in; out = strm->total_out; inflateReset(strm); strm->total_in = in; strm->total_out = out; state->mode = TYPE; return Z_OK; } /* Returns true if inflate is currently at the end of a block generated by Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP implementation to provide an additional safety check. PPP uses Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored block. When decompressing, PPP checks that at the end of input packet, inflate is waiting for these length bytes. */ int ZEXPORT inflateSyncPoint(strm) z_streamp strm; { struct inflate_state FAR *state; if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; return state->mode == STORED && state->bits == 0; } int ZEXPORT inflateCopy(dest, source) z_streamp dest; z_streamp source; { struct inflate_state FAR *state; struct inflate_state FAR *copy; unsigned char FAR *window; unsigned wsize; /* check input */ if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL || source->zalloc == (alloc_func)0 || source->zfree == (free_func)0) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)source->state; /* allocate space */ copy = (struct inflate_state FAR *) ZALLOC(source, 1, sizeof(struct inflate_state)); if (copy == Z_NULL) return Z_MEM_ERROR; window = Z_NULL; if (state->window != Z_NULL) { window = (unsigned char FAR *) ZALLOC(source, 1U << state->wbits, sizeof(unsigned char)); if (window == Z_NULL) { ZFREE(source, copy); return Z_MEM_ERROR; } } /* copy state */ zmemcpy(dest, source, sizeof(z_stream)); zmemcpy(copy, state, sizeof(struct inflate_state)); if (state->lencode >= state->codes && state->lencode <= state->codes + ENOUGH - 1) { copy->lencode = copy->codes + (state->lencode - state->codes); copy->distcode = copy->codes + (state->distcode - state->codes); } copy->next = copy->codes + (state->next - state->codes); if (window != Z_NULL) { wsize = 1U << state->wbits; zmemcpy(window, state->window, wsize); } copy->window = window; dest->state = (struct internal_state FAR *)copy; return Z_OK; } int ZEXPORT inflateUndermine(strm, subvert) z_streamp strm; int subvert; { struct inflate_state FAR *state; if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; state->sane = !subvert; #ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR return Z_OK; #else state->sane = 1; return Z_DATA_ERROR; #endif } long ZEXPORT inflateMark(strm) z_streamp strm; { struct inflate_state FAR *state; if (strm == Z_NULL || strm->state == Z_NULL) return -1L << 16; state = (struct inflate_state FAR *)strm->state; return ((long)(state->back) << 16) + (state->mode == COPY ? state->length : (state->mode == MATCH ? state->was - state->length : 0)); } ================================================ FILE: src/engine/external/zlib/inflate.h ================================================ /* inflate.h -- internal inflate state definition * Copyright (C) 1995-2009 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ /* WARNING: this file should *not* be used by applications. It is part of the implementation of the compression library and is subject to change. Applications should only use zlib.h. */ /* define NO_GZIP when compiling if you want to disable gzip header and trailer decoding by inflate(). NO_GZIP would be used to avoid linking in the crc code when it is not needed. For shared libraries, gzip decoding should be left enabled. */ #ifndef NO_GZIP # define GUNZIP #endif /* Possible inflate modes between inflate() calls */ typedef enum { HEAD, /* i: waiting for magic header */ FLAGS, /* i: waiting for method and flags (gzip) */ TIME, /* i: waiting for modification time (gzip) */ OS, /* i: waiting for extra flags and operating system (gzip) */ EXLEN, /* i: waiting for extra length (gzip) */ EXTRA, /* i: waiting for extra bytes (gzip) */ NAME, /* i: waiting for end of file name (gzip) */ COMMENT, /* i: waiting for end of comment (gzip) */ HCRC, /* i: waiting for header crc (gzip) */ DICTID, /* i: waiting for dictionary check value */ DICT, /* waiting for inflateSetDictionary() call */ TYPE, /* i: waiting for type bits, including last-flag bit */ TYPEDO, /* i: same, but skip check to exit inflate on new block */ STORED, /* i: waiting for stored size (length and complement) */ COPY_, /* i/o: same as COPY below, but only first time in */ COPY, /* i/o: waiting for input or output to copy stored block */ TABLE, /* i: waiting for dynamic block table lengths */ LENLENS, /* i: waiting for code length code lengths */ CODELENS, /* i: waiting for length/lit and distance code lengths */ LEN_, /* i: same as LEN below, but only first time in */ LEN, /* i: waiting for length/lit/eob code */ LENEXT, /* i: waiting for length extra bits */ DIST, /* i: waiting for distance code */ DISTEXT, /* i: waiting for distance extra bits */ MATCH, /* o: waiting for output space to copy string */ LIT, /* o: waiting for output space to write literal */ CHECK, /* i: waiting for 32-bit check value */ LENGTH, /* i: waiting for 32-bit length (gzip) */ DONE, /* finished check, done -- remain here until reset */ BAD, /* got a data error -- remain here until reset */ MEM, /* got an inflate() memory error -- remain here until reset */ SYNC /* looking for synchronization bytes to restart inflate() */ } inflate_mode; /* State transitions between above modes - (most modes can go to BAD or MEM on error -- not shown for clarity) Process header: HEAD -> (gzip) or (zlib) or (raw) (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME -> COMMENT -> HCRC -> TYPE (zlib) -> DICTID or TYPE DICTID -> DICT -> TYPE (raw) -> TYPEDO Read deflate blocks: TYPE -> TYPEDO -> STORED or TABLE or LEN_ or CHECK STORED -> COPY_ -> COPY -> TYPE TABLE -> LENLENS -> CODELENS -> LEN_ LEN_ -> LEN Read deflate codes in fixed or dynamic block: LEN -> LENEXT or LIT or TYPE LENEXT -> DIST -> DISTEXT -> MATCH -> LEN LIT -> LEN Process trailer: CHECK -> LENGTH -> DONE */ /* state maintained between inflate() calls. Approximately 10K bytes. */ struct inflate_state { inflate_mode mode; /* current inflate mode */ int last; /* true if processing last block */ int wrap; /* bit 0 true for zlib, bit 1 true for gzip */ int havedict; /* true if dictionary provided */ int flags; /* gzip header method and flags (0 if zlib) */ unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */ unsigned long check; /* protected copy of check value */ unsigned long total; /* protected copy of output count */ gz_headerp head; /* where to save gzip header information */ /* sliding window */ unsigned wbits; /* log base 2 of requested window size */ unsigned wsize; /* window size or zero if not using window */ unsigned whave; /* valid bytes in the window */ unsigned wnext; /* window write index */ unsigned char FAR *window; /* allocated sliding window, if needed */ /* bit accumulator */ unsigned long hold; /* input bit accumulator */ unsigned bits; /* number of bits in "in" */ /* for string and stored block copying */ unsigned length; /* literal or length of data to copy */ unsigned offset; /* distance back to copy string from */ /* for table and code decoding */ unsigned extra; /* extra bits needed */ /* fixed and dynamic code tables */ code const FAR *lencode; /* starting table for length/literal codes */ code const FAR *distcode; /* starting table for distance codes */ unsigned lenbits; /* index bits for lencode */ unsigned distbits; /* index bits for distcode */ /* dynamic table building */ unsigned ncode; /* number of code length code lengths */ unsigned nlen; /* number of length code lengths */ unsigned ndist; /* number of distance code lengths */ unsigned have; /* number of code lengths in lens[] */ code FAR *next; /* next available space in codes[] */ unsigned short lens[320]; /* temporary storage for code lengths */ unsigned short work[288]; /* work area for code table building */ code codes[ENOUGH]; /* space for code tables */ int sane; /* if false, allow invalid distance too far */ int back; /* bits back of last unprocessed length/lit */ unsigned was; /* initial length of match */ }; ================================================ FILE: src/engine/external/zlib/inftrees.c ================================================ /* inftrees.c -- generate Huffman trees for efficient decoding * Copyright (C) 1995-2010 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ #include "zutil.h" #include "inftrees.h" #define MAXBITS 15 const char inflate_copyright[] = " inflate 1.2.5 Copyright 1995-2010 Mark Adler "; /* If you use the zlib library in a product, an acknowledgment is welcome in the documentation of your product. If for some reason you cannot include such an acknowledgment, I would appreciate that you keep this copyright string in the executable of your product. */ /* Build a set of tables to decode the provided canonical Huffman code. The code lengths are lens[0..codes-1]. The result starts at *table, whose indices are 0..2^bits-1. work is a writable array of at least lens shorts, which is used as a work area. type is the type of code to be generated, CODES, LENS, or DISTS. On return, zero is success, -1 is an invalid code, and +1 means that ENOUGH isn't enough. table on return points to the next available entry's address. bits is the requested root table index bits, and on return it is the actual root table index bits. It will differ if the request is greater than the longest code or if it is less than the shortest code. */ int ZLIB_INTERNAL inflate_table(type, lens, codes, table, bits, work) codetype type; unsigned short FAR *lens; unsigned codes; code FAR * FAR *table; unsigned FAR *bits; unsigned short FAR *work; { unsigned len; /* a code's length in bits */ unsigned sym; /* index of code symbols */ unsigned min, max; /* minimum and maximum code lengths */ unsigned root; /* number of index bits for root table */ unsigned curr; /* number of index bits for current table */ unsigned drop; /* code bits to drop for sub-table */ int left; /* number of prefix codes available */ unsigned used; /* code entries in table used */ unsigned huff; /* Huffman code */ unsigned incr; /* for incrementing code, index */ unsigned fill; /* index for replicating entries */ unsigned low; /* low bits for current root entry */ unsigned mask; /* mask for low root bits */ code here; /* table entry for duplication */ code FAR *next; /* next available space in table */ const unsigned short FAR *base; /* base value table to use */ const unsigned short FAR *extra; /* extra bits table to use */ int end; /* use base and extra for symbol > end */ unsigned short count[MAXBITS+1]; /* number of codes of each length */ unsigned short offs[MAXBITS+1]; /* offsets in table for each length */ static const unsigned short lbase[31] = { /* Length codes 257..285 base */ 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; static const unsigned short lext[31] = { /* Length codes 257..285 extra */ 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 73, 195}; static const unsigned short dbase[32] = { /* Distance codes 0..29 base */ 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0}; static const unsigned short dext[32] = { /* Distance codes 0..29 extra */ 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, 28, 28, 29, 29, 64, 64}; /* Process a set of code lengths to create a canonical Huffman code. The code lengths are lens[0..codes-1]. Each length corresponds to the symbols 0..codes-1. The Huffman code is generated by first sorting the symbols by length from short to long, and retaining the symbol order for codes with equal lengths. Then the code starts with all zero bits for the first code of the shortest length, and the codes are integer increments for the same length, and zeros are appended as the length increases. For the deflate format, these bits are stored backwards from their more natural integer increment ordering, and so when the decoding tables are built in the large loop below, the integer codes are incremented backwards. This routine assumes, but does not check, that all of the entries in lens[] are in the range 0..MAXBITS. The caller must assure this. 1..MAXBITS is interpreted as that code length. zero means that that symbol does not occur in this code. The codes are sorted by computing a count of codes for each length, creating from that a table of starting indices for each length in the sorted table, and then entering the symbols in order in the sorted table. The sorted table is work[], with that space being provided by the caller. The length counts are used for other purposes as well, i.e. finding the minimum and maximum length codes, determining if there are any codes at all, checking for a valid set of lengths, and looking ahead at length counts to determine sub-table sizes when building the decoding tables. */ /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ for (len = 0; len <= MAXBITS; len++) count[len] = 0; for (sym = 0; sym < codes; sym++) count[lens[sym]]++; /* bound code lengths, force root to be within code lengths */ root = *bits; for (max = MAXBITS; max >= 1; max--) if (count[max] != 0) break; if (root > max) root = max; if (max == 0) { /* no symbols to code at all */ here.op = (unsigned char)64; /* invalid code marker */ here.bits = (unsigned char)1; here.val = (unsigned short)0; *(*table)++ = here; /* make a table to force an error */ *(*table)++ = here; *bits = 1; return 0; /* no symbols, but wait for decoding to report error */ } for (min = 1; min < max; min++) if (count[min] != 0) break; if (root < min) root = min; /* check for an over-subscribed or incomplete set of lengths */ left = 1; for (len = 1; len <= MAXBITS; len++) { left <<= 1; left -= count[len]; if (left < 0) return -1; /* over-subscribed */ } if (left > 0 && (type == CODES || max != 1)) return -1; /* incomplete set */ /* generate offsets into symbol table for each length for sorting */ offs[1] = 0; for (len = 1; len < MAXBITS; len++) offs[len + 1] = offs[len] + count[len]; /* sort symbols by length, by symbol order within each length */ for (sym = 0; sym < codes; sym++) if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym; /* Create and fill in decoding tables. In this loop, the table being filled is at next and has curr index bits. The code being used is huff with length len. That code is converted to an index by dropping drop bits off of the bottom. For codes where len is less than drop + curr, those top drop + curr - len bits are incremented through all values to fill the table with replicated entries. root is the number of index bits for the root table. When len exceeds root, sub-tables are created pointed to by the root entry with an index of the low root bits of huff. This is saved in low to check for when a new sub-table should be started. drop is zero when the root table is being filled, and drop is root when sub-tables are being filled. When a new sub-table is needed, it is necessary to look ahead in the code lengths to determine what size sub-table is needed. The length counts are used for this, and so count[] is decremented as codes are entered in the tables. used keeps track of how many table entries have been allocated from the provided *table space. It is checked for LENS and DIST tables against the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in the initial root table size constants. See the comments in inftrees.h for more information. sym increments through all symbols, and the loop terminates when all codes of length max, i.e. all codes, have been processed. This routine permits incomplete codes, so another loop after this one fills in the rest of the decoding tables with invalid code markers. */ /* set up for code type */ switch (type) { case CODES: base = extra = work; /* dummy value--not used */ end = 19; break; case LENS: base = lbase; base -= 257; extra = lext; extra -= 257; end = 256; break; default: /* DISTS */ base = dbase; extra = dext; end = -1; } /* initialize state for loop */ huff = 0; /* starting code */ sym = 0; /* starting code symbol */ len = min; /* starting code length */ next = *table; /* current table to fill in */ curr = root; /* current table index bits */ drop = 0; /* current bits to drop from code for index */ low = (unsigned)(-1); /* trigger new sub-table when len > root */ used = 1U << root; /* use root table entries */ mask = used - 1; /* mask for comparing low */ /* check available table space */ if ((type == LENS && used >= ENOUGH_LENS) || (type == DISTS && used >= ENOUGH_DISTS)) return 1; /* process all codes and make table entries */ for (;;) { /* create table entry */ here.bits = (unsigned char)(len - drop); if ((int)(work[sym]) < end) { here.op = (unsigned char)0; here.val = work[sym]; } else if ((int)(work[sym]) > end) { here.op = (unsigned char)(extra[work[sym]]); here.val = base[work[sym]]; } else { here.op = (unsigned char)(32 + 64); /* end of block */ here.val = 0; } /* replicate for those indices with low len bits equal to huff */ incr = 1U << (len - drop); fill = 1U << curr; min = fill; /* save offset to next table */ do { fill -= incr; next[(huff >> drop) + fill] = here; } while (fill != 0); /* backwards increment the len-bit code huff */ incr = 1U << (len - 1); while (huff & incr) incr >>= 1; if (incr != 0) { huff &= incr - 1; huff += incr; } else huff = 0; /* go to next symbol, update count, len */ sym++; if (--(count[len]) == 0) { if (len == max) break; len = lens[work[sym]]; } /* create new sub-table if needed */ if (len > root && (huff & mask) != low) { /* if first time, transition to sub-tables */ if (drop == 0) drop = root; /* increment past last table */ next += min; /* here min is 1 << curr */ /* determine length of next table */ curr = len - drop; left = (int)(1 << curr); while (curr + drop < max) { left -= count[curr + drop]; if (left <= 0) break; curr++; left <<= 1; } /* check for enough space */ used += 1U << curr; if ((type == LENS && used >= ENOUGH_LENS) || (type == DISTS && used >= ENOUGH_DISTS)) return 1; /* point entry in root table to sub-table */ low = huff & mask; (*table)[low].op = (unsigned char)curr; (*table)[low].bits = (unsigned char)root; (*table)[low].val = (unsigned short)(next - *table); } } /* Fill in rest of table for incomplete codes. This loop is similar to the loop above in incrementing huff for table indices. It is assumed that len is equal to curr + drop, so there is no loop needed to increment through high index bits. When the current sub-table is filled, the loop drops back to the root table to fill in any remaining entries there. */ here.op = (unsigned char)64; /* invalid code marker */ here.bits = (unsigned char)(len - drop); here.val = (unsigned short)0; while (huff != 0) { /* when done with sub-table, drop back to root table */ if (drop != 0 && (huff & mask) != low) { drop = 0; len = root; next = *table; here.bits = (unsigned char)len; } /* put invalid code marker in table */ next[huff >> drop] = here; /* backwards increment the len-bit code huff */ incr = 1U << (len - 1); while (huff & incr) incr >>= 1; if (incr != 0) { huff &= incr - 1; huff += incr; } else huff = 0; } /* set return parameters */ *table += used; *bits = root; return 0; } ================================================ FILE: src/engine/external/zlib/inftrees.h ================================================ /* inftrees.h -- header to use inftrees.c * Copyright (C) 1995-2005, 2010 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ /* WARNING: this file should *not* be used by applications. It is part of the implementation of the compression library and is subject to change. Applications should only use zlib.h. */ /* Structure for decoding tables. Each entry provides either the information needed to do the operation requested by the code that indexed that table entry, or it provides a pointer to another table that indexes more bits of the code. op indicates whether the entry is a pointer to another table, a literal, a length or distance, an end-of-block, or an invalid code. For a table pointer, the low four bits of op is the number of index bits of that table. For a length or distance, the low four bits of op is the number of extra bits to get after the code. bits is the number of bits in this code or part of the code to drop off of the bit buffer. val is the actual byte to output in the case of a literal, the base length or distance, or the offset from the current table to the next table. Each entry is four bytes. */ typedef struct { unsigned char op; /* operation, extra bits, table bits */ unsigned char bits; /* bits in this part of the code */ unsigned short val; /* offset in table or code value */ } code; /* op values as set by inflate_table(): 00000000 - literal 0000tttt - table link, tttt != 0 is the number of table index bits 0001eeee - length or distance, eeee is the number of extra bits 01100000 - end of block 01000000 - invalid code */ /* Maximum size of the dynamic table. The maximum number of code structures is 1444, which is the sum of 852 for literal/length codes and 592 for distance codes. These values were found by exhaustive searches using the program examples/enough.c found in the zlib distribtution. The arguments to that program are the number of symbols, the initial root table size, and the maximum bit length of a code. "enough 286 9 15" for literal/length codes returns returns 852, and "enough 30 6 15" for distance codes returns 592. The initial root table size (9 or 6) is found in the fifth argument of the inflate_table() calls in inflate.c and infback.c. If the root table size is changed, then these maximum sizes would be need to be recalculated and updated. */ #define ENOUGH_LENS 852 #define ENOUGH_DISTS 592 #define ENOUGH (ENOUGH_LENS+ENOUGH_DISTS) /* Type of code to build for inflate_table() */ typedef enum { CODES, LENS, DISTS } codetype; int ZLIB_INTERNAL inflate_table OF((codetype type, unsigned short FAR *lens, unsigned codes, code FAR * FAR *table, unsigned FAR *bits, unsigned short FAR *work)); ================================================ FILE: src/engine/external/zlib/trees.c ================================================ /* trees.c -- output deflated data using Huffman coding * Copyright (C) 1995-2010 Jean-loup Gailly * detect_data_type() function provided freely by Cosmin Truta, 2006 * For conditions of distribution and use, see copyright notice in zlib.h */ /* * ALGORITHM * * The "deflation" process uses several Huffman trees. The more * common source values are represented by shorter bit sequences. * * Each code tree is stored in a compressed form which is itself * a Huffman encoding of the lengths of all the code strings (in * ascending order by source values). The actual code strings are * reconstructed from the lengths in the inflate process, as described * in the deflate specification. * * REFERENCES * * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification". * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc * * Storer, James A. * Data Compression: Methods and Theory, pp. 49-50. * Computer Science Press, 1988. ISBN 0-7167-8156-5. * * Sedgewick, R. * Algorithms, p290. * Addison-Wesley, 1983. ISBN 0-201-06672-6. */ /* @(#) $Id$ */ /* #define GEN_TREES_H */ #include "deflate.h" #ifdef DEBUG # include <ctype.h> #endif /* =========================================================================== * Constants */ #define MAX_BL_BITS 7 /* Bit length codes must not exceed MAX_BL_BITS bits */ #define END_BLOCK 256 /* end of block literal code */ #define REP_3_6 16 /* repeat previous bit length 3-6 times (2 bits of repeat count) */ #define REPZ_3_10 17 /* repeat a zero length 3-10 times (3 bits of repeat count) */ #define REPZ_11_138 18 /* repeat a zero length 11-138 times (7 bits of repeat count) */ local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */ = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0}; local const int extra_dbits[D_CODES] /* extra bits for each distance code */ = {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */ = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7}; local const uch bl_order[BL_CODES] = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15}; /* The lengths of the bit length codes are sent in order of decreasing * probability, to avoid transmitting the lengths for unused bit length codes. */ #define Buf_size (8 * 2*sizeof(char)) /* Number of bits used within bi_buf. (bi_buf might be implemented on * more than 16 bits on some systems.) */ /* =========================================================================== * Local data. These are initialized only once. */ #define DIST_CODE_LEN 512 /* see definition of array dist_code below */ #if defined(GEN_TREES_H) || !defined(STDC) /* non ANSI compilers may not accept trees.h */ local ct_data static_ltree[L_CODES+2]; /* The static literal tree. Since the bit lengths are imposed, there is no * need for the L_CODES extra codes used during heap construction. However * The codes 286 and 287 are needed to build a canonical tree (see _tr_init * below). */ local ct_data static_dtree[D_CODES]; /* The static distance tree. (Actually a trivial tree since all codes use * 5 bits.) */ uch _dist_code[DIST_CODE_LEN]; /* Distance codes. The first 256 values correspond to the distances * 3 .. 258, the last 256 values correspond to the top 8 bits of * the 15 bit distances. */ uch _length_code[MAX_MATCH-MIN_MATCH+1]; /* length code for each normalized match length (0 == MIN_MATCH) */ local int base_length[LENGTH_CODES]; /* First normalized length for each code (0 = MIN_MATCH) */ local int base_dist[D_CODES]; /* First normalized distance for each code (0 = distance of 1) */ #else # include "trees.h" #endif /* GEN_TREES_H */ struct static_tree_desc_s { const ct_data *static_tree; /* static tree or NULL */ const intf *extra_bits; /* extra bits for each code or NULL */ int extra_base; /* base index for extra_bits */ int elems; /* max number of elements in the tree */ int max_length; /* max bit length for the codes */ }; local static_tree_desc static_l_desc = {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS}; local static_tree_desc static_d_desc = {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS}; local static_tree_desc static_bl_desc = {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS}; /* =========================================================================== * Local (static) routines in this file. */ local void tr_static_init OF((void)); local void init_block OF((deflate_state *s)); local void pqdownheap OF((deflate_state *s, ct_data *tree, int k)); local void gen_bitlen OF((deflate_state *s, tree_desc *desc)); local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count)); local void build_tree OF((deflate_state *s, tree_desc *desc)); local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code)); local void send_tree OF((deflate_state *s, ct_data *tree, int max_code)); local int build_bl_tree OF((deflate_state *s)); local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes, int blcodes)); local void compress_block OF((deflate_state *s, ct_data *ltree, ct_data *dtree)); local int detect_data_type OF((deflate_state *s)); local unsigned bi_reverse OF((unsigned value, int length)); local void bi_windup OF((deflate_state *s)); local void bi_flush OF((deflate_state *s)); local void copy_block OF((deflate_state *s, charf *buf, unsigned len, int header)); #ifdef GEN_TREES_H local void gen_trees_header OF((void)); #endif #ifndef DEBUG # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len) /* Send a code of the given tree. c and tree must not have side effects */ #else /* DEBUG */ # define send_code(s, c, tree) \ { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \ send_bits(s, tree[c].Code, tree[c].Len); } #endif /* =========================================================================== * Output a short LSB first on the stream. * IN assertion: there is enough room in pendingBuf. */ #define put_short(s, w) { \ put_byte(s, (uch)((w) & 0xff)); \ put_byte(s, (uch)((ush)(w) >> 8)); \ } /* =========================================================================== * Send a value on a given number of bits. * IN assertion: length <= 16 and value fits in length bits. */ #ifdef DEBUG local void send_bits OF((deflate_state *s, int value, int length)); local void send_bits(s, value, length) deflate_state *s; int value; /* value to send */ int length; /* number of bits */ { Tracevv((stderr," l %2d v %4x ", length, value)); Assert(length > 0 && length <= 15, "invalid length"); s->bits_sent += (ulg)length; /* If not enough room in bi_buf, use (valid) bits from bi_buf and * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid)) * unused bits in value. */ if (s->bi_valid > (int)Buf_size - length) { s->bi_buf |= (ush)value << s->bi_valid; put_short(s, s->bi_buf); s->bi_buf = (ush)value >> (Buf_size - s->bi_valid); s->bi_valid += length - Buf_size; } else { s->bi_buf |= (ush)value << s->bi_valid; s->bi_valid += length; } } #else /* !DEBUG */ #define send_bits(s, value, length) \ { int len = length;\ if (s->bi_valid > (int)Buf_size - len) {\ int val = value;\ s->bi_buf |= (ush)val << s->bi_valid;\ put_short(s, s->bi_buf);\ s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\ s->bi_valid += len - Buf_size;\ } else {\ s->bi_buf |= (ush)(value) << s->bi_valid;\ s->bi_valid += len;\ }\ } #endif /* DEBUG */ /* the arguments must not have side effects */ /* =========================================================================== * Initialize the various 'constant' tables. */ local void tr_static_init() { #if defined(GEN_TREES_H) || !defined(STDC) static int static_init_done = 0; int n; /* iterates over tree elements */ int bits; /* bit counter */ int length; /* length value */ int code; /* code value */ int dist; /* distance index */ ush bl_count[MAX_BITS+1]; /* number of codes at each bit length for an optimal tree */ if (static_init_done) return; /* For some embedded targets, global variables are not initialized: */ #ifdef NO_INIT_GLOBAL_POINTERS static_l_desc.static_tree = static_ltree; static_l_desc.extra_bits = extra_lbits; static_d_desc.static_tree = static_dtree; static_d_desc.extra_bits = extra_dbits; static_bl_desc.extra_bits = extra_blbits; #endif /* Initialize the mapping length (0..255) -> length code (0..28) */ length = 0; for (code = 0; code < LENGTH_CODES-1; code++) { base_length[code] = length; for (n = 0; n < (1<<extra_lbits[code]); n++) { _length_code[length++] = (uch)code; } } Assert (length == 256, "tr_static_init: length != 256"); /* Note that the length 255 (match length 258) can be represented * in two different ways: code 284 + 5 bits or code 285, so we * overwrite length_code[255] to use the best encoding: */ _length_code[length-1] = (uch)code; /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ dist = 0; for (code = 0 ; code < 16; code++) { base_dist[code] = dist; for (n = 0; n < (1<<extra_dbits[code]); n++) { _dist_code[dist++] = (uch)code; } } Assert (dist == 256, "tr_static_init: dist != 256"); dist >>= 7; /* from now on, all distances are divided by 128 */ for ( ; code < D_CODES; code++) { base_dist[code] = dist << 7; for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) { _dist_code[256 + dist++] = (uch)code; } } Assert (dist == 256, "tr_static_init: 256+dist != 512"); /* Construct the codes of the static literal tree */ for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0; n = 0; while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++; while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++; while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++; while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++; /* Codes 286 and 287 do not exist, but we must include them in the * tree construction to get a canonical Huffman tree (longest code * all ones) */ gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count); /* The static distance tree is trivial: */ for (n = 0; n < D_CODES; n++) { static_dtree[n].Len = 5; static_dtree[n].Code = bi_reverse((unsigned)n, 5); } static_init_done = 1; # ifdef GEN_TREES_H gen_trees_header(); # endif #endif /* defined(GEN_TREES_H) || !defined(STDC) */ } /* =========================================================================== * Genererate the file trees.h describing the static trees. */ #ifdef GEN_TREES_H # ifndef DEBUG # include <stdio.h> # endif # define SEPARATOR(i, last, width) \ ((i) == (last)? "\n};\n\n" : \ ((i) % (width) == (width)-1 ? ",\n" : ", ")) void gen_trees_header() { FILE *header = fopen("trees.h", "w"); int i; Assert (header != NULL, "Can't open trees.h"); fprintf(header, "/* header created automatically with -DGEN_TREES_H */\n\n"); fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n"); for (i = 0; i < L_CODES+2; i++) { fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code, static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5)); } fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n"); for (i = 0; i < D_CODES; i++) { fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code, static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5)); } fprintf(header, "const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {\n"); for (i = 0; i < DIST_CODE_LEN; i++) { fprintf(header, "%2u%s", _dist_code[i], SEPARATOR(i, DIST_CODE_LEN-1, 20)); } fprintf(header, "const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {\n"); for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) { fprintf(header, "%2u%s", _length_code[i], SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20)); } fprintf(header, "local const int base_length[LENGTH_CODES] = {\n"); for (i = 0; i < LENGTH_CODES; i++) { fprintf(header, "%1u%s", base_length[i], SEPARATOR(i, LENGTH_CODES-1, 20)); } fprintf(header, "local const int base_dist[D_CODES] = {\n"); for (i = 0; i < D_CODES; i++) { fprintf(header, "%5u%s", base_dist[i], SEPARATOR(i, D_CODES-1, 10)); } fclose(header); } #endif /* GEN_TREES_H */ /* =========================================================================== * Initialize the tree data structures for a new zlib stream. */ void ZLIB_INTERNAL _tr_init(s) deflate_state *s; { tr_static_init(); s->l_desc.dyn_tree = s->dyn_ltree; s->l_desc.stat_desc = &static_l_desc; s->d_desc.dyn_tree = s->dyn_dtree; s->d_desc.stat_desc = &static_d_desc; s->bl_desc.dyn_tree = s->bl_tree; s->bl_desc.stat_desc = &static_bl_desc; s->bi_buf = 0; s->bi_valid = 0; s->last_eob_len = 8; /* enough lookahead for inflate */ #ifdef DEBUG s->compressed_len = 0L; s->bits_sent = 0L; #endif /* Initialize the first block of the first file: */ init_block(s); } /* =========================================================================== * Initialize a new block. */ local void init_block(s) deflate_state *s; { int n; /* iterates over tree elements */ /* Initialize the trees. */ for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0; for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0; for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0; s->dyn_ltree[END_BLOCK].Freq = 1; s->opt_len = s->static_len = 0L; s->last_lit = s->matches = 0; } #define SMALLEST 1 /* Index within the heap array of least frequent node in the Huffman tree */ /* =========================================================================== * Remove the smallest element from the heap and recreate the heap with * one less element. Updates heap and heap_len. */ #define pqremove(s, tree, top) \ {\ top = s->heap[SMALLEST]; \ s->heap[SMALLEST] = s->heap[s->heap_len--]; \ pqdownheap(s, tree, SMALLEST); \ } /* =========================================================================== * Compares to subtrees, using the tree depth as tie breaker when * the subtrees have equal frequency. This minimizes the worst case length. */ #define smaller(tree, n, m, depth) \ (tree[n].Freq < tree[m].Freq || \ (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m])) /* =========================================================================== * Restore the heap property by moving down the tree starting at node k, * exchanging a node with the smallest of its two sons if necessary, stopping * when the heap property is re-established (each father smaller than its * two sons). */ local void pqdownheap(s, tree, k) deflate_state *s; ct_data *tree; /* the tree to restore */ int k; /* node to move down */ { int v = s->heap[k]; int j = k << 1; /* left son of k */ while (j <= s->heap_len) { /* Set j to the smallest of the two sons: */ if (j < s->heap_len && smaller(tree, s->heap[j+1], s->heap[j], s->depth)) { j++; } /* Exit if v is smaller than both sons */ if (smaller(tree, v, s->heap[j], s->depth)) break; /* Exchange v with the smallest son */ s->heap[k] = s->heap[j]; k = j; /* And continue down the tree, setting j to the left son of k */ j <<= 1; } s->heap[k] = v; } /* =========================================================================== * Compute the optimal bit lengths for a tree and update the total bit length * for the current block. * IN assertion: the fields freq and dad are set, heap[heap_max] and * above are the tree nodes sorted by increasing frequency. * OUT assertions: the field len is set to the optimal bit length, the * array bl_count contains the frequencies for each bit length. * The length opt_len is updated; static_len is also updated if stree is * not null. */ local void gen_bitlen(s, desc) deflate_state *s; tree_desc *desc; /* the tree descriptor */ { ct_data *tree = desc->dyn_tree; int max_code = desc->max_code; const ct_data *stree = desc->stat_desc->static_tree; const intf *extra = desc->stat_desc->extra_bits; int base = desc->stat_desc->extra_base; int max_length = desc->stat_desc->max_length; int h; /* heap index */ int n, m; /* iterate over the tree elements */ int bits; /* bit length */ int xbits; /* extra bits */ ush f; /* frequency */ int overflow = 0; /* number of elements with bit length too large */ for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0; /* In a first pass, compute the optimal bit lengths (which may * overflow in the case of the bit length tree). */ tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */ for (h = s->heap_max+1; h < HEAP_SIZE; h++) { n = s->heap[h]; bits = tree[tree[n].Dad].Len + 1; if (bits > max_length) bits = max_length, overflow++; tree[n].Len = (ush)bits; /* We overwrite tree[n].Dad which is no longer needed */ if (n > max_code) continue; /* not a leaf node */ s->bl_count[bits]++; xbits = 0; if (n >= base) xbits = extra[n-base]; f = tree[n].Freq; s->opt_len += (ulg)f * (bits + xbits); if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits); } if (overflow == 0) return; Trace((stderr,"\nbit length overflow\n")); /* This happens for example on obj2 and pic of the Calgary corpus */ /* Find the first bit length which could increase: */ do { bits = max_length-1; while (s->bl_count[bits] == 0) bits--; s->bl_count[bits]--; /* move one leaf down the tree */ s->bl_count[bits+1] += 2; /* move one overflow item as its brother */ s->bl_count[max_length]--; /* The brother of the overflow item also moves one step up, * but this does not affect bl_count[max_length] */ overflow -= 2; } while (overflow > 0); /* Now recompute all bit lengths, scanning in increasing frequency. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all * lengths instead of fixing only the wrong ones. This idea is taken * from 'ar' written by Haruhiko Okumura.) */ for (bits = max_length; bits != 0; bits--) { n = s->bl_count[bits]; while (n != 0) { m = s->heap[--h]; if (m > max_code) continue; if ((unsigned) tree[m].Len != (unsigned) bits) { Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); s->opt_len += ((long)bits - (long)tree[m].Len) *(long)tree[m].Freq; tree[m].Len = (ush)bits; } n--; } } } /* =========================================================================== * Generate the codes for a given tree and bit counts (which need not be * optimal). * IN assertion: the array bl_count contains the bit length statistics for * the given tree and the field len is set for all tree elements. * OUT assertion: the field code is set for all tree elements of non * zero code length. */ local void gen_codes (tree, max_code, bl_count) ct_data *tree; /* the tree to decorate */ int max_code; /* largest code with non zero frequency */ ushf *bl_count; /* number of codes at each bit length */ { ush next_code[MAX_BITS+1]; /* next code value for each bit length */ ush code = 0; /* running code value */ int bits; /* bit index */ int n; /* code index */ /* The distribution counts are first used to generate the code values * without bit reversal. */ for (bits = 1; bits <= MAX_BITS; bits++) { next_code[bits] = code = (code + bl_count[bits-1]) << 1; } /* Check that the bit counts in bl_count are consistent. The last code * must be all ones. */ Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1, "inconsistent bit counts"); Tracev((stderr,"\ngen_codes: max_code %d ", max_code)); for (n = 0; n <= max_code; n++) { int len = tree[n].Len; if (len == 0) continue; /* Now reverse the bits */ tree[n].Code = bi_reverse(next_code[len]++, len); Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ", n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1)); } } /* =========================================================================== * Construct one Huffman tree and assigns the code bit strings and lengths. * Update the total bit length for the current block. * IN assertion: the field freq is set for all tree elements. * OUT assertions: the fields len and code are set to the optimal bit length * and corresponding code. The length opt_len is updated; static_len is * also updated if stree is not null. The field max_code is set. */ local void build_tree(s, desc) deflate_state *s; tree_desc *desc; /* the tree descriptor */ { ct_data *tree = desc->dyn_tree; const ct_data *stree = desc->stat_desc->static_tree; int elems = desc->stat_desc->elems; int n, m; /* iterate over heap elements */ int max_code = -1; /* largest code with non zero frequency */ int node; /* new node being created */ /* Construct the initial heap, with least frequent element in * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. * heap[0] is not used. */ s->heap_len = 0, s->heap_max = HEAP_SIZE; for (n = 0; n < elems; n++) { if (tree[n].Freq != 0) { s->heap[++(s->heap_len)] = max_code = n; s->depth[n] = 0; } else { tree[n].Len = 0; } } /* The pkzip format requires that at least one distance code exists, * and that at least one bit should be sent even if there is only one * possible code. So to avoid special checks later on we force at least * two codes of non zero frequency. */ while (s->heap_len < 2) { node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0); tree[node].Freq = 1; s->depth[node] = 0; s->opt_len--; if (stree) s->static_len -= stree[node].Len; /* node is 0 or 1 so it does not have extra bits */ } desc->max_code = max_code; /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, * establish sub-heaps of increasing lengths: */ for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n); /* Construct the Huffman tree by repeatedly combining the least two * frequent nodes. */ node = elems; /* next internal node of the tree */ do { pqremove(s, tree, n); /* n = node of least frequency */ m = s->heap[SMALLEST]; /* m = node of next least frequency */ s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */ s->heap[--(s->heap_max)] = m; /* Create a new node father of n and m */ tree[node].Freq = tree[n].Freq + tree[m].Freq; s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ? s->depth[n] : s->depth[m]) + 1); tree[n].Dad = tree[m].Dad = (ush)node; #ifdef DUMP_BL_TREE if (tree == s->bl_tree) { fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)", node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq); } #endif /* and insert the new node in the heap */ s->heap[SMALLEST] = node++; pqdownheap(s, tree, SMALLEST); } while (s->heap_len >= 2); s->heap[--(s->heap_max)] = s->heap[SMALLEST]; /* At this point, the fields freq and dad are set. We can now * generate the bit lengths. */ gen_bitlen(s, (tree_desc *)desc); /* The field len is now set, we can generate the bit codes */ gen_codes ((ct_data *)tree, max_code, s->bl_count); } /* =========================================================================== * Scan a literal or distance tree to determine the frequencies of the codes * in the bit length tree. */ local void scan_tree (s, tree, max_code) deflate_state *s; ct_data *tree; /* the tree to be scanned */ int max_code; /* and its largest code of non zero frequency */ { int n; /* iterates over all tree elements */ int prevlen = -1; /* last emitted length */ int curlen; /* length of current code */ int nextlen = tree[0].Len; /* length of next code */ int count = 0; /* repeat count of the current code */ int max_count = 7; /* max repeat count */ int min_count = 4; /* min repeat count */ if (nextlen == 0) max_count = 138, min_count = 3; tree[max_code+1].Len = (ush)0xffff; /* guard */ for (n = 0; n <= max_code; n++) { curlen = nextlen; nextlen = tree[n+1].Len; if (++count < max_count && curlen == nextlen) { continue; } else if (count < min_count) { s->bl_tree[curlen].Freq += count; } else if (curlen != 0) { if (curlen != prevlen) s->bl_tree[curlen].Freq++; s->bl_tree[REP_3_6].Freq++; } else if (count <= 10) { s->bl_tree[REPZ_3_10].Freq++; } else { s->bl_tree[REPZ_11_138].Freq++; } count = 0; prevlen = curlen; if (nextlen == 0) { max_count = 138, min_count = 3; } else if (curlen == nextlen) { max_count = 6, min_count = 3; } else { max_count = 7, min_count = 4; } } } /* =========================================================================== * Send a literal or distance tree in compressed form, using the codes in * bl_tree. */ local void send_tree (s, tree, max_code) deflate_state *s; ct_data *tree; /* the tree to be scanned */ int max_code; /* and its largest code of non zero frequency */ { int n; /* iterates over all tree elements */ int prevlen = -1; /* last emitted length */ int curlen; /* length of current code */ int nextlen = tree[0].Len; /* length of next code */ int count = 0; /* repeat count of the current code */ int max_count = 7; /* max repeat count */ int min_count = 4; /* min repeat count */ /* tree[max_code+1].Len = -1; */ /* guard already set */ if (nextlen == 0) max_count = 138, min_count = 3; for (n = 0; n <= max_code; n++) { curlen = nextlen; nextlen = tree[n+1].Len; if (++count < max_count && curlen == nextlen) { continue; } else if (count < min_count) { do { send_code(s, curlen, s->bl_tree); } while (--count != 0); } else if (curlen != 0) { if (curlen != prevlen) { send_code(s, curlen, s->bl_tree); count--; } Assert(count >= 3 && count <= 6, " 3_6?"); send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2); } else if (count <= 10) { send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3); } else { send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7); } count = 0; prevlen = curlen; if (nextlen == 0) { max_count = 138, min_count = 3; } else if (curlen == nextlen) { max_count = 6, min_count = 3; } else { max_count = 7, min_count = 4; } } } /* =========================================================================== * Construct the Huffman tree for the bit lengths and return the index in * bl_order of the last bit length code to send. */ local int build_bl_tree(s) deflate_state *s; { int max_blindex; /* index of last bit length code of non zero freq */ /* Determine the bit length frequencies for literal and distance trees */ scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code); scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code); /* Build the bit length tree: */ build_tree(s, (tree_desc *)(&(s->bl_desc))); /* opt_len now includes the length of the tree representations, except * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. */ /* Determine the number of bit length codes to send. The pkzip format * requires that at least 4 bit length codes be sent. (appnote.txt says * 3 but the actual value used is 4.) */ for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) { if (s->bl_tree[bl_order[max_blindex]].Len != 0) break; } /* Update opt_len to include the bit length tree and counts */ s->opt_len += 3*(max_blindex+1) + 5+5+4; Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", s->opt_len, s->static_len)); return max_blindex; } /* =========================================================================== * Send the header for a block using dynamic Huffman trees: the counts, the * lengths of the bit length codes, the literal tree and the distance tree. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. */ local void send_all_trees(s, lcodes, dcodes, blcodes) deflate_state *s; int lcodes, dcodes, blcodes; /* number of codes for each tree */ { int rank; /* index in bl_order */ Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, "too many codes"); Tracev((stderr, "\nbl counts: ")); send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */ send_bits(s, dcodes-1, 5); send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */ for (rank = 0; rank < blcodes; rank++) { Tracev((stderr, "\nbl code %2d ", bl_order[rank])); send_bits(s, s->bl_tree[bl_order[rank]].Len, 3); } Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */ Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */ Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); } /* =========================================================================== * Send a stored block */ void ZLIB_INTERNAL _tr_stored_block(s, buf, stored_len, last) deflate_state *s; charf *buf; /* input block */ ulg stored_len; /* length of input block */ int last; /* one if this is the last block for a file */ { send_bits(s, (STORED_BLOCK<<1)+last, 3); /* send block type */ #ifdef DEBUG s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L; s->compressed_len += (stored_len + 4) << 3; #endif copy_block(s, buf, (unsigned)stored_len, 1); /* with header */ } /* =========================================================================== * Send one empty static block to give enough lookahead for inflate. * This takes 10 bits, of which 7 may remain in the bit buffer. * The current inflate code requires 9 bits of lookahead. If the * last two codes for the previous block (real code plus EOB) were coded * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode * the last real code. In this case we send two empty static blocks instead * of one. (There are no problems if the previous block is stored or fixed.) * To simplify the code, we assume the worst case of last real code encoded * on one bit only. */ void ZLIB_INTERNAL _tr_align(s) deflate_state *s; { send_bits(s, STATIC_TREES<<1, 3); send_code(s, END_BLOCK, static_ltree); #ifdef DEBUG s->compressed_len += 10L; /* 3 for block type, 7 for EOB */ #endif bi_flush(s); /* Of the 10 bits for the empty block, we have already sent * (10 - bi_valid) bits. The lookahead for the last real code (before * the EOB of the previous block) was thus at least one plus the length * of the EOB plus what we have just sent of the empty static block. */ if (1 + s->last_eob_len + 10 - s->bi_valid < 9) { send_bits(s, STATIC_TREES<<1, 3); send_code(s, END_BLOCK, static_ltree); #ifdef DEBUG s->compressed_len += 10L; #endif bi_flush(s); } s->last_eob_len = 7; } /* =========================================================================== * Determine the best encoding for the current block: dynamic trees, static * trees or store, and output the encoded block to the zip file. */ void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last) deflate_state *s; charf *buf; /* input block, or NULL if too old */ ulg stored_len; /* length of input block */ int last; /* one if this is the last block for a file */ { ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */ int max_blindex = 0; /* index of last bit length code of non zero freq */ /* Build the Huffman trees unless a stored block is forced */ if (s->level > 0) { /* Check if the file is binary or text */ if (s->strm->data_type == Z_UNKNOWN) s->strm->data_type = detect_data_type(s); /* Construct the literal and distance trees */ build_tree(s, (tree_desc *)(&(s->l_desc))); Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, s->static_len)); build_tree(s, (tree_desc *)(&(s->d_desc))); Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, s->static_len)); /* At this point, opt_len and static_len are the total bit lengths of * the compressed block data, excluding the tree representations. */ /* Build the bit length tree for the above two trees, and get the index * in bl_order of the last bit length code to send. */ max_blindex = build_bl_tree(s); /* Determine the best encoding. Compute the block lengths in bytes. */ opt_lenb = (s->opt_len+3+7)>>3; static_lenb = (s->static_len+3+7)>>3; Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, s->last_lit)); if (static_lenb <= opt_lenb) opt_lenb = static_lenb; } else { Assert(buf != (char*)0, "lost buf"); opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ } #ifdef FORCE_STORED if (buf != (char*)0) { /* force stored block */ #else if (stored_len+4 <= opt_lenb && buf != (char*)0) { /* 4: two words for the lengths */ #endif /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. * Otherwise we can't have processed more than WSIZE input bytes since * the last block flush, because compression would have been * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to * transform a block into a stored block. */ _tr_stored_block(s, buf, stored_len, last); #ifdef FORCE_STATIC } else if (static_lenb >= 0) { /* force static trees */ #else } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) { #endif send_bits(s, (STATIC_TREES<<1)+last, 3); compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree); #ifdef DEBUG s->compressed_len += 3 + s->static_len; #endif } else { send_bits(s, (DYN_TREES<<1)+last, 3); send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1, max_blindex+1); compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree); #ifdef DEBUG s->compressed_len += 3 + s->opt_len; #endif } Assert (s->compressed_len == s->bits_sent, "bad compressed size"); /* The above check is made mod 2^32, for files larger than 512 MB * and uLong implemented on 32 bits. */ init_block(s); if (last) { bi_windup(s); #ifdef DEBUG s->compressed_len += 7; /* align on byte boundary */ #endif } Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, s->compressed_len-7*last)); } /* =========================================================================== * Save the match info and tally the frequency counts. Return true if * the current block must be flushed. */ int ZLIB_INTERNAL _tr_tally (s, dist, lc) deflate_state *s; unsigned dist; /* distance of matched string */ unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ { s->d_buf[s->last_lit] = (ush)dist; s->l_buf[s->last_lit++] = (uch)lc; if (dist == 0) { /* lc is the unmatched char */ s->dyn_ltree[lc].Freq++; } else { s->matches++; /* Here, lc is the match length - MIN_MATCH */ dist--; /* dist = match distance - 1 */ Assert((ush)dist < (ush)MAX_DIST(s) && (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++; s->dyn_dtree[d_code(dist)].Freq++; } #ifdef TRUNCATE_BLOCK /* Try to guess if it is profitable to stop the current block here */ if ((s->last_lit & 0x1fff) == 0 && s->level > 2) { /* Compute an upper bound for the compressed length */ ulg out_length = (ulg)s->last_lit*8L; ulg in_length = (ulg)((long)s->strstart - s->block_start); int dcode; for (dcode = 0; dcode < D_CODES; dcode++) { out_length += (ulg)s->dyn_dtree[dcode].Freq * (5L+extra_dbits[dcode]); } out_length >>= 3; Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", s->last_lit, in_length, out_length, 100L - out_length*100L/in_length)); if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1; } #endif return (s->last_lit == s->lit_bufsize-1); /* We avoid equality with lit_bufsize because of wraparound at 64K * on 16 bit machines and because stored blocks are restricted to * 64K-1 bytes. */ } /* =========================================================================== * Send the block data compressed using the given Huffman trees */ local void compress_block(s, ltree, dtree) deflate_state *s; ct_data *ltree; /* literal tree */ ct_data *dtree; /* distance tree */ { unsigned dist; /* distance of matched string */ int lc; /* match length or unmatched char (if dist == 0) */ unsigned lx = 0; /* running index in l_buf */ unsigned code; /* the code to send */ int extra; /* number of extra bits to send */ if (s->last_lit != 0) do { dist = s->d_buf[lx]; lc = s->l_buf[lx++]; if (dist == 0) { send_code(s, lc, ltree); /* send a literal byte */ Tracecv(isgraph(lc), (stderr," '%c' ", lc)); } else { /* Here, lc is the match length - MIN_MATCH */ code = _length_code[lc]; send_code(s, code+LITERALS+1, ltree); /* send the length code */ extra = extra_lbits[code]; if (extra != 0) { lc -= base_length[code]; send_bits(s, lc, extra); /* send the extra length bits */ } dist--; /* dist is now the match distance - 1 */ code = d_code(dist); Assert (code < D_CODES, "bad d_code"); send_code(s, code, dtree); /* send the distance code */ extra = extra_dbits[code]; if (extra != 0) { dist -= base_dist[code]; send_bits(s, dist, extra); /* send the extra distance bits */ } } /* literal or match pair ? */ /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, "pendingBuf overflow"); } while (lx < s->last_lit); send_code(s, END_BLOCK, ltree); s->last_eob_len = ltree[END_BLOCK].Len; } /* =========================================================================== * Check if the data type is TEXT or BINARY, using the following algorithm: * - TEXT if the two conditions below are satisfied: * a) There are no non-portable control characters belonging to the * "black list" (0..6, 14..25, 28..31). * b) There is at least one printable character belonging to the * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). * - BINARY otherwise. * - The following partially-portable control characters form a * "gray list" that is ignored in this detection algorithm: * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). * IN assertion: the fields Freq of dyn_ltree are set. */ local int detect_data_type(s) deflate_state *s; { /* black_mask is the bit mask of black-listed bytes * set bits 0..6, 14..25, and 28..31 * 0xf3ffc07f = binary 11110011111111111100000001111111 */ unsigned long black_mask = 0xf3ffc07fUL; int n; /* Check for non-textual ("black-listed") bytes. */ for (n = 0; n <= 31; n++, black_mask >>= 1) if ((black_mask & 1) && (s->dyn_ltree[n].Freq != 0)) return Z_BINARY; /* Check for textual ("white-listed") bytes. */ if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 0 || s->dyn_ltree[13].Freq != 0) return Z_TEXT; for (n = 32; n < LITERALS; n++) if (s->dyn_ltree[n].Freq != 0) return Z_TEXT; /* There are no "black-listed" or "white-listed" bytes: * this stream either is empty or has tolerated ("gray-listed") bytes only. */ return Z_BINARY; } /* =========================================================================== * Reverse the first len bits of a code, using straightforward code (a faster * method would use a table) * IN assertion: 1 <= len <= 15 */ local unsigned bi_reverse(code, len) unsigned code; /* the value to invert */ int len; /* its bit length */ { register unsigned res = 0; do { res |= code & 1; code >>= 1, res <<= 1; } while (--len > 0); return res >> 1; } /* =========================================================================== * Flush the bit buffer, keeping at most 7 bits in it. */ local void bi_flush(s) deflate_state *s; { if (s->bi_valid == 16) { put_short(s, s->bi_buf); s->bi_buf = 0; s->bi_valid = 0; } else if (s->bi_valid >= 8) { put_byte(s, (Byte)s->bi_buf); s->bi_buf >>= 8; s->bi_valid -= 8; } } /* =========================================================================== * Flush the bit buffer and align the output on a byte boundary */ local void bi_windup(s) deflate_state *s; { if (s->bi_valid > 8) { put_short(s, s->bi_buf); } else if (s->bi_valid > 0) { put_byte(s, (Byte)s->bi_buf); } s->bi_buf = 0; s->bi_valid = 0; #ifdef DEBUG s->bits_sent = (s->bits_sent+7) & ~7; #endif } /* =========================================================================== * Copy a stored block, storing first the length and its * one's complement if requested. */ local void copy_block(s, buf, len, header) deflate_state *s; charf *buf; /* the input data */ unsigned len; /* its length */ int header; /* true if block header must be written */ { bi_windup(s); /* align on byte boundary */ s->last_eob_len = 8; /* enough lookahead for inflate */ if (header) { put_short(s, (ush)len); put_short(s, (ush)~len); #ifdef DEBUG s->bits_sent += 2*16; #endif } #ifdef DEBUG s->bits_sent += (ulg)len<<3; #endif while (len--) { put_byte(s, *buf++); } } ================================================ FILE: src/engine/external/zlib/trees.h ================================================ /* header created automatically with -DGEN_TREES_H */ local const ct_data static_ltree[L_CODES+2] = { {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}}, {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}}, {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}}, {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}}, {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}}, {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}}, {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}}, {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}}, {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}}, {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}}, {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}}, {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}}, {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}}, {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}}, {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}}, {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}}, {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}}, {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}}, {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}}, {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}}, {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}}, {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}}, {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}}, {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}}, {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}}, {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}}, {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}}, {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}}, {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}}, {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}}, {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}}, {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}}, {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}}, {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}}, {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}}, {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}}, {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}}, {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}}, {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}}, {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}}, {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}}, {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}}, {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}}, {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}}, {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}}, {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}}, {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}}, {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}}, {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}}, {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}}, {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}}, {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}}, {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}}, {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}}, {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}}, {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}}, {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}}, {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}} }; local const ct_data static_dtree[D_CODES] = { {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}}, {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}}, {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}}, {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}}, {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}}, {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}} }; const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = { 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17, 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29 }; const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= { 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28 }; local const int base_length[LENGTH_CODES] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 0 }; local const int base_dist[D_CODES] = { 0, 1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576 }; ================================================ FILE: src/engine/external/zlib/uncompr.c ================================================ /* uncompr.c -- decompress a memory buffer * Copyright (C) 1995-2003, 2010 Jean-loup Gailly. * For conditions of distribution and use, see copyright notice in zlib.h */ /* @(#) $Id$ */ #define ZLIB_INTERNAL #include "zlib.h" /* =========================================================================== Decompresses the source buffer into the destination buffer. sourceLen is the byte length of the source buffer. Upon entry, destLen is the total size of the destination buffer, which must be large enough to hold the entire uncompressed data. (The size of the uncompressed data must have been saved previously by the compressor and transmitted to the decompressor by some mechanism outside the scope of this compression library.) Upon exit, destLen is the actual size of the compressed buffer. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if there was not enough room in the output buffer, or Z_DATA_ERROR if the input data was corrupted. */ int ZEXPORT uncompress (dest, destLen, source, sourceLen) Bytef *dest; uLongf *destLen; const Bytef *source; uLong sourceLen; { z_stream stream; int err; stream.next_in = (Bytef*)source; stream.avail_in = (uInt)sourceLen; /* Check for source > 64K on 16-bit machine: */ if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR; stream.next_out = dest; stream.avail_out = (uInt)*destLen; if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR; stream.zalloc = (alloc_func)0; stream.zfree = (free_func)0; err = inflateInit(&stream); if (err != Z_OK) return err; err = inflate(&stream, Z_FINISH); if (err != Z_STREAM_END) { inflateEnd(&stream); if (err == Z_NEED_DICT || (err == Z_BUF_ERROR && stream.avail_in == 0)) return Z_DATA_ERROR; return err; } *destLen = stream.total_out; err = inflateEnd(&stream); return err; } ================================================ FILE: src/engine/external/zlib/zconf.h ================================================ /* zconf.h -- configuration of the zlib compression library * Copyright (C) 1995-2010 Jean-loup Gailly. * For conditions of distribution and use, see copyright notice in zlib.h */ /* @(#) $Id$ */ #ifndef ZCONF_H #define ZCONF_H /* * If you *really* need a unique prefix for all types and library functions, * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it. * Even better than compiling with -DZ_PREFIX would be to use configure to set * this permanently in zconf.h using "./configure --zprefix". */ #ifdef Z_PREFIX /* may be set to #if 1 by ./configure */ /* all linked symbols */ # define _dist_code z__dist_code # define _length_code z__length_code # define _tr_align z__tr_align # define _tr_flush_block z__tr_flush_block # define _tr_init z__tr_init # define _tr_stored_block z__tr_stored_block # define _tr_tally z__tr_tally # define adler32 z_adler32 # define adler32_combine z_adler32_combine # define adler32_combine64 z_adler32_combine64 # define compress z_compress # define compress2 z_compress2 # define compressBound z_compressBound # define crc32 z_crc32 # define crc32_combine z_crc32_combine # define crc32_combine64 z_crc32_combine64 # define deflate z_deflate # define deflateBound z_deflateBound # define deflateCopy z_deflateCopy # define deflateEnd z_deflateEnd # define deflateInit2_ z_deflateInit2_ # define deflateInit_ z_deflateInit_ # define deflateParams z_deflateParams # define deflatePrime z_deflatePrime # define deflateReset z_deflateReset # define deflateSetDictionary z_deflateSetDictionary # define deflateSetHeader z_deflateSetHeader # define deflateTune z_deflateTune # define deflate_copyright z_deflate_copyright # define get_crc_table z_get_crc_table # define gz_error z_gz_error # define gz_intmax z_gz_intmax # define gz_strwinerror z_gz_strwinerror # define gzbuffer z_gzbuffer # define gzclearerr z_gzclearerr # define gzclose z_gzclose # define gzclose_r z_gzclose_r # define gzclose_w z_gzclose_w # define gzdirect z_gzdirect # define gzdopen z_gzdopen # define gzeof z_gzeof # define gzerror z_gzerror # define gzflush z_gzflush # define gzgetc z_gzgetc # define gzgets z_gzgets # define gzoffset z_gzoffset # define gzoffset64 z_gzoffset64 # define gzopen z_gzopen # define gzopen64 z_gzopen64 # define gzprintf z_gzprintf # define gzputc z_gzputc # define gzputs z_gzputs # define gzread z_gzread # define gzrewind z_gzrewind # define gzseek z_gzseek # define gzseek64 z_gzseek64 # define gzsetparams z_gzsetparams # define gztell z_gztell # define gztell64 z_gztell64 # define gzungetc z_gzungetc # define gzwrite z_gzwrite # define inflate z_inflate # define inflateBack z_inflateBack # define inflateBackEnd z_inflateBackEnd # define inflateBackInit_ z_inflateBackInit_ # define inflateCopy z_inflateCopy # define inflateEnd z_inflateEnd # define inflateGetHeader z_inflateGetHeader # define inflateInit2_ z_inflateInit2_ # define inflateInit_ z_inflateInit_ # define inflateMark z_inflateMark # define inflatePrime z_inflatePrime # define inflateReset z_inflateReset # define inflateReset2 z_inflateReset2 # define inflateSetDictionary z_inflateSetDictionary # define inflateSync z_inflateSync # define inflateSyncPoint z_inflateSyncPoint # define inflateUndermine z_inflateUndermine # define inflate_copyright z_inflate_copyright # define inflate_fast z_inflate_fast # define inflate_table z_inflate_table # define uncompress z_uncompress # define zError z_zError # define zcalloc z_zcalloc # define zcfree z_zcfree # define zlibCompileFlags z_zlibCompileFlags # define zlibVersion z_zlibVersion /* all zlib typedefs in zlib.h and zconf.h */ # define Byte z_Byte # define Bytef z_Bytef # define alloc_func z_alloc_func # define charf z_charf # define free_func z_free_func # define gzFile z_gzFile # define gz_header z_gz_header # define gz_headerp z_gz_headerp # define in_func z_in_func # define intf z_intf # define out_func z_out_func # define uInt z_uInt # define uIntf z_uIntf # define uLong z_uLong # define uLongf z_uLongf # define voidp z_voidp # define voidpc z_voidpc # define voidpf z_voidpf /* all zlib structs in zlib.h and zconf.h */ # define gz_header_s z_gz_header_s # define internal_state z_internal_state #endif #if defined(__MSDOS__) && !defined(MSDOS) # define MSDOS #endif #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2) # define OS2 #endif #if defined(_WINDOWS) && !defined(WINDOWS) # define WINDOWS #endif #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__) # ifndef WIN32 # define WIN32 # endif #endif #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32) # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__) # ifndef SYS16BIT # define SYS16BIT # endif # endif #endif /* * Compile with -DMAXSEG_64K if the alloc function cannot allocate more * than 64k bytes at a time (needed on systems with 16-bit int). */ #ifdef SYS16BIT # define MAXSEG_64K #endif #ifdef MSDOS # define UNALIGNED_OK #endif #ifdef __STDC_VERSION__ # ifndef STDC # define STDC # endif # if __STDC_VERSION__ >= 199901L # ifndef STDC99 # define STDC99 # endif # endif #endif #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus)) # define STDC #endif #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__)) # define STDC #endif #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32)) # define STDC #endif #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__)) # define STDC #endif #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */ # define STDC #endif #ifndef STDC # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */ # define const /* note: need a more gentle solution here */ # endif #endif /* Some Mac compilers merge all .h files incorrectly: */ #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__) # define NO_DUMMY_DECL #endif /* Maximum value for memLevel in deflateInit2 */ #ifndef MAX_MEM_LEVEL # ifdef MAXSEG_64K # define MAX_MEM_LEVEL 8 # else # define MAX_MEM_LEVEL 9 # endif #endif /* Maximum value for windowBits in deflateInit2 and inflateInit2. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files * created by gzip. (Files created by minigzip can still be extracted by * gzip.) */ #ifndef MAX_WBITS # define MAX_WBITS 15 /* 32K LZ77 window */ #endif /* The memory requirements for deflate are (in bytes): (1 << (windowBits+2)) + (1 << (memLevel+9)) that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) plus a few kilobytes for small objects. For example, if you want to reduce the default memory requirements from 256K to 128K, compile with make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7" Of course this will generally degrade compression (there's no free lunch). The memory requirements for inflate are (in bytes) 1 << windowBits that is, 32K for windowBits=15 (default value) plus a few kilobytes for small objects. */ /* Type declarations */ #ifndef OF /* function prototypes */ # ifdef STDC # define OF(args) args # else # define OF(args) () # endif #endif /* The following definitions for FAR are needed only for MSDOS mixed * model programming (small or medium model with some far allocations). * This was tested only with MSC; for other MSDOS compilers you may have * to define NO_MEMCPY in zutil.h. If you don't need the mixed model, * just define FAR to be empty. */ #ifdef SYS16BIT # if defined(M_I86SM) || defined(M_I86MM) /* MSC small or medium model */ # define SMALL_MEDIUM # ifdef _MSC_VER # define FAR _far # else # define FAR far # endif # endif # if (defined(__SMALL__) || defined(__MEDIUM__)) /* Turbo C small or medium model */ # define SMALL_MEDIUM # ifdef __BORLANDC__ # define FAR _far # else # define FAR far # endif # endif #endif #if defined(WINDOWS) || defined(WIN32) /* If building or using zlib as a DLL, define ZLIB_DLL. * This is not mandatory, but it offers a little performance increase. */ # ifdef ZLIB_DLL # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500)) # ifdef ZLIB_INTERNAL # define ZEXTERN extern __declspec(dllexport) # else # define ZEXTERN extern __declspec(dllimport) # endif # endif # endif /* ZLIB_DLL */ /* If building or using zlib with the WINAPI/WINAPIV calling convention, * define ZLIB_WINAPI. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI. */ # ifdef ZLIB_WINAPI # ifdef FAR # undef FAR # endif # include <windows.h> /* No need for _export, use ZLIB.DEF instead. */ /* For complete Windows compatibility, use WINAPI, not __stdcall. */ # define ZEXPORT WINAPI # ifdef WIN32 # define ZEXPORTVA WINAPIV # else # define ZEXPORTVA FAR CDECL # endif # endif #endif #if defined (__BEOS__) # ifdef ZLIB_DLL # ifdef ZLIB_INTERNAL # define ZEXPORT __declspec(dllexport) # define ZEXPORTVA __declspec(dllexport) # else # define ZEXPORT __declspec(dllimport) # define ZEXPORTVA __declspec(dllimport) # endif # endif #endif #ifndef ZEXTERN # define ZEXTERN extern #endif #ifndef ZEXPORT # define ZEXPORT #endif #ifndef ZEXPORTVA # define ZEXPORTVA #endif #ifndef FAR # define FAR #endif #if !defined(__MACTYPES__) typedef unsigned char Byte; /* 8 bits */ #endif typedef unsigned int uInt; /* 16 bits or more */ typedef unsigned long uLong; /* 32 bits or more */ #ifdef SMALL_MEDIUM /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */ # define Bytef Byte FAR #else typedef Byte FAR Bytef; #endif typedef char FAR charf; typedef int FAR intf; typedef uInt FAR uIntf; typedef uLong FAR uLongf; #ifdef STDC typedef void const *voidpc; typedef void FAR *voidpf; typedef void *voidp; #else typedef Byte const *voidpc; typedef Byte FAR *voidpf; typedef Byte *voidp; #endif #ifdef HAVE_UNISTD_H /* may be set to #if 1 by ./configure */ # define Z_HAVE_UNISTD_H #endif #ifdef STDC # include <sys/types.h> /* for off_t */ #endif /* a little trick to accommodate both "#define _LARGEFILE64_SOURCE" and * "#define _LARGEFILE64_SOURCE 1" as requesting 64-bit operations, (even * though the former does not conform to the LFS document), but considering * both "#undef _LARGEFILE64_SOURCE" and "#define _LARGEFILE64_SOURCE 0" as * equivalently requesting no 64-bit operations */ #if -_LARGEFILE64_SOURCE - -1 == 1 # undef _LARGEFILE64_SOURCE #endif #if defined(Z_HAVE_UNISTD_H) || defined(_LARGEFILE64_SOURCE) # include <unistd.h> /* for SEEK_* and off_t */ # ifdef VMS # include <unixio.h> /* for off_t */ # endif # ifndef z_off_t # define z_off_t off_t # endif #endif #ifndef SEEK_SET # define SEEK_SET 0 /* Seek from beginning of file. */ # define SEEK_CUR 1 /* Seek from current position. */ # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */ #endif #ifndef z_off_t # define z_off_t long #endif #if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0 # define z_off64_t off64_t #else # define z_off64_t z_off_t #endif #if defined(__OS400__) # define NO_vsnprintf #endif #if defined(__MVS__) # define NO_vsnprintf #endif /* MVS linker does not support external names larger than 8 bytes */ #if defined(__MVS__) #pragma map(deflateInit_,"DEIN") #pragma map(deflateInit2_,"DEIN2") #pragma map(deflateEnd,"DEEND") #pragma map(deflateBound,"DEBND") #pragma map(inflateInit_,"ININ") #pragma map(inflateInit2_,"ININ2") #pragma map(inflateEnd,"INEND") #pragma map(inflateSync,"INSY") #pragma map(inflateSetDictionary,"INSEDI") #pragma map(compressBound,"CMBND") #pragma map(inflate_table,"INTABL") #pragma map(inflate_fast,"INFA") #pragma map(inflate_copyright,"INCOPY") #endif #endif /* ZCONF_H */ ================================================ FILE: src/engine/external/zlib/zlib.h ================================================ /* zlib.h -- interface of the 'zlib' general purpose compression library version 1.2.5, April 19th, 2010 Copyright (C) 1995-2010 Jean-loup Gailly and Mark Adler This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Jean-loup Gailly Mark Adler jloup@gzip.org madler@alumni.caltech.edu The data format used by the zlib library is described by RFCs (Request for Comments) 1950 to 1952 in the files http://www.ietf.org/rfc/rfc1950.txt (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format). */ #ifndef ZLIB_H #define ZLIB_H #include "zconf.h" #ifdef __cplusplus extern "C" { #endif #define ZLIB_VERSION "1.2.5" #define ZLIB_VERNUM 0x1250 #define ZLIB_VER_MAJOR 1 #define ZLIB_VER_MINOR 2 #define ZLIB_VER_REVISION 5 #define ZLIB_VER_SUBREVISION 0 /* The 'zlib' compression library provides in-memory compression and decompression functions, including integrity checks of the uncompressed data. This version of the library supports only one compression method (deflation) but other algorithms will be added later and will have the same stream interface. Compression can be done in a single step if the buffers are large enough, or can be done by repeated calls of the compression function. In the latter case, the application must provide more input and/or consume the output (providing more output space) before each call. The compressed data format used by default by the in-memory functions is the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped around a deflate stream, which is itself documented in RFC 1951. The library also supports reading and writing files in gzip (.gz) format with an interface similar to that of stdio using the functions that start with "gz". The gzip format is different from the zlib format. gzip is a gzip wrapper, documented in RFC 1952, wrapped around a deflate stream. This library can optionally read and write gzip streams in memory as well. The zlib format was designed to be compact and fast for use in memory and on communications channels. The gzip format was designed for single- file compression on file systems, has a larger header than zlib to maintain directory information, and uses a different, slower check method than zlib. The library does not install any signal handler. The decoder checks the consistency of the compressed data, so the library should never crash even in case of corrupted input. */ typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size)); typedef void (*free_func) OF((voidpf opaque, voidpf address)); struct internal_state; typedef struct z_stream_s { Bytef *next_in; /* next input byte */ uInt avail_in; /* number of bytes available at next_in */ uLong total_in; /* total nb of input bytes read so far */ Bytef *next_out; /* next output byte should be put there */ uInt avail_out; /* remaining free space at next_out */ uLong total_out; /* total nb of bytes output so far */ char *msg; /* last error message, NULL if no error */ struct internal_state FAR *state; /* not visible by applications */ alloc_func zalloc; /* used to allocate the internal state */ free_func zfree; /* used to free the internal state */ voidpf opaque; /* private data object passed to zalloc and zfree */ int data_type; /* best guess about the data type: binary or text */ uLong adler; /* adler32 value of the uncompressed data */ uLong reserved; /* reserved for future use */ } z_stream; typedef z_stream FAR *z_streamp; /* gzip header information passed to and from zlib routines. See RFC 1952 for more details on the meanings of these fields. */ typedef struct gz_header_s { int text; /* true if compressed data believed to be text */ uLong time; /* modification time */ int xflags; /* extra flags (not used when writing a gzip file) */ int os; /* operating system */ Bytef *extra; /* pointer to extra field or Z_NULL if none */ uInt extra_len; /* extra field length (valid if extra != Z_NULL) */ uInt extra_max; /* space at extra (only when reading header) */ Bytef *name; /* pointer to zero-terminated file name or Z_NULL */ uInt name_max; /* space at name (only when reading header) */ Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */ uInt comm_max; /* space at comment (only when reading header) */ int hcrc; /* true if there was or will be a header crc */ int done; /* true when done reading gzip header (not used when writing a gzip file) */ } gz_header; typedef gz_header FAR *gz_headerp; /* The application must update next_in and avail_in when avail_in has dropped to zero. It must update next_out and avail_out when avail_out has dropped to zero. The application must initialize zalloc, zfree and opaque before calling the init function. All other fields are set by the compression library and must not be updated by the application. The opaque value provided by the application will be passed as the first parameter for calls of zalloc and zfree. This can be useful for custom memory management. The compression library attaches no meaning to the opaque value. zalloc must return Z_NULL if there is not enough memory for the object. If zlib is used in a multi-threaded application, zalloc and zfree must be thread safe. On 16-bit systems, the functions zalloc and zfree must be able to allocate exactly 65536 bytes, but will not be required to allocate more than this if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS, pointers returned by zalloc for objects of exactly 65536 bytes *must* have their offset normalized to zero. The default allocation function provided by this library ensures this (see zutil.c). To reduce memory requirements and avoid any allocation of 64K objects, at the expense of compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h). The fields total_in and total_out can be used for statistics or progress reports. After compression, total_in holds the total size of the uncompressed data and may be saved for use in the decompressor (particularly if the decompressor wants to decompress everything in a single step). */ /* constants */ #define Z_NO_FLUSH 0 #define Z_PARTIAL_FLUSH 1 #define Z_SYNC_FLUSH 2 #define Z_FULL_FLUSH 3 #define Z_FINISH 4 #define Z_BLOCK 5 #define Z_TREES 6 /* Allowed flush values; see deflate() and inflate() below for details */ #define Z_OK 0 #define Z_STREAM_END 1 #define Z_NEED_DICT 2 #define Z_ERRNO (-1) #define Z_STREAM_ERROR (-2) #define Z_DATA_ERROR (-3) #define Z_MEM_ERROR (-4) #define Z_BUF_ERROR (-5) #define Z_VERSION_ERROR (-6) /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ #define Z_NO_COMPRESSION 0 #define Z_BEST_SPEED 1 #define Z_BEST_COMPRESSION 9 #define Z_DEFAULT_COMPRESSION (-1) /* compression levels */ #define Z_FILTERED 1 #define Z_HUFFMAN_ONLY 2 #define Z_RLE 3 #define Z_FIXED 4 #define Z_DEFAULT_STRATEGY 0 /* compression strategy; see deflateInit2() below for details */ #define Z_BINARY 0 #define Z_TEXT 1 #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */ #define Z_UNKNOWN 2 /* Possible values of the data_type field (though see inflate()) */ #define Z_DEFLATED 8 /* The deflate compression method (the only one supported in this version) */ #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */ #define zlib_version zlibVersion() /* for compatibility with versions < 1.0.2 */ /* basic functions */ ZEXTERN const char * ZEXPORT zlibVersion OF((void)); /* The application can compare zlibVersion and ZLIB_VERSION for consistency. If the first character differs, the library code actually used is not compatible with the zlib.h header file used by the application. This check is automatically made by deflateInit and inflateInit. */ /* ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level)); Initializes the internal stream state for compression. The fields zalloc, zfree and opaque must be initialized before by the caller. If zalloc and zfree are set to Z_NULL, deflateInit updates them to use default allocation functions. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: 1 gives best speed, 9 gives best compression, 0 gives no compression at all (the input data is simply copied a block at a time). Z_DEFAULT_COMPRESSION requests a default compromise between speed and compression (currently equivalent to level 6). deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_STREAM_ERROR if level is not a valid compression level, or Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible with the version assumed by the caller (ZLIB_VERSION). msg is set to null if there is no error message. deflateInit does not perform any compression: this will be done by deflate(). */ ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush)); /* deflate compresses as much data as possible, and stops when the input buffer becomes empty or the output buffer becomes full. It may introduce some output latency (reading input without producing any output) except when forced to flush. The detailed semantics are as follows. deflate performs one or both of the following actions: - Compress more input starting at next_in and update next_in and avail_in accordingly. If not all input can be processed (because there is not enough room in the output buffer), next_in and avail_in are updated and processing will resume at this point for the next call of deflate(). - Provide more output starting at next_out and update next_out and avail_out accordingly. This action is forced if the parameter flush is non zero. Forcing flush frequently degrades the compression ratio, so this parameter should be set only when necessary (in interactive applications). Some output may be provided even if flush is not set. Before the call of deflate(), the application should ensure that at least one of the actions is possible, by providing more input and/or consuming more output, and updating avail_in or avail_out accordingly; avail_out should never be zero before the call. The application can consume the compressed output when it wants, for example when the output buffer is full (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK and with zero avail_out, it must be called again after making room in the output buffer because there might be more output pending. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to decide how much data to accumulate before producing output, in order to maximize compression. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is flushed to the output buffer and the output is aligned on a byte boundary, so that the decompressor can get all input data available so far. (In particular avail_in is zero after the call if enough output space has been provided before the call.) Flushing may degrade compression for some compression algorithms and so it should be used only when necessary. This completes the current deflate block and follows it with an empty stored block that is three bits plus filler bits to the next byte, followed by four bytes (00 00 ff ff). If flush is set to Z_PARTIAL_FLUSH, all pending output is flushed to the output buffer, but the output is not aligned to a byte boundary. All of the input data so far will be available to the decompressor, as for Z_SYNC_FLUSH. This completes the current deflate block and follows it with an empty fixed codes block that is 10 bits long. This assures that enough bytes are output in order for the decompressor to finish the block before the empty fixed code block. If flush is set to Z_BLOCK, a deflate block is completed and emitted, as for Z_SYNC_FLUSH, but the output is not aligned on a byte boundary, and up to seven bits of the current block are held to be written as the next byte after the next deflate block is completed. In this case, the decompressor may not be provided enough bits at this point in order to complete decompression of the data provided so far to the compressor. It may need to wait for the next block to be emitted. This is for advanced applications that need to control the emission of deflate blocks. If flush is set to Z_FULL_FLUSH, all output is flushed as with Z_SYNC_FLUSH, and the compression state is reset so that decompression can restart from this point if previous compressed data has been damaged or if random access is desired. Using Z_FULL_FLUSH too often can seriously degrade compression. If deflate returns with avail_out == 0, this function must be called again with the same value of the flush parameter and more output space (updated avail_out), until the flush is complete (deflate returns with non-zero avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that avail_out is greater than six to avoid repeated flush markers due to avail_out == 0 on return. If the parameter flush is set to Z_FINISH, pending input is processed, pending output is flushed and deflate returns with Z_STREAM_END if there was enough output space; if deflate returns with Z_OK, this function must be called again with Z_FINISH and more output space (updated avail_out) but no more input data, until it returns with Z_STREAM_END or an error. After deflate has returned Z_STREAM_END, the only possible operations on the stream are deflateReset or deflateEnd. Z_FINISH can be used immediately after deflateInit if all the compression is to be done in a single step. In this case, avail_out must be at least the value returned by deflateBound (see below). If deflate does not return Z_STREAM_END, then it must be called again as described above. deflate() sets strm->adler to the adler32 checksum of all input read so far (that is, total_in bytes). deflate() may update strm->data_type if it can make a good guess about the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered binary. This field is only for information purposes and does not affect the compression algorithm in any manner. deflate() returns Z_OK if some progress has been made (more input processed or more output produced), Z_STREAM_END if all input has been consumed and all output has been produced (only when flush is set to Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example if next_in or next_out was Z_NULL), Z_BUF_ERROR if no progress is possible (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not fatal, and deflate() can be called again with more input and more output space to continue compressing. */ ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm)); /* All dynamically allocated data structures for this stream are freed. This function discards any unprocessed input and does not flush any pending output. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state was inconsistent, Z_DATA_ERROR if the stream was freed prematurely (some input or output was discarded). In the error case, msg may be set but then points to a static string (which must not be deallocated). */ /* ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm)); Initializes the internal stream state for decompression. The fields next_in, avail_in, zalloc, zfree and opaque must be initialized before by the caller. If next_in is not Z_NULL and avail_in is large enough (the exact value depends on the compression method), inflateInit determines the compression method from the zlib header and allocates all data structures accordingly; otherwise the allocation will be deferred to the first call of inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to use default allocation functions. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_VERSION_ERROR if the zlib library version is incompatible with the version assumed by the caller, or Z_STREAM_ERROR if the parameters are invalid, such as a null pointer to the structure. msg is set to null if there is no error message. inflateInit does not perform any decompression apart from possibly reading the zlib header if present: actual decompression will be done by inflate(). (So next_in and avail_in may be modified, but next_out and avail_out are unused and unchanged.) The current implementation of inflateInit() does not process any header information -- that is deferred until inflate() is called. */ ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush)); /* inflate decompresses as much data as possible, and stops when the input buffer becomes empty or the output buffer becomes full. It may introduce some output latency (reading input without producing any output) except when forced to flush. The detailed semantics are as follows. inflate performs one or both of the following actions: - Decompress more input starting at next_in and update next_in and avail_in accordingly. If not all input can be processed (because there is not enough room in the output buffer), next_in is updated and processing will resume at this point for the next call of inflate(). - Provide more output starting at next_out and update next_out and avail_out accordingly. inflate() provides as much output as possible, until there is no more input data or no more space in the output buffer (see below about the flush parameter). Before the call of inflate(), the application should ensure that at least one of the actions is possible, by providing more input and/or consuming more output, and updating the next_* and avail_* values accordingly. The application can consume the uncompressed output when it wants, for example when the output buffer is full (avail_out == 0), or after each call of inflate(). If inflate returns Z_OK and with zero avail_out, it must be called again after making room in the output buffer because there might be more output pending. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FINISH, Z_BLOCK, or Z_TREES. Z_SYNC_FLUSH requests that inflate() flush as much output as possible to the output buffer. Z_BLOCK requests that inflate() stop if and when it gets to the next deflate block boundary. When decoding the zlib or gzip format, this will cause inflate() to return immediately after the header and before the first block. When doing a raw inflate, inflate() will go ahead and process the first block, and will return when it gets to the end of that block, or when it runs out of data. The Z_BLOCK option assists in appending to or combining deflate streams. Also to assist in this, on return inflate() will set strm->data_type to the number of unused bits in the last byte taken from strm->next_in, plus 64 if inflate() is currently decoding the last block in the deflate stream, plus 128 if inflate() returned immediately after decoding an end-of-block code or decoding the complete header up to just before the first byte of the deflate stream. The end-of-block will not be indicated until all of the uncompressed data from that block has been written to strm->next_out. The number of unused bits may in general be greater than seven, except when bit 7 of data_type is set, in which case the number of unused bits will be less than eight. data_type is set as noted here every time inflate() returns for all flush options, and so can be used to determine the amount of currently consumed input in bits. The Z_TREES option behaves as Z_BLOCK does, but it also returns when the end of each deflate block header is reached, before any actual data in that block is decoded. This allows the caller to determine the length of the deflate block header for later use in random access within a deflate block. 256 is added to the value of strm->data_type when inflate() returns immediately after reaching the end of the deflate block header. inflate() should normally be called until it returns Z_STREAM_END or an error. However if all decompression is to be performed in a single step (a single call of inflate), the parameter flush should be set to Z_FINISH. In this case all pending input is processed and all pending output is flushed; avail_out must be large enough to hold all the uncompressed data. (The size of the uncompressed data may have been saved by the compressor for this purpose.) The next operation on this stream must be inflateEnd to deallocate the decompression state. The use of Z_FINISH is never required, but can be used to inform inflate that a faster approach may be used for the single inflate() call. In this implementation, inflate() always flushes as much output as possible to the output buffer, and always uses the faster approach on the first call. So the only effect of the flush parameter in this implementation is on the return value of inflate(), as noted below, or when it returns early because Z_BLOCK or Z_TREES is used. If a preset dictionary is needed after this call (see inflateSetDictionary below), inflate sets strm->adler to the adler32 checksum of the dictionary chosen by the compressor and returns Z_NEED_DICT; otherwise it sets strm->adler to the adler32 checksum of all output produced so far (that is, total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described below. At the end of the stream, inflate() checks that its computed adler32 checksum is equal to that saved by the compressor and returns Z_STREAM_END only if the checksum is correct. inflate() can decompress and check either zlib-wrapped or gzip-wrapped deflate data. The header type is detected automatically, if requested when initializing with inflateInit2(). Any information contained in the gzip header is not retained, so applications that need that information should instead use raw inflate, see inflateInit2() below, or inflateBack() and perform their own processing of the gzip header and trailer. inflate() returns Z_OK if some progress has been made (more input processed or more output produced), Z_STREAM_END if the end of the compressed data has been reached and all uncompressed output has been produced, Z_NEED_DICT if a preset dictionary is needed at this point, Z_DATA_ERROR if the input data was corrupted (input stream not conforming to the zlib format or incorrect check value), Z_STREAM_ERROR if the stream structure was inconsistent (for example next_in or next_out was Z_NULL), Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if no progress is possible or if there was not enough room in the output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and inflate() can be called again with more input and more output space to continue decompressing. If Z_DATA_ERROR is returned, the application may then call inflateSync() to look for a good compression block if a partial recovery of the data is desired. */ ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm)); /* All dynamically allocated data structures for this stream are freed. This function discards any unprocessed input and does not flush any pending output. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state was inconsistent. In the error case, msg may be set but then points to a static string (which must not be deallocated). */ /* Advanced functions */ /* The following functions are needed only in some special applications. */ /* ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy)); This is another version of deflateInit with more compression options. The fields next_in, zalloc, zfree and opaque must be initialized before by the caller. The method parameter is the compression method. It must be Z_DEFLATED in this version of the library. The windowBits parameter is the base two logarithm of the window size (the size of the history buffer). It should be in the range 8..15 for this version of the library. Larger values of this parameter result in better compression at the expense of memory usage. The default value is 15 if deflateInit is used instead. windowBits can also be -8..-15 for raw deflate. In this case, -windowBits determines the window size. deflate() will then generate raw deflate data with no zlib header or trailer, and will not compute an adler32 check value. windowBits can also be greater than 15 for optional gzip encoding. Add 16 to windowBits to write a simple gzip header and trailer around the compressed data instead of a zlib wrapper. The gzip header will have no file name, no extra data, no comment, no modification time (set to zero), no header crc, and the operating system will be set to 255 (unknown). If a gzip stream is being written, strm->adler is a crc32 instead of an adler32. The memLevel parameter specifies how much memory should be allocated for the internal compression state. memLevel=1 uses minimum memory but is slow and reduces compression ratio; memLevel=9 uses maximum memory for optimal speed. The default value is 8. See zconf.h for total memory usage as a function of windowBits and memLevel. The strategy parameter is used to tune the compression algorithm. Use the value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no string match), or Z_RLE to limit match distances to one (run-length encoding). Filtered data consists mostly of small values with a somewhat random distribution. In this case, the compression algorithm is tuned to compress them better. The effect of Z_FILTERED is to force more Huffman coding and less string matching; it is somewhat intermediate between Z_DEFAULT_STRATEGY and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy parameter only affects the compression ratio but not the correctness of the compressed output even if it is not set appropriately. Z_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler decoder for special applications. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_STREAM_ERROR if any parameter is invalid (such as an invalid method), or Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible with the version assumed by the caller (ZLIB_VERSION). msg is set to null if there is no error message. deflateInit2 does not perform any compression: this will be done by deflate(). */ ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm, const Bytef *dictionary, uInt dictLength)); /* Initializes the compression dictionary from the given byte sequence without producing any compressed output. This function must be called immediately after deflateInit, deflateInit2 or deflateReset, before any call of deflate. The compressor and decompressor must use exactly the same dictionary (see inflateSetDictionary). The dictionary should consist of strings (byte sequences) that are likely to be encountered later in the data to be compressed, with the most commonly used strings preferably put towards the end of the dictionary. Using a dictionary is most useful when the data to be compressed is short and can be predicted with good accuracy; the data can then be compressed better than with the default empty dictionary. Depending on the size of the compression data structures selected by deflateInit or deflateInit2, a part of the dictionary may in effect be discarded, for example if the dictionary is larger than the window size provided in deflateInit or deflateInit2. Thus the strings most likely to be useful should be put at the end of the dictionary, not at the front. In addition, the current implementation of deflate will use at most the window size minus 262 bytes of the provided dictionary. Upon return of this function, strm->adler is set to the adler32 value of the dictionary; the decompressor may later use this value to determine which dictionary has been used by the compressor. (The adler32 value applies to the whole dictionary even if only a subset of the dictionary is actually used by the compressor.) If a raw deflate was requested, then the adler32 value is not computed and strm->adler is not set. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is inconsistent (for example if deflate has already been called for this stream or if the compression method is bsort). deflateSetDictionary does not perform any compression: this will be done by deflate(). */ ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest, z_streamp source)); /* Sets the destination stream as a complete copy of the source stream. This function can be useful when several compression strategies will be tried, for example when there are several ways of pre-processing the input data with a filter. The streams that will be discarded should then be freed by calling deflateEnd. Note that deflateCopy duplicates the internal compression state which can be quite large, so this strategy is slow and can consume lots of memory. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_STREAM_ERROR if the source stream state was inconsistent (such as zalloc being Z_NULL). msg is left unchanged in both source and destination. */ ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm)); /* This function is equivalent to deflateEnd followed by deflateInit, but does not free and reallocate all the internal compression state. The stream will keep the same compression level and any other attributes that may have been set by deflateInit2. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent (such as zalloc or state being Z_NULL). */ ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm, int level, int strategy)); /* Dynamically update the compression level and compression strategy. The interpretation of level and strategy is as in deflateInit2. This can be used to switch between compression and straight copy of the input data, or to switch to a different kind of input data requiring a different strategy. If the compression level is changed, the input available so far is compressed with the old level (and may be flushed); the new level will take effect only at the next call of deflate(). Before the call of deflateParams, the stream state must be set as for a call of deflate(), since the currently available input may have to be compressed and flushed. In particular, strm->avail_out must be non-zero. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR if strm->avail_out was zero. */ ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)); /* Fine tune deflate's internal compression parameters. This should only be used by someone who understands the algorithm used by zlib's deflate for searching for the best matching string, and even then only by the most fanatic optimizer trying to squeeze out the last compressed bit for their specific input data. Read the deflate.c source code for the meaning of the max_lazy, good_length, nice_length, and max_chain parameters. deflateTune() can be called after deflateInit() or deflateInit2(), and returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream. */ ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm, uLong sourceLen)); /* deflateBound() returns an upper bound on the compressed size after deflation of sourceLen bytes. It must be called after deflateInit() or deflateInit2(), and after deflateSetHeader(), if used. This would be used to allocate an output buffer for deflation in a single pass, and so would be called before deflate(). */ ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm, int bits, int value)); /* deflatePrime() inserts bits in the deflate output stream. The intent is that this function is used to start off the deflate output with the bits leftover from a previous deflate stream when appending to it. As such, this function can only be used for raw deflate, and must be used before the first deflate() call after a deflateInit2() or deflateReset(). bits must be less than or equal to 16, and that many of the least significant bits of value will be inserted in the output. deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent. */ ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm, gz_headerp head)); /* deflateSetHeader() provides gzip header information for when a gzip stream is requested by deflateInit2(). deflateSetHeader() may be called after deflateInit2() or deflateReset() and before the first call of deflate(). The text, time, os, extra field, name, and comment information in the provided gz_header structure are written to the gzip header (xflag is ignored -- the extra flags are set according to the compression level). The caller must assure that, if not Z_NULL, name and comment are terminated with a zero byte, and that if extra is not Z_NULL, that extra_len bytes are available there. If hcrc is true, a gzip header crc is included. Note that the current versions of the command-line version of gzip (up through version 1.3.x) do not support header crc's, and will report that it is a "multi-part gzip file" and give up. If deflateSetHeader is not used, the default gzip header has text false, the time set to zero, and os set to 255, with no extra, name, or comment fields. The gzip header is returned to the default state by deflateReset(). deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent. */ /* ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm, int windowBits)); This is another version of inflateInit with an extra parameter. The fields next_in, avail_in, zalloc, zfree and opaque must be initialized before by the caller. The windowBits parameter is the base two logarithm of the maximum window size (the size of the history buffer). It should be in the range 8..15 for this version of the library. The default value is 15 if inflateInit is used instead. windowBits must be greater than or equal to the windowBits value provided to deflateInit2() while compressing, or it must be equal to 15 if deflateInit2() was not used. If a compressed stream with a larger window size is given as input, inflate() will return with the error code Z_DATA_ERROR instead of trying to allocate a larger window. windowBits can also be zero to request that inflate use the window size in the zlib header of the compressed stream. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits determines the window size. inflate() will then process raw deflate data, not looking for a zlib or gzip header, not generating a check value, and not looking for any check values for comparison at the end of the stream. This is for use with other formats that use the deflate compressed data format such as zip. Those formats provide their own check values. If a custom format is developed using the raw deflate format for compressed data, it is recommended that a check value such as an adler32 or a crc32 be applied to the uncompressed data as is done in the zlib, gzip, and zip formats. For most applications, the zlib format should be used as is. Note that comments above on the use in deflateInit2() applies to the magnitude of windowBits. windowBits can also be greater than 15 for optional gzip decoding. Add 32 to windowBits to enable zlib and gzip decoding with automatic header detection, or add 16 to decode only the gzip format (the zlib format will return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is a crc32 instead of an adler32. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_VERSION_ERROR if the zlib library version is incompatible with the version assumed by the caller, or Z_STREAM_ERROR if the parameters are invalid, such as a null pointer to the structure. msg is set to null if there is no error message. inflateInit2 does not perform any decompression apart from possibly reading the zlib header if present: actual decompression will be done by inflate(). (So next_in and avail_in may be modified, but next_out and avail_out are unused and unchanged.) The current implementation of inflateInit2() does not process any header information -- that is deferred until inflate() is called. */ ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm, const Bytef *dictionary, uInt dictLength)); /* Initializes the decompression dictionary from the given uncompressed byte sequence. This function must be called immediately after a call of inflate, if that call returned Z_NEED_DICT. The dictionary chosen by the compressor can be determined from the adler32 value returned by that call of inflate. The compressor and decompressor must use exactly the same dictionary (see deflateSetDictionary). For raw inflate, this function can be called immediately after inflateInit2() or inflateReset() and before any call of inflate() to set the dictionary. The application must insure that the dictionary that was used for compression is provided. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the expected one (incorrect adler32 value). inflateSetDictionary does not perform any decompression: this will be done by subsequent calls of inflate(). */ ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm)); /* Skips invalid compressed data until a full flush point (see above the description of deflate with Z_FULL_FLUSH) can be found, or until all available input is skipped. No output is provided. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR if no more input was provided, Z_DATA_ERROR if no flush point has been found, or Z_STREAM_ERROR if the stream structure was inconsistent. In the success case, the application may save the current current value of total_in which indicates where valid compressed data was found. In the error case, the application may repeatedly call inflateSync, providing more input each time, until success or end of the input data. */ ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest, z_streamp source)); /* Sets the destination stream as a complete copy of the source stream. This function can be useful when randomly accessing a large stream. The first pass through the stream can periodically record the inflate state, allowing restarting inflate at those points when randomly accessing the stream. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_STREAM_ERROR if the source stream state was inconsistent (such as zalloc being Z_NULL). msg is left unchanged in both source and destination. */ ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm)); /* This function is equivalent to inflateEnd followed by inflateInit, but does not free and reallocate all the internal decompression state. The stream will keep attributes that may have been set by inflateInit2. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent (such as zalloc or state being Z_NULL). */ ZEXTERN int ZEXPORT inflateReset2 OF((z_streamp strm, int windowBits)); /* This function is the same as inflateReset, but it also permits changing the wrap and window size requests. The windowBits parameter is interpreted the same as it is for inflateInit2. inflateReset2 returns Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent (such as zalloc or state being Z_NULL), or if the windowBits parameter is invalid. */ ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm, int bits, int value)); /* This function inserts bits in the inflate input stream. The intent is that this function is used to start inflating at a bit position in the middle of a byte. The provided bits will be used before any bytes are used from next_in. This function should only be used with raw inflate, and should be used before the first inflate() call after inflateInit2() or inflateReset(). bits must be less than or equal to 16, and that many of the least significant bits of value will be inserted in the input. If bits is negative, then the input stream bit buffer is emptied. Then inflatePrime() can be called again to put bits in the buffer. This is used to clear out bits leftover after feeding inflate a block description prior to feeding inflate codes. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent. */ ZEXTERN long ZEXPORT inflateMark OF((z_streamp strm)); /* This function returns two values, one in the lower 16 bits of the return value, and the other in the remaining upper bits, obtained by shifting the return value down 16 bits. If the upper value is -1 and the lower value is zero, then inflate() is currently decoding information outside of a block. If the upper value is -1 and the lower value is non-zero, then inflate is in the middle of a stored block, with the lower value equaling the number of bytes from the input remaining to copy. If the upper value is not -1, then it is the number of bits back from the current bit position in the input of the code (literal or length/distance pair) currently being processed. In that case the lower value is the number of bytes already emitted for that code. A code is being processed if inflate is waiting for more input to complete decoding of the code, or if it has completed decoding but is waiting for more output space to write the literal or match data. inflateMark() is used to mark locations in the input data for random access, which may be at bit positions, and to note those cases where the output of a code may span boundaries of random access blocks. The current location in the input stream can be determined from avail_in and data_type as noted in the description for the Z_BLOCK flush parameter for inflate. inflateMark returns the value noted above or -1 << 16 if the provided source stream state was inconsistent. */ ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm, gz_headerp head)); /* inflateGetHeader() requests that gzip header information be stored in the provided gz_header structure. inflateGetHeader() may be called after inflateInit2() or inflateReset(), and before the first call of inflate(). As inflate() processes the gzip stream, head->done is zero until the header is completed, at which time head->done is set to one. If a zlib stream is being decoded, then head->done is set to -1 to indicate that there will be no gzip header information forthcoming. Note that Z_BLOCK or Z_TREES can be used to force inflate() to return immediately after header processing is complete and before any actual data is decompressed. The text, time, xflags, and os fields are filled in with the gzip header contents. hcrc is set to true if there is a header CRC. (The header CRC was valid if done is set to one.) If extra is not Z_NULL, then extra_max contains the maximum number of bytes to write to extra. Once done is true, extra_len contains the actual extra field length, and extra contains the extra field, or that field truncated if extra_max is less than extra_len. If name is not Z_NULL, then up to name_max characters are written there, terminated with a zero unless the length is greater than name_max. If comment is not Z_NULL, then up to comm_max characters are written there, terminated with a zero unless the length is greater than comm_max. When any of extra, name, or comment are not Z_NULL and the respective field is not present in the header, then that field is set to Z_NULL to signal its absence. This allows the use of deflateSetHeader() with the returned structure to duplicate the header. However if those fields are set to allocated memory, then the application will need to save those pointers elsewhere so that they can be eventually freed. If inflateGetHeader is not used, then the header information is simply discarded. The header is always checked for validity, including the header CRC if present. inflateReset() will reset the process to discard the header information. The application would need to call inflateGetHeader() again to retrieve the header from the next gzip stream. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source stream state was inconsistent. */ /* ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits, unsigned char FAR *window)); Initialize the internal stream state for decompression using inflateBack() calls. The fields zalloc, zfree and opaque in strm must be initialized before the call. If zalloc and zfree are Z_NULL, then the default library- derived memory allocation routines are used. windowBits is the base two logarithm of the window size, in the range 8..15. window is a caller supplied buffer of that size. Except for special applications where it is assured that deflate was used with small window sizes, windowBits must be 15 and a 32K byte window must be supplied to be able to decompress general deflate streams. See inflateBack() for the usage of these routines. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of the paramaters are invalid, Z_MEM_ERROR if the internal state could not be allocated, or Z_VERSION_ERROR if the version of the library does not match the version of the header file. */ typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *)); typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned)); ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm, in_func in, void FAR *in_desc, out_func out, void FAR *out_desc)); /* inflateBack() does a raw inflate with a single call using a call-back interface for input and output. This is more efficient than inflate() for file i/o applications in that it avoids copying between the output and the sliding window by simply making the window itself the output buffer. This function trusts the application to not change the output buffer passed by the output function, at least until inflateBack() returns. inflateBackInit() must be called first to allocate the internal state and to initialize the state with the user-provided window buffer. inflateBack() may then be used multiple times to inflate a complete, raw deflate stream with each call. inflateBackEnd() is then called to free the allocated state. A raw deflate stream is one with no zlib or gzip header or trailer. This routine would normally be used in a utility that reads zip or gzip files and writes out uncompressed files. The utility would decode the header and process the trailer on its own, hence this routine expects only the raw deflate stream to decompress. This is different from the normal behavior of inflate(), which expects either a zlib or gzip header and trailer around the deflate stream. inflateBack() uses two subroutines supplied by the caller that are then called by inflateBack() for input and output. inflateBack() calls those routines until it reads a complete deflate stream and writes out all of the uncompressed data, or until it encounters an error. The function's parameters and return types are defined above in the in_func and out_func typedefs. inflateBack() will call in(in_desc, &buf) which should return the number of bytes of provided input, and a pointer to that input in buf. If there is no input available, in() must return zero--buf is ignored in that case--and inflateBack() will return a buffer error. inflateBack() will call out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out() should return zero on success, or non-zero on failure. If out() returns non-zero, inflateBack() will return with an error. Neither in() nor out() are permitted to change the contents of the window provided to inflateBackInit(), which is also the buffer that out() uses to write from. The length written by out() will be at most the window size. Any non-zero amount of input may be provided by in(). For convenience, inflateBack() can be provided input on the first call by setting strm->next_in and strm->avail_in. If that input is exhausted, then in() will be called. Therefore strm->next_in must be initialized before calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in must also be initialized, and then if strm->avail_in is not zero, input will initially be taken from strm->next_in[0 .. strm->avail_in - 1]. The in_desc and out_desc parameters of inflateBack() is passed as the first parameter of in() and out() respectively when they are called. These descriptors can be optionally used to pass any information that the caller- supplied in() and out() functions need to do their job. On return, inflateBack() will set strm->next_in and strm->avail_in to pass back any unused input that was provided by the last in() call. The return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR if in() or out() returned an error, Z_DATA_ERROR if there was a format error in the deflate stream (in which case strm->msg is set to indicate the nature of the error), or Z_STREAM_ERROR if the stream was not properly initialized. In the case of Z_BUF_ERROR, an input or output error can be distinguished using strm->next_in which will be Z_NULL only if in() returned an error. If strm->next_in is not Z_NULL, then the Z_BUF_ERROR was due to out() returning non-zero. (in() will always be called before out(), so strm->next_in is assured to be defined if out() returns non-zero.) Note that inflateBack() cannot return Z_OK. */ ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm)); /* All memory allocated by inflateBackInit() is freed. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream state was inconsistent. */ ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void)); /* Return flags indicating compile-time options. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other: 1.0: size of uInt 3.2: size of uLong 5.4: size of voidpf (pointer) 7.6: size of z_off_t Compiler, assembler, and debug options: 8: DEBUG 9: ASMV or ASMINF -- use ASM code 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention 11: 0 (reserved) One-time table building (smaller code, but not thread-safe if true): 12: BUILDFIXED -- build static block decoding tables when needed 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed 14,15: 0 (reserved) Library content (indicates missing functionality): 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking deflate code when not needed) 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect and decode gzip streams (to avoid linking crc code) 18-19: 0 (reserved) Operation variations (changes in library functionality): 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate 21: FASTEST -- deflate algorithm with only one, lowest compression level 22,23: 0 (reserved) The sprintf variant used by gzprintf (zero is best): 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure! 26: 0 = returns value, 1 = void -- 1 means inferred string length returned Remainder: 27-31: 0 (reserved) */ /* utility functions */ /* The following utility functions are implemented on top of the basic stream-oriented functions. To simplify the interface, some default options are assumed (compression level and memory usage, standard memory allocation functions). The source code of these utility functions can be modified if you need special options. */ ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)); /* Compresses the source buffer into the destination buffer. sourceLen is the byte length of the source buffer. Upon entry, destLen is the total size of the destination buffer, which must be at least the value returned by compressBound(sourceLen). Upon exit, destLen is the actual size of the compressed buffer. compress returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if there was not enough room in the output buffer. */ ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen, int level)); /* Compresses the source buffer into the destination buffer. The level parameter has the same meaning as in deflateInit. sourceLen is the byte length of the source buffer. Upon entry, destLen is the total size of the destination buffer, which must be at least the value returned by compressBound(sourceLen). Upon exit, destLen is the actual size of the compressed buffer. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if there was not enough room in the output buffer, Z_STREAM_ERROR if the level parameter is invalid. */ ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen)); /* compressBound() returns an upper bound on the compressed size after compress() or compress2() on sourceLen bytes. It would be used before a compress() or compress2() call to allocate the destination buffer. */ ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)); /* Decompresses the source buffer into the destination buffer. sourceLen is the byte length of the source buffer. Upon entry, destLen is the total size of the destination buffer, which must be large enough to hold the entire uncompressed data. (The size of the uncompressed data must have been saved previously by the compressor and transmitted to the decompressor by some mechanism outside the scope of this compression library.) Upon exit, destLen is the actual size of the uncompressed buffer. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if there was not enough room in the output buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete. */ /* gzip file access functions */ /* This library supports reading and writing files in gzip (.gz) format with an interface similar to that of stdio, using the functions that start with "gz". The gzip format is different from the zlib format. gzip is a gzip wrapper, documented in RFC 1952, wrapped around a deflate stream. */ typedef voidp gzFile; /* opaque gzip file descriptor */ /* ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode)); Opens a gzip (.gz) file for reading or writing. The mode parameter is as in fopen ("rb" or "wb") but can also include a compression level ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for Huffman-only compression as in "wb1h", 'R' for run-length encoding as in "wb1R", or 'F' for fixed code compression as in "wb9F". (See the description of deflateInit2 for more information about the strategy parameter.) Also "a" can be used instead of "w" to request that the gzip stream that will be written be appended to the file. "+" will result in an error, since reading and writing to the same gzip file is not supported. gzopen can be used to read a file which is not in gzip format; in this case gzread will directly read from the file without decompression. gzopen returns NULL if the file could not be opened, if there was insufficient memory to allocate the gzFile state, or if an invalid mode was specified (an 'r', 'w', or 'a' was not provided, or '+' was provided). errno can be checked to determine if the reason gzopen failed was that the file could not be opened. */ ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode)); /* gzdopen associates a gzFile with the file descriptor fd. File descriptors are obtained from calls like open, dup, creat, pipe or fileno (if the file has been previously opened with fopen). The mode parameter is as in gzopen. The next call of gzclose on the returned gzFile will also close the file descriptor fd, just like fclose(fdopen(fd, mode)) closes the file descriptor fd. If you want to keep fd open, use fd = dup(fd_keep); gz = gzdopen(fd, mode);. The duplicated descriptor should be saved to avoid a leak, since gzdopen does not close fd if it fails. gzdopen returns NULL if there was insufficient memory to allocate the gzFile state, if an invalid mode was specified (an 'r', 'w', or 'a' was not provided, or '+' was provided), or if fd is -1. The file descriptor is not used until the next gz* read, write, seek, or close operation, so gzdopen will not detect if fd is invalid (unless fd is -1). */ ZEXTERN int ZEXPORT gzbuffer OF((gzFile file, unsigned size)); /* Set the internal buffer size used by this library's functions. The default buffer size is 8192 bytes. This function must be called after gzopen() or gzdopen(), and before any other calls that read or write the file. The buffer memory allocation is always deferred to the first read or write. Two buffers are allocated, either both of the specified size when writing, or one of the specified size and the other twice that size when reading. A larger buffer size of, for example, 64K or 128K bytes will noticeably increase the speed of decompression (reading). The new buffer size also affects the maximum length for gzprintf(). gzbuffer() returns 0 on success, or -1 on failure, such as being called too late. */ ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy)); /* Dynamically update the compression level or strategy. See the description of deflateInit2 for the meaning of these parameters. gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not opened for writing. */ ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len)); /* Reads the given number of uncompressed bytes from the compressed file. If the input file was not in gzip format, gzread copies the given number of bytes into the buffer. After reaching the end of a gzip stream in the input, gzread will continue to read, looking for another gzip stream, or failing that, reading the rest of the input file directly without decompression. The entire input file will be read if gzread is called until it returns less than the requested len. gzread returns the number of uncompressed bytes actually read, less than len for end of file, or -1 for error. */ ZEXTERN int ZEXPORT gzwrite OF((gzFile file, voidpc buf, unsigned len)); /* Writes the given number of uncompressed bytes into the compressed file. gzwrite returns the number of uncompressed bytes written or 0 in case of error. */ ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...)); /* Converts, formats, and writes the arguments to the compressed file under control of the format string, as in fprintf. gzprintf returns the number of uncompressed bytes actually written, or 0 in case of error. The number of uncompressed bytes written is limited to 8191, or one less than the buffer size given to gzbuffer(). The caller should assure that this limit is not exceeded. If it is exceeded, then gzprintf() will return an error (0) with nothing written. In this case, there may also be a buffer overflow with unpredictable consequences, which is possible only if zlib was compiled with the insecure functions sprintf() or vsprintf() because the secure snprintf() or vsnprintf() functions were not available. This can be determined using zlibCompileFlags(). */ ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s)); /* Writes the given null-terminated string to the compressed file, excluding the terminating null character. gzputs returns the number of characters written, or -1 in case of error. */ ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len)); /* Reads bytes from the compressed file until len-1 characters are read, or a newline character is read and transferred to buf, or an end-of-file condition is encountered. If any characters are read or if len == 1, the string is terminated with a null character. If no characters are read due to an end-of-file or len < 1, then the buffer is left untouched. gzgets returns buf which is a null-terminated string, or it returns NULL for end-of-file or in case of error. If there was an error, the contents at buf are indeterminate. */ ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c)); /* Writes c, converted to an unsigned char, into the compressed file. gzputc returns the value that was written, or -1 in case of error. */ ZEXTERN int ZEXPORT gzgetc OF((gzFile file)); /* Reads one byte from the compressed file. gzgetc returns this byte or -1 in case of end of file or error. */ ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file)); /* Push one character back onto the stream to be read as the first character on the next read. At least one character of push-back is allowed. gzungetc() returns the character pushed, or -1 on failure. gzungetc() will fail if c is -1, and may fail if a character has been pushed but not read yet. If gzungetc is used immediately after gzopen or gzdopen, at least the output buffer size of pushed characters is allowed. (See gzbuffer above.) The pushed character will be discarded if the stream is repositioned with gzseek() or gzrewind(). */ ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush)); /* Flushes all pending output into the compressed file. The parameter flush is as in the deflate() function. The return value is the zlib error number (see function gzerror below). gzflush is only permitted when writing. If the flush parameter is Z_FINISH, the remaining data is written and the gzip stream is completed in the output. If gzwrite() is called again, a new gzip stream will be started in the output. gzread() is able to read such concatented gzip streams. gzflush should be called only when strictly necessary because it will degrade compression if called too often. */ /* ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file, z_off_t offset, int whence)); Sets the starting position for the next gzread or gzwrite on the given compressed file. The offset represents a number of bytes in the uncompressed data stream. The whence parameter is defined as in lseek(2); the value SEEK_END is not supported. If the file is opened for reading, this function is emulated but can be extremely slow. If the file is opened for writing, only forward seeks are supported; gzseek then compresses a sequence of zeroes up to the new starting position. gzseek returns the resulting offset location as measured in bytes from the beginning of the uncompressed stream, or -1 in case of error, in particular if the file is opened for writing and the new starting position would be before the current position. */ ZEXTERN int ZEXPORT gzrewind OF((gzFile file)); /* Rewinds the given file. This function is supported only for reading. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET) */ /* ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file)); Returns the starting position for the next gzread or gzwrite on the given compressed file. This position represents a number of bytes in the uncompressed data stream, and is zero when starting, even if appending or reading a gzip stream from the middle of a file using gzdopen(). gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR) */ /* ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile file)); Returns the current offset in the file being read or written. This offset includes the count of bytes that precede the gzip stream, for example when appending or when using gzdopen() for reading. When reading, the offset does not include as yet unused buffered input. This information can be used for a progress indicator. On error, gzoffset() returns -1. */ ZEXTERN int ZEXPORT gzeof OF((gzFile file)); /* Returns true (1) if the end-of-file indicator has been set while reading, false (0) otherwise. Note that the end-of-file indicator is set only if the read tried to go past the end of the input, but came up short. Therefore, just like feof(), gzeof() may return false even if there is no more data to read, in the event that the last read request was for the exact number of bytes remaining in the input file. This will happen if the input file size is an exact multiple of the buffer size. If gzeof() returns true, then the read functions will return no more data, unless the end-of-file indicator is reset by gzclearerr() and the input file has grown since the previous end of file was detected. */ ZEXTERN int ZEXPORT gzdirect OF((gzFile file)); /* Returns true (1) if file is being copied directly while reading, or false (0) if file is a gzip stream being decompressed. This state can change from false to true while reading the input file if the end of a gzip stream is reached, but is followed by data that is not another gzip stream. If the input file is empty, gzdirect() will return true, since the input does not contain a gzip stream. If gzdirect() is used immediately after gzopen() or gzdopen() it will cause buffers to be allocated to allow reading the file to determine if it is a gzip file. Therefore if gzbuffer() is used, it should be called before gzdirect(). */ ZEXTERN int ZEXPORT gzclose OF((gzFile file)); /* Flushes all pending output if necessary, closes the compressed file and deallocates the (de)compression state. Note that once file is closed, you cannot call gzerror with file, since its structures have been deallocated. gzclose must not be called more than once on the same file, just as free must not be called more than once on the same allocation. gzclose will return Z_STREAM_ERROR if file is not valid, Z_ERRNO on a file operation error, or Z_OK on success. */ ZEXTERN int ZEXPORT gzclose_r OF((gzFile file)); ZEXTERN int ZEXPORT gzclose_w OF((gzFile file)); /* Same as gzclose(), but gzclose_r() is only for use when reading, and gzclose_w() is only for use when writing or appending. The advantage to using these instead of gzclose() is that they avoid linking in zlib compression or decompression code that is not used when only reading or only writing respectively. If gzclose() is used, then both compression and decompression code will be included the application when linking to a static zlib library. */ ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum)); /* Returns the error message for the last error which occurred on the given compressed file. errnum is set to zlib error number. If an error occurred in the file system and not in the compression library, errnum is set to Z_ERRNO and the application may consult errno to get the exact error code. The application must not modify the returned string. Future calls to this function may invalidate the previously returned string. If file is closed, then the string previously returned by gzerror will no longer be available. gzerror() should be used to distinguish errors from end-of-file for those functions above that do not distinguish those cases in their return values. */ ZEXTERN void ZEXPORT gzclearerr OF((gzFile file)); /* Clears the error and end-of-file flags for file. This is analogous to the clearerr() function in stdio. This is useful for continuing to read a gzip file that is being written concurrently. */ /* checksum functions */ /* These functions are not related to compression but are exported anyway because they might be useful in applications using the compression library. */ ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len)); /* Update a running Adler-32 checksum with the bytes buf[0..len-1] and return the updated checksum. If buf is Z_NULL, this function returns the required initial value for the checksum. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed much faster. Usage example: uLong adler = adler32(0L, Z_NULL, 0); while (read_buffer(buffer, length) != EOF) { adler = adler32(adler, buffer, length); } if (adler != original_adler) error(); */ /* ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2, z_off_t len2)); Combine two Adler-32 checksums into one. For two sequences of bytes, seq1 and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of seq1 and seq2 concatenated, requiring only adler1, adler2, and len2. */ ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len)); /* Update a running CRC-32 with the bytes buf[0..len-1] and return the updated CRC-32. If buf is Z_NULL, this function returns the required initial value for the for the crc. Pre- and post-conditioning (one's complement) is performed within this function so it shouldn't be done by the application. Usage example: uLong crc = crc32(0L, Z_NULL, 0); while (read_buffer(buffer, length) != EOF) { crc = crc32(crc, buffer, length); } if (crc != original_crc) error(); */ /* ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2)); Combine two CRC-32 check values into one. For two sequences of bytes, seq1 and seq2 with lengths len1 and len2, CRC-32 check values were calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32 check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and len2. */ /* various hacks, don't look :) */ /* deflateInit and inflateInit are macros to allow checking the zlib version * and the compiler's view of z_stream: */ ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level, const char *version, int stream_size)); ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm, const char *version, int stream_size)); ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)); ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits, const char *version, int stream_size)); ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits, unsigned char FAR *window, const char *version, int stream_size)); #define deflateInit(strm, level) \ deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream)) #define inflateInit(strm) \ inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream)) #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ (strategy), ZLIB_VERSION, sizeof(z_stream)) #define inflateInit2(strm, windowBits) \ inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream)) #define inflateBackInit(strm, windowBits, window) \ inflateBackInit_((strm), (windowBits), (window), \ ZLIB_VERSION, sizeof(z_stream)) /* provide 64-bit offset functions if _LARGEFILE64_SOURCE defined, and/or * change the regular functions to 64 bits if _FILE_OFFSET_BITS is 64 (if * both are true, the application gets the *64 functions, and the regular * functions are changed to 64 bits) -- in case these are set on systems * without large file support, _LFS64_LARGEFILE must also be true */ #if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0 ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int)); ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile)); ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile)); ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off64_t)); ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off64_t)); #endif #if !defined(ZLIB_INTERNAL) && _FILE_OFFSET_BITS-0 == 64 && _LFS64_LARGEFILE-0 # define gzopen gzopen64 # define gzseek gzseek64 # define gztell gztell64 # define gzoffset gzoffset64 # define adler32_combine adler32_combine64 # define crc32_combine crc32_combine64 # ifdef _LARGEFILE64_SOURCE ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); ZEXTERN z_off_t ZEXPORT gzseek64 OF((gzFile, z_off_t, int)); ZEXTERN z_off_t ZEXPORT gztell64 OF((gzFile)); ZEXTERN z_off_t ZEXPORT gzoffset64 OF((gzFile)); ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t)); ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t)); # endif #else ZEXTERN gzFile ZEXPORT gzopen OF((const char *, const char *)); ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile, z_off_t, int)); ZEXTERN z_off_t ZEXPORT gztell OF((gzFile)); ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile)); ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t)); ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t)); #endif /* hack for buggy compilers */ #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL) struct internal_state {int dummy;}; #endif /* undocumented functions */ ZEXTERN const char * ZEXPORT zError OF((int)); ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp)); ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void)); ZEXTERN int ZEXPORT inflateUndermine OF((z_streamp, int)); #ifdef __cplusplus } #endif #endif /* ZLIB_H */ ================================================ FILE: src/engine/external/zlib/zutil.c ================================================ /* zutil.c -- target dependent utility functions for the compression library * Copyright (C) 1995-2005, 2010 Jean-loup Gailly. * For conditions of distribution and use, see copyright notice in zlib.h */ /* @(#) $Id$ */ #include "zutil.h" #ifndef NO_DUMMY_DECL struct internal_state {int dummy;}; /* for buggy compilers */ #endif const char * const z_errmsg[10] = { "need dictionary", /* Z_NEED_DICT 2 */ "stream end", /* Z_STREAM_END 1 */ "", /* Z_OK 0 */ "file error", /* Z_ERRNO (-1) */ "stream error", /* Z_STREAM_ERROR (-2) */ "data error", /* Z_DATA_ERROR (-3) */ "insufficient memory", /* Z_MEM_ERROR (-4) */ "buffer error", /* Z_BUF_ERROR (-5) */ "incompatible version",/* Z_VERSION_ERROR (-6) */ ""}; const char * ZEXPORT zlibVersion() { return ZLIB_VERSION; } uLong ZEXPORT zlibCompileFlags() { uLong flags; flags = 0; switch ((int)(sizeof(uInt))) { case 2: break; case 4: flags += 1; break; case 8: flags += 2; break; default: flags += 3; } switch ((int)(sizeof(uLong))) { case 2: break; case 4: flags += 1 << 2; break; case 8: flags += 2 << 2; break; default: flags += 3 << 2; } switch ((int)(sizeof(voidpf))) { case 2: break; case 4: flags += 1 << 4; break; case 8: flags += 2 << 4; break; default: flags += 3 << 4; } switch ((int)(sizeof(z_off_t))) { case 2: break; case 4: flags += 1 << 6; break; case 8: flags += 2 << 6; break; default: flags += 3 << 6; } #ifdef DEBUG flags += 1 << 8; #endif #if defined(ASMV) || defined(ASMINF) flags += 1 << 9; #endif #ifdef ZLIB_WINAPI flags += 1 << 10; #endif #ifdef BUILDFIXED flags += 1 << 12; #endif #ifdef DYNAMIC_CRC_TABLE flags += 1 << 13; #endif #ifdef NO_GZCOMPRESS flags += 1L << 16; #endif #ifdef NO_GZIP flags += 1L << 17; #endif #ifdef PKZIP_BUG_WORKAROUND flags += 1L << 20; #endif #ifdef FASTEST flags += 1L << 21; #endif #ifdef STDC # ifdef NO_vsnprintf flags += 1L << 25; # ifdef HAS_vsprintf_void flags += 1L << 26; # endif # else # ifdef HAS_vsnprintf_void flags += 1L << 26; # endif # endif #else flags += 1L << 24; # ifdef NO_snprintf flags += 1L << 25; # ifdef HAS_sprintf_void flags += 1L << 26; # endif # else # ifdef HAS_snprintf_void flags += 1L << 26; # endif # endif #endif return flags; } #ifdef DEBUG # ifndef verbose # define verbose 0 # endif int ZLIB_INTERNAL z_verbose = verbose; void ZLIB_INTERNAL z_error (m) char *m; { fprintf(stderr, "%s\n", m); exit(1); } #endif /* exported to allow conversion of error code to string for compress() and * uncompress() */ const char * ZEXPORT zError(err) int err; { return ERR_MSG(err); } #if defined(_WIN32_WCE) /* The Microsoft C Run-Time Library for Windows CE doesn't have * errno. We define it as a global variable to simplify porting. * Its value is always 0 and should not be used. */ int errno = 0; #endif #ifndef HAVE_MEMCPY void ZLIB_INTERNAL zmemcpy(dest, source, len) Bytef* dest; const Bytef* source; uInt len; { if (len == 0) return; do { *dest++ = *source++; /* ??? to be unrolled */ } while (--len != 0); } int ZLIB_INTERNAL zmemcmp(s1, s2, len) const Bytef* s1; const Bytef* s2; uInt len; { uInt j; for (j = 0; j < len; j++) { if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1; } return 0; } void ZLIB_INTERNAL zmemzero(dest, len) Bytef* dest; uInt len; { if (len == 0) return; do { *dest++ = 0; /* ??? to be unrolled */ } while (--len != 0); } #endif #ifdef SYS16BIT #ifdef __TURBOC__ /* Turbo C in 16-bit mode */ # define MY_ZCALLOC /* Turbo C malloc() does not allow dynamic allocation of 64K bytes * and farmalloc(64K) returns a pointer with an offset of 8, so we * must fix the pointer. Warning: the pointer must be put back to its * original form in order to free it, use zcfree(). */ #define MAX_PTR 10 /* 10*64K = 640K */ local int next_ptr = 0; typedef struct ptr_table_s { voidpf org_ptr; voidpf new_ptr; } ptr_table; local ptr_table table[MAX_PTR]; /* This table is used to remember the original form of pointers * to large buffers (64K). Such pointers are normalized with a zero offset. * Since MSDOS is not a preemptive multitasking OS, this table is not * protected from concurrent access. This hack doesn't work anyway on * a protected system like OS/2. Use Microsoft C instead. */ voidpf ZLIB_INTERNAL zcalloc (voidpf opaque, unsigned items, unsigned size) { voidpf buf = opaque; /* just to make some compilers happy */ ulg bsize = (ulg)items*size; /* If we allocate less than 65520 bytes, we assume that farmalloc * will return a usable pointer which doesn't have to be normalized. */ if (bsize < 65520L) { buf = farmalloc(bsize); if (*(ush*)&buf != 0) return buf; } else { buf = farmalloc(bsize + 16L); } if (buf == NULL || next_ptr >= MAX_PTR) return NULL; table[next_ptr].org_ptr = buf; /* Normalize the pointer to seg:0 */ *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4; *(ush*)&buf = 0; table[next_ptr++].new_ptr = buf; return buf; } void ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr) { int n; if (*(ush*)&ptr != 0) { /* object < 64K */ farfree(ptr); return; } /* Find the original pointer */ for (n = 0; n < next_ptr; n++) { if (ptr != table[n].new_ptr) continue; farfree(table[n].org_ptr); while (++n < next_ptr) { table[n-1] = table[n]; } next_ptr--; return; } ptr = opaque; /* just to make some compilers happy */ Assert(0, "zcfree: ptr not found"); } #endif /* __TURBOC__ */ #ifdef M_I86 /* Microsoft C in 16-bit mode */ # define MY_ZCALLOC #if (!defined(_MSC_VER) || (_MSC_VER <= 600)) # define _halloc halloc # define _hfree hfree #endif voidpf ZLIB_INTERNAL zcalloc (voidpf opaque, uInt items, uInt size) { if (opaque) opaque = 0; /* to make compiler happy */ return _halloc((long)items, size); } void ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr) { if (opaque) opaque = 0; /* to make compiler happy */ _hfree(ptr); } #endif /* M_I86 */ #endif /* SYS16BIT */ #ifndef MY_ZCALLOC /* Any system without a special alloc function */ #ifndef STDC extern voidp malloc OF((uInt size)); extern voidp calloc OF((uInt items, uInt size)); extern void free OF((voidpf ptr)); #endif voidpf ZLIB_INTERNAL zcalloc (opaque, items, size) voidpf opaque; unsigned items; unsigned size; { if (opaque) items += size - size; /* make compiler happy */ return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) : (voidpf)calloc(items, size); } void ZLIB_INTERNAL zcfree (opaque, ptr) voidpf opaque; voidpf ptr; { free(ptr); if (opaque) return; /* make compiler happy */ } #endif /* MY_ZCALLOC */ ================================================ FILE: src/engine/external/zlib/zutil.h ================================================ /* zutil.h -- internal interface and configuration of the compression library * Copyright (C) 1995-2010 Jean-loup Gailly. * For conditions of distribution and use, see copyright notice in zlib.h */ /* WARNING: this file should *not* be used by applications. It is part of the implementation of the compression library and is subject to change. Applications should only use zlib.h. */ /* @(#) $Id$ */ #ifndef ZUTIL_H #define ZUTIL_H #if ((__GNUC__-0) * 10 + __GNUC_MINOR__-0 >= 33) && !defined(NO_VIZ) # define ZLIB_INTERNAL __attribute__((visibility ("hidden"))) #else # define ZLIB_INTERNAL #endif #include "zlib.h" #ifdef STDC # if !(defined(_WIN32_WCE) && defined(_MSC_VER)) # include <stddef.h> # endif # include <string.h> # include <stdlib.h> #endif #ifndef local # define local static #endif /* compile with -Dlocal if your debugger can't find static symbols */ typedef unsigned char uch; typedef uch FAR uchf; typedef unsigned short ush; typedef ush FAR ushf; typedef unsigned long ulg; extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */ /* (size given to avoid silly warnings with Visual C++) */ #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)] #define ERR_RETURN(strm,err) \ return (strm->msg = (char*)ERR_MSG(err), (err)) /* To be used only when the state is known to be valid */ /* common constants */ #ifndef DEF_WBITS # define DEF_WBITS MAX_WBITS #endif /* default windowBits for decompression. MAX_WBITS is for compression only */ #if MAX_MEM_LEVEL >= 8 # define DEF_MEM_LEVEL 8 #else # define DEF_MEM_LEVEL MAX_MEM_LEVEL #endif /* default memLevel */ #define STORED_BLOCK 0 #define STATIC_TREES 1 #define DYN_TREES 2 /* The three kinds of block type */ #define MIN_MATCH 3 #define MAX_MATCH 258 /* The minimum and maximum match lengths */ #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */ /* target dependencies */ #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32)) # define OS_CODE 0x00 # if defined(__TURBOC__) || defined(__BORLANDC__) # if (__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__)) /* Allow compilation with ANSI keywords only enabled */ void _Cdecl farfree( void *block ); void *_Cdecl farmalloc( unsigned long nbytes ); # else # include <alloc.h> # endif # else /* MSC or DJGPP */ # include <malloc.h> # endif #endif #ifdef AMIGA # define OS_CODE 0x01 #endif #if defined(VAXC) || defined(VMS) # define OS_CODE 0x02 # define F_OPEN(name, mode) \ fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512") #endif #if defined(ATARI) || defined(atarist) # define OS_CODE 0x05 #endif #ifdef OS2 # define OS_CODE 0x06 # ifdef M_I86 # include <malloc.h> # endif #endif #if defined(MACOS) || defined(TARGET_OS_MAC) # define OS_CODE 0x07 # if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os # include <unix.h> /* for fdopen */ # else # ifndef fdopen # define fdopen(fd,mode) NULL /* No fdopen() */ # endif # endif #endif #ifdef TOPS20 # define OS_CODE 0x0a #endif #ifdef WIN32 # ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */ # define OS_CODE 0x0b # endif #endif #ifdef __50SERIES /* Prime/PRIMOS */ # define OS_CODE 0x0f #endif #if defined(_BEOS_) || defined(RISCOS) # define fdopen(fd,mode) NULL /* No fdopen() */ #endif #if (defined(_MSC_VER) && (_MSC_VER > 600)) && !defined __INTERIX # if defined(_WIN32_WCE) # define fdopen(fd,mode) NULL /* No fdopen() */ # ifndef _PTRDIFF_T_DEFINED typedef int ptrdiff_t; # define _PTRDIFF_T_DEFINED # endif # else # define fdopen(fd,type) _fdopen(fd,type) # endif #endif #if defined(__BORLANDC__) #pragma warn -8004 #pragma warn -8008 #pragma warn -8066 #endif /* provide prototypes for these when building zlib without LFS */ #if !defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0 ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t)); ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t)); #endif /* common defaults */ #ifndef OS_CODE # define OS_CODE 0x03 /* assume Unix */ #endif #ifndef F_OPEN # define F_OPEN(name, mode) fopen((name), (mode)) #endif /* functions */ #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550) # ifndef HAVE_VSNPRINTF # define HAVE_VSNPRINTF # endif #endif #if defined(__CYGWIN__) # ifndef HAVE_VSNPRINTF # define HAVE_VSNPRINTF # endif #endif #ifndef HAVE_VSNPRINTF # ifdef MSDOS /* vsnprintf may exist on some MS-DOS compilers (DJGPP?), but for now we just assume it doesn't. */ # define NO_vsnprintf # endif # ifdef __TURBOC__ # define NO_vsnprintf # endif # ifdef WIN32 /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */ # if !defined(vsnprintf) && !defined(NO_vsnprintf) # if !defined(_MSC_VER) || ( defined(_MSC_VER) && _MSC_VER < 1500 ) # define vsnprintf _vsnprintf # endif # endif # endif # ifdef __SASC # define NO_vsnprintf # endif #endif #ifdef VMS # define NO_vsnprintf #endif #if defined(pyr) # define NO_MEMCPY #endif #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__) /* Use our own functions for small and medium model with MSC <= 5.0. * You may have to use the same strategy for Borland C (untested). * The __SC__ check is for Symantec. */ # define NO_MEMCPY #endif #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY) # define HAVE_MEMCPY #endif #ifdef HAVE_MEMCPY # ifdef SMALL_MEDIUM /* MSDOS small or medium model */ # define zmemcpy _fmemcpy # define zmemcmp _fmemcmp # define zmemzero(dest, len) _fmemset(dest, 0, len) # else # define zmemcpy memcpy # define zmemcmp memcmp # define zmemzero(dest, len) memset(dest, 0, len) # endif #else void ZLIB_INTERNAL zmemcpy OF((Bytef* dest, const Bytef* source, uInt len)); int ZLIB_INTERNAL zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len)); void ZLIB_INTERNAL zmemzero OF((Bytef* dest, uInt len)); #endif /* Diagnostic functions */ #ifdef DEBUG # include <stdio.h> extern int ZLIB_INTERNAL z_verbose; extern void ZLIB_INTERNAL z_error OF((char *m)); # define Assert(cond,msg) {if(!(cond)) z_error(msg);} # define Trace(x) {if (z_verbose>=0) fprintf x ;} # define Tracev(x) {if (z_verbose>0) fprintf x ;} # define Tracevv(x) {if (z_verbose>1) fprintf x ;} # define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;} # define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;} #else # define Assert(cond,msg) # define Trace(x) # define Tracev(x) # define Tracevv(x) # define Tracec(c,x) # define Tracecv(c,x) #endif voidpf ZLIB_INTERNAL zcalloc OF((voidpf opaque, unsigned items, unsigned size)); void ZLIB_INTERNAL zcfree OF((voidpf opaque, voidpf ptr)); #define ZALLOC(strm, items, size) \ (*((strm)->zalloc))((strm)->opaque, (items), (size)) #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr)) #define TRY_FREE(s, p) {if (p) ZFREE(s, p);} #endif /* ZUTIL_H */ ================================================ FILE: src/engine/friends.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef ENGINE_FRIENDS_H #define ENGINE_FRIENDS_H #include <engine/shared/protocol.h> #include "kernel.h" struct CFriendInfo { char m_aName[MAX_NAME_LENGTH]; char m_aClan[MAX_CLAN_LENGTH]; unsigned m_NameHash; unsigned m_ClanHash; }; class IFriends : public IInterface { MACRO_INTERFACE("friends", 0) public: enum { FRIEND_NO=0, FRIEND_CLAN, FRIEND_PLAYER, MAX_FRIENDS=128, }; virtual void Init() = 0; virtual int NumFriends() const = 0; virtual const CFriendInfo *GetFriend(int Index) const = 0; virtual int GetFriendState(const char *pName, const char *pClan) const = 0; virtual bool IsFriend(const char *pName, const char *pClan, bool PlayersOnly) const = 0; virtual void AddFriend(const char *pName, const char *pClan) = 0; virtual void RemoveFriend(const char *pName, const char *pClan) = 0; }; #endif ================================================ FILE: src/engine/graphics.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef ENGINE_GRAPHICS_H #define ENGINE_GRAPHICS_H #include <base/vmath.h> #include "kernel.h" class CImageInfo { public: enum { FORMAT_AUTO=-1, FORMAT_RGB=0, FORMAT_RGBA=1, FORMAT_ALPHA=2, }; /* Variable: width Contains the width of the image */ int m_Width; /* Variable: height Contains the height of the image */ int m_Height; /* Variable: format Contains the format of the image. See <Image Formats> for more information. */ int m_Format; /* Variable: data Pointer to the image data. */ void *m_pData; }; /* Structure: CVideoMode */ class CVideoMode { public: int m_Width, m_Height; int m_Red, m_Green, m_Blue; bool operator<(const CVideoMode &Other) { return Other.m_Width < m_Width; } }; class IGraphics : public IInterface { MACRO_INTERFACE("graphics", 0) protected: int m_ScreenWidth; int m_ScreenHeight; int m_DesktopScreenWidth; int m_DesktopScreenHeight; public: /* Constants: Texture Loading Flags TEXLOAD_NORESAMPLE - Prevents the texture from any resampling */ enum { TEXLOAD_NORESAMPLE = 1, TEXLOAD_NOMIPMAPS = 2, }; class CTextureHandle { friend class IGraphics; int m_Id; public: CTextureHandle() : m_Id(-1) {} bool IsValid() const { return Id() >= 0; } int Id() const { return m_Id; } }; int ScreenWidth() const { return m_ScreenWidth; } int ScreenHeight() const { return m_ScreenHeight; } float ScreenAspect() const { return (float)ScreenWidth()/(float)ScreenHeight(); } virtual void Clear(float r, float g, float b) = 0; virtual void ClipEnable(int x, int y, int w, int h) = 0; virtual void ClipDisable() = 0; virtual void MapScreen(float TopLeftX, float TopLeftY, float BottomRightX, float BottomRightY) = 0; virtual void GetScreen(float *pTopLeftX, float *pTopLeftY, float *pBottomRightX, float *pBottomRightY) = 0; // TODO: These should perhaps not be virtuals virtual void BlendNone() = 0; virtual void BlendNormal() = 0; virtual void BlendAdditive() = 0; virtual void WrapNormal() = 0; virtual void WrapClamp() = 0; virtual int MemoryUsage() const = 0; virtual int LoadPNG(CImageInfo *pImg, const char *pFilename, int StorageType) = 0; virtual int UnloadTexture(CTextureHandle Index) = 0; virtual CTextureHandle LoadTextureRaw(int Width, int Height, int Format, const void *pData, int StoreFormat, int Flags) = 0; virtual int LoadTextureRawSub(CTextureHandle TextureID, int x, int y, int Width, int Height, int Format, const void *pData) = 0; virtual CTextureHandle LoadTexture(const char *pFilename, int StorageType, int StoreFormat, int Flags) = 0; virtual void TextureSet(CTextureHandle Texture) = 0; void TextureClear() { TextureSet(CTextureHandle()); } struct CLineItem { float m_X0, m_Y0, m_X1, m_Y1; CLineItem() {} CLineItem(float x0, float y0, float x1, float y1) : m_X0(x0), m_Y0(y0), m_X1(x1), m_Y1(y1) {} }; virtual void LinesBegin() = 0; virtual void LinesEnd() = 0; virtual void LinesDraw(const CLineItem *pArray, int Num) = 0; virtual void QuadsBegin() = 0; virtual void QuadsEnd() = 0; virtual void QuadsSetRotation(float Angle) = 0; virtual void QuadsSetSubset(float TopLeftY, float TopLeftV, float BottomRightU, float BottomRightV) = 0; virtual void QuadsSetSubsetFree(float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3) = 0; struct CQuadItem { float m_X, m_Y, m_Width, m_Height; CQuadItem() {} CQuadItem(float x, float y, float w, float h) : m_X(x), m_Y(y), m_Width(w), m_Height(h) {} }; virtual void QuadsDraw(CQuadItem *pArray, int Num) = 0; virtual void QuadsDrawTL(const CQuadItem *pArray, int Num) = 0; struct CFreeformItem { float m_X0, m_Y0, m_X1, m_Y1, m_X2, m_Y2, m_X3, m_Y3; CFreeformItem() {} CFreeformItem(float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3) : m_X0(x0), m_Y0(y0), m_X1(x1), m_Y1(y1), m_X2(x2), m_Y2(y2), m_X3(x3), m_Y3(y3) {} }; virtual void QuadsDrawFreeform(const CFreeformItem *pArray, int Num) = 0; virtual void QuadsText(float x, float y, float Size, const char *pText) = 0; struct CColorVertex { int m_Index; float m_R, m_G, m_B, m_A; CColorVertex() {} CColorVertex(int i, float r, float g, float b, float a) : m_Index(i), m_R(r), m_G(g), m_B(b), m_A(a) {} }; virtual void SetColorVertex(const CColorVertex *pArray, int Num) = 0; virtual void SetColor(float r, float g, float b, float a) = 0; virtual void SetColor4(vec4 TopLeft, vec4 TopRight, vec4 BottomLeft, vec4 BottomRight) = 0; virtual void TakeScreenshot(const char *pFilename) = 0; virtual int GetVideoModes(CVideoMode *pModes, int MaxModes) = 0; virtual int GetDesktopScreenWidth() = 0; virtual int GetDesktopScreenHeight() = 0; virtual void Swap() = 0; // syncronization virtual void InsertSignal(class semaphore *pSemaphore) = 0; virtual bool IsIdle() = 0; virtual void WaitForIdle() = 0; protected: inline CTextureHandle CreateTextureHandle(int Index) { CTextureHandle Tex; Tex.m_Id = Index; return Tex; } }; class IEngineGraphics : public IGraphics { MACRO_INTERFACE("enginegraphics", 0) public: virtual int Init() = 0; virtual void Shutdown() = 0; virtual void Minimize() = 0; virtual void Maximize() = 0; virtual int WindowActive() = 0; virtual int WindowOpen() = 0; }; extern IEngineGraphics *CreateEngineGraphics(); extern IEngineGraphics *CreateEngineGraphicsThreaded(); #endif ================================================ FILE: src/engine/input.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef ENGINE_INPUT_H #define ENGINE_INPUT_H #include "kernel.h" extern const char g_aaKeyStrings[512][16]; class IInput : public IInterface { MACRO_INTERFACE("input", 0) public: class CEvent { public: int m_Flags; int m_Unicode; int m_Key; }; protected: enum { INPUT_BUFFER_SIZE=32 }; // quick access to events int m_NumEvents; IInput::CEvent m_aInputEvents[INPUT_BUFFER_SIZE]; //quick access to input struct { unsigned char m_Presses; unsigned char m_Releases; } m_aInputCount[2][1024]; unsigned char m_aInputState[2][1024]; int m_InputCurrent; bool m_InputDispatched; int KeyWasPressed(int Key) { return m_aInputState[m_InputCurrent^1][Key]; } public: enum { FLAG_PRESS=1, FLAG_RELEASE=2, FLAG_REPEAT=4 }; // events int NumEvents() const { return m_NumEvents; } void ClearEvents() { m_NumEvents = 0; m_InputDispatched = true; } CEvent GetEvent(int Index) const { if(Index < 0 || Index >= m_NumEvents) { IInput::CEvent e = {0,0}; return e; } return m_aInputEvents[Index]; } // keys int KeyPressed(int Key) { return m_aInputState[m_InputCurrent][Key]; } int KeyReleases(int Key) { return m_aInputCount[m_InputCurrent][Key].m_Releases; } int KeyPresses(int Key) { return m_aInputCount[m_InputCurrent][Key].m_Presses; } int KeyDown(int Key) { return KeyPressed(Key)&&!KeyWasPressed(Key); } const char *KeyName(int Key) { return (Key >= 0 && Key < 512) ? g_aaKeyStrings[Key] : g_aaKeyStrings[0]; } // virtual void MouseModeRelative() = 0; virtual void MouseModeAbsolute() = 0; virtual int MouseDoubleClick() = 0; virtual void MouseRelative(float *x, float *y) = 0; }; class IEngineInput : public IInput { MACRO_INTERFACE("engineinput", 0) public: virtual void Init() = 0; virtual int Update() = 0; }; extern IEngineInput *CreateEngineInput(); #endif ================================================ FILE: src/engine/kernel.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef ENGINE_KERNEL_H #define ENGINE_KERNEL_H #include <base/system.h> class IKernel; class IInterface; class IInterface { // friend with the kernel implementation friend class CKernel; IKernel *m_pKernel; protected: IKernel *Kernel() { return m_pKernel; } public: IInterface() : m_pKernel(0) {} virtual ~IInterface() {} //virtual unsigned InterfaceID() = 0; //virtual const char *InterfaceName() = 0; }; #define MACRO_INTERFACE(Name, ver) \ public: \ static const char *InterfaceName() { return Name; } \ private: //virtual unsigned InterfaceID() { return INTERFACE_ID; } //virtual const char *InterfaceName() { return name; } // This kernel thingie makes the structure very flat and basiclly singletons. // I'm not sure if this is a good idea but it works for now. class IKernel { // hide the implementation virtual bool RegisterInterfaceImpl(const char *InterfaceName, IInterface *pInterface) = 0; virtual bool ReregisterInterfaceImpl(const char *InterfaceName, IInterface *pInterface) = 0; virtual IInterface *RequestInterfaceImpl(const char *InterfaceName) = 0; public: static IKernel *Create(); virtual ~IKernel() {} // templated access to handle pointer convertions and interface names template<class TINTERFACE> bool RegisterInterface(TINTERFACE *pInterface) { return RegisterInterfaceImpl(TINTERFACE::InterfaceName(), pInterface); } template<class TINTERFACE> bool ReregisterInterface(TINTERFACE *pInterface) { return ReregisterInterfaceImpl(TINTERFACE::InterfaceName(), pInterface); } // Usage example: // IMyInterface *pMyHandle = Kernel()->RequestInterface<IMyInterface>() template<class TINTERFACE> TINTERFACE *RequestInterface() { return reinterpret_cast<TINTERFACE *>(RequestInterfaceImpl(TINTERFACE::InterfaceName())); } }; #endif ================================================ FILE: src/engine/keys.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef ENGINE_KEYS_H #define ENGINE_KEYS_H /* AUTO GENERATED! DO NOT EDIT MANUALLY! */ enum { KEY_UNKNOWN = 0, KEY_FIRST = 0, KEY_BACKSPACE = 8, KEY_TAB = 9, KEY_CLEAR = 12, KEY_RETURN = 13, KEY_PAUSE = 19, KEY_ESCAPE = 27, KEY_SPACE = 32, KEY_EXCLAIM = 33, KEY_QUOTEDBL = 34, KEY_HASH = 35, KEY_DOLLAR = 36, KEY_AMPERSAND = 38, KEY_QUOTE = 39, KEY_LEFTPAREN = 40, KEY_RIGHTPAREN = 41, KEY_ASTERISK = 42, KEY_PLUS = 43, KEY_COMMA = 44, KEY_MINUS = 45, KEY_PERIOD = 46, KEY_SLASH = 47, KEY_0 = 48, KEY_1 = 49, KEY_2 = 50, KEY_3 = 51, KEY_4 = 52, KEY_5 = 53, KEY_6 = 54, KEY_7 = 55, KEY_8 = 56, KEY_9 = 57, KEY_COLON = 58, KEY_SEMICOLON = 59, KEY_LESS = 60, KEY_EQUALS = 61, KEY_GREATER = 62, KEY_QUESTION = 63, KEY_AT = 64, KEY_LEFTBRACKET = 91, KEY_BACKSLASH = 92, KEY_RIGHTBRACKET = 93, KEY_CARET = 94, KEY_UNDERSCORE = 95, KEY_BACKQUOTE = 96, KEY_a = 97, KEY_b = 98, KEY_c = 99, KEY_d = 100, KEY_e = 101, KEY_f = 102, KEY_g = 103, KEY_h = 104, KEY_i = 105, KEY_j = 106, KEY_k = 107, KEY_l = 108, KEY_m = 109, KEY_n = 110, KEY_o = 111, KEY_p = 112, KEY_q = 113, KEY_r = 114, KEY_s = 115, KEY_t = 116, KEY_u = 117, KEY_v = 118, KEY_w = 119, KEY_x = 120, KEY_y = 121, KEY_z = 122, KEY_DELETE = 127, KEY_WORLD_0 = 160, KEY_WORLD_1 = 161, KEY_WORLD_2 = 162, KEY_WORLD_3 = 163, KEY_WORLD_4 = 164, KEY_WORLD_5 = 165, KEY_WORLD_6 = 166, KEY_WORLD_7 = 167, KEY_WORLD_8 = 168, KEY_WORLD_9 = 169, KEY_WORLD_10 = 170, KEY_WORLD_11 = 171, KEY_WORLD_12 = 172, KEY_WORLD_13 = 173, KEY_WORLD_14 = 174, KEY_WORLD_15 = 175, KEY_WORLD_16 = 176, KEY_WORLD_17 = 177, KEY_WORLD_18 = 178, KEY_WORLD_19 = 179, KEY_WORLD_20 = 180, KEY_WORLD_21 = 181, KEY_WORLD_22 = 182, KEY_WORLD_23 = 183, KEY_WORLD_24 = 184, KEY_WORLD_25 = 185, KEY_WORLD_26 = 186, KEY_WORLD_27 = 187, KEY_WORLD_28 = 188, KEY_WORLD_29 = 189, KEY_WORLD_30 = 190, KEY_WORLD_31 = 191, KEY_WORLD_32 = 192, KEY_WORLD_33 = 193, KEY_WORLD_34 = 194, KEY_WORLD_35 = 195, KEY_WORLD_36 = 196, KEY_WORLD_37 = 197, KEY_WORLD_38 = 198, KEY_WORLD_39 = 199, KEY_WORLD_40 = 200, KEY_WORLD_41 = 201, KEY_WORLD_42 = 202, KEY_WORLD_43 = 203, KEY_WORLD_44 = 204, KEY_WORLD_45 = 205, KEY_WORLD_46 = 206, KEY_WORLD_47 = 207, KEY_WORLD_48 = 208, KEY_WORLD_49 = 209, KEY_WORLD_50 = 210, KEY_WORLD_51 = 211, KEY_WORLD_52 = 212, KEY_WORLD_53 = 213, KEY_WORLD_54 = 214, KEY_WORLD_55 = 215, KEY_WORLD_56 = 216, KEY_WORLD_57 = 217, KEY_WORLD_58 = 218, KEY_WORLD_59 = 219, KEY_WORLD_60 = 220, KEY_WORLD_61 = 221, KEY_WORLD_62 = 222, KEY_WORLD_63 = 223, KEY_WORLD_64 = 224, KEY_WORLD_65 = 225, KEY_WORLD_66 = 226, KEY_WORLD_67 = 227, KEY_WORLD_68 = 228, KEY_WORLD_69 = 229, KEY_WORLD_70 = 230, KEY_WORLD_71 = 231, KEY_WORLD_72 = 232, KEY_WORLD_73 = 233, KEY_WORLD_74 = 234, KEY_WORLD_75 = 235, KEY_WORLD_76 = 236, KEY_WORLD_77 = 237, KEY_WORLD_78 = 238, KEY_WORLD_79 = 239, KEY_WORLD_80 = 240, KEY_WORLD_81 = 241, KEY_WORLD_82 = 242, KEY_WORLD_83 = 243, KEY_WORLD_84 = 244, KEY_WORLD_85 = 245, KEY_WORLD_86 = 246, KEY_WORLD_87 = 247, KEY_WORLD_88 = 248, KEY_WORLD_89 = 249, KEY_WORLD_90 = 250, KEY_WORLD_91 = 251, KEY_WORLD_92 = 252, KEY_WORLD_93 = 253, KEY_WORLD_94 = 254, KEY_WORLD_95 = 255, KEY_KP0 = 256, KEY_KP1 = 257, KEY_KP2 = 258, KEY_KP3 = 259, KEY_KP4 = 260, KEY_KP5 = 261, KEY_KP6 = 262, KEY_KP7 = 263, KEY_KP8 = 264, KEY_KP9 = 265, KEY_KP_PERIOD = 266, KEY_KP_DIVIDE = 267, KEY_KP_MULTIPLY = 268, KEY_KP_MINUS = 269, KEY_KP_PLUS = 270, KEY_KP_ENTER = 271, KEY_KP_EQUALS = 272, KEY_UP = 273, KEY_DOWN = 274, KEY_RIGHT = 275, KEY_LEFT = 276, KEY_INSERT = 277, KEY_HOME = 278, KEY_END = 279, KEY_PAGEUP = 280, KEY_PAGEDOWN = 281, KEY_F1 = 282, KEY_F2 = 283, KEY_F3 = 284, KEY_F4 = 285, KEY_F5 = 286, KEY_F6 = 287, KEY_F7 = 288, KEY_F8 = 289, KEY_F9 = 290, KEY_F10 = 291, KEY_F11 = 292, KEY_F12 = 293, KEY_F13 = 294, KEY_F14 = 295, KEY_F15 = 296, KEY_NUMLOCK = 300, KEY_CAPSLOCK = 301, KEY_SCROLLOCK = 302, KEY_RSHIFT = 303, KEY_LSHIFT = 304, KEY_RCTRL = 305, KEY_LCTRL = 306, KEY_RALT = 307, KEY_LALT = 308, KEY_RMETA = 309, KEY_LMETA = 310, KEY_LSUPER = 311, KEY_RSUPER = 312, KEY_MODE = 313, KEY_COMPOSE = 314, KEY_HELP = 315, KEY_PRINT = 316, KEY_SYSREQ = 317, KEY_BREAK = 318, KEY_MENU = 319, KEY_POWER = 320, KEY_EURO = 321, KEY_UNDO = 322, KEY_MOUSE_1 = 323, KEY_MOUSE_2 = 324, KEY_MOUSE_3 = 325, KEY_MOUSE_4 = 326, KEY_MOUSE_5 = 327, KEY_MOUSE_6 = 328, KEY_MOUSE_7 = 329, KEY_MOUSE_8 = 330, KEY_MOUSE_WHEEL_UP = 331, KEY_MOUSE_WHEEL_DOWN = 332, KEY_LAST, }; #endif ================================================ FILE: src/engine/map.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef ENGINE_MAP_H #define ENGINE_MAP_H #include "kernel.h" class IMap : public IInterface { MACRO_INTERFACE("map", 0) public: virtual void *GetData(int Index) = 0; virtual void *GetDataSwapped(int Index) = 0; virtual void UnloadData(int Index) = 0; virtual void *GetItem(int Index, int *Type, int *pID) = 0; virtual void GetType(int Type, int *pStart, int *pNum) = 0; virtual void *FindItem(int Type, int ID) = 0; virtual int NumItems() = 0; }; class IEngineMap : public IMap { MACRO_INTERFACE("enginemap", 0) public: virtual bool Load(const char *pMapName, class IStorage *pStorage=0) = 0; virtual bool IsLoaded() = 0; virtual void Unload() = 0; virtual unsigned Crc() = 0; }; extern IEngineMap *CreateEngineMap(); #endif ================================================ FILE: src/engine/masterserver.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef ENGINE_MASTERSERVER_H #define ENGINE_MASTERSERVER_H #include "kernel.h" class IMasterServer : public IInterface { MACRO_INTERFACE("masterserver", 0) public: enum { MAX_MASTERSERVERS=4 }; virtual void Init() = 0; virtual void SetDefault() = 0; virtual int Load() = 0; virtual int Save() = 0; virtual int RefreshAddresses(int Nettype) = 0; virtual void Update() = 0; virtual int IsRefreshing() = 0; virtual NETADDR GetAddr(int Index) = 0; virtual const char *GetName(int Index) = 0; virtual bool IsValid(int Index) = 0; }; class IEngineMasterServer : public IMasterServer { MACRO_INTERFACE("enginemasterserver", 0) public: }; extern IEngineMasterServer *CreateEngineMasterServer(); #endif ================================================ FILE: src/engine/message.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef ENGINE_MESSAGE_H #define ENGINE_MESSAGE_H #include <engine/shared/packer.h> class CMsgPacker : public CPacker { public: CMsgPacker(int Type, bool System=false) { Reset(); AddInt((Type<<1)|(System?1:0)); } }; #endif ================================================ FILE: src/engine/server/register.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <base/system.h> #include <engine/shared/network.h> #include <engine/shared/config.h> #include <engine/console.h> #include <engine/masterserver.h> #include <mastersrv/mastersrv.h> #include "register.h" CRegister::CRegister() { m_pNetServer = 0; m_pMasterServer = 0; m_pConsole = 0; m_RegisterState = REGISTERSTATE_START; m_RegisterStateStart = 0; m_RegisterFirst = 1; m_RegisterCount = 0; mem_zero(m_aMasterserverInfo, sizeof(m_aMasterserverInfo)); m_RegisterRegisteredServer = -1; } void CRegister::RegisterNewState(int State) { m_RegisterState = State; m_RegisterStateStart = time_get(); } void CRegister::RegisterSendFwcheckresponse(NETADDR *pAddr) { CNetChunk Packet; Packet.m_ClientID = -1; Packet.m_Address = *pAddr; Packet.m_Flags = NETSENDFLAG_CONNLESS; Packet.m_DataSize = sizeof(SERVERBROWSE_FWRESPONSE); Packet.m_pData = SERVERBROWSE_FWRESPONSE; m_pNetServer->Send(&Packet); } void CRegister::RegisterSendHeartbeat(NETADDR Addr) { static unsigned char aData[sizeof(SERVERBROWSE_HEARTBEAT) + 2]; unsigned short Port = g_Config.m_SvPort; CNetChunk Packet; mem_copy(aData, SERVERBROWSE_HEARTBEAT, sizeof(SERVERBROWSE_HEARTBEAT)); Packet.m_ClientID = -1; Packet.m_Address = Addr; Packet.m_Flags = NETSENDFLAG_CONNLESS; Packet.m_DataSize = sizeof(SERVERBROWSE_HEARTBEAT) + 2; Packet.m_pData = &aData; // supply the set port that the master can use if it has problems if(g_Config.m_SvExternalPort) Port = g_Config.m_SvExternalPort; aData[sizeof(SERVERBROWSE_HEARTBEAT)] = Port >> 8; aData[sizeof(SERVERBROWSE_HEARTBEAT)+1] = Port&0xff; m_pNetServer->Send(&Packet); } void CRegister::RegisterSendCountRequest(NETADDR Addr) { CNetChunk Packet; Packet.m_ClientID = -1; Packet.m_Address = Addr; Packet.m_Flags = NETSENDFLAG_CONNLESS; Packet.m_DataSize = sizeof(SERVERBROWSE_GETCOUNT); Packet.m_pData = SERVERBROWSE_GETCOUNT; m_pNetServer->Send(&Packet); } void CRegister::RegisterGotCount(CNetChunk *pChunk) { unsigned char *pData = (unsigned char *)pChunk->m_pData; int Count = (pData[sizeof(SERVERBROWSE_COUNT)]<<8) | pData[sizeof(SERVERBROWSE_COUNT)+1]; for(int i = 0; i < IMasterServer::MAX_MASTERSERVERS; i++) { if(net_addr_comp(&m_aMasterserverInfo[i].m_Addr, &pChunk->m_Address) == 0) { m_aMasterserverInfo[i].m_Count = Count; break; } } } void CRegister::Init(CNetServer *pNetServer, IEngineMasterServer *pMasterServer, IConsole *pConsole) { m_pNetServer = pNetServer; m_pMasterServer = pMasterServer; m_pConsole = pConsole; } void CRegister::RegisterUpdate(int Nettype) { int64 Now = time_get(); int64 Freq = time_freq(); if(!g_Config.m_SvRegister) return; m_pMasterServer->Update(); if(m_RegisterState == REGISTERSTATE_START) { m_RegisterCount = 0; m_RegisterFirst = 1; RegisterNewState(REGISTERSTATE_UPDATE_ADDRS); m_pMasterServer->RefreshAddresses(Nettype); m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "register", "refreshing ip addresses"); } else if(m_RegisterState == REGISTERSTATE_UPDATE_ADDRS) { m_RegisterRegisteredServer = -1; if(!m_pMasterServer->IsRefreshing()) { int i; for(i = 0; i < IMasterServer::MAX_MASTERSERVERS; i++) { if(!m_pMasterServer->IsValid(i)) { m_aMasterserverInfo[i].m_Valid = 0; m_aMasterserverInfo[i].m_Count = 0; continue; } NETADDR Addr = m_pMasterServer->GetAddr(i); m_aMasterserverInfo[i].m_Addr = Addr; m_aMasterserverInfo[i].m_Valid = 1; m_aMasterserverInfo[i].m_Count = -1; m_aMasterserverInfo[i].m_LastSend = 0; } m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "register", "fetching server counts"); RegisterNewState(REGISTERSTATE_QUERY_COUNT); } } else if(m_RegisterState == REGISTERSTATE_QUERY_COUNT) { int Left = 0; for(int i = 0; i < IMasterServer::MAX_MASTERSERVERS; i++) { if(!m_aMasterserverInfo[i].m_Valid) continue; if(m_aMasterserverInfo[i].m_Count == -1) { Left++; if(m_aMasterserverInfo[i].m_LastSend+Freq < Now) { m_aMasterserverInfo[i].m_LastSend = Now; RegisterSendCountRequest(m_aMasterserverInfo[i].m_Addr); } } } // check if we are done or timed out if(Left == 0 || Now > m_RegisterStateStart+Freq*3) { // choose server int Best = -1; int i; for(i = 0; i < IMasterServer::MAX_MASTERSERVERS; i++) { if(!m_aMasterserverInfo[i].m_Valid || m_aMasterserverInfo[i].m_Count == -1) continue; if(Best == -1 || m_aMasterserverInfo[i].m_Count < m_aMasterserverInfo[Best].m_Count) Best = i; } // server chosen m_RegisterRegisteredServer = Best; if(m_RegisterRegisteredServer == -1) { m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "register", "WARNING: No master servers. Retrying in 60 seconds"); RegisterNewState(REGISTERSTATE_ERROR); } else { char aBuf[256]; str_format(aBuf, sizeof(aBuf), "chose '%s' as master, sending heartbeats", m_pMasterServer->GetName(m_RegisterRegisteredServer)); m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "register", aBuf); m_aMasterserverInfo[m_RegisterRegisteredServer].m_LastSend = 0; RegisterNewState(REGISTERSTATE_HEARTBEAT); } } } else if(m_RegisterState == REGISTERSTATE_HEARTBEAT) { // check if we should send heartbeat if(Now > m_aMasterserverInfo[m_RegisterRegisteredServer].m_LastSend+Freq*15) { m_aMasterserverInfo[m_RegisterRegisteredServer].m_LastSend = Now; RegisterSendHeartbeat(m_aMasterserverInfo[m_RegisterRegisteredServer].m_Addr); } if(Now > m_RegisterStateStart+Freq*60) { m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "register", "WARNING: Master server is not responding, switching master"); RegisterNewState(REGISTERSTATE_START); } } else if(m_RegisterState == REGISTERSTATE_REGISTERED) { if(m_RegisterFirst) m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "register", "server registered"); m_RegisterFirst = 0; // check if we should send new heartbeat again if(Now > m_RegisterStateStart+Freq) { if(m_RegisterCount == 120) // redo the whole process after 60 minutes to balance out the master servers RegisterNewState(REGISTERSTATE_START); else { m_RegisterCount++; RegisterNewState(REGISTERSTATE_HEARTBEAT); } } } else if(m_RegisterState == REGISTERSTATE_ERROR) { // check for restart if(Now > m_RegisterStateStart+Freq*60) RegisterNewState(REGISTERSTATE_START); } } int CRegister::RegisterProcessPacket(CNetChunk *pPacket) { // check for masterserver address bool Valid = false; NETADDR Addr1 = pPacket->m_Address; Addr1.port = 0; for(int i = 0; i < IMasterServer::MAX_MASTERSERVERS; i++) { NETADDR Addr2 = m_aMasterserverInfo[i].m_Addr; Addr2.port = 0; if(net_addr_comp(&Addr1, &Addr2) == 0) { Valid = true; break; } } if(!Valid) return 0; if(pPacket->m_DataSize == sizeof(SERVERBROWSE_FWCHECK) && mem_comp(pPacket->m_pData, SERVERBROWSE_FWCHECK, sizeof(SERVERBROWSE_FWCHECK)) == 0) { RegisterSendFwcheckresponse(&pPacket->m_Address); return 1; } else if(pPacket->m_DataSize == sizeof(SERVERBROWSE_FWOK) && mem_comp(pPacket->m_pData, SERVERBROWSE_FWOK, sizeof(SERVERBROWSE_FWOK)) == 0) { if(m_RegisterFirst && m_RegisterState != REGISTERSTATE_REGISTERED) m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "register", "no firewall/nat problems detected"); RegisterNewState(REGISTERSTATE_REGISTERED); return 1; } else if(pPacket->m_DataSize == sizeof(SERVERBROWSE_FWERROR) && mem_comp(pPacket->m_pData, SERVERBROWSE_FWERROR, sizeof(SERVERBROWSE_FWERROR)) == 0) { m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "register", "ERROR: the master server reports that clients can not connect to this server."); char aBuf[256]; str_format(aBuf, sizeof(aBuf), "ERROR: configure your firewall/nat to let through udp on port %d.", g_Config.m_SvPort); m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "register", aBuf); RegisterNewState(REGISTERSTATE_ERROR); return 1; } else if(pPacket->m_DataSize == sizeof(SERVERBROWSE_COUNT)+2 && mem_comp(pPacket->m_pData, SERVERBROWSE_COUNT, sizeof(SERVERBROWSE_COUNT)) == 0) { RegisterGotCount(pPacket); return 1; } return 0; } ================================================ FILE: src/engine/server/register.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef ENGINE_SERVER_REGISTER_H #define ENGINE_SERVER_REGISTER_H class CRegister { enum { REGISTERSTATE_START=0, REGISTERSTATE_UPDATE_ADDRS, REGISTERSTATE_QUERY_COUNT, REGISTERSTATE_HEARTBEAT, REGISTERSTATE_REGISTERED, REGISTERSTATE_ERROR }; struct CMasterserverInfo { NETADDR m_Addr; int m_Count; int m_Valid; int64 m_LastSend; }; class CNetServer *m_pNetServer; class IEngineMasterServer *m_pMasterServer; class IConsole *m_pConsole; int m_RegisterState; int64 m_RegisterStateStart; int m_RegisterFirst; int m_RegisterCount; CMasterserverInfo m_aMasterserverInfo[IMasterServer::MAX_MASTERSERVERS]; int m_RegisterRegisteredServer; void RegisterNewState(int State); void RegisterSendFwcheckresponse(NETADDR *pAddr); void RegisterSendHeartbeat(NETADDR Addr); void RegisterSendCountRequest(NETADDR Addr); void RegisterGotCount(struct CNetChunk *pChunk); public: CRegister(); void Init(class CNetServer *pNetServer, class IEngineMasterServer *pMasterServer, class IConsole *pConsole); void RegisterUpdate(int Nettype); int RegisterProcessPacket(struct CNetChunk *pPacket); }; #endif ================================================ FILE: src/engine/server/server.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <base/math.h> #include <base/system.h> #include <engine/config.h> #include <engine/console.h> #include <engine/engine.h> #include <engine/map.h> #include <engine/masterserver.h> #include <engine/server.h> #include <engine/storage.h> #include <engine/shared/compression.h> #include <engine/shared/config.h> #include <engine/shared/datafile.h> #include <engine/shared/demo.h> #include <engine/shared/econ.h> #include <engine/shared/filecollection.h> #include <engine/shared/mapchecker.h> #include <engine/shared/netban.h> #include <engine/shared/network.h> #include <engine/shared/packer.h> #include <engine/shared/protocol.h> #include <engine/shared/snapshot.h> #include <mastersrv/mastersrv.h> #include "register.h" #include "server.h" #if defined(CONF_FAMILY_WINDOWS) #define _WIN32_WINNT 0x0501 #define WIN32_LEAN_AND_MEAN #include <windows.h> #endif static const char *StrLtrim(const char *pStr) { while(*pStr && *pStr >= 0 && *pStr <= 32) pStr++; return pStr; } static void StrRtrim(char *pStr) { int i = str_length(pStr); while(i >= 0) { if(pStr[i] < 0 || pStr[i] > 32) break; pStr[i] = 0; i--; } } CSnapIDPool::CSnapIDPool() { Reset(); } void CSnapIDPool::Reset() { for(int i = 0; i < MAX_IDS; i++) { m_aIDs[i].m_Next = i+1; m_aIDs[i].m_State = 0; } m_aIDs[MAX_IDS-1].m_Next = -1; m_FirstFree = 0; m_FirstTimed = -1; m_LastTimed = -1; m_Usage = 0; m_InUsage = 0; } void CSnapIDPool::RemoveFirstTimeout() { int NextTimed = m_aIDs[m_FirstTimed].m_Next; // add it to the free list m_aIDs[m_FirstTimed].m_Next = m_FirstFree; m_aIDs[m_FirstTimed].m_State = 0; m_FirstFree = m_FirstTimed; // remove it from the timed list m_FirstTimed = NextTimed; if(m_FirstTimed == -1) m_LastTimed = -1; m_Usage--; } int CSnapIDPool::NewID() { int64 Now = time_get(); // process timed ids while(m_FirstTimed != -1 && m_aIDs[m_FirstTimed].m_Timeout < Now) RemoveFirstTimeout(); int ID = m_FirstFree; dbg_assert(ID != -1, "id error"); if(ID == -1) return ID; m_FirstFree = m_aIDs[m_FirstFree].m_Next; m_aIDs[ID].m_State = 1; m_Usage++; m_InUsage++; return ID; } void CSnapIDPool::TimeoutIDs() { // process timed ids while(m_FirstTimed != -1) RemoveFirstTimeout(); } void CSnapIDPool::FreeID(int ID) { if(ID < 0) return; dbg_assert(m_aIDs[ID].m_State == 1, "id is not alloced"); m_InUsage--; m_aIDs[ID].m_State = 2; m_aIDs[ID].m_Timeout = time_get()+time_freq()*5; m_aIDs[ID].m_Next = -1; if(m_LastTimed != -1) { m_aIDs[m_LastTimed].m_Next = ID; m_LastTimed = ID; } else { m_FirstTimed = ID; m_LastTimed = ID; } } void CServerBan::InitServerBan(IConsole *pConsole, IStorage *pStorage, CServer* pServer) { CNetBan::Init(pConsole, pStorage); m_pServer = pServer; // overwrites base command, todo: improve this Console()->Register("ban", "s?ir", CFGFLAG_SERVER|CFGFLAG_STORE, ConBanExt, this, "Ban player with ip/client id for x minutes for any reason"); } template<class T> int CServerBan::BanExt(T *pBanPool, const typename T::CDataType *pData, int Seconds, const char *pReason) { // validate address if(Server()->m_RconClientID >= 0 && Server()->m_RconClientID < MAX_CLIENTS && Server()->m_aClients[Server()->m_RconClientID].m_State != CServer::CClient::STATE_EMPTY) { if(NetMatch(pData, Server()->m_NetServer.ClientAddr(Server()->m_RconClientID))) { Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban error (you can't ban yourself)"); return -1; } for(int i = 0; i < MAX_CLIENTS; ++i) { if(i == Server()->m_RconClientID || Server()->m_aClients[i].m_State == CServer::CClient::STATE_EMPTY) continue; if(Server()->m_aClients[i].m_Authed >= Server()->m_RconAuthLevel && NetMatch(pData, Server()->m_NetServer.ClientAddr(i))) { Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban error (command denied)"); return -1; } } } else if(Server()->m_RconClientID == IServer::RCON_CID_VOTE) { for(int i = 0; i < MAX_CLIENTS; ++i) { if(Server()->m_aClients[i].m_State == CServer::CClient::STATE_EMPTY) continue; if(Server()->m_aClients[i].m_Authed != CServer::AUTHED_NO && NetMatch(pData, Server()->m_NetServer.ClientAddr(i))) { Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban error (command denied)"); return -1; } } } int Result = Ban(pBanPool, pData, Seconds, pReason); if(Result != 0) return Result; // drop banned clients typename T::CDataType Data = *pData; for(int i = 0; i < MAX_CLIENTS; ++i) { if(Server()->m_aClients[i].m_State == CServer::CClient::STATE_EMPTY) continue; if(NetMatch(&Data, Server()->m_NetServer.ClientAddr(i))) { CNetHash NetHash(&Data); char aBuf[256]; MakeBanInfo(pBanPool->Find(&Data, &NetHash), aBuf, sizeof(aBuf), MSGTYPE_PLAYER); Server()->m_NetServer.Drop(i, aBuf); } } return Result; } int CServerBan::BanAddr(const NETADDR *pAddr, int Seconds, const char *pReason) { return BanExt(&m_BanAddrPool, pAddr, Seconds, pReason); } int CServerBan::BanRange(const CNetRange *pRange, int Seconds, const char *pReason) { if(pRange->IsValid()) return BanExt(&m_BanRangePool, pRange, Seconds, pReason); Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban failed (invalid range)"); return -1; } void CServerBan::ConBanExt(IConsole::IResult *pResult, void *pUser) { CServerBan *pThis = static_cast<CServerBan *>(pUser); const char *pStr = pResult->GetString(0); int Minutes = pResult->NumArguments()>1 ? clamp(pResult->GetInteger(1), 0, 44640) : 30; const char *pReason = pResult->NumArguments()>2 ? pResult->GetString(2) : "No reason given"; if(StrAllnum(pStr)) { int ClientID = str_toint(pStr); if(ClientID < 0 || ClientID >= MAX_CLIENTS || pThis->Server()->m_aClients[ClientID].m_State == CServer::CClient::STATE_EMPTY) pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban error (invalid client id)"); else pThis->BanAddr(pThis->Server()->m_NetServer.ClientAddr(ClientID), Minutes*60, pReason); } else ConBan(pResult, pUser); } void CServer::CClient::Reset() { // reset input for(int i = 0; i < 200; i++) m_aInputs[i].m_GameTick = -1; m_CurrentInput = 0; mem_zero(&m_LatestInput, sizeof(m_LatestInput)); m_Snapshots.PurgeAll(); m_LastAckedSnapshot = -1; m_LastInputTick = -1; m_SnapRate = CClient::SNAPRATE_INIT; m_Score = 0; m_MapChunk = 0; } CServer::CServer() : m_DemoRecorder(&m_SnapshotDelta) { m_TickSpeed = SERVER_TICK_SPEED; m_pGameServer = 0; m_CurrentGameTick = 0; m_RunServer = 1; m_pCurrentMapData = 0; m_CurrentMapSize = 0; m_MapReload = 0; m_RconClientID = IServer::RCON_CID_SERV; m_RconAuthLevel = AUTHED_ADMIN; Init(); } int CServer::TrySetClientName(int ClientID, const char *pName) { char aTrimmedName[64]; // trim the name str_copy(aTrimmedName, StrLtrim(pName), sizeof(aTrimmedName)); StrRtrim(aTrimmedName); // check for empty names if(!aTrimmedName[0]) return -1; // check if new and old name are the same if(m_aClients[ClientID].m_aName[0] && str_comp(m_aClients[ClientID].m_aName, aTrimmedName) == 0) return 0; char aBuf[256]; str_format(aBuf, sizeof(aBuf), "'%s' -> '%s'", pName, aTrimmedName); Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "server", aBuf); pName = aTrimmedName; // make sure that two clients doesn't have the same name for(int i = 0; i < MAX_CLIENTS; i++) if(i != ClientID && m_aClients[i].m_State >= CClient::STATE_READY) { if(str_comp(pName, m_aClients[i].m_aName) == 0) return -1; } // set the client name str_copy(m_aClients[ClientID].m_aName, pName, MAX_NAME_LENGTH); return 0; } void CServer::SetClientName(int ClientID, const char *pName) { if(ClientID < 0 || ClientID >= MAX_CLIENTS || m_aClients[ClientID].m_State < CClient::STATE_READY) return; if(!pName) return; char aCleanName[MAX_NAME_LENGTH]; str_copy(aCleanName, pName, sizeof(aCleanName)); // clear name for(char *p = aCleanName; *p; ++p) { if(*p < 32) *p = ' '; } if(TrySetClientName(ClientID, aCleanName)) { // auto rename for(int i = 1;; i++) { char aNameTry[MAX_NAME_LENGTH]; str_format(aNameTry, sizeof(aCleanName), "(%d)%s", i, aCleanName); if(TrySetClientName(ClientID, aNameTry) == 0) break; } } } void CServer::SetClientClan(int ClientID, const char *pClan) { if(ClientID < 0 || ClientID >= MAX_CLIENTS || m_aClients[ClientID].m_State < CClient::STATE_READY || !pClan) return; str_copy(m_aClients[ClientID].m_aClan, pClan, MAX_CLAN_LENGTH); } void CServer::SetClientCountry(int ClientID, int Country) { if(ClientID < 0 || ClientID >= MAX_CLIENTS || m_aClients[ClientID].m_State < CClient::STATE_READY) return; m_aClients[ClientID].m_Country = Country; } void CServer::SetClientScore(int ClientID, int Score) { if(ClientID < 0 || ClientID >= MAX_CLIENTS || m_aClients[ClientID].m_State < CClient::STATE_READY) return; m_aClients[ClientID].m_Score = Score; } void CServer::Kick(int ClientID, const char *pReason) { if(ClientID < 0 || ClientID >= MAX_CLIENTS || m_aClients[ClientID].m_State == CClient::STATE_EMPTY) { Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", "invalid client id to kick"); return; } else if(m_RconClientID == ClientID) { Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", "you can't kick yourself"); return; } else if(m_aClients[ClientID].m_Authed > m_RconAuthLevel) { Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", "kick command denied"); return; } m_NetServer.Drop(ClientID, pReason); } /*int CServer::Tick() { return m_CurrentGameTick; }*/ int64 CServer::TickStartTime(int Tick) { return m_GameStartTime + (time_freq()*Tick)/SERVER_TICK_SPEED; } /*int CServer::TickSpeed() { return SERVER_TICK_SPEED; }*/ int CServer::Init() { for(int i = 0; i < MAX_CLIENTS; i++) { m_aClients[i].m_State = CClient::STATE_EMPTY; m_aClients[i].m_aName[0] = 0; m_aClients[i].m_aClan[0] = 0; m_aClients[i].m_Country = -1; m_aClients[i].m_Snapshots.Init(); } m_CurrentGameTick = 0; return 0; } void CServer::SetRconCID(int ClientID) { m_RconClientID = ClientID; } bool CServer::IsAuthed(int ClientID) { return m_aClients[ClientID].m_Authed; } bool CServer::IsBanned(int ClientID) { return m_ServerBan.IsBanned(m_NetServer.ClientAddr(ClientID), 0, 0); } int CServer::GetClientInfo(int ClientID, CClientInfo *pInfo) { dbg_assert(ClientID >= 0 && ClientID < MAX_CLIENTS, "client_id is not valid"); dbg_assert(pInfo != 0, "info can not be null"); if(m_aClients[ClientID].m_State == CClient::STATE_INGAME) { pInfo->m_pName = m_aClients[ClientID].m_aName; pInfo->m_Latency = m_aClients[ClientID].m_Latency; return 1; } return 0; } void CServer::GetClientAddr(int ClientID, char *pAddrStr, int Size) { if(ClientID >= 0 && ClientID < MAX_CLIENTS && m_aClients[ClientID].m_State == CClient::STATE_INGAME) net_addr_str(m_NetServer.ClientAddr(ClientID), pAddrStr, Size, false); } const char *CServer::ClientName(int ClientID) { if(ClientID < 0 || ClientID >= MAX_CLIENTS || m_aClients[ClientID].m_State == CServer::CClient::STATE_EMPTY) return "(invalid)"; if(m_aClients[ClientID].m_State == CServer::CClient::STATE_INGAME) return m_aClients[ClientID].m_aName; else return "(connecting)"; } const char *CServer::ClientClan(int ClientID) { if(ClientID < 0 || ClientID >= MAX_CLIENTS || m_aClients[ClientID].m_State == CServer::CClient::STATE_EMPTY) return ""; if(m_aClients[ClientID].m_State == CServer::CClient::STATE_INGAME) return m_aClients[ClientID].m_aClan; else return ""; } int CServer::ClientCountry(int ClientID) { if(ClientID < 0 || ClientID >= MAX_CLIENTS || m_aClients[ClientID].m_State == CServer::CClient::STATE_EMPTY) return -1; if(m_aClients[ClientID].m_State == CServer::CClient::STATE_INGAME) return m_aClients[ClientID].m_Country; else return -1; } bool CServer::ClientIngame(int ClientID) { return ClientID >= 0 && ClientID < MAX_CLIENTS && m_aClients[ClientID].m_State == CServer::CClient::STATE_INGAME; } int CServer::MaxClients() const { return m_NetServer.MaxClients(); } int CServer::SendMsg(CMsgPacker *pMsg, int Flags, int ClientID) { CNetChunk Packet; if(!pMsg) return -1; mem_zero(&Packet, sizeof(CNetChunk)); Packet.m_ClientID = ClientID; Packet.m_pData = pMsg->Data(); Packet.m_DataSize = pMsg->Size(); if(Flags&MSGFLAG_VITAL) Packet.m_Flags |= NETSENDFLAG_VITAL; if(Flags&MSGFLAG_FLUSH) Packet.m_Flags |= NETSENDFLAG_FLUSH; // write message to demo recorder if(!(Flags&MSGFLAG_NORECORD)) m_DemoRecorder.RecordMessage(pMsg->Data(), pMsg->Size()); if(!(Flags&MSGFLAG_NOSEND)) { if(ClientID == -1) { // broadcast int i; for(i = 0; i < MAX_CLIENTS; i++) if(m_aClients[i].m_State == CClient::STATE_INGAME && !m_aClients[i].m_Quitting) { Packet.m_ClientID = i; m_NetServer.Send(&Packet); } } else m_NetServer.Send(&Packet); } return 0; } void CServer::DoSnapshot() { GameServer()->OnPreSnap(); // create snapshot for demo recording if(m_DemoRecorder.IsRecording()) { char aData[CSnapshot::MAX_SIZE]; int SnapshotSize; // build snap and possibly add some messages m_SnapshotBuilder.Init(); GameServer()->OnSnap(-1); SnapshotSize = m_SnapshotBuilder.Finish(aData); // write snapshot m_DemoRecorder.RecordSnapshot(Tick(), aData, SnapshotSize); } // create snapshots for all clients for(int i = 0; i < MAX_CLIENTS; i++) { // client must be ingame to recive snapshots if(m_aClients[i].m_State != CClient::STATE_INGAME) continue; // this client is trying to recover, don't spam snapshots if(m_aClients[i].m_SnapRate == CClient::SNAPRATE_RECOVER && (Tick()%50) != 0) continue; // this client is trying to recover, don't spam snapshots if(m_aClients[i].m_SnapRate == CClient::SNAPRATE_INIT && (Tick()%10) != 0) continue; { char aData[CSnapshot::MAX_SIZE]; CSnapshot *pData = (CSnapshot*)aData; // Fix compiler warning for strict-aliasing char aDeltaData[CSnapshot::MAX_SIZE]; char aCompData[CSnapshot::MAX_SIZE]; int SnapshotSize; int Crc; static CSnapshot EmptySnap; CSnapshot *pDeltashot = &EmptySnap; int DeltashotSize; int DeltaTick = -1; int DeltaSize; m_SnapshotBuilder.Init(); GameServer()->OnSnap(i); // finish snapshot SnapshotSize = m_SnapshotBuilder.Finish(pData); Crc = pData->Crc(); // remove old snapshos // keep 3 seconds worth of snapshots m_aClients[i].m_Snapshots.PurgeUntil(m_CurrentGameTick-SERVER_TICK_SPEED*3); // save it the snapshot m_aClients[i].m_Snapshots.Add(m_CurrentGameTick, time_get(), SnapshotSize, pData, 0); // find snapshot that we can preform delta against EmptySnap.Clear(); { DeltashotSize = m_aClients[i].m_Snapshots.Get(m_aClients[i].m_LastAckedSnapshot, 0, &pDeltashot, 0); if(DeltashotSize >= 0) DeltaTick = m_aClients[i].m_LastAckedSnapshot; else { // no acked package found, force client to recover rate if(m_aClients[i].m_SnapRate == CClient::SNAPRATE_FULL) m_aClients[i].m_SnapRate = CClient::SNAPRATE_RECOVER; } } // create delta DeltaSize = m_SnapshotDelta.CreateDelta(pDeltashot, pData, aDeltaData); if(DeltaSize) { // compress it int SnapshotSize; const int MaxSize = MAX_SNAPSHOT_PACKSIZE; int NumPackets; SnapshotSize = CVariableInt::Compress(aDeltaData, DeltaSize, aCompData); NumPackets = (SnapshotSize+MaxSize-1)/MaxSize; for(int n = 0, Left = SnapshotSize; Left; n++) { int Chunk = Left < MaxSize ? Left : MaxSize; Left -= Chunk; if(NumPackets == 1) { CMsgPacker Msg(NETMSG_SNAPSINGLE, true); Msg.AddInt(m_CurrentGameTick); Msg.AddInt(m_CurrentGameTick-DeltaTick); Msg.AddInt(Crc); Msg.AddInt(Chunk); Msg.AddRaw(&aCompData[n*MaxSize], Chunk); SendMsg(&Msg, MSGFLAG_FLUSH, i); } else { CMsgPacker Msg(NETMSG_SNAP, true); Msg.AddInt(m_CurrentGameTick); Msg.AddInt(m_CurrentGameTick-DeltaTick); Msg.AddInt(NumPackets); Msg.AddInt(n); Msg.AddInt(Crc); Msg.AddInt(Chunk); Msg.AddRaw(&aCompData[n*MaxSize], Chunk); SendMsg(&Msg, MSGFLAG_FLUSH, i); } } } else { CMsgPacker Msg(NETMSG_SNAPEMPTY, true); Msg.AddInt(m_CurrentGameTick); Msg.AddInt(m_CurrentGameTick-DeltaTick); SendMsg(&Msg, MSGFLAG_FLUSH, i); } } } GameServer()->OnPostSnap(); } int CServer::NewClientCallback(int ClientID, void *pUser) { CServer *pThis = (CServer *)pUser; pThis->m_aClients[ClientID].m_State = CClient::STATE_AUTH; pThis->m_aClients[ClientID].m_aName[0] = 0; pThis->m_aClients[ClientID].m_aClan[0] = 0; pThis->m_aClients[ClientID].m_Country = -1; pThis->m_aClients[ClientID].m_Authed = AUTHED_NO; pThis->m_aClients[ClientID].m_AuthTries = 0; pThis->m_aClients[ClientID].m_pRconCmdToSend = 0; pThis->m_aClients[ClientID].m_Quitting = false; pThis->m_aClients[ClientID].Reset(); return 0; } int CServer::DelClientCallback(int ClientID, const char *pReason, void *pUser) { CServer *pThis = (CServer *)pUser; char aAddrStr[NETADDR_MAXSTRSIZE]; net_addr_str(pThis->m_NetServer.ClientAddr(ClientID), aAddrStr, sizeof(aAddrStr), true); char aBuf[256]; str_format(aBuf, sizeof(aBuf), "client dropped. cid=%d addr=%s reason='%s'", ClientID, aAddrStr, pReason); pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); // notify the mod about the drop if(pThis->m_aClients[ClientID].m_State >= CClient::STATE_READY) { pThis->m_aClients[ClientID].m_Quitting = true; pThis->GameServer()->OnClientDrop(ClientID, pReason); } pThis->m_aClients[ClientID].m_State = CClient::STATE_EMPTY; pThis->m_aClients[ClientID].m_aName[0] = 0; pThis->m_aClients[ClientID].m_aClan[0] = 0; pThis->m_aClients[ClientID].m_Country = -1; pThis->m_aClients[ClientID].m_Authed = AUTHED_NO; pThis->m_aClients[ClientID].m_AuthTries = 0; pThis->m_aClients[ClientID].m_pRconCmdToSend = 0; pThis->m_aClients[ClientID].m_Quitting = false; pThis->m_aClients[ClientID].m_Snapshots.PurgeAll(); return 0; } void CServer::SendMap(int ClientID) { CMsgPacker Msg(NETMSG_MAP_CHANGE, true); Msg.AddString(GetMapName(), 0); Msg.AddInt(m_CurrentMapCrc); Msg.AddInt(m_CurrentMapSize); Msg.AddInt(m_MapChunksPerRequest); Msg.AddInt(MAP_CHUNK_SIZE); SendMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_FLUSH, ClientID); } void CServer::SendConnectionReady(int ClientID) { CMsgPacker Msg(NETMSG_CON_READY, true); SendMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_FLUSH, ClientID); } void CServer::SendRconLine(int ClientID, const char *pLine) { CMsgPacker Msg(NETMSG_RCON_LINE, true); Msg.AddString(pLine, 512); SendMsg(&Msg, MSGFLAG_VITAL, ClientID); } void CServer::SendRconLineAuthed(const char *pLine, void *pUser) { CServer *pThis = (CServer *)pUser; static volatile int ReentryGuard = 0; int i; if(ReentryGuard) return; ReentryGuard++; for(i = 0; i < MAX_CLIENTS; i++) { if(pThis->m_aClients[i].m_State != CClient::STATE_EMPTY && pThis->m_aClients[i].m_Authed >= pThis->m_RconAuthLevel) pThis->SendRconLine(i, pLine); } ReentryGuard--; } void CServer::SendRconCmdAdd(const IConsole::CCommandInfo *pCommandInfo, int ClientID) { CMsgPacker Msg(NETMSG_RCON_CMD_ADD, true); Msg.AddString(pCommandInfo->m_pName, IConsole::TEMPCMD_NAME_LENGTH); Msg.AddString(pCommandInfo->m_pHelp, IConsole::TEMPCMD_HELP_LENGTH); Msg.AddString(pCommandInfo->m_pParams, IConsole::TEMPCMD_PARAMS_LENGTH); SendMsg(&Msg, MSGFLAG_VITAL, ClientID); } void CServer::SendRconCmdRem(const IConsole::CCommandInfo *pCommandInfo, int ClientID) { CMsgPacker Msg(NETMSG_RCON_CMD_REM, true); Msg.AddString(pCommandInfo->m_pName, 256); SendMsg(&Msg, MSGFLAG_VITAL, ClientID); } void CServer::UpdateClientRconCommands() { int ClientID = Tick() % MAX_CLIENTS; if(m_aClients[ClientID].m_State != CClient::STATE_EMPTY && m_aClients[ClientID].m_Authed) { int ConsoleAccessLevel = m_aClients[ClientID].m_Authed == AUTHED_ADMIN ? IConsole::ACCESS_LEVEL_ADMIN : IConsole::ACCESS_LEVEL_MOD; for(int i = 0; i < MAX_RCONCMD_SEND && m_aClients[ClientID].m_pRconCmdToSend; ++i) { SendRconCmdAdd(m_aClients[ClientID].m_pRconCmdToSend, ClientID); m_aClients[ClientID].m_pRconCmdToSend = m_aClients[ClientID].m_pRconCmdToSend->NextCommandInfo(ConsoleAccessLevel, CFGFLAG_SERVER); } } } void CServer::ProcessClientPacket(CNetChunk *pPacket) { int ClientID = pPacket->m_ClientID; CUnpacker Unpacker; Unpacker.Reset(pPacket->m_pData, pPacket->m_DataSize); // unpack msgid and system flag int Msg = Unpacker.GetInt(); int Sys = Msg&1; Msg >>= 1; if(Unpacker.Error()) return; if(Sys) { // system message if(Msg == NETMSG_INFO) { if(m_aClients[ClientID].m_State == CClient::STATE_AUTH) { const char *pVersion = Unpacker.GetString(CUnpacker::SANITIZE_CC); if(str_comp(pVersion, GameServer()->NetVersion()) != 0) { // wrong version char aReason[256]; str_format(aReason, sizeof(aReason), "Wrong version. Server is running '%s' and client '%s'", GameServer()->NetVersion(), pVersion); m_NetServer.Drop(ClientID, aReason); return; } const char *pPassword = Unpacker.GetString(CUnpacker::SANITIZE_CC); if(g_Config.m_Password[0] != 0 && str_comp(g_Config.m_Password, pPassword) != 0) { // wrong password m_NetServer.Drop(ClientID, "Wrong password"); return; } m_aClients[ClientID].m_State = CClient::STATE_CONNECTING; SendMap(ClientID); } } else if(Msg == NETMSG_REQUEST_MAP_DATA) { if(m_aClients[ClientID].m_State == CClient::STATE_CONNECTING) { int ChunkSize = MAP_CHUNK_SIZE; // send map chunks for(int i = 0; i < m_MapChunksPerRequest && m_aClients[ClientID].m_MapChunk >= 0; ++i) { int Chunk = m_aClients[ClientID].m_MapChunk; int Offset = Chunk * ChunkSize; // check for last part if(Offset+ChunkSize >= m_CurrentMapSize) { ChunkSize = m_CurrentMapSize-Offset; m_aClients[ClientID].m_MapChunk = -1; } else m_aClients[ClientID].m_MapChunk++; CMsgPacker Msg(NETMSG_MAP_DATA, true); Msg.AddRaw(&m_pCurrentMapData[Offset], ChunkSize); SendMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_FLUSH, ClientID); if(g_Config.m_Debug) { char aBuf[64]; str_format(aBuf, sizeof(aBuf), "sending chunk %d with size %d", Chunk, ChunkSize); Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "server", aBuf); } } } } else if(Msg == NETMSG_READY) { if(m_aClients[ClientID].m_State == CClient::STATE_CONNECTING) { char aAddrStr[NETADDR_MAXSTRSIZE]; net_addr_str(m_NetServer.ClientAddr(ClientID), aAddrStr, sizeof(aAddrStr), true); char aBuf[256]; str_format(aBuf, sizeof(aBuf), "player is ready. ClientID=%x addr=%s", ClientID, aAddrStr); Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "server", aBuf); m_aClients[ClientID].m_State = CClient::STATE_READY; GameServer()->OnClientConnected(ClientID); SendConnectionReady(ClientID); } } else if(Msg == NETMSG_ENTERGAME) { if(m_aClients[ClientID].m_State == CClient::STATE_READY && GameServer()->IsClientReady(ClientID)) { char aAddrStr[NETADDR_MAXSTRSIZE]; net_addr_str(m_NetServer.ClientAddr(ClientID), aAddrStr, sizeof(aAddrStr), true); char aBuf[256]; str_format(aBuf, sizeof(aBuf), "player has entered the game. ClientID=%x addr=%s", ClientID, aAddrStr); Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); m_aClients[ClientID].m_State = CClient::STATE_INGAME; GameServer()->OnClientEnter(ClientID); } } else if(Msg == NETMSG_INPUT) { CClient::CInput *pInput; int64 TagTime; m_aClients[ClientID].m_LastAckedSnapshot = Unpacker.GetInt(); int IntendedTick = Unpacker.GetInt(); int Size = Unpacker.GetInt(); // check for errors if(Unpacker.Error() || Size/4 > MAX_INPUT_SIZE) return; if(m_aClients[ClientID].m_LastAckedSnapshot > 0) m_aClients[ClientID].m_SnapRate = CClient::SNAPRATE_FULL; if(m_aClients[ClientID].m_Snapshots.Get(m_aClients[ClientID].m_LastAckedSnapshot, &TagTime, 0, 0) >= 0) m_aClients[ClientID].m_Latency = (int)(((time_get()-TagTime)*1000)/time_freq()); // add message to report the input timing // skip packets that are old if(IntendedTick > m_aClients[ClientID].m_LastInputTick) { int TimeLeft = ((TickStartTime(IntendedTick)-time_get())*1000) / time_freq(); CMsgPacker Msg(NETMSG_INPUTTIMING, true); Msg.AddInt(IntendedTick); Msg.AddInt(TimeLeft); SendMsg(&Msg, 0, ClientID); } m_aClients[ClientID].m_LastInputTick = IntendedTick; pInput = &m_aClients[ClientID].m_aInputs[m_aClients[ClientID].m_CurrentInput]; if(IntendedTick <= Tick()) IntendedTick = Tick()+1; pInput->m_GameTick = IntendedTick; for(int i = 0; i < Size/4; i++) pInput->m_aData[i] = Unpacker.GetInt(); mem_copy(m_aClients[ClientID].m_LatestInput.m_aData, pInput->m_aData, MAX_INPUT_SIZE*sizeof(int)); m_aClients[ClientID].m_CurrentInput++; m_aClients[ClientID].m_CurrentInput %= 200; // call the mod with the fresh input data if(m_aClients[ClientID].m_State == CClient::STATE_INGAME) GameServer()->OnClientDirectInput(ClientID, m_aClients[ClientID].m_LatestInput.m_aData); } else if(Msg == NETMSG_RCON_CMD) { const char *pCmd = Unpacker.GetString(); if(Unpacker.Error() == 0 && m_aClients[ClientID].m_Authed) { char aBuf[256]; str_format(aBuf, sizeof(aBuf), "ClientID=%d rcon='%s'", ClientID, pCmd); Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "server", aBuf); m_RconClientID = ClientID; m_RconAuthLevel = m_aClients[ClientID].m_Authed; Console()->SetAccessLevel(m_aClients[ClientID].m_Authed == AUTHED_ADMIN ? IConsole::ACCESS_LEVEL_ADMIN : IConsole::ACCESS_LEVEL_MOD); Console()->ExecuteLineFlag(pCmd, CFGFLAG_SERVER); Console()->SetAccessLevel(IConsole::ACCESS_LEVEL_ADMIN); m_RconClientID = IServer::RCON_CID_SERV; m_RconAuthLevel = AUTHED_ADMIN; } } else if(Msg == NETMSG_RCON_AUTH) { const char *pPw = Unpacker.GetString(CUnpacker::SANITIZE_CC); if(Unpacker.Error() == 0) { if(g_Config.m_SvRconPassword[0] == 0 && g_Config.m_SvRconModPassword[0] == 0) { SendRconLine(ClientID, "No rcon password set on server. Set sv_rcon_password and/or sv_rcon_mod_password to enable the remote console."); } else if(g_Config.m_SvRconPassword[0] && str_comp(pPw, g_Config.m_SvRconPassword) == 0) { CMsgPacker Msg(NETMSG_RCON_AUTH_ON, true); SendMsg(&Msg, MSGFLAG_VITAL, ClientID); m_aClients[ClientID].m_Authed = AUTHED_ADMIN; m_aClients[ClientID].m_pRconCmdToSend = Console()->FirstCommandInfo(IConsole::ACCESS_LEVEL_ADMIN, CFGFLAG_SERVER); SendRconLine(ClientID, "Admin authentication successful. Full remote console access granted."); char aBuf[256]; str_format(aBuf, sizeof(aBuf), "ClientID=%d authed (admin)", ClientID); Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); } else if(g_Config.m_SvRconModPassword[0] && str_comp(pPw, g_Config.m_SvRconModPassword) == 0) { CMsgPacker Msg(NETMSG_RCON_AUTH_ON, true); SendMsg(&Msg, MSGFLAG_VITAL, ClientID); m_aClients[ClientID].m_Authed = AUTHED_MOD; m_aClients[ClientID].m_pRconCmdToSend = Console()->FirstCommandInfo(IConsole::ACCESS_LEVEL_MOD, CFGFLAG_SERVER); SendRconLine(ClientID, "Moderator authentication successful. Limited remote console access granted."); char aBuf[256]; str_format(aBuf, sizeof(aBuf), "ClientID=%d authed (moderator)", ClientID); Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); } else if(g_Config.m_SvRconMaxTries) { m_aClients[ClientID].m_AuthTries++; char aBuf[128]; str_format(aBuf, sizeof(aBuf), "Wrong password %d/%d.", m_aClients[ClientID].m_AuthTries, g_Config.m_SvRconMaxTries); SendRconLine(ClientID, aBuf); if(m_aClients[ClientID].m_AuthTries >= g_Config.m_SvRconMaxTries) { if(!g_Config.m_SvRconBantime) m_NetServer.Drop(ClientID, "Too many remote console authentication tries"); else m_ServerBan.BanAddr(m_NetServer.ClientAddr(ClientID), g_Config.m_SvRconBantime*60, "Too many remote console authentication tries"); } } else { SendRconLine(ClientID, "Wrong password."); } } } else if(Msg == NETMSG_PING) { CMsgPacker Msg(NETMSG_PING_REPLY, true); SendMsg(&Msg, 0, ClientID); } else { if(g_Config.m_Debug) { char aHex[] = "0123456789ABCDEF"; char aBuf[512]; for(int b = 0; b < pPacket->m_DataSize && b < 32; b++) { aBuf[b*3] = aHex[((const unsigned char *)pPacket->m_pData)[b]>>4]; aBuf[b*3+1] = aHex[((const unsigned char *)pPacket->m_pData)[b]&0xf]; aBuf[b*3+2] = ' '; aBuf[b*3+3] = 0; } char aBufMsg[256]; str_format(aBufMsg, sizeof(aBufMsg), "strange message ClientID=%d msg=%d data_size=%d", ClientID, Msg, pPacket->m_DataSize); Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "server", aBufMsg); Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "server", aBuf); } } } else { // game message if(m_aClients[ClientID].m_State >= CClient::STATE_READY) GameServer()->OnMessage(Msg, &Unpacker, ClientID); } } void CServer::SendServerInfo(const NETADDR *pAddr, int Token) { CNetChunk Packet; CPacker Packer; // count the players int PlayerCount = 0, ClientCount = 0; for(int i = 0; i < MAX_CLIENTS; i++) { if(m_aClients[i].m_State != CClient::STATE_EMPTY) { if(GameServer()->IsClientPlayer(i)) PlayerCount++; ClientCount++; } } Packer.Reset(); Packer.AddRaw(SERVERBROWSE_INFO, sizeof(SERVERBROWSE_INFO)); Packer.AddInt(Token); Packer.AddString(GameServer()->Version(), 32); Packer.AddString(g_Config.m_SvName, 64); Packer.AddString(g_Config.m_SvHostname, 128); Packer.AddString(GetMapName(), 32); // gametype Packer.AddString(GameServer()->GameType(), 16); // flags int Flag = g_Config.m_Password[0] ? SERVERINFO_FLAG_PASSWORD : 0; // password set Packer.AddInt(Flag); Packer.AddInt(g_Config.m_SvSkillLevel); // server skill level Packer.AddInt(PlayerCount); // num players Packer.AddInt(m_NetServer.MaxClients()-g_Config.m_SvSpectatorSlots); // max players Packer.AddInt(ClientCount); // num clients Packer.AddInt(m_NetServer.MaxClients()); // max clients for(int i = 0; i < MAX_CLIENTS; i++) { if(m_aClients[i].m_State != CClient::STATE_EMPTY) { Packer.AddString(ClientName(i), MAX_NAME_LENGTH); // client name Packer.AddString(ClientClan(i), MAX_CLAN_LENGTH); // client clan Packer.AddInt(m_aClients[i].m_Country); // client country Packer.AddInt(m_aClients[i].m_Score); // client score Packer.AddInt(GameServer()->IsClientPlayer(i)?1:0); // is player? } } Packet.m_ClientID = -1; Packet.m_Address = *pAddr; Packet.m_Flags = NETSENDFLAG_CONNLESS; Packet.m_DataSize = Packer.Size(); Packet.m_pData = Packer.Data(); m_NetServer.Send(&Packet); } void CServer::UpdateServerInfo() { for(int i = 0; i < MAX_CLIENTS; ++i) { if(m_aClients[i].m_State != CClient::STATE_EMPTY) SendServerInfo(m_NetServer.ClientAddr(i), -1); } } void CServer::PumpNetwork() { CNetChunk Packet; m_NetServer.Update(); // process packets while(m_NetServer.Recv(&Packet)) { if(Packet.m_ClientID == -1) { // stateless if(!m_Register.RegisterProcessPacket(&Packet)) { if(Packet.m_DataSize == sizeof(SERVERBROWSE_GETINFO)+1 && mem_comp(Packet.m_pData, SERVERBROWSE_GETINFO, sizeof(SERVERBROWSE_GETINFO)) == 0) { SendServerInfo(&Packet.m_Address, ((unsigned char *)Packet.m_pData)[sizeof(SERVERBROWSE_GETINFO)]); } } } else ProcessClientPacket(&Packet); } m_ServerBan.Update(); m_Econ.Update(); } char *CServer::GetMapName() { // get the name of the map without his path char *pMapShortName = &g_Config.m_SvMap[0]; for(int i = 0; i < str_length(g_Config.m_SvMap)-1; i++) { if(g_Config.m_SvMap[i] == '/' || g_Config.m_SvMap[i] == '\\') pMapShortName = &g_Config.m_SvMap[i+1]; } return pMapShortName; } int CServer::LoadMap(const char *pMapName) { //DATAFILE *df; char aBuf[512]; str_format(aBuf, sizeof(aBuf), "maps/%s.map", pMapName); /*df = datafile_load(buf); if(!df) return 0;*/ // check for valid standard map if(!m_MapChecker.ReadAndValidateMap(Storage(), aBuf, IStorage::TYPE_ALL)) { Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "mapchecker", "invalid standard map"); return 0; } if(!m_pMap->Load(aBuf)) return 0; // stop recording when we change map m_DemoRecorder.Stop(); // reinit snapshot ids m_IDPool.TimeoutIDs(); // get the crc of the map m_CurrentMapCrc = m_pMap->Crc(); char aBufMsg[256]; str_format(aBufMsg, sizeof(aBufMsg), "%s crc is %08x", aBuf, m_CurrentMapCrc); Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "server", aBufMsg); str_copy(m_aCurrentMap, pMapName, sizeof(m_aCurrentMap)); //map_set(df); // load complete map into memory for download { IOHANDLE File = Storage()->OpenFile(aBuf, IOFLAG_READ, IStorage::TYPE_ALL); m_CurrentMapSize = (int)io_length(File); if(m_pCurrentMapData) mem_free(m_pCurrentMapData); m_pCurrentMapData = (unsigned char *)mem_alloc(m_CurrentMapSize, 1); io_read(File, m_pCurrentMapData, m_CurrentMapSize); io_close(File); } return 1; } void CServer::InitRegister(CNetServer *pNetServer, IEngineMasterServer *pMasterServer, IConsole *pConsole) { m_Register.Init(pNetServer, pMasterServer, pConsole); } int CServer::Run() { // m_PrintCBIndex = Console()->RegisterPrintCallback(g_Config.m_ConsoleOutputLevel, SendRconLineAuthed, this); // load map if(!LoadMap(g_Config.m_SvMap)) { dbg_msg("server", "failed to load map. mapname='%s'", g_Config.m_SvMap); return -1; } m_MapChunksPerRequest = g_Config.m_SvMapDownloadSpeed; // start server NETADDR BindAddr; if(g_Config.m_Bindaddr[0] && net_host_lookup(g_Config.m_Bindaddr, &BindAddr, NETTYPE_ALL) == 0) { // sweet! BindAddr.type = NETTYPE_ALL; BindAddr.port = g_Config.m_SvPort; } else { mem_zero(&BindAddr, sizeof(BindAddr)); BindAddr.type = NETTYPE_ALL; BindAddr.port = g_Config.m_SvPort; } if(!m_NetServer.Open(BindAddr, &m_ServerBan, g_Config.m_SvMaxClients, g_Config.m_SvMaxClientsPerIP, 0)) { dbg_msg("server", "couldn't open socket. port %d might already be in use", g_Config.m_SvPort); return -1; } m_NetServer.SetCallbacks(NewClientCallback, DelClientCallback, this); m_Econ.Init(Console(), &m_ServerBan); char aBuf[256]; str_format(aBuf, sizeof(aBuf), "server name is '%s'", g_Config.m_SvName); Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); GameServer()->OnInit(); str_format(aBuf, sizeof(aBuf), "version %s", GameServer()->NetVersion()); Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); // process pending commands m_pConsole->StoreCommands(false); // start game { int64 ReportTime = time_get(); int ReportInterval = 3; m_Lastheartbeat = 0; m_GameStartTime = time_get(); if(g_Config.m_Debug) { str_format(aBuf, sizeof(aBuf), "baseline memory usage %dk", mem_stats()->allocated/1024); Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "server", aBuf); } while(m_RunServer) { int64 t = time_get(); int NewTicks = 0; // load new map TODO: don't poll this if(str_comp(g_Config.m_SvMap, m_aCurrentMap) != 0 || m_MapReload || m_CurrentGameTick >= 0x6FFFFFFF) // force reload to make sure the ticks stay within a valid range { m_MapReload = 0; // load map if(LoadMap(g_Config.m_SvMap)) { // new map loaded GameServer()->OnShutdown(); for(int c = 0; c < MAX_CLIENTS; c++) { if(m_aClients[c].m_State <= CClient::STATE_AUTH) continue; SendMap(c); m_aClients[c].Reset(); m_aClients[c].m_State = CClient::STATE_CONNECTING; } m_GameStartTime = time_get(); m_CurrentGameTick = 0; Kernel()->ReregisterInterface(GameServer()); GameServer()->OnInit(); UpdateServerInfo(); } else { str_format(aBuf, sizeof(aBuf), "failed to load map. mapname='%s'", g_Config.m_SvMap); Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); str_copy(g_Config.m_SvMap, m_aCurrentMap, sizeof(g_Config.m_SvMap)); } } while(t > TickStartTime(m_CurrentGameTick+1)) { m_CurrentGameTick++; NewTicks++; // apply new input for(int c = 0; c < MAX_CLIENTS; c++) { if(m_aClients[c].m_State == CClient::STATE_EMPTY) continue; for(int i = 0; i < 200; i++) { if(m_aClients[c].m_aInputs[i].m_GameTick == Tick()) { if(m_aClients[c].m_State == CClient::STATE_INGAME) GameServer()->OnClientPredictedInput(c, m_aClients[c].m_aInputs[i].m_aData); break; } } } GameServer()->OnTick(); } // snap game if(NewTicks) { if(g_Config.m_SvHighBandwidth || (m_CurrentGameTick%2) == 0) DoSnapshot(); UpdateClientRconCommands(); } // master server stuff m_Register.RegisterUpdate(m_NetServer.NetType()); PumpNetwork(); if(ReportTime < time_get()) { if(g_Config.m_Debug) { /* static NETSTATS prev_stats; NETSTATS stats; netserver_stats(net, &stats); perf_next(); if(config.dbg_pref) perf_dump(&rootscope); dbg_msg("server", "send=%8d recv=%8d", (stats.send_bytes - prev_stats.send_bytes)/reportinterval, (stats.recv_bytes - prev_stats.recv_bytes)/reportinterval); prev_stats = stats; */ } ReportTime += time_freq()*ReportInterval; } // wait for incomming data net_socket_read_wait(m_NetServer.Socket(), 5); } } // disconnect all clients on shutdown for(int i = 0; i < MAX_CLIENTS; ++i) { if(m_aClients[i].m_State != CClient::STATE_EMPTY) m_NetServer.Drop(i, "Server shutdown"); m_Econ.Shutdown(); } GameServer()->OnShutdown(); m_pMap->Unload(); if(m_pCurrentMapData) mem_free(m_pCurrentMapData); return 0; } void CServer::ConKick(IConsole::IResult *pResult, void *pUser) { if(pResult->NumArguments() > 1) { char aBuf[128]; str_format(aBuf, sizeof(aBuf), "Kicked (%s)", pResult->GetString(1)); ((CServer *)pUser)->Kick(pResult->GetInteger(0), aBuf); } else ((CServer *)pUser)->Kick(pResult->GetInteger(0), "Kicked by console"); } void CServer::ConStatus(IConsole::IResult *pResult, void *pUser) { char aBuf[1024]; char aAddrStr[NETADDR_MAXSTRSIZE]; CServer* pThis = static_cast<CServer *>(pUser); for(int i = 0; i < MAX_CLIENTS; i++) { if(pThis->m_aClients[i].m_State != CClient::STATE_EMPTY) { net_addr_str(pThis->m_NetServer.ClientAddr(i), aAddrStr, sizeof(aAddrStr), true); if(pThis->m_aClients[i].m_State == CClient::STATE_INGAME) { const char *pAuthStr = pThis->m_aClients[i].m_Authed == CServer::AUTHED_ADMIN ? "(Admin)" : pThis->m_aClients[i].m_Authed == CServer::AUTHED_MOD ? "(Mod)" : ""; str_format(aBuf, sizeof(aBuf), "id=%d addr=%s name='%s' score=%d %s", i, aAddrStr, pThis->m_aClients[i].m_aName, pThis->m_aClients[i].m_Score, pAuthStr); } else str_format(aBuf, sizeof(aBuf), "id=%d addr=%s connecting", i, aAddrStr); pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "Server", aBuf); } } } void CServer::ConShutdown(IConsole::IResult *pResult, void *pUser) { ((CServer *)pUser)->m_RunServer = 0; } void CServer::DemoRecorder_HandleAutoStart() { if(g_Config.m_SvAutoDemoRecord) { m_DemoRecorder.Stop(); char aFilename[128]; char aDate[20]; str_timestamp(aDate, sizeof(aDate)); str_format(aFilename, sizeof(aFilename), "demos/%s_%s.demo", "auto/autorecord", aDate); m_DemoRecorder.Start(Storage(), m_pConsole, aFilename, GameServer()->NetVersion(), m_aCurrentMap, m_CurrentMapCrc, "server"); if(g_Config.m_SvAutoDemoMax) { // clean up auto recorded demos CFileCollection AutoDemos; AutoDemos.Init(Storage(), "demos/server", "autorecord", ".demo", g_Config.m_SvAutoDemoMax); } } } bool CServer::DemoRecorder_IsRecording() { return m_DemoRecorder.IsRecording(); } void CServer::ConRecord(IConsole::IResult *pResult, void *pUser) { CServer* pServer = (CServer *)pUser; char aFilename[128]; if(pResult->NumArguments()) str_format(aFilename, sizeof(aFilename), "demos/%s.demo", pResult->GetString(0)); else { char aDate[20]; str_timestamp(aDate, sizeof(aDate)); str_format(aFilename, sizeof(aFilename), "demos/demo_%s.demo", aDate); } pServer->m_DemoRecorder.Start(pServer->Storage(), pServer->Console(), aFilename, pServer->GameServer()->NetVersion(), pServer->m_aCurrentMap, pServer->m_CurrentMapCrc, "server"); } void CServer::ConStopRecord(IConsole::IResult *pResult, void *pUser) { ((CServer *)pUser)->m_DemoRecorder.Stop(); } void CServer::ConMapReload(IConsole::IResult *pResult, void *pUser) { ((CServer *)pUser)->m_MapReload = 1; } void CServer::ConLogout(IConsole::IResult *pResult, void *pUser) { CServer *pServer = (CServer *)pUser; if(pServer->m_RconClientID >= 0 && pServer->m_RconClientID < MAX_CLIENTS && pServer->m_aClients[pServer->m_RconClientID].m_State != CServer::CClient::STATE_EMPTY) { CMsgPacker Msg(NETMSG_RCON_AUTH_OFF, true); pServer->SendMsg(&Msg, MSGFLAG_VITAL, pServer->m_RconClientID); pServer->m_aClients[pServer->m_RconClientID].m_Authed = AUTHED_NO; pServer->m_aClients[pServer->m_RconClientID].m_AuthTries = 0; pServer->m_aClients[pServer->m_RconClientID].m_pRconCmdToSend = 0; pServer->SendRconLine(pServer->m_RconClientID, "Logout successful."); char aBuf[32]; str_format(aBuf, sizeof(aBuf), "ClientID=%d logged out", pServer->m_RconClientID); pServer->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); } } void CServer::ConchainSpecialInfoupdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData) { pfnCallback(pResult, pCallbackUserData); if(pResult->NumArguments()) ((CServer *)pUserData)->UpdateServerInfo(); } void CServer::ConchainMaxclientsperipUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData) { pfnCallback(pResult, pCallbackUserData); if(pResult->NumArguments()) ((CServer *)pUserData)->m_NetServer.SetMaxClientsPerIP(pResult->GetInteger(0)); } void CServer::ConchainModCommandUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData) { if(pResult->NumArguments() == 2) { CServer *pThis = static_cast<CServer *>(pUserData); const IConsole::CCommandInfo *pInfo = pThis->Console()->GetCommandInfo(pResult->GetString(0), CFGFLAG_SERVER, false); int OldAccessLevel = 0; if(pInfo) OldAccessLevel = pInfo->GetAccessLevel(); pfnCallback(pResult, pCallbackUserData); if(pInfo && OldAccessLevel != pInfo->GetAccessLevel()) { for(int i = 0; i < MAX_CLIENTS; ++i) { if(pThis->m_aClients[i].m_State == CServer::CClient::STATE_EMPTY || pThis->m_aClients[i].m_Authed != CServer::AUTHED_MOD || (pThis->m_aClients[i].m_pRconCmdToSend && str_comp(pResult->GetString(0), pThis->m_aClients[i].m_pRconCmdToSend->m_pName) >= 0)) continue; if(OldAccessLevel == IConsole::ACCESS_LEVEL_ADMIN) pThis->SendRconCmdAdd(pInfo, i); else pThis->SendRconCmdRem(pInfo, i); } } } else pfnCallback(pResult, pCallbackUserData); } void CServer::ConchainConsoleOutputLevelUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData) { pfnCallback(pResult, pCallbackUserData); if(pResult->NumArguments() == 1) { CServer *pThis = static_cast<CServer *>(pUserData); pThis->Console()->SetPrintOutputLevel(pThis->m_PrintCBIndex, pResult->GetInteger(0)); } } void CServer::RegisterCommands() { m_pConsole = Kernel()->RequestInterface<IConsole>(); m_pGameServer = Kernel()->RequestInterface<IGameServer>(); m_pMap = Kernel()->RequestInterface<IEngineMap>(); m_pStorage = Kernel()->RequestInterface<IStorage>(); // register console commands Console()->Register("kick", "i?r", CFGFLAG_SERVER, ConKick, this, "Kick player with specified id for any reason"); Console()->Register("status", "", CFGFLAG_SERVER, ConStatus, this, "List players"); Console()->Register("shutdown", "", CFGFLAG_SERVER, ConShutdown, this, "Shut down"); Console()->Register("logout", "", CFGFLAG_SERVER, ConLogout, this, "Logout of rcon"); Console()->Register("record", "?s", CFGFLAG_SERVER|CFGFLAG_STORE, ConRecord, this, "Record to a file"); Console()->Register("stoprecord", "", CFGFLAG_SERVER, ConStopRecord, this, "Stop recording"); Console()->Register("reload", "", CFGFLAG_SERVER, ConMapReload, this, "Reload the map"); Console()->Chain("sv_name", ConchainSpecialInfoupdate, this); Console()->Chain("password", ConchainSpecialInfoupdate, this); Console()->Chain("sv_max_clients_per_ip", ConchainMaxclientsperipUpdate, this); Console()->Chain("mod_command", ConchainModCommandUpdate, this); Console()->Chain("console_output_level", ConchainConsoleOutputLevelUpdate, this); // register console commands in sub parts m_ServerBan.InitServerBan(Console(), Storage(), this); m_pGameServer->OnConsoleInit(); } int CServer::SnapNewID() { return m_IDPool.NewID(); } void CServer::SnapFreeID(int ID) { m_IDPool.FreeID(ID); } void *CServer::SnapNewItem(int Type, int ID, int Size) { dbg_assert(Type >= 0 && Type <=0xffff, "incorrect type"); dbg_assert(ID >= 0 && ID <=0xffff, "incorrect id"); return ID < 0 ? 0 : m_SnapshotBuilder.NewItem(Type, ID, Size); } void CServer::SnapSetStaticsize(int ItemType, int Size) { m_SnapshotDelta.SetStaticsize(ItemType, Size); } static CServer *CreateServer() { return new CServer(); } int main(int argc, const char **argv) // ignore_convention { #if defined(CONF_FAMILY_WINDOWS) for(int i = 1; i < argc; i++) // ignore_convention { if(str_comp("-s", argv[i]) == 0 || str_comp("--silent", argv[i]) == 0) // ignore_convention { ShowWindow(GetConsoleWindow(), SW_HIDE); break; } } #endif CServer *pServer = CreateServer(); IKernel *pKernel = IKernel::Create(); // create the components IEngine *pEngine = CreateEngine("Teeworlds"); IEngineMap *pEngineMap = CreateEngineMap(); IGameServer *pGameServer = CreateGameServer(); IConsole *pConsole = CreateConsole(CFGFLAG_SERVER|CFGFLAG_ECON); IEngineMasterServer *pEngineMasterServer = CreateEngineMasterServer(); IStorage *pStorage = CreateStorage("Teeworlds", IStorage::STORAGETYPE_SERVER, argc, argv); // ignore_convention IConfig *pConfig = CreateConfig(); pServer->InitRegister(&pServer->m_NetServer, pEngineMasterServer, pConsole); { bool RegisterFail = false; RegisterFail = RegisterFail || !pKernel->RegisterInterface(pServer); // register as both RegisterFail = RegisterFail || !pKernel->RegisterInterface(pEngine); RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<IEngineMap*>(pEngineMap)); // register as both RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<IMap*>(pEngineMap)); RegisterFail = RegisterFail || !pKernel->RegisterInterface(pGameServer); RegisterFail = RegisterFail || !pKernel->RegisterInterface(pConsole); RegisterFail = RegisterFail || !pKernel->RegisterInterface(pStorage); RegisterFail = RegisterFail || !pKernel->RegisterInterface(pConfig); RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<IEngineMasterServer*>(pEngineMasterServer)); // register as both RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<IMasterServer*>(pEngineMasterServer)); if(RegisterFail) return -1; } pEngine->Init(); pConfig->Init(); pEngineMasterServer->Init(); pEngineMasterServer->Load(); // register all console commands pServer->RegisterCommands(); // execute autoexec file pConsole->ExecuteFile("autoexec.cfg"); // parse the command line arguments if(argc > 1) // ignore_convention pConsole->ParseArguments(argc-1, &argv[1]); // ignore_convention // restore empty config strings to their defaults pConfig->RestoreStrings(); pEngine->InitLogfile(); // run the server dbg_msg("server", "starting..."); pServer->Run(); // free delete pServer; delete pKernel; delete pEngine; delete pEngineMap; delete pGameServer; delete pConsole; delete pEngineMasterServer; delete pStorage; delete pConfig; return 0; } ================================================ FILE: src/engine/server/server.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef ENGINE_SERVER_SERVER_H #define ENGINE_SERVER_SERVER_H #include <engine/server.h> class CSnapIDPool { enum { MAX_IDS = 16*1024, }; class CID { public: short m_Next; short m_State; // 0 = free, 1 = alloced, 2 = timed int m_Timeout; }; CID m_aIDs[MAX_IDS]; int m_FirstFree; int m_FirstTimed; int m_LastTimed; int m_Usage; int m_InUsage; public: CSnapIDPool(); void Reset(); void RemoveFirstTimeout(); int NewID(); void TimeoutIDs(); void FreeID(int ID); }; class CServerBan : public CNetBan { class CServer *m_pServer; template<class T> int BanExt(T *pBanPool, const typename T::CDataType *pData, int Seconds, const char *pReason); public: class CServer *Server() const { return m_pServer; } void InitServerBan(class IConsole *pConsole, class IStorage *pStorage, class CServer* pServer); virtual int BanAddr(const NETADDR *pAddr, int Seconds, const char *pReason); virtual int BanRange(const CNetRange *pRange, int Seconds, const char *pReason); static void ConBanExt(class IConsole::IResult *pResult, void *pUser); }; class CServer : public IServer { class IGameServer *m_pGameServer; class IConsole *m_pConsole; class IStorage *m_pStorage; public: class IGameServer *GameServer() { return m_pGameServer; } class IConsole *Console() { return m_pConsole; } class IStorage *Storage() { return m_pStorage; } enum { AUTHED_NO=0, AUTHED_MOD, AUTHED_ADMIN, MAX_RCONCMD_SEND=16, }; class CClient { public: enum { STATE_EMPTY = 0, STATE_AUTH, STATE_CONNECTING, STATE_READY, STATE_INGAME, SNAPRATE_INIT=0, SNAPRATE_FULL, SNAPRATE_RECOVER }; class CInput { public: int m_aData[MAX_INPUT_SIZE]; int m_GameTick; // the tick that was chosen for the input }; // connection state info int m_State; int m_Latency; int m_SnapRate; int m_LastAckedSnapshot; int m_LastInputTick; CSnapshotStorage m_Snapshots; CInput m_LatestInput; CInput m_aInputs[200]; // TODO: handle input better int m_CurrentInput; char m_aName[MAX_NAME_LENGTH]; char m_aClan[MAX_CLAN_LENGTH]; int m_Country; int m_Score; int m_Authed; int m_AuthTries; int m_MapChunk; bool m_Quitting; const IConsole::CCommandInfo *m_pRconCmdToSend; void Reset(); }; CClient m_aClients[MAX_CLIENTS]; CSnapshotDelta m_SnapshotDelta; CSnapshotBuilder m_SnapshotBuilder; CSnapIDPool m_IDPool; CNetServer m_NetServer; CEcon m_Econ; CServerBan m_ServerBan; IEngineMap *m_pMap; int64 m_GameStartTime; //int m_CurrentGameTick; int m_RunServer; int m_MapReload; int m_RconClientID; int m_RconAuthLevel; int m_PrintCBIndex; int64 m_Lastheartbeat; //static NETADDR4 master_server; // map enum { MAP_CHUNK_SIZE=NET_MAX_PAYLOAD-NET_MAX_CHUNKHEADERSIZE-4, // msg type }; char m_aCurrentMap[64]; unsigned m_CurrentMapCrc; unsigned char *m_pCurrentMapData; int m_CurrentMapSize; int m_MapChunksPerRequest; CDemoRecorder m_DemoRecorder; CRegister m_Register; CMapChecker m_MapChecker; CServer(); int TrySetClientName(int ClientID, const char *pName); virtual void SetClientName(int ClientID, const char *pName); virtual void SetClientClan(int ClientID, char const *pClan); virtual void SetClientCountry(int ClientID, int Country); virtual void SetClientScore(int ClientID, int Score); void Kick(int ClientID, const char *pReason); void DemoRecorder_HandleAutoStart(); bool DemoRecorder_IsRecording(); //int Tick() int64 TickStartTime(int Tick); //int TickSpeed() int Init(); void SetRconCID(int ClientID); bool IsAuthed(int ClientID); bool IsBanned(int ClientID); int GetClientInfo(int ClientID, CClientInfo *pInfo); void GetClientAddr(int ClientID, char *pAddrStr, int Size); const char *ClientName(int ClientID); const char *ClientClan(int ClientID); int ClientCountry(int ClientID); bool ClientIngame(int ClientID); int MaxClients() const; virtual int SendMsg(CMsgPacker *pMsg, int Flags, int ClientID); void DoSnapshot(); static int NewClientCallback(int ClientID, void *pUser); static int DelClientCallback(int ClientID, const char *pReason, void *pUser); void SendMap(int ClientID); void SendConnectionReady(int ClientID); void SendRconLine(int ClientID, const char *pLine); static void SendRconLineAuthed(const char *pLine, void *pUser); void SendRconCmdAdd(const IConsole::CCommandInfo *pCommandInfo, int ClientID); void SendRconCmdRem(const IConsole::CCommandInfo *pCommandInfo, int ClientID); void UpdateClientRconCommands(); void ProcessClientPacket(CNetChunk *pPacket); void SendServerInfo(const NETADDR *pAddr, int Token); void UpdateServerInfo(); void PumpNetwork(); char *GetMapName(); int LoadMap(const char *pMapName); void InitRegister(CNetServer *pNetServer, IEngineMasterServer *pMasterServer, IConsole *pConsole); int Run(); static void ConKick(IConsole::IResult *pResult, void *pUser); static void ConStatus(IConsole::IResult *pResult, void *pUser); static void ConShutdown(IConsole::IResult *pResult, void *pUser); static void ConRecord(IConsole::IResult *pResult, void *pUser); static void ConStopRecord(IConsole::IResult *pResult, void *pUser); static void ConMapReload(IConsole::IResult *pResult, void *pUser); static void ConLogout(IConsole::IResult *pResult, void *pUser); static void ConchainSpecialInfoupdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData); static void ConchainMaxclientsperipUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData); static void ConchainModCommandUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData); static void ConchainConsoleOutputLevelUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData); void RegisterCommands(); virtual int SnapNewID(); virtual void SnapFreeID(int ID); virtual void *SnapNewItem(int Type, int ID, int Size); void SnapSetStaticsize(int ItemType, int Size); }; #endif ================================================ FILE: src/engine/server.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef ENGINE_SERVER_H #define ENGINE_SERVER_H #include "kernel.h" #include "message.h" class IServer : public IInterface { MACRO_INTERFACE("server", 0) protected: int m_CurrentGameTick; int m_TickSpeed; public: /* Structure: CClientInfo */ struct CClientInfo { const char *m_pName; int m_Latency; }; int Tick() const { return m_CurrentGameTick; } int TickSpeed() const { return m_TickSpeed; } virtual int MaxClients() const = 0; virtual const char *ClientName(int ClientID) = 0; virtual const char *ClientClan(int ClientID) = 0; virtual int ClientCountry(int ClientID) = 0; virtual bool ClientIngame(int ClientID) = 0; virtual int GetClientInfo(int ClientID, CClientInfo *pInfo) = 0; virtual void GetClientAddr(int ClientID, char *pAddrStr, int Size) = 0; virtual int SendMsg(CMsgPacker *pMsg, int Flags, int ClientID) = 0; template<class T> int SendPackMsg(T *pMsg, int Flags, int ClientID) { CMsgPacker Packer(pMsg->MsgID(), false); if(pMsg->Pack(&Packer)) return -1; return SendMsg(&Packer, Flags, ClientID); } virtual void SetClientName(int ClientID, char const *pName) = 0; virtual void SetClientClan(int ClientID, char const *pClan) = 0; virtual void SetClientCountry(int ClientID, int Country) = 0; virtual void SetClientScore(int ClientID, int Score) = 0; virtual int SnapNewID() = 0; virtual void SnapFreeID(int ID) = 0; virtual void *SnapNewItem(int Type, int ID, int Size) = 0; virtual void SnapSetStaticsize(int ItemType, int Size) = 0; enum { RCON_CID_SERV=-1, RCON_CID_VOTE=-2, }; virtual void SetRconCID(int ClientID) = 0; virtual bool IsAuthed(int ClientID) = 0; virtual bool IsBanned(int ClientID) = 0; virtual void Kick(int ClientID, const char *pReason) = 0; virtual void DemoRecorder_HandleAutoStart() = 0; virtual bool DemoRecorder_IsRecording() = 0; }; class IGameServer : public IInterface { MACRO_INTERFACE("gameserver", 0) protected: public: virtual void OnInit() = 0; virtual void OnConsoleInit() = 0; virtual void OnShutdown() = 0; virtual void OnTick() = 0; virtual void OnPreSnap() = 0; virtual void OnSnap(int ClientID) = 0; virtual void OnPostSnap() = 0; virtual void OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID) = 0; virtual void OnClientConnected(int ClientID) = 0; virtual void OnClientEnter(int ClientID) = 0; virtual void OnClientDrop(int ClientID, const char *pReason) = 0; virtual void OnClientDirectInput(int ClientID, void *pInput) = 0; virtual void OnClientPredictedInput(int ClientID, void *pInput) = 0; virtual bool IsClientReady(int ClientID) = 0; virtual bool IsClientPlayer(int ClientID) = 0; virtual const char *GameType() = 0; virtual const char *Version() = 0; virtual const char *NetVersion() = 0; }; extern IGameServer *CreateGameServer(); #endif ================================================ FILE: src/engine/serverbrowser.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef ENGINE_SERVERBROWSER_H #define ENGINE_SERVERBROWSER_H #include <engine/shared/protocol.h> #include "kernel.h" /* Structure: CServerInfo */ class CServerInfo { public: /* Structure: CInfoClient */ class CClient { public: char m_aName[MAX_NAME_LENGTH]; char m_aClan[MAX_CLAN_LENGTH]; int m_Country; int m_Score; bool m_Player; int m_FriendState; }; //int m_SortedIndex; int m_ServerIndex; NETADDR m_NetAddr; int m_QuickSearchHit; int m_FriendState; int m_MaxClients; int m_NumClients; int m_MaxPlayers; int m_NumPlayers; int m_Flags; int m_ServerLevel; int m_Favorite; int m_Latency; // in ms char m_aGameType[16]; char m_aName[64]; char m_aHostname[128]; char m_aMap[32]; char m_aVersion[32]; char m_aAddress[NETADDR_MAXSTRSIZE]; CClient m_aClients[MAX_CLIENTS]; }; class IServerBrowser : public IInterface { MACRO_INTERFACE("serverbrowser", 0) public: /* Constants: Server Browser Sorting SORT_NAME - Sort by name. SORT_PING - Sort by ping. SORT_MAP - Sort by map SORT_GAMETYPE - Sort by game type. DM, TDM etc. SORT_NUMPLAYERS - Sort after how many players there are on the server. */ enum{ SORT_NAME = 0, SORT_PING, SORT_MAP, SORT_GAMETYPE, SORT_NUMPLAYERS, QUICK_SERVERNAME=1, QUICK_PLAYER=2, QUICK_MAPNAME=4, TYPE_INTERNET = 0, TYPE_LAN = 1, FLAG_PASSWORD =1, FLAG_PURE =2, FLAG_PUREMAP =4, FILTER_EMPTY=32, FILTER_FULL=64, FILTER_SPECTATORS=128, FILTER_FRIENDS=256, FILTER_PW=512, FILTER_FAVORITE=1024, FILTER_COMPAT_VERSION=2048, FILTER_PURE=4096, FILTER_PURE_MAP=8192, FILTER_GAMETYPE_STRICT=16384, FILTER_COUNTRY=32768, FILTER_PING=65536, }; virtual void Refresh(int Type) = 0; virtual bool IsRefreshing() const = 0; virtual bool IsRefreshingMasters() const = 0; virtual int LoadingProgression() const = 0; virtual int NumServers() const = 0; virtual int NumPlayers() const = 0; virtual int NumSortedServers(int Index) const = 0; virtual int NumSortedPlayers(int Index) const = 0; virtual const CServerInfo *SortedGet(int FilterIndex, int Index) const = 0; virtual const void *GetID(int FilterIndex, int Index) const = 0; virtual bool IsFavorite(const NETADDR &Addr) = 0; // todo: remove this virtual void AddFavorite(const CServerInfo *pEntry) = 0; virtual void RemoveFavorite(const CServerInfo *pEntry) = 0; virtual int AddFilter(int Flag, int Ping, int Country, const char* pGametype, const char* pServerAddress) = 0; virtual void SetFilter(int Index, int SortHash, int Ping, int Country, const char* pGametype, const char* pServerAddress) = 0; virtual void GetFilter(int Index, int *pSortHash, int *pPing, int *pCountry, char* pGametype, char* pServerAddress) = 0; virtual void RemoveFilter(int Index) = 0; }; #endif ================================================ FILE: src/engine/shared/compression.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <base/system.h> #include "compression.h" // Format: ESDDDDDD EDDDDDDD EDD... Extended, Data, Sign unsigned char *CVariableInt::Pack(unsigned char *pDst, int i) { *pDst = (i>>25)&0x40; // set sign bit if i<0 i = i^(i>>31); // if(i<0) i = ~i *pDst |= i&0x3F; // pack 6bit into dst i >>= 6; // discard 6 bits if(i) { *pDst |= 0x80; // set extend bit while(1) { pDst++; *pDst = i&(0x7F); // pack 7bit i >>= 7; // discard 7 bits *pDst |= (i!=0)<<7; // set extend bit (may branch) if(!i) break; } } pDst++; return pDst; } const unsigned char *CVariableInt::Unpack(const unsigned char *pSrc, int *pInOut) { int Sign = (*pSrc>>6)&1; *pInOut = *pSrc&0x3F; do { if(!(*pSrc&0x80)) break; pSrc++; *pInOut |= (*pSrc&(0x7F))<<(6); if(!(*pSrc&0x80)) break; pSrc++; *pInOut |= (*pSrc&(0x7F))<<(6+7); if(!(*pSrc&0x80)) break; pSrc++; *pInOut |= (*pSrc&(0x7F))<<(6+7+7); if(!(*pSrc&0x80)) break; pSrc++; *pInOut |= (*pSrc&(0x7F))<<(6+7+7+7); } while(0); pSrc++; *pInOut ^= -Sign; // if(sign) *i = ~(*i) return pSrc; } long CVariableInt::Decompress(const void *pSrc_, int Size, void *pDst_) { const unsigned char *pSrc = (unsigned char *)pSrc_; const unsigned char *pEnd = pSrc + Size; int *pDst = (int *)pDst_; while(pSrc < pEnd) { pSrc = CVariableInt::Unpack(pSrc, pDst); pDst++; } return (long)((unsigned char *)pDst-(unsigned char *)pDst_); } long CVariableInt::Compress(const void *pSrc_, int Size, void *pDst_) { int *pSrc = (int *)pSrc_; unsigned char *pDst = (unsigned char *)pDst_; Size /= 4; while(Size) { pDst = CVariableInt::Pack(pDst, *pSrc); Size--; pSrc++; } return (long)(pDst-(unsigned char *)pDst_); } ================================================ FILE: src/engine/shared/compression.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef ENGINE_SHARED_COMPRESSION_H #define ENGINE_SHARED_COMPRESSION_H // variable int packing class CVariableInt { public: static unsigned char *Pack(unsigned char *pDst, int i); static const unsigned char *Unpack(const unsigned char *pSrc, int *pInOut); static long Compress(const void *pSrc, int Size, void *pDst); static long Decompress(const void *pSrc, int Size, void *pDst); }; #endif ================================================ FILE: src/engine/shared/config.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <engine/config.h> #include <engine/storage.h> #include <engine/shared/config.h> CConfiguration g_Config; class CConfig : public IConfig { IStorage *m_pStorage; IOHANDLE m_ConfigFile; struct CCallback { SAVECALLBACKFUNC m_pfnFunc; void *m_pUserData; }; enum { MAX_CALLBACKS = 16 }; CCallback m_aCallbacks[MAX_CALLBACKS]; int m_NumCallbacks; void EscapeParam(char *pDst, const char *pSrc, int size) { for(int i = 0; *pSrc && i < size - 1; ++i) { if(*pSrc == '"' || *pSrc == '\\') // escape \ and " *pDst++ = '\\'; *pDst++ = *pSrc++; } *pDst = 0; } public: CConfig() { m_ConfigFile = 0; m_NumCallbacks = 0; } virtual void Init() { m_pStorage = Kernel()->RequestInterface<IStorage>(); Reset(); } virtual void Reset() { #define MACRO_CONFIG_INT(Name,ScriptName,def,min,max,flags,desc) g_Config.m_##Name = def; #define MACRO_CONFIG_STR(Name,ScriptName,len,def,flags,desc) str_copy(g_Config.m_##Name, def, len); #include "config_variables.h" #undef MACRO_CONFIG_INT #undef MACRO_CONFIG_STR } virtual void RestoreStrings() { #define MACRO_CONFIG_INT(Name,ScriptName,def,min,max,flags,desc) // nop #define MACRO_CONFIG_STR(Name,ScriptName,len,def,flags,desc) if(!g_Config.m_##Name[0] && def[0]) str_copy(g_Config.m_##Name, def, len); #include "config_variables.h" #undef MACRO_CONFIG_INT #undef MACRO_CONFIG_STR } virtual void Save() { if(!m_pStorage) return; m_ConfigFile = m_pStorage->OpenFile("settings.cfg", IOFLAG_WRITE, IStorage::TYPE_SAVE); if(!m_ConfigFile) return; char aLineBuf[1024*2]; char aEscapeBuf[1024*2]; #define MACRO_CONFIG_INT(Name,ScriptName,def,min,max,flags,desc) if((flags)&CFGFLAG_SAVE){ str_format(aLineBuf, sizeof(aLineBuf), "%s %i", #ScriptName, g_Config.m_##Name); WriteLine(aLineBuf); } #define MACRO_CONFIG_STR(Name,ScriptName,len,def,flags,desc) if((flags)&CFGFLAG_SAVE){ EscapeParam(aEscapeBuf, g_Config.m_##Name, sizeof(aEscapeBuf)); str_format(aLineBuf, sizeof(aLineBuf), "%s \"%s\"", #ScriptName, aEscapeBuf); WriteLine(aLineBuf); } #include "config_variables.h" #undef MACRO_CONFIG_INT #undef MACRO_CONFIG_STR for(int i = 0; i < m_NumCallbacks; i++) m_aCallbacks[i].m_pfnFunc(this, m_aCallbacks[i].m_pUserData); io_close(m_ConfigFile); m_ConfigFile = 0; } virtual void RegisterCallback(SAVECALLBACKFUNC pfnFunc, void *pUserData) { dbg_assert(m_NumCallbacks < MAX_CALLBACKS, "too many config callbacks"); m_aCallbacks[m_NumCallbacks].m_pfnFunc = pfnFunc; m_aCallbacks[m_NumCallbacks].m_pUserData = pUserData; m_NumCallbacks++; } virtual void WriteLine(const char *pLine) { if(!m_ConfigFile) return; io_write(m_ConfigFile, pLine, str_length(pLine)); io_write_newline(m_ConfigFile); } }; IConfig *CreateConfig() { return new CConfig; } ================================================ FILE: src/engine/shared/config.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef ENGINE_SHARED_CONFIG_H #define ENGINE_SHARED_CONFIG_H struct CConfiguration { #define MACRO_CONFIG_INT(Name,ScriptName,Def,Min,Max,Save,Desc) int m_##Name; #define MACRO_CONFIG_STR(Name,ScriptName,Len,Def,Save,Desc) char m_##Name[Len]; // Flawfinder: ignore #include "config_variables.h" #undef MACRO_CONFIG_INT #undef MACRO_CONFIG_STR }; extern CConfiguration g_Config; enum { CFGFLAG_SAVE=1, CFGFLAG_CLIENT=2, CFGFLAG_SERVER=4, CFGFLAG_STORE=8, CFGFLAG_MASTER=16, CFGFLAG_ECON=32, }; #endif ================================================ FILE: src/engine/shared/config_variables.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef ENGINE_SHARED_CONFIG_VARIABLES_H #define ENGINE_SHARED_CONFIG_VARIABLES_H #undef ENGINE_SHARED_CONFIG_VARIABLES_H // this file will be included several times // TODO: remove this #include "././game/variables.h" MACRO_CONFIG_STR(PlayerName, player_name, 16, "nameless tee", CFGFLAG_SAVE|CFGFLAG_CLIENT, "Name of the player") MACRO_CONFIG_STR(PlayerClan, player_clan, 12, "", CFGFLAG_SAVE|CFGFLAG_CLIENT, "Clan of the player") MACRO_CONFIG_INT(PlayerCountry, player_country, -1, -1, 1000, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Country of the player") MACRO_CONFIG_STR(Password, password, 32, "", CFGFLAG_CLIENT|CFGFLAG_SERVER, "Password to the server") MACRO_CONFIG_STR(Logfile, logfile, 128, "", CFGFLAG_SAVE|CFGFLAG_CLIENT|CFGFLAG_SERVER, "Filename to log all output to") MACRO_CONFIG_INT(ConsoleOutputLevel, console_output_level, 0, 0, 2, CFGFLAG_CLIENT|CFGFLAG_SERVER, "Adjusts the amount of information in the console") MACRO_CONFIG_INT(ClCpuThrottle, cl_cpu_throttle, 0, 0, 100, CFGFLAG_SAVE|CFGFLAG_CLIENT, "") MACRO_CONFIG_INT(ClEditor, cl_editor, 0, 0, 1, CFGFLAG_CLIENT, "") MACRO_CONFIG_INT(ClLoadCountryFlags, cl_load_country_flags, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Load and show country flags") MACRO_CONFIG_INT(ClAutoDemoRecord, cl_auto_demo_record, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Automatically record demos") MACRO_CONFIG_INT(ClAutoDemoMax, cl_auto_demo_max, 10, 0, 1000, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Maximum number of automatically recorded demos (0 = no limit)") MACRO_CONFIG_INT(ClAutoScreenshot, cl_auto_screenshot, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Automatically take game over screenshot") MACRO_CONFIG_INT(ClAutoScreenshotMax, cl_auto_screenshot_max, 10, 0, 1000, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Maximum number of automatically created screenshots (0 = no limit)") MACRO_CONFIG_INT(ClEventthread, cl_eventthread, 0, 0, 1, CFGFLAG_CLIENT, "Enables the usage of a thread to pump the events") MACRO_CONFIG_INT(InpGrab, inp_grab, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Use forceful input grabbing method") MACRO_CONFIG_STR(BrFilterString, br_filter_string, 25, "", CFGFLAG_SAVE|CFGFLAG_CLIENT, "Server browser filtering string") MACRO_CONFIG_INT(BrFilterFull, br_filter_full, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Filter out full server in browser") MACRO_CONFIG_INT(BrFilterEmpty, br_filter_empty, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Filter out empty server in browser") MACRO_CONFIG_INT(BrFilterSpectators, br_filter_spectators, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Filter out spectators from player numbers") MACRO_CONFIG_INT(BrFilterFriends, br_filter_friends, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Filter out servers with no friends") MACRO_CONFIG_INT(BrFilterCountry, br_filter_country, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Filter out servers with non-matching player country") MACRO_CONFIG_INT(BrFilterCountryIndex, br_filter_country_index, -1, -1, 999, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Player country to filter by in the server browser") MACRO_CONFIG_INT(BrFilterPw, br_filter_pw, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Filter out password protected servers in browser") MACRO_CONFIG_INT(BrFilterPing, br_filter_ping, 999, 0, 999, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Ping to filter by in the server browser") MACRO_CONFIG_STR(BrFilterGametype, br_filter_gametype, 128, "", CFGFLAG_SAVE|CFGFLAG_CLIENT, "Game types to filter") MACRO_CONFIG_INT(BrFilterGametypeStrict, br_filter_gametype_strict, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Strict gametype filter") MACRO_CONFIG_STR(BrFilterServerAddress, br_filter_serveraddress, 128, "", CFGFLAG_SAVE|CFGFLAG_CLIENT, "Server address to filter") MACRO_CONFIG_INT(BrFilterPure, br_filter_pure, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Filter out non-standard servers in browser") MACRO_CONFIG_INT(BrFilterPureMap, br_filter_pure_map, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Filter out non-standard maps in browser") MACRO_CONFIG_INT(BrFilterCompatversion, br_filter_compatversion, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Filter out non-compatible servers in browser") MACRO_CONFIG_INT(BrSort, br_sort, 0, 0, 256, CFGFLAG_SAVE|CFGFLAG_CLIENT, "") MACRO_CONFIG_INT(BrSortOrder, br_sort_order, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "") MACRO_CONFIG_INT(BrMaxRequests, br_max_requests, 25, 0, 1000, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Number of requests to use when refreshing server browser") MACRO_CONFIG_INT(SndBufferSize, snd_buffer_size, 512, 128, 32768, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Sound buffer size") MACRO_CONFIG_INT(SndRate, snd_rate, 48000, 0, 0, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Sound mixing rate") MACRO_CONFIG_INT(SndEnable, snd_enable, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Sound enable") MACRO_CONFIG_INT(SndMusic, snd_enable_music, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Play background music") MACRO_CONFIG_INT(SndVolume, snd_volume, 100, 0, 100, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Sound volume") MACRO_CONFIG_INT(SndDevice, snd_device, -1, 0, 0, CFGFLAG_SAVE|CFGFLAG_CLIENT, "(deprecated) Sound device to use") MACRO_CONFIG_INT(SndNonactiveMute, snd_nonactive_mute, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "") MACRO_CONFIG_INT(GfxScreenWidth, gfx_screen_width, 0, 0, 0, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Screen resolution width") MACRO_CONFIG_INT(GfxScreenHeight, gfx_screen_height, 0, 0, 0, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Screen resolution height") MACRO_CONFIG_INT(GfxBorderless, gfx_borderless, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Borderless window (not to be used with fullscreen)") MACRO_CONFIG_INT(GfxFullscreen, gfx_fullscreen, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Fullscreen") MACRO_CONFIG_INT(GfxAlphabits, gfx_alphabits, 0, 0, 0, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Alpha bits for framebuffer (fullscreen only)") MACRO_CONFIG_INT(GfxClear, gfx_clear, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Clear screen before rendering") MACRO_CONFIG_INT(GfxVsync, gfx_vsync, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Vertical sync") MACRO_CONFIG_INT(GfxDisplayAllModes, gfx_display_all_modes, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "") MACRO_CONFIG_INT(GfxTextureCompression, gfx_texture_compression, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Use texture compression") MACRO_CONFIG_INT(GfxHighDetail, gfx_high_detail, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "High detail") MACRO_CONFIG_INT(GfxTextureQuality, gfx_texture_quality, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "") MACRO_CONFIG_INT(GfxFsaaSamples, gfx_fsaa_samples, 0, 0, 16, CFGFLAG_SAVE|CFGFLAG_CLIENT, "FSAA Samples") MACRO_CONFIG_INT(GfxRefreshRate, gfx_refresh_rate, 0, 0, 0, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Screen refresh rate") MACRO_CONFIG_INT(GfxFinish, gfx_finish, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "") MACRO_CONFIG_INT(GfxAsyncRender, gfx_asyncrender, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Do rendering async from the the update") MACRO_CONFIG_INT(InpMousesens, inp_mousesens, 100, 5, 100000, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Mouse sensitivity") MACRO_CONFIG_STR(SvName, sv_name, 128, "unnamed server", CFGFLAG_SERVER, "Server name") MACRO_CONFIG_STR(SvHostname, sv_hostname, 128, "", CFGFLAG_SERVER, "Server hostname") MACRO_CONFIG_STR(Bindaddr, bindaddr, 128, "", CFGFLAG_CLIENT|CFGFLAG_SERVER|CFGFLAG_MASTER, "Address to bind the client/server to") MACRO_CONFIG_INT(SvPort, sv_port, 8303, 0, 0, CFGFLAG_SERVER, "Port to use for the server") MACRO_CONFIG_INT(SvExternalPort, sv_external_port, 0, 0, 0, CFGFLAG_SERVER, "External port to report to the master servers") MACRO_CONFIG_STR(SvMap, sv_map, 128, "dm1", CFGFLAG_SERVER, "Map to use on the server") MACRO_CONFIG_INT(SvMaxClients, sv_max_clients, 8, 1, MAX_CLIENTS, CFGFLAG_SERVER, "Maximum number of clients that are allowed on a server") MACRO_CONFIG_INT(SvMaxClientsPerIP, sv_max_clients_per_ip, 4, 1, MAX_CLIENTS, CFGFLAG_SERVER, "Maximum number of clients with the same IP that can connect to the server") MACRO_CONFIG_INT(SvMapDownloadSpeed, sv_map_download_speed, 2, 1, 16, CFGFLAG_SERVER, "Number of map data packages a client gets on each request") MACRO_CONFIG_INT(SvHighBandwidth, sv_high_bandwidth, 0, 0, 1, CFGFLAG_SERVER, "Use high bandwidth mode. Doubles the bandwidth required for the server. LAN use only") MACRO_CONFIG_INT(SvRegister, sv_register, 1, 0, 1, CFGFLAG_SERVER, "Register server with master server for public listing") MACRO_CONFIG_STR(SvRconPassword, sv_rcon_password, 32, "", CFGFLAG_SERVER, "Remote console password (full access)") MACRO_CONFIG_STR(SvRconModPassword, sv_rcon_mod_password, 32, "", CFGFLAG_SERVER, "Remote console password for moderators (limited access)") MACRO_CONFIG_INT(SvRconMaxTries, sv_rcon_max_tries, 3, 0, 100, CFGFLAG_SERVER, "Maximum number of tries for remote console authentication") MACRO_CONFIG_INT(SvRconBantime, sv_rcon_bantime, 5, 0, 1440, CFGFLAG_SERVER, "The time a client gets banned if remote console authentication fails. 0 makes it just use kick") MACRO_CONFIG_INT(SvAutoDemoRecord, sv_auto_demo_record, 0, 0, 1, CFGFLAG_SERVER, "Automatically record demos") MACRO_CONFIG_INT(SvAutoDemoMax, sv_auto_demo_max, 10, 0, 1000, CFGFLAG_SERVER, "Maximum number of automatically recorded demos (0 = no limit)") MACRO_CONFIG_STR(EcBindaddr, ec_bindaddr, 128, "localhost", CFGFLAG_ECON, "Address to bind the external console to. Anything but 'localhost' is dangerous") MACRO_CONFIG_INT(EcPort, ec_port, 0, 0, 0, CFGFLAG_ECON, "Port to use for the external console") MACRO_CONFIG_STR(EcPassword, ec_password, 32, "", CFGFLAG_ECON, "External console password") MACRO_CONFIG_INT(EcBantime, ec_bantime, 0, 0, 1440, CFGFLAG_ECON, "The time a client gets banned if econ authentication fails. 0 just closes the connection") MACRO_CONFIG_INT(EcAuthTimeout, ec_auth_timeout, 30, 1, 120, CFGFLAG_ECON, "Time in seconds before the the econ authentification times out") MACRO_CONFIG_INT(EcOutputLevel, ec_output_level, 1, 0, 2, CFGFLAG_ECON, "Adjusts the amount of information in the external console") MACRO_CONFIG_INT(Debug, debug, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SERVER, "Debug mode") MACRO_CONFIG_INT(DbgStress, dbg_stress, 0, 0, 0, CFGFLAG_CLIENT|CFGFLAG_SERVER, "Stress systems") MACRO_CONFIG_INT(DbgStressNetwork, dbg_stress_network, 0, 0, 0, CFGFLAG_CLIENT|CFGFLAG_SERVER, "Stress network") MACRO_CONFIG_INT(DbgPref, dbg_pref, 0, 0, 1, CFGFLAG_SERVER, "Performance outputs") MACRO_CONFIG_INT(DbgGraphs, dbg_graphs, 0, 0, 1, CFGFLAG_CLIENT, "Performance graphs") MACRO_CONFIG_INT(DbgHitch, dbg_hitch, 0, 0, 0, CFGFLAG_SERVER, "Hitch warnings") MACRO_CONFIG_STR(DbgStressServer, dbg_stress_server, 32, "localhost", CFGFLAG_CLIENT, "Server to stress") MACRO_CONFIG_INT(DbgResizable, dbg_resizable, 0, 0, 0, CFGFLAG_CLIENT, "Enables window resizing") #endif ================================================ FILE: src/engine/shared/console.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <new> #include <base/math.h> #include <base/system.h> #include <engine/storage.h> #include <engine/shared/protocol.h> #include "config.h" #include "console.h" #include "linereader.h" // todo: rework this const char *CConsole::CResult::GetString(unsigned Index) { if (Index >= m_NumArgs) return ""; return m_apArgs[Index]; } int CConsole::CResult::GetInteger(unsigned Index) { if (Index >= m_NumArgs) return 0; return str_toint(m_apArgs[Index]); } float CConsole::CResult::GetFloat(unsigned Index) { if (Index >= m_NumArgs) return 0.0f; return str_tofloat(m_apArgs[Index]); } const IConsole::CCommandInfo *CConsole::CCommand::NextCommandInfo(int AccessLevel, int FlagMask) const { const CCommand *pInfo = m_pNext; while(pInfo) { if(pInfo->m_Flags&FlagMask && pInfo->m_AccessLevel >= AccessLevel) break; pInfo = pInfo->m_pNext; } return pInfo; } const IConsole::CCommandInfo *CConsole::FirstCommandInfo(int AccessLevel, int FlagMask) const { for(const CCommand *pCommand = m_pFirstCommand; pCommand; pCommand = pCommand->m_pNext) { if(pCommand->m_Flags&FlagMask && pCommand->GetAccessLevel() >= AccessLevel) return pCommand; } return 0; } // the maximum number of tokens occurs in a string of length CONSOLE_MAX_STR_LENGTH with tokens size 1 separated by single spaces int CConsole::ParseStart(CResult *pResult, const char *pString, int Length) { char *pStr; int Len = sizeof(pResult->m_aStringStorage); if(Length < Len) Len = Length; str_copy(pResult->m_aStringStorage, pString, Len); pStr = pResult->m_aStringStorage; // get command pStr = str_skip_whitespaces(pStr); pResult->m_pCommand = pStr; pStr = str_skip_to_whitespace(pStr); if(*pStr) { pStr[0] = 0; pStr++; } pResult->m_pArgsStart = pStr; return 0; } int CConsole::ParseArgs(CResult *pResult, const char *pFormat) { char Command; char *pStr; int Optional = 0; int Error = 0; pStr = pResult->m_pArgsStart; while(1) { // fetch command Command = *pFormat; pFormat++; if(!Command) break; if(Command == '?') Optional = 1; else { pStr = str_skip_whitespaces(pStr); if(!(*pStr)) // error, non optional command needs value { if(!Optional) Error = 1; break; } // add token if(*pStr == '"') { char *pDst; pStr++; pResult->AddArgument(pStr); pDst = pStr; // we might have to process escape data while(1) { if(pStr[0] == '"') break; else if(pStr[0] == '\\') { if(pStr[1] == '\\') pStr++; // skip due to escape else if(pStr[1] == '"') pStr++; // skip due to escape } else if(pStr[0] == 0) return 1; // return error *pDst = *pStr; pDst++; pStr++; } // write null termination *pDst = 0; pStr++; } else { pResult->AddArgument(pStr); if(Command == 'r') // rest of the string break; else if(Command == 'i') // validate int pStr = str_skip_to_whitespace(pStr); else if(Command == 'f') // validate float pStr = str_skip_to_whitespace(pStr); else if(Command == 's') // validate string pStr = str_skip_to_whitespace(pStr); if(pStr[0] != 0) // check for end of string { pStr[0] = 0; pStr++; } } } } return Error; } int CConsole::RegisterPrintCallback(int OutputLevel, FPrintCallback pfnPrintCallback, void *pUserData) { if(m_NumPrintCB == MAX_PRINT_CB) return -1; m_aPrintCB[m_NumPrintCB].m_OutputLevel = clamp(OutputLevel, (int)(OUTPUT_LEVEL_STANDARD), (int)(OUTPUT_LEVEL_DEBUG)); m_aPrintCB[m_NumPrintCB].m_pfnPrintCallback = pfnPrintCallback; m_aPrintCB[m_NumPrintCB].m_pPrintCallbackUserdata = pUserData; return m_NumPrintCB++; } void CConsole::SetPrintOutputLevel(int Index, int OutputLevel) { if(Index >= 0 && Index < MAX_PRINT_CB) m_aPrintCB[Index].m_OutputLevel = clamp(OutputLevel, (int)(OUTPUT_LEVEL_STANDARD), (int)(OUTPUT_LEVEL_DEBUG)); } void CConsole::Print(int Level, const char *pFrom, const char *pStr) { dbg_msg(pFrom ,"%s", pStr); for(int i = 0; i < m_NumPrintCB; ++i) { if(Level <= m_aPrintCB[i].m_OutputLevel && m_aPrintCB[i].m_pfnPrintCallback) { char aBuf[1024]; str_format(aBuf, sizeof(aBuf), "[%s]: %s", pFrom, pStr); m_aPrintCB[i].m_pfnPrintCallback(aBuf, m_aPrintCB[i].m_pPrintCallbackUserdata); } } } bool CConsole::LineIsValid(const char *pStr) { if(!pStr || *pStr == 0) return false; do { CResult Result; const char *pEnd = pStr; const char *pNextPart = 0; int InString = 0; while(*pEnd) { if(*pEnd == '"') InString ^= 1; else if(*pEnd == '\\') // escape sequences { if(pEnd[1] == '"') pEnd++; } else if(!InString) { if(*pEnd == ';') // command separator { pNextPart = pEnd+1; break; } else if(*pEnd == '#') // comment, no need to do anything more break; } pEnd++; } if(ParseStart(&Result, pStr, (pEnd-pStr) + 1) != 0) return false; CCommand *pCommand = FindCommand(Result.m_pCommand, m_FlagMask); if(!pCommand || ParseArgs(&Result, pCommand->m_pParams)) return false; pStr = pNextPart; } while(pStr && *pStr); return true; } void CConsole::ExecuteLineStroked(int Stroke, const char *pStr) { while(pStr && *pStr) { CResult Result; const char *pEnd = pStr; const char *pNextPart = 0; int InString = 0; while(*pEnd) { if(*pEnd == '"') InString ^= 1; else if(*pEnd == '\\') // escape sequences { if(pEnd[1] == '"') pEnd++; } else if(!InString) { if(*pEnd == ';') // command separator { pNextPart = pEnd+1; break; } else if(*pEnd == '#') // comment, no need to do anything more break; } pEnd++; } if(ParseStart(&Result, pStr, (pEnd-pStr) + 1) != 0) return; if(!*Result.m_pCommand) return; CCommand *pCommand = FindCommand(Result.m_pCommand, m_FlagMask); if(pCommand) { if(pCommand->GetAccessLevel() >= m_AccessLevel) { int IsStrokeCommand = 0; if(Result.m_pCommand[0] == '+') { // insert the stroke direction token Result.AddArgument(m_paStrokeStr[Stroke]); IsStrokeCommand = 1; } if(Stroke || IsStrokeCommand) { if(ParseArgs(&Result, pCommand->m_pParams)) { char aBuf[256]; str_format(aBuf, sizeof(aBuf), "Invalid arguments... Usage: %s %s", pCommand->m_pName, pCommand->m_pParams); Print(OUTPUT_LEVEL_STANDARD, "Console", aBuf); } else if(m_StoreCommands && pCommand->m_Flags&CFGFLAG_STORE) { m_ExecutionQueue.AddEntry(); m_ExecutionQueue.m_pLast->m_pfnCommandCallback = pCommand->m_pfnCallback; m_ExecutionQueue.m_pLast->m_pCommandUserData = pCommand->m_pUserData; m_ExecutionQueue.m_pLast->m_Result = Result; } else pCommand->m_pfnCallback(&Result, pCommand->m_pUserData); } } else if(Stroke) { char aBuf[256]; str_format(aBuf, sizeof(aBuf), "Access for command %s denied.", Result.m_pCommand); Print(OUTPUT_LEVEL_STANDARD, "Console", aBuf); } } else if(Stroke) { char aBuf[256]; str_format(aBuf, sizeof(aBuf), "No such command: %s.", Result.m_pCommand); Print(OUTPUT_LEVEL_STANDARD, "Console", aBuf); } pStr = pNextPart; } } void CConsole::PossibleCommands(const char *pStr, int FlagMask, bool Temp, FPossibleCallback pfnCallback, void *pUser) { for(CCommand *pCommand = m_pFirstCommand; pCommand; pCommand = pCommand->m_pNext) { if(pCommand->m_Flags&FlagMask && pCommand->m_Temp == Temp) { if(str_find_nocase(pCommand->m_pName, pStr)) pfnCallback(pCommand->m_pName, pUser); } } } CConsole::CCommand *CConsole::FindCommand(const char *pName, int FlagMask) { for(CCommand *pCommand = m_pFirstCommand; pCommand; pCommand = pCommand->m_pNext) { if(pCommand->m_Flags&FlagMask) { if(str_comp_nocase(pCommand->m_pName, pName) == 0) return pCommand; } } return 0x0; } void CConsole::ExecuteLine(const char *pStr) { CConsole::ExecuteLineStroked(1, pStr); // press it CConsole::ExecuteLineStroked(0, pStr); // then release it } void CConsole::ExecuteLineFlag(const char *pStr, int FlagMask) { int Temp = m_FlagMask; m_FlagMask = FlagMask; ExecuteLine(pStr); m_FlagMask = Temp; } void CConsole::ExecuteFile(const char *pFilename) { // make sure that this isn't being executed already for(CExecFile *pCur = m_pFirstExec; pCur; pCur = pCur->m_pPrev) if(str_comp(pFilename, pCur->m_pFilename) == 0) return; if(!m_pStorage) m_pStorage = Kernel()->RequestInterface<IStorage>(); if(!m_pStorage) return; // push this one to the stack CExecFile ThisFile; CExecFile *pPrev = m_pFirstExec; ThisFile.m_pFilename = pFilename; ThisFile.m_pPrev = m_pFirstExec; m_pFirstExec = &ThisFile; // exec the file IOHANDLE File = m_pStorage->OpenFile(pFilename, IOFLAG_READ, IStorage::TYPE_ALL); char aBuf[256]; if(File) { char *pLine; CLineReader lr; str_format(aBuf, sizeof(aBuf), "executing '%s'", pFilename); Print(IConsole::OUTPUT_LEVEL_STANDARD, "console", aBuf); lr.Init(File); while((pLine = lr.Get())) ExecuteLine(pLine); io_close(File); } else { str_format(aBuf, sizeof(aBuf), "failed to open '%s'", pFilename); Print(IConsole::OUTPUT_LEVEL_STANDARD, "console", aBuf); } m_pFirstExec = pPrev; } void CConsole::Con_Echo(IResult *pResult, void *pUserData) { ((CConsole*)pUserData)->Print(IConsole::OUTPUT_LEVEL_STANDARD, "Console", pResult->GetString(0)); } void CConsole::Con_Exec(IResult *pResult, void *pUserData) { ((CConsole*)pUserData)->ExecuteFile(pResult->GetString(0)); } void CConsole::ConModCommandAccess(IResult *pResult, void *pUser) { CConsole* pConsole = static_cast<CConsole *>(pUser); char aBuf[128]; CCommand *pCommand = pConsole->FindCommand(pResult->GetString(0), CFGFLAG_SERVER); if(pCommand) { if(pResult->NumArguments() == 2) { pCommand->SetAccessLevel(pResult->GetInteger(1)); str_format(aBuf, sizeof(aBuf), "moderator access for '%s' is now %s", pResult->GetString(0), pCommand->GetAccessLevel() ? "enabled" : "disabled"); } else str_format(aBuf, sizeof(aBuf), "moderator access for '%s' is %s", pResult->GetString(0), pCommand->GetAccessLevel() ? "enabled" : "disabled"); } else str_format(aBuf, sizeof(aBuf), "No such command: '%s'.", pResult->GetString(0)); pConsole->Print(OUTPUT_LEVEL_STANDARD, "Console", aBuf); } void CConsole::ConModCommandStatus(IResult *pResult, void *pUser) { CConsole* pConsole = static_cast<CConsole *>(pUser); char aBuf[240]; mem_zero(aBuf, sizeof(aBuf)); int Used = 0; for(CCommand *pCommand = pConsole->m_pFirstCommand; pCommand; pCommand = pCommand->m_pNext) { if(pCommand->m_Flags&pConsole->m_FlagMask && pCommand->GetAccessLevel() == ACCESS_LEVEL_MOD) { int Length = str_length(pCommand->m_pName); if(Used + Length + 2 < (int)(sizeof(aBuf))) { if(Used > 0) { Used += 2; str_append(aBuf, ", ", sizeof(aBuf)); } str_append(aBuf, pCommand->m_pName, sizeof(aBuf)); Used += Length; } else { pConsole->Print(OUTPUT_LEVEL_STANDARD, "Console", aBuf); mem_zero(aBuf, sizeof(aBuf)); str_copy(aBuf, pCommand->m_pName, sizeof(aBuf)); Used = Length; } } } if(Used > 0) pConsole->Print(OUTPUT_LEVEL_STANDARD, "Console", aBuf); } struct CIntVariableData { IConsole *m_pConsole; int *m_pVariable; int m_Min; int m_Max; }; struct CStrVariableData { IConsole *m_pConsole; char *m_pStr; int m_MaxSize; }; static void IntVariableCommand(IConsole::IResult *pResult, void *pUserData) { CIntVariableData *pData = (CIntVariableData *)pUserData; if(pResult->NumArguments()) { int Val = pResult->GetInteger(0); // do clamping if(pData->m_Min != pData->m_Max) { if (Val < pData->m_Min) Val = pData->m_Min; if (pData->m_Max != 0 && Val > pData->m_Max) Val = pData->m_Max; } *(pData->m_pVariable) = Val; } else { char aBuf[1024]; str_format(aBuf, sizeof(aBuf), "Value: %d", *(pData->m_pVariable)); pData->m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "Console", aBuf); } } static void StrVariableCommand(IConsole::IResult *pResult, void *pUserData) { CStrVariableData *pData = (CStrVariableData *)pUserData; if(pResult->NumArguments()) { const char *pString = pResult->GetString(0); if(!str_utf8_check(pString)) { char Temp[4]; int Length = 0; while(*pString) { int Size = str_utf8_encode(Temp, static_cast<const unsigned char>(*pString++)); if(Length+Size < pData->m_MaxSize) { mem_copy(pData->m_pStr+Length, &Temp, Size); Length += Size; } else break; } pData->m_pStr[Length] = 0; } else str_copy(pData->m_pStr, pString, pData->m_MaxSize); } else { char aBuf[1024]; str_format(aBuf, sizeof(aBuf), "Value: %s", pData->m_pStr); pData->m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "Console", aBuf); } } void CConsole::ConToggle(IConsole::IResult *pResult, void *pUser) { CConsole* pConsole = static_cast<CConsole *>(pUser); char aBuf[128] = {0}; CCommand *pCommand = pConsole->FindCommand(pResult->GetString(0), pConsole->m_FlagMask); if(pCommand) { FCommandCallback pfnCallback = pCommand->m_pfnCallback; void *pUserData = pCommand->m_pUserData; // check for chain if(pCommand->m_pfnCallback == Con_Chain) { CChain *pChainInfo = static_cast<CChain *>(pCommand->m_pUserData); pfnCallback = pChainInfo->m_pfnCallback; pUserData = pChainInfo->m_pCallbackUserData; } if(pfnCallback == IntVariableCommand) { CIntVariableData *pData = static_cast<CIntVariableData *>(pUserData); int Val = *(pData->m_pVariable)==pResult->GetInteger(1) ? pResult->GetInteger(2) : pResult->GetInteger(1); str_format(aBuf, sizeof(aBuf), "%s %i", pResult->GetString(0), Val); pConsole->ExecuteLine(aBuf); aBuf[0] = 0; } else str_format(aBuf, sizeof(aBuf), "Invalid command: '%s'.", pResult->GetString(0)); } else str_format(aBuf, sizeof(aBuf), "No such command: '%s'.", pResult->GetString(0)); if(aBuf[0] != 0) pConsole->Print(OUTPUT_LEVEL_STANDARD, "Console", aBuf); } void CConsole::ConToggleStroke(IConsole::IResult *pResult, void *pUser) { CConsole* pConsole = static_cast<CConsole *>(pUser); char aBuf[128] = {0}; CCommand *pCommand = pConsole->FindCommand(pResult->GetString(1), pConsole->m_FlagMask); if(pCommand) { FCommandCallback pfnCallback = pCommand->m_pfnCallback; // check for chain if(pCommand->m_pfnCallback == Con_Chain) { CChain *pChainInfo = static_cast<CChain *>(pCommand->m_pUserData); pfnCallback = pChainInfo->m_pfnCallback; } if(pfnCallback == IntVariableCommand) { int Val = pResult->GetInteger(0)==0 ? pResult->GetInteger(3) : pResult->GetInteger(2); str_format(aBuf, sizeof(aBuf), "%s %i", pResult->GetString(1), Val); pConsole->ExecuteLine(aBuf); aBuf[0] = 0; } else str_format(aBuf, sizeof(aBuf), "Invalid command: '%s'.", pResult->GetString(1)); } else str_format(aBuf, sizeof(aBuf), "No such command: '%s'.", pResult->GetString(1)); if(aBuf[0] != 0) pConsole->Print(OUTPUT_LEVEL_STANDARD, "Console", aBuf); } CConsole::CConsole(int FlagMask) { m_FlagMask = FlagMask; m_AccessLevel = ACCESS_LEVEL_ADMIN; m_pRecycleList = 0; m_TempCommands.Reset(); m_StoreCommands = true; m_paStrokeStr[0] = "0"; m_paStrokeStr[1] = "1"; m_ExecutionQueue.Reset(); m_pFirstCommand = 0; m_pFirstExec = 0; mem_zero(m_aPrintCB, sizeof(m_aPrintCB)); m_NumPrintCB = 0; m_pStorage = 0; // register some basic commands Register("echo", "r", CFGFLAG_SERVER|CFGFLAG_CLIENT, Con_Echo, this, "Echo the text"); Register("exec", "r", CFGFLAG_SERVER|CFGFLAG_CLIENT, Con_Exec, this, "Execute the specified file"); Register("toggle", "sii", CFGFLAG_SERVER|CFGFLAG_CLIENT, ConToggle, this, "Toggle config value"); Register("+toggle", "sii", CFGFLAG_CLIENT, ConToggleStroke, this, "Toggle config value via keypress"); Register("mod_command", "s?i", CFGFLAG_SERVER, ConModCommandAccess, this, "Specify command accessibility for moderators"); Register("mod_status", "", CFGFLAG_SERVER, ConModCommandStatus, this, "List all commands which are accessible for moderators"); // TODO: this should disappear #define MACRO_CONFIG_INT(Name,ScriptName,Def,Min,Max,Flags,Desc) \ { \ static CIntVariableData Data = { this, &g_Config.m_##Name, Min, Max }; \ Register(#ScriptName, "?i", Flags, IntVariableCommand, &Data, Desc); \ } #define MACRO_CONFIG_STR(Name,ScriptName,Len,Def,Flags,Desc) \ { \ static CStrVariableData Data = { this, g_Config.m_##Name, Len }; \ Register(#ScriptName, "?r", Flags, StrVariableCommand, &Data, Desc); \ } #include "config_variables.h" #undef MACRO_CONFIG_INT #undef MACRO_CONFIG_STR } void CConsole::ParseArguments(int NumArgs, const char **ppArguments) { for(int i = 0; i < NumArgs; i++) { // check for scripts to execute if(ppArguments[i][0] == '-' && ppArguments[i][1] == 'f' && ppArguments[i][2] == 0) { if(NumArgs - i > 1) ExecuteFile(ppArguments[i+1]); i++; } else if(!str_comp("-s", ppArguments[i]) || !str_comp("--silent", ppArguments[i])) { // skip silent param continue; } else { // search arguments for overrides ExecuteLine(ppArguments[i]); } } } void CConsole::AddCommandSorted(CCommand *pCommand) { if(!m_pFirstCommand || str_comp(pCommand->m_pName, m_pFirstCommand->m_pName) <= 0) { if(m_pFirstCommand && m_pFirstCommand->m_pNext) pCommand->m_pNext = m_pFirstCommand; else pCommand->m_pNext = 0; m_pFirstCommand = pCommand; } else { for(CCommand *p = m_pFirstCommand; p; p = p->m_pNext) { if(!p->m_pNext || str_comp(pCommand->m_pName, p->m_pNext->m_pName) <= 0) { pCommand->m_pNext = p->m_pNext; p->m_pNext = pCommand; break; } } } } void CConsole::Register(const char *pName, const char *pParams, int Flags, FCommandCallback pfnFunc, void *pUser, const char *pHelp) { CCommand *pCommand = FindCommand(pName, Flags); bool DoAdd = false; if(pCommand == 0) { pCommand = new(mem_alloc(sizeof(CCommand), sizeof(void*))) CCommand; DoAdd = true; } pCommand->m_pfnCallback = pfnFunc; pCommand->m_pUserData = pUser; pCommand->m_pName = pName; pCommand->m_pHelp = pHelp; pCommand->m_pParams = pParams; pCommand->m_Flags = Flags; pCommand->m_Temp = false; if(DoAdd) AddCommandSorted(pCommand); } void CConsole::RegisterTemp(const char *pName, const char *pParams, int Flags, const char *pHelp) { CCommand *pCommand; if(m_pRecycleList) { pCommand = m_pRecycleList; str_copy(const_cast<char *>(pCommand->m_pName), pName, TEMPCMD_NAME_LENGTH); str_copy(const_cast<char *>(pCommand->m_pHelp), pHelp, TEMPCMD_HELP_LENGTH); str_copy(const_cast<char *>(pCommand->m_pParams), pParams, TEMPCMD_PARAMS_LENGTH); m_pRecycleList = m_pRecycleList->m_pNext; } else { pCommand = new(m_TempCommands.Allocate(sizeof(CCommand))) CCommand; char *pMem = static_cast<char *>(m_TempCommands.Allocate(TEMPCMD_NAME_LENGTH)); str_copy(pMem, pName, TEMPCMD_NAME_LENGTH); pCommand->m_pName = pMem; pMem = static_cast<char *>(m_TempCommands.Allocate(TEMPCMD_HELP_LENGTH)); str_copy(pMem, pHelp, TEMPCMD_HELP_LENGTH); pCommand->m_pHelp = pMem; pMem = static_cast<char *>(m_TempCommands.Allocate(TEMPCMD_PARAMS_LENGTH)); str_copy(pMem, pParams, TEMPCMD_PARAMS_LENGTH); pCommand->m_pParams = pMem; } pCommand->m_pfnCallback = 0; pCommand->m_pUserData = 0; pCommand->m_Flags = Flags; pCommand->m_Temp = true; AddCommandSorted(pCommand); } void CConsole::DeregisterTemp(const char *pName) { if(!m_pFirstCommand) return; CCommand *pRemoved = 0; // remove temp entry from command list if(m_pFirstCommand->m_Temp && str_comp(m_pFirstCommand->m_pName, pName) == 0) { pRemoved = m_pFirstCommand; m_pFirstCommand = m_pFirstCommand->m_pNext; } else { for(CCommand *pCommand = m_pFirstCommand; pCommand->m_pNext; pCommand = pCommand->m_pNext) if(pCommand->m_pNext->m_Temp && str_comp(pCommand->m_pNext->m_pName, pName) == 0) { pRemoved = pCommand->m_pNext; pCommand->m_pNext = pCommand->m_pNext->m_pNext; break; } } // add to recycle list if(pRemoved) { pRemoved->m_pNext = m_pRecycleList; m_pRecycleList = pRemoved; } } void CConsole::DeregisterTempAll() { // set non temp as first one for(; m_pFirstCommand && m_pFirstCommand->m_Temp; m_pFirstCommand = m_pFirstCommand->m_pNext); // remove temp entries from command list for(CCommand *pCommand = m_pFirstCommand; pCommand && pCommand->m_pNext; pCommand = pCommand->m_pNext) { CCommand *pNext = pCommand->m_pNext; if(pNext->m_Temp) { for(; pNext && pNext->m_Temp; pNext = pNext->m_pNext); pCommand->m_pNext = pNext; } } m_TempCommands.Reset(); m_pRecycleList = 0; } void CConsole::Con_Chain(IResult *pResult, void *pUserData) { CChain *pInfo = (CChain *)pUserData; pInfo->m_pfnChainCallback(pResult, pInfo->m_pUserData, pInfo->m_pfnCallback, pInfo->m_pCallbackUserData); } void CConsole::Chain(const char *pName, FChainCommandCallback pfnChainFunc, void *pUser) { CCommand *pCommand = FindCommand(pName, m_FlagMask); if(!pCommand) { char aBuf[256]; str_format(aBuf, sizeof(aBuf), "failed to chain '%s'", pName); Print(IConsole::OUTPUT_LEVEL_DEBUG, "console", aBuf); return; } CChain *pChainInfo = (CChain *)mem_alloc(sizeof(CChain), sizeof(void*)); // store info pChainInfo->m_pfnChainCallback = pfnChainFunc; pChainInfo->m_pUserData = pUser; pChainInfo->m_pfnCallback = pCommand->m_pfnCallback; pChainInfo->m_pCallbackUserData = pCommand->m_pUserData; // chain pCommand->m_pfnCallback = Con_Chain; pCommand->m_pUserData = pChainInfo; } void CConsole::StoreCommands(bool Store) { if(!Store) { for(CExecutionQueue::CQueueEntry *pEntry = m_ExecutionQueue.m_pFirst; pEntry; pEntry = pEntry->m_pNext) pEntry->m_pfnCommandCallback(&pEntry->m_Result, pEntry->m_pCommandUserData); m_ExecutionQueue.Reset(); } m_StoreCommands = Store; } const IConsole::CCommandInfo *CConsole::GetCommandInfo(const char *pName, int FlagMask, bool Temp) { for(CCommand *pCommand = m_pFirstCommand; pCommand; pCommand = pCommand->m_pNext) { if(pCommand->m_Flags&FlagMask && pCommand->m_Temp == Temp) { if(str_comp_nocase(pCommand->m_pName, pName) == 0) return pCommand; } } return 0; } extern IConsole *CreateConsole(int FlagMask) { return new CConsole(FlagMask); } ================================================ FILE: src/engine/shared/console.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef ENGINE_SHARED_CONSOLE_H #define ENGINE_SHARED_CONSOLE_H #include <engine/console.h> #include "memheap.h" class CConsole : public IConsole { class CCommand : public CCommandInfo { public: CCommand *m_pNext; int m_Flags; bool m_Temp; FCommandCallback m_pfnCallback; void *m_pUserData; virtual const CCommandInfo *NextCommandInfo(int AccessLevel, int FlagMask) const; void SetAccessLevel(int AccessLevel) { m_AccessLevel = clamp(AccessLevel, (int)(ACCESS_LEVEL_ADMIN), (int)(ACCESS_LEVEL_MOD)); } }; class CChain { public: FChainCommandCallback m_pfnChainCallback; FCommandCallback m_pfnCallback; void *m_pCallbackUserData; void *m_pUserData; }; int m_FlagMask; bool m_StoreCommands; const char *m_paStrokeStr[2]; CCommand *m_pFirstCommand; class CExecFile { public: const char *m_pFilename; CExecFile *m_pPrev; }; CExecFile *m_pFirstExec; class IStorage *m_pStorage; int m_AccessLevel; CCommand *m_pRecycleList; CHeap m_TempCommands; static void Con_Chain(IResult *pResult, void *pUserData); static void Con_Echo(IResult *pResult, void *pUserData); static void Con_Exec(IResult *pResult, void *pUserData); static void ConToggle(IResult *pResult, void *pUser); static void ConToggleStroke(IResult *pResult, void *pUser); static void ConModCommandAccess(IResult *pResult, void *pUser); static void ConModCommandStatus(IConsole::IResult *pResult, void *pUser); void ExecuteFileRecurse(const char *pFilename); void ExecuteLineStroked(int Stroke, const char *pStr); struct { int m_OutputLevel; FPrintCallback m_pfnPrintCallback; void *m_pPrintCallbackUserdata; } m_aPrintCB[MAX_PRINT_CB]; int m_NumPrintCB; enum { CONSOLE_MAX_STR_LENGTH = 1024, MAX_PARTS = (CONSOLE_MAX_STR_LENGTH+1)/2 }; class CResult : public IResult { public: char m_aStringStorage[CONSOLE_MAX_STR_LENGTH+1]; char *m_pArgsStart; const char *m_pCommand; const char *m_apArgs[MAX_PARTS]; CResult() : IResult() { mem_zero(m_aStringStorage, sizeof(m_aStringStorage)); m_pArgsStart = 0; m_pCommand = 0; mem_zero(m_apArgs, sizeof(m_apArgs)); } CResult &operator =(const CResult &Other) { if(this != &Other) { IResult::operator=(Other); int Offset = m_aStringStorage - Other.m_aStringStorage; mem_copy(m_aStringStorage, Other.m_aStringStorage, sizeof(m_aStringStorage)); m_pArgsStart = Other.m_pArgsStart + Offset; m_pCommand = Other.m_pCommand + Offset; for(unsigned i = 0; i < Other.m_NumArgs; ++i) m_apArgs[i] = Other.m_apArgs[i] + Offset; } return *this; } void AddArgument(const char *pArg) { m_apArgs[m_NumArgs++] = pArg; } virtual const char *GetString(unsigned Index); virtual int GetInteger(unsigned Index); virtual float GetFloat(unsigned Index); }; int ParseStart(CResult *pResult, const char *pString, int Length); int ParseArgs(CResult *pResult, const char *pFormat); class CExecutionQueue { CHeap m_Queue; public: struct CQueueEntry { CQueueEntry *m_pNext; FCommandCallback m_pfnCommandCallback; void *m_pCommandUserData; CResult m_Result; } *m_pFirst, *m_pLast; void AddEntry() { CQueueEntry *pEntry = static_cast<CQueueEntry *>(m_Queue.Allocate(sizeof(CQueueEntry))); pEntry->m_pNext = 0; if(!m_pFirst) m_pFirst = pEntry; if(m_pLast) m_pLast->m_pNext = pEntry; m_pLast = pEntry; (void)new(&(pEntry->m_Result)) CResult; } void Reset() { m_Queue.Reset(); m_pFirst = m_pLast = 0; } } m_ExecutionQueue; void AddCommandSorted(CCommand *pCommand); CCommand *FindCommand(const char *pName, int FlagMask); public: CConsole(int FlagMask); virtual const CCommandInfo *FirstCommandInfo(int AccessLevel, int FlagMask) const; virtual const CCommandInfo *GetCommandInfo(const char *pName, int FlagMask, bool Temp); virtual void PossibleCommands(const char *pStr, int FlagMask, bool Temp, FPossibleCallback pfnCallback, void *pUser); virtual void ParseArguments(int NumArgs, const char **ppArguments); virtual void Register(const char *pName, const char *pParams, int Flags, FCommandCallback pfnFunc, void *pUser, const char *pHelp); virtual void RegisterTemp(const char *pName, const char *pParams, int Flags, const char *pHelp); virtual void DeregisterTemp(const char *pName); virtual void DeregisterTempAll(); virtual void Chain(const char *pName, FChainCommandCallback pfnChainFunc, void *pUser); virtual void StoreCommands(bool Store); virtual bool LineIsValid(const char *pStr); virtual void ExecuteLine(const char *pStr); virtual void ExecuteLineFlag(const char *pStr, int FlagMask); virtual void ExecuteFile(const char *pFilename); virtual int RegisterPrintCallback(int OutputLevel, FPrintCallback pfnPrintCallback, void *pUserData); virtual void SetPrintOutputLevel(int Index, int OutputLevel); virtual void Print(int Level, const char *pFrom, const char *pStr); void SetAccessLevel(int AccessLevel) { m_AccessLevel = clamp(AccessLevel, (int)(ACCESS_LEVEL_ADMIN), (int)(ACCESS_LEVEL_MOD)); } }; #endif ================================================ FILE: src/engine/shared/datafile.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <base/math.h> #include <base/system.h> #include <engine/storage.h> #include "datafile.h" #include <zlib.h> static const int DEBUG=0; struct CDatafileItemType { int m_Type; int m_Start; int m_Num; } ; struct CDatafileItem { int m_TypeAndID; int m_Size; }; struct CDatafileHeader { char m_aID[4]; int m_Version; int m_Size; int m_Swaplen; int m_NumItemTypes; int m_NumItems; int m_NumRawData; int m_ItemSize; int m_DataSize; }; struct CDatafileData { int m_NumItemTypes; int m_NumItems; int m_NumRawData; int m_ItemSize; int m_DataSize; char m_aStart[4]; }; struct CDatafileInfo { CDatafileItemType *m_pItemTypes; int *m_pItemOffsets; int *m_pDataOffsets; int *m_pDataSizes; char *m_pItemStart; char *m_pDataStart; }; struct CDatafile { IOHANDLE m_File; unsigned m_Crc; CDatafileInfo m_Info; CDatafileHeader m_Header; int m_DataStartOffset; char **m_ppDataPtrs; char *m_pData; }; bool CDataFileReader::Open(class IStorage *pStorage, const char *pFilename, int StorageType) { dbg_msg("datafile", "loading. filename='%s'", pFilename); IOHANDLE File = pStorage->OpenFile(pFilename, IOFLAG_READ, StorageType); if(!File) { dbg_msg("datafile", "could not open '%s'", pFilename); return false; } // take the CRC of the file and store it unsigned Crc = 0; { enum { BUFFER_SIZE = 64*1024 }; unsigned char aBuffer[BUFFER_SIZE]; while(1) { unsigned Bytes = io_read(File, aBuffer, BUFFER_SIZE); if(Bytes <= 0) break; Crc = crc32(Crc, aBuffer, Bytes); // ignore_convention } io_seek(File, 0, IOSEEK_START); } // TODO: change this header CDatafileHeader Header; io_read(File, &Header, sizeof(Header)); if(Header.m_aID[0] != 'A' || Header.m_aID[1] != 'T' || Header.m_aID[2] != 'A' || Header.m_aID[3] != 'D') { if(Header.m_aID[0] != 'D' || Header.m_aID[1] != 'A' || Header.m_aID[2] != 'T' || Header.m_aID[3] != 'A') { dbg_msg("datafile", "wrong signature. %x %x %x %x", Header.m_aID[0], Header.m_aID[1], Header.m_aID[2], Header.m_aID[3]); io_close(File); return 0; } } #if defined(CONF_ARCH_ENDIAN_BIG) swap_endian(&Header, sizeof(int), sizeof(Header)/sizeof(int)); #endif if(Header.m_Version != 3 && Header.m_Version != 4) { dbg_msg("datafile", "wrong version. version=%x", Header.m_Version); io_close(File); return 0; } // read in the rest except the data unsigned Size = 0; Size += Header.m_NumItemTypes*sizeof(CDatafileItemType); Size += (Header.m_NumItems+Header.m_NumRawData)*sizeof(int); if(Header.m_Version == 4) Size += Header.m_NumRawData*sizeof(int); // v4 has uncompressed data sizes aswell Size += Header.m_ItemSize; unsigned AllocSize = Size; AllocSize += sizeof(CDatafile); // add space for info structure AllocSize += Header.m_NumRawData*sizeof(void*); // add space for data pointers CDatafile *pTmpDataFile = (CDatafile*)mem_alloc(AllocSize, 1); pTmpDataFile->m_Header = Header; pTmpDataFile->m_DataStartOffset = sizeof(CDatafileHeader) + Size; pTmpDataFile->m_ppDataPtrs = (char**)(pTmpDataFile+1); pTmpDataFile->m_pData = (char *)(pTmpDataFile+1)+Header.m_NumRawData*sizeof(char *); pTmpDataFile->m_File = File; pTmpDataFile->m_Crc = Crc; // clear the data pointers mem_zero(pTmpDataFile->m_ppDataPtrs, Header.m_NumRawData*sizeof(void*)); // read types, offsets, sizes and item data unsigned ReadSize = io_read(File, pTmpDataFile->m_pData, Size); if(ReadSize != Size) { io_close(pTmpDataFile->m_File); mem_free(pTmpDataFile); pTmpDataFile = 0; dbg_msg("datafile", "couldn't load the whole thing, wanted=%d got=%d", Size, ReadSize); return false; } Close(); m_pDataFile = pTmpDataFile; #if defined(CONF_ARCH_ENDIAN_BIG) swap_endian(m_pDataFile->m_pData, sizeof(int), min(static_cast<unsigned>(Header.m_Swaplen), Size) / sizeof(int)); #endif //if(DEBUG) { dbg_msg("datafile", "allocsize=%d", AllocSize); dbg_msg("datafile", "readsize=%d", ReadSize); dbg_msg("datafile", "swaplen=%d", Header.m_Swaplen); dbg_msg("datafile", "item_size=%d", m_pDataFile->m_Header.m_ItemSize); } m_pDataFile->m_Info.m_pItemTypes = (CDatafileItemType *)m_pDataFile->m_pData; m_pDataFile->m_Info.m_pItemOffsets = (int *)&m_pDataFile->m_Info.m_pItemTypes[m_pDataFile->m_Header.m_NumItemTypes]; m_pDataFile->m_Info.m_pDataOffsets = (int *)&m_pDataFile->m_Info.m_pItemOffsets[m_pDataFile->m_Header.m_NumItems]; m_pDataFile->m_Info.m_pDataSizes = (int *)&m_pDataFile->m_Info.m_pDataOffsets[m_pDataFile->m_Header.m_NumRawData]; if(Header.m_Version == 4) m_pDataFile->m_Info.m_pItemStart = (char *)&m_pDataFile->m_Info.m_pDataSizes[m_pDataFile->m_Header.m_NumRawData]; else m_pDataFile->m_Info.m_pItemStart = (char *)&m_pDataFile->m_Info.m_pDataOffsets[m_pDataFile->m_Header.m_NumRawData]; m_pDataFile->m_Info.m_pDataStart = m_pDataFile->m_Info.m_pItemStart + m_pDataFile->m_Header.m_ItemSize; dbg_msg("datafile", "loading done. datafile='%s'", pFilename); if(DEBUG) { /* for(int i = 0; i < m_pDataFile->data.num_raw_data; i++) { void *p = datafile_get_data(df, i); dbg_msg("datafile", "%d %d", (int)((char*)p - (char*)(&m_pDataFile->data)), size); } for(int i = 0; i < datafile_num_items(df); i++) { int type, id; void *data = datafile_get_item(df, i, &type, &id); dbg_msg("map", "\t%d: type=%x id=%x p=%p offset=%d", i, type, id, data, m_pDataFile->info.item_offsets[i]); int *idata = (int*)data; for(int k = 0; k < 3; k++) dbg_msg("datafile", "\t\t%d=%d (%x)", k, idata[k], idata[k]); } for(int i = 0; i < m_pDataFile->data.num_m_aItemTypes; i++) { dbg_msg("map", "\t%d: type=%x start=%d num=%d", i, m_pDataFile->info.m_aItemTypes[i].type, m_pDataFile->info.m_aItemTypes[i].start, m_pDataFile->info.m_aItemTypes[i].num); for(int k = 0; k < m_pDataFile->info.m_aItemTypes[i].num; k++) { int type, id; datafile_get_item(df, m_pDataFile->info.m_aItemTypes[i].start+k, &type, &id); if(type != m_pDataFile->info.m_aItemTypes[i].type) dbg_msg("map", "\tERROR"); } } */ } return true; } bool CDataFileReader::GetCrcSize(class IStorage *pStorage, const char *pFilename, int StorageType, unsigned *pCrc, unsigned *pSize) { IOHANDLE File = pStorage->OpenFile(pFilename, IOFLAG_READ, StorageType); if(!File) return false; // get crc and size unsigned Crc = 0; unsigned Size = 0; unsigned char aBuffer[64*1024]; while(1) { unsigned Bytes = io_read(File, aBuffer, sizeof(aBuffer)); if(Bytes <= 0) break; Crc = crc32(Crc, aBuffer, Bytes); // ignore_convention Size += Bytes; } io_close(File); *pCrc = Crc; *pSize = Size; return true; } int CDataFileReader::NumData() { if(!m_pDataFile) { return 0; } return m_pDataFile->m_Header.m_NumRawData; } // always returns the size in the file int CDataFileReader::GetDataSize(int Index) { if(!m_pDataFile) { return 0; } if(Index == m_pDataFile->m_Header.m_NumRawData-1) return m_pDataFile->m_Header.m_DataSize-m_pDataFile->m_Info.m_pDataOffsets[Index]; return m_pDataFile->m_Info.m_pDataOffsets[Index+1]-m_pDataFile->m_Info.m_pDataOffsets[Index]; } void *CDataFileReader::GetDataImpl(int Index, int Swap) { if(!m_pDataFile) { return 0; } // load it if needed if(!m_pDataFile->m_ppDataPtrs[Index]) { // fetch the data size int DataSize = GetDataSize(Index); #if defined(CONF_ARCH_ENDIAN_BIG) int SwapSize = DataSize; #endif if(m_pDataFile->m_Header.m_Version == 4) { // v4 has compressed data void *pTemp = (char *)mem_alloc(DataSize, 1); unsigned long UncompressedSize = m_pDataFile->m_Info.m_pDataSizes[Index]; unsigned long s; dbg_msg("datafile", "loading data index=%d size=%d uncompressed=%d", Index, DataSize, UncompressedSize); m_pDataFile->m_ppDataPtrs[Index] = (char *)mem_alloc(UncompressedSize, 1); // read the compressed data io_seek(m_pDataFile->m_File, m_pDataFile->m_DataStartOffset+m_pDataFile->m_Info.m_pDataOffsets[Index], IOSEEK_START); io_read(m_pDataFile->m_File, pTemp, DataSize); // decompress the data, TODO: check for errors s = UncompressedSize; uncompress((Bytef*)m_pDataFile->m_ppDataPtrs[Index], &s, (Bytef*)pTemp, DataSize); // ignore_convention #if defined(CONF_ARCH_ENDIAN_BIG) SwapSize = s; #endif // clean up the temporary buffers mem_free(pTemp); } else { // load the data dbg_msg("datafile", "loading data index=%d size=%d", Index, DataSize); m_pDataFile->m_ppDataPtrs[Index] = (char *)mem_alloc(DataSize, 1); io_seek(m_pDataFile->m_File, m_pDataFile->m_DataStartOffset+m_pDataFile->m_Info.m_pDataOffsets[Index], IOSEEK_START); io_read(m_pDataFile->m_File, m_pDataFile->m_ppDataPtrs[Index], DataSize); } #if defined(CONF_ARCH_ENDIAN_BIG) if(Swap && SwapSize) swap_endian(m_pDataFile->m_ppDataPtrs[Index], sizeof(int), SwapSize/sizeof(int)); #endif } return m_pDataFile->m_ppDataPtrs[Index]; } void *CDataFileReader::GetData(int Index) { return GetDataImpl(Index, 0); } void *CDataFileReader::GetDataSwapped(int Index) { return GetDataImpl(Index, 1); } void CDataFileReader::UnloadData(int Index) { if(Index < 0) return; // mem_free(m_pDataFile->m_ppDataPtrs[Index]); m_pDataFile->m_ppDataPtrs[Index] = 0x0; } int CDataFileReader::GetItemSize(int Index) { if(!m_pDataFile) { return 0; } if(Index == m_pDataFile->m_Header.m_NumItems-1) return m_pDataFile->m_Header.m_ItemSize-m_pDataFile->m_Info.m_pItemOffsets[Index]; return m_pDataFile->m_Info.m_pItemOffsets[Index+1]-m_pDataFile->m_Info.m_pItemOffsets[Index]; } void *CDataFileReader::GetItem(int Index, int *pType, int *pID) { if(!m_pDataFile) { if(pType) *pType = 0; if(pID) *pID = 0; return 0; } CDatafileItem *i = (CDatafileItem *)(m_pDataFile->m_Info.m_pItemStart+m_pDataFile->m_Info.m_pItemOffsets[Index]); if(pType) *pType = (i->m_TypeAndID>>16)&0xffff; // remove sign extention if(pID) *pID = i->m_TypeAndID&0xffff; return (void *)(i+1); } void CDataFileReader::GetType(int Type, int *pStart, int *pNum) { *pStart = 0; *pNum = 0; if(!m_pDataFile) return; for(int i = 0; i < m_pDataFile->m_Header.m_NumItemTypes; i++) { if(m_pDataFile->m_Info.m_pItemTypes[i].m_Type == Type) { *pStart = m_pDataFile->m_Info.m_pItemTypes[i].m_Start; *pNum = m_pDataFile->m_Info.m_pItemTypes[i].m_Num; return; } } } void *CDataFileReader::FindItem(int Type, int ID) { if(!m_pDataFile) return 0; int Start, Num; GetType(Type, &Start, &Num); for(int i = 0; i < Num; i++) { int ItemID; void *pItem = GetItem(Start+i,0, &ItemID); if(ID == ItemID) return pItem; } return 0; } int CDataFileReader::NumItems() { if(!m_pDataFile) return 0; return m_pDataFile->m_Header.m_NumItems; } bool CDataFileReader::Close() { if(!m_pDataFile) return true; // free the data that is loaded int i; for(i = 0; i < m_pDataFile->m_Header.m_NumRawData; i++) mem_free(m_pDataFile->m_ppDataPtrs[i]); io_close(m_pDataFile->m_File); mem_free(m_pDataFile); m_pDataFile = 0; return true; } unsigned CDataFileReader::Crc() { if(!m_pDataFile) return 0xFFFFFFFF; return m_pDataFile->m_Crc; } CDataFileWriter::CDataFileWriter() { m_File = 0; m_pItemTypes = static_cast<CItemTypeInfo *>(mem_alloc(sizeof(CItemTypeInfo) * MAX_ITEM_TYPES, 1)); m_pItems = static_cast<CItemInfo *>(mem_alloc(sizeof(CItemInfo) * MAX_ITEMS, 1)); m_pDatas = static_cast<CDataInfo *>(mem_alloc(sizeof(CDataInfo) * MAX_DATAS, 1)); } CDataFileWriter::~CDataFileWriter() { mem_free(m_pItemTypes); m_pItemTypes = 0; mem_free(m_pItems); m_pItems = 0; mem_free(m_pDatas); m_pDatas = 0; } bool CDataFileWriter::Open(class IStorage *pStorage, const char *pFilename) { dbg_assert(!m_File, "a file already exists"); m_File = pStorage->OpenFile(pFilename, IOFLAG_WRITE, IStorage::TYPE_SAVE); if(!m_File) return false; m_NumItems = 0; m_NumDatas = 0; m_NumItemTypes = 0; mem_zero(m_pItemTypes, sizeof(CItemTypeInfo) * MAX_ITEM_TYPES); for(int i = 0; i < MAX_ITEM_TYPES; i++) { m_pItemTypes[i].m_First = -1; m_pItemTypes[i].m_Last = -1; } return true; } int CDataFileWriter::AddItem(int Type, int ID, int Size, void *pData) { if(!m_File) return 0; dbg_assert(Type >= 0 && Type < 0xFFFF, "incorrect type"); dbg_assert(m_NumItems < 1024, "too many items"); dbg_assert(Size%sizeof(int) == 0, "incorrect boundary"); m_pItems[m_NumItems].m_Type = Type; m_pItems[m_NumItems].m_ID = ID; m_pItems[m_NumItems].m_Size = Size; // copy data m_pItems[m_NumItems].m_pData = mem_alloc(Size, 1); mem_copy(m_pItems[m_NumItems].m_pData, pData, Size); if(!m_pItemTypes[Type].m_Num) // count item types m_NumItemTypes++; // link m_pItems[m_NumItems].m_Prev = m_pItemTypes[Type].m_Last; m_pItems[m_NumItems].m_Next = -1; if(m_pItemTypes[Type].m_Last != -1) m_pItems[m_pItemTypes[Type].m_Last].m_Next = m_NumItems; m_pItemTypes[Type].m_Last = m_NumItems; if(m_pItemTypes[Type].m_First == -1) m_pItemTypes[Type].m_First = m_NumItems; m_pItemTypes[Type].m_Num++; m_NumItems++; return m_NumItems-1; } int CDataFileWriter::AddData(int Size, void *pData) { if(!m_File) return 0; dbg_assert(m_NumDatas < 1024, "too much data"); CDataInfo *pInfo = &m_pDatas[m_NumDatas]; unsigned long s = compressBound(Size); void *pCompData = mem_alloc(s, 1); // temporary buffer that we use during compression int Result = compress((Bytef*)pCompData, &s, (Bytef*)pData, Size); // ignore_convention if(Result != Z_OK) { dbg_msg("datafile", "compression error %d", Result); dbg_assert(0, "zlib error"); } pInfo->m_UncompressedSize = Size; pInfo->m_CompressedSize = (int)s; pInfo->m_pCompressedData = mem_alloc(pInfo->m_CompressedSize, 1); mem_copy(pInfo->m_pCompressedData, pCompData, pInfo->m_CompressedSize); mem_free(pCompData); m_NumDatas++; return m_NumDatas-1; } int CDataFileWriter::AddDataSwapped(int Size, void *pData) { dbg_assert(Size%sizeof(int) == 0, "incorrect boundary"); #if defined(CONF_ARCH_ENDIAN_BIG) void *pSwapped = mem_alloc(Size, 1); // temporary buffer that we use during compression mem_copy(pSwapped, pData, Size); swap_endian(pSwapped, sizeof(int), Size/sizeof(int)); int Index = AddData(Size, pSwapped); mem_free(pSwapped); return Index; #else return AddData(Size, pData); #endif } int CDataFileWriter::Finish() { if(!m_File) return 1; int ItemSize = 0; int TypesSize, HeaderSize, OffsetSize, FileSize, SwapSize; int DataSize = 0; CDatafileHeader Header; // we should now write this file! if(DEBUG) dbg_msg("datafile", "writing"); // calculate sizes for(int i = 0; i < m_NumItems; i++) { if(DEBUG) dbg_msg("datafile", "item=%d size=%d (%d)", i, m_pItems[i].m_Size, m_pItems[i].m_Size+sizeof(CDatafileItem)); ItemSize += m_pItems[i].m_Size + sizeof(CDatafileItem); } for(int i = 0; i < m_NumDatas; i++) DataSize += m_pDatas[i].m_CompressedSize; // calculate the complete size TypesSize = m_NumItemTypes*sizeof(CDatafileItemType); HeaderSize = sizeof(CDatafileHeader); OffsetSize = (m_NumItems + m_NumDatas + m_NumDatas) * sizeof(int); // ItemOffsets, DataOffsets, DataUncompressedSizes FileSize = HeaderSize + TypesSize + OffsetSize + ItemSize + DataSize; SwapSize = FileSize - DataSize; (void)SwapSize; if(DEBUG) dbg_msg("datafile", "num_m_aItemTypes=%d TypesSize=%d m_aItemsize=%d DataSize=%d", m_NumItemTypes, TypesSize, ItemSize, DataSize); // construct Header { Header.m_aID[0] = 'D'; Header.m_aID[1] = 'A'; Header.m_aID[2] = 'T'; Header.m_aID[3] = 'A'; Header.m_Version = 4; Header.m_Size = FileSize - 16; Header.m_Swaplen = SwapSize - 16; Header.m_NumItemTypes = m_NumItemTypes; Header.m_NumItems = m_NumItems; Header.m_NumRawData = m_NumDatas; Header.m_ItemSize = ItemSize; Header.m_DataSize = DataSize; // write Header if(DEBUG) dbg_msg("datafile", "HeaderSize=%d", sizeof(Header)); #if defined(CONF_ARCH_ENDIAN_BIG) swap_endian(&Header, sizeof(int), sizeof(Header)/sizeof(int)); #endif io_write(m_File, &Header, sizeof(Header)); } // write types for(int i = 0, Count = 0; i < 0xffff; i++) { if(m_pItemTypes[i].m_Num) { // write info CDatafileItemType Info; Info.m_Type = i; Info.m_Start = Count; Info.m_Num = m_pItemTypes[i].m_Num; if(DEBUG) dbg_msg("datafile", "writing type=%x start=%d num=%d", Info.m_Type, Info.m_Start, Info.m_Num); #if defined(CONF_ARCH_ENDIAN_BIG) swap_endian(&Info, sizeof(int), sizeof(CDatafileItemType)/sizeof(int)); #endif io_write(m_File, &Info, sizeof(Info)); Count += m_pItemTypes[i].m_Num; } } // write item offsets for(int i = 0, Offset = 0; i < 0xffff; i++) { if(m_pItemTypes[i].m_Num) { // write all m_pItems in of this type int k = m_pItemTypes[i].m_First; while(k != -1) { if(DEBUG) dbg_msg("datafile", "writing item offset num=%d offset=%d", k, Offset); int Temp = Offset; #if defined(CONF_ARCH_ENDIAN_BIG) swap_endian(&Temp, sizeof(int), sizeof(Temp)/sizeof(int)); #endif io_write(m_File, &Temp, sizeof(Temp)); Offset += m_pItems[k].m_Size + sizeof(CDatafileItem); // next k = m_pItems[k].m_Next; } } } // write data offsets for(int i = 0, Offset = 0; i < m_NumDatas; i++) { if(DEBUG) dbg_msg("datafile", "writing data offset num=%d offset=%d", i, Offset); int Temp = Offset; #if defined(CONF_ARCH_ENDIAN_BIG) swap_endian(&Temp, sizeof(int), sizeof(Temp)/sizeof(int)); #endif io_write(m_File, &Temp, sizeof(Temp)); Offset += m_pDatas[i].m_CompressedSize; } // write data uncompressed sizes for(int i = 0; i < m_NumDatas; i++) { if(DEBUG) dbg_msg("datafile", "writing data uncompressed size num=%d size=%d", i, m_pDatas[i].m_UncompressedSize); int UncompressedSize = m_pDatas[i].m_UncompressedSize; #if defined(CONF_ARCH_ENDIAN_BIG) swap_endian(&UncompressedSize, sizeof(int), sizeof(UncompressedSize)/sizeof(int)); #endif io_write(m_File, &UncompressedSize, sizeof(UncompressedSize)); } // write m_pItems for(int i = 0; i < 0xffff; i++) { if(m_pItemTypes[i].m_Num) { // write all m_pItems in of this type int k = m_pItemTypes[i].m_First; while(k != -1) { CDatafileItem Item; Item.m_TypeAndID = (i<<16)|m_pItems[k].m_ID; Item.m_Size = m_pItems[k].m_Size; if(DEBUG) dbg_msg("datafile", "writing item type=%x idx=%d id=%d size=%d", i, k, m_pItems[k].m_ID, m_pItems[k].m_Size); #if defined(CONF_ARCH_ENDIAN_BIG) swap_endian(&Item, sizeof(int), sizeof(Item)/sizeof(int)); swap_endian(m_pItems[k].m_pData, sizeof(int), m_pItems[k].m_Size/sizeof(int)); #endif io_write(m_File, &Item, sizeof(Item)); io_write(m_File, m_pItems[k].m_pData, m_pItems[k].m_Size); // next k = m_pItems[k].m_Next; } } } // write data for(int i = 0; i < m_NumDatas; i++) { if(DEBUG) dbg_msg("datafile", "writing data id=%d size=%d", i, m_pDatas[i].m_CompressedSize); io_write(m_File, m_pDatas[i].m_pCompressedData, m_pDatas[i].m_CompressedSize); } // free data for(int i = 0; i < m_NumItems; i++) mem_free(m_pItems[i].m_pData); for(int i = 0; i < m_NumDatas; ++i) mem_free(m_pDatas[i].m_pCompressedData); io_close(m_File); m_File = 0; if(DEBUG) dbg_msg("datafile", "done"); return 0; } ================================================ FILE: src/engine/shared/datafile.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef ENGINE_SHARED_DATAFILE_H #define ENGINE_SHARED_DATAFILE_H // raw datafile access class CDataFileReader { struct CDatafile *m_pDataFile; void *GetDataImpl(int Index, int Swap); public: CDataFileReader() : m_pDataFile(0) {} ~CDataFileReader() { Close(); } bool IsOpen() const { return m_pDataFile != 0; } bool Open(class IStorage *pStorage, const char *pFilename, int StorageType); bool Close(); static bool GetCrcSize(class IStorage *pStorage, const char *pFilename, int StorageType, unsigned *pCrc, unsigned *pSize); void *GetData(int Index); void *GetDataSwapped(int Index); // makes sure that the data is 32bit LE ints when saved int GetDataSize(int Index); void UnloadData(int Index); void *GetItem(int Index, int *pType, int *pID); int GetItemSize(int Index); void GetType(int Type, int *pStart, int *pNum); void *FindItem(int Type, int ID); int NumItems(); int NumData(); void Unload(); unsigned Crc(); }; // write access class CDataFileWriter { struct CDataInfo { int m_UncompressedSize; int m_CompressedSize; void *m_pCompressedData; }; struct CItemInfo { int m_Type; int m_ID; int m_Size; int m_Next; int m_Prev; void *m_pData; }; struct CItemTypeInfo { int m_Num; int m_First; int m_Last; }; enum { MAX_ITEM_TYPES=0xffff, MAX_ITEMS=1024, MAX_DATAS=1024, }; IOHANDLE m_File; int m_NumItems; int m_NumDatas; int m_NumItemTypes; CItemTypeInfo *m_pItemTypes; CItemInfo *m_pItems; CDataInfo *m_pDatas; public: CDataFileWriter(); ~CDataFileWriter(); bool Open(class IStorage *pStorage, const char *Filename); int AddData(int Size, void *pData); int AddDataSwapped(int Size, void *pData); int AddItem(int Type, int ID, int Size, void *pData); int Finish(); }; #endif ================================================ FILE: src/engine/shared/demo.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <base/math.h> #include <base/system.h> #include <engine/console.h> #include <engine/storage.h> #include "compression.h" #include "demo.h" #include "memheap.h" #include "network.h" #include "snapshot.h" static const unsigned char gs_aHeaderMarker[7] = {'T', 'W', 'D', 'E', 'M', 'O', 0}; static const unsigned char gs_ActVersion = 4; static const int gs_LengthOffset = 152; static const int gs_NumMarkersOffset = 176; CDemoRecorder::CDemoRecorder(class CSnapshotDelta *pSnapshotDelta) { m_File = 0; m_LastTickMarker = -1; m_pSnapshotDelta = pSnapshotDelta; } // Record int CDemoRecorder::Start(class IStorage *pStorage, class IConsole *pConsole, const char *pFilename, const char *pNetVersion, const char *pMap, unsigned Crc, const char *pType) { CDemoHeader Header; if(m_File) return -1; m_pConsole = pConsole; // open mapfile char aMapFilename[128]; // try the normal maps folder str_format(aMapFilename, sizeof(aMapFilename), "maps/%s.map", pMap); IOHANDLE MapFile = pStorage->OpenFile(aMapFilename, IOFLAG_READ, IStorage::TYPE_ALL); if(!MapFile) { // try the downloaded maps str_format(aMapFilename, sizeof(aMapFilename), "downloadedmaps/%s_%08x.map", pMap, Crc); MapFile = pStorage->OpenFile(aMapFilename, IOFLAG_READ, IStorage::TYPE_ALL); } if(!MapFile) { // search for the map within subfolders char aBuf[512]; str_format(aMapFilename, sizeof(aMapFilename), "%s.map", pMap); if(pStorage->FindFile(aMapFilename, "maps", IStorage::TYPE_ALL, aBuf, sizeof(aBuf))) MapFile = pStorage->OpenFile(aBuf, IOFLAG_READ, IStorage::TYPE_ALL); } if(!MapFile) { char aBuf[256]; str_format(aBuf, sizeof(aBuf), "Unable to open mapfile '%s'", pMap); m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "demo_recorder", aBuf); return -1; } IOHANDLE DemoFile = pStorage->OpenFile(pFilename, IOFLAG_WRITE, IStorage::TYPE_SAVE); if(!DemoFile) { io_close(MapFile); MapFile = 0; char aBuf[256]; str_format(aBuf, sizeof(aBuf), "Unable to open '%s' for recording", pFilename); m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "demo_recorder", aBuf); return -1; } // write header mem_zero(&Header, sizeof(Header)); mem_copy(Header.m_aMarker, gs_aHeaderMarker, sizeof(Header.m_aMarker)); Header.m_Version = gs_ActVersion; str_copy(Header.m_aNetversion, pNetVersion, sizeof(Header.m_aNetversion)); str_copy(Header.m_aMapName, pMap, sizeof(Header.m_aMapName)); unsigned MapSize = io_length(MapFile); Header.m_aMapSize[0] = (MapSize>>24)&0xff; Header.m_aMapSize[1] = (MapSize>>16)&0xff; Header.m_aMapSize[2] = (MapSize>>8)&0xff; Header.m_aMapSize[3] = (MapSize)&0xff; Header.m_aMapCrc[0] = (Crc>>24)&0xff; Header.m_aMapCrc[1] = (Crc>>16)&0xff; Header.m_aMapCrc[2] = (Crc>>8)&0xff; Header.m_aMapCrc[3] = (Crc)&0xff; str_copy(Header.m_aType, pType, sizeof(Header.m_aType)); // Header.m_Length - add this on stop str_timestamp(Header.m_aTimestamp, sizeof(Header.m_aTimestamp)); // Header.m_aNumTimelineMarkers - add this on stop // Header.m_aTimelineMarkers - add this on stop io_write(DemoFile, &Header, sizeof(Header)); // write map data while(1) { unsigned char aChunk[1024*64]; int Bytes = io_read(MapFile, &aChunk, sizeof(aChunk)); if(Bytes <= 0) break; io_write(DemoFile, &aChunk, Bytes); } io_close(MapFile); m_LastKeyFrame = -1; m_LastTickMarker = -1; m_FirstTick = -1; m_NumTimelineMarkers = 0; char aBuf[256]; str_format(aBuf, sizeof(aBuf), "Recording to '%s'", pFilename); m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "demo_recorder", aBuf); m_File = DemoFile; return 0; } /* Tickmarker 7 = Always set 6 = Keyframe flag 0-5 = Delta tick Normal 7 = Not set 5-6 = Type 0-4 = Size */ enum { CHUNKTYPEFLAG_TICKMARKER = 0x80, CHUNKTICKFLAG_KEYFRAME = 0x40, // only when tickmarker is set CHUNKMASK_TICK = 0x3f, CHUNKMASK_TYPE = 0x60, CHUNKMASK_SIZE = 0x1f, CHUNKTYPE_SNAPSHOT = 1, CHUNKTYPE_MESSAGE = 2, CHUNKTYPE_DELTA = 3, CHUNKFLAG_BIGSIZE = 0x10 }; void CDemoRecorder::WriteTickMarker(int Tick, int Keyframe) { if(m_LastTickMarker == -1 || Tick-m_LastTickMarker > 63 || Keyframe) { unsigned char aChunk[5]; aChunk[0] = CHUNKTYPEFLAG_TICKMARKER; aChunk[1] = (Tick>>24)&0xff; aChunk[2] = (Tick>>16)&0xff; aChunk[3] = (Tick>>8)&0xff; aChunk[4] = (Tick)&0xff; if(Keyframe) aChunk[0] |= CHUNKTICKFLAG_KEYFRAME; io_write(m_File, aChunk, sizeof(aChunk)); } else { unsigned char aChunk[1]; aChunk[0] = CHUNKTYPEFLAG_TICKMARKER | (Tick-m_LastTickMarker); io_write(m_File, aChunk, sizeof(aChunk)); } m_LastTickMarker = Tick; if(m_FirstTick < 0) m_FirstTick = Tick; } void CDemoRecorder::Write(int Type, const void *pData, int Size) { char aBuffer[64*1024]; char aBuffer2[64*1024]; unsigned char aChunk[3]; if(!m_File) return; /* pad the data with 0 so we get an alignment of 4, else the compression won't work and miss some bytes */ mem_copy(aBuffer2, pData, Size); while(Size&3) aBuffer2[Size++] = 0; Size = CVariableInt::Compress(aBuffer2, Size, aBuffer); // buffer2 -> buffer Size = CNetBase::Compress(aBuffer, Size, aBuffer2, sizeof(aBuffer2)); // buffer -> buffer2 aChunk[0] = ((Type&0x3)<<5); if(Size < 30) { aChunk[0] |= Size; io_write(m_File, aChunk, 1); } else { if(Size < 256) { aChunk[0] |= 30; aChunk[1] = Size&0xff; io_write(m_File, aChunk, 2); } else { aChunk[0] |= 31; aChunk[1] = Size&0xff; aChunk[2] = Size>>8; io_write(m_File, aChunk, 3); } } io_write(m_File, aBuffer2, Size); } void CDemoRecorder::RecordSnapshot(int Tick, const void *pData, int Size) { if(m_LastKeyFrame == -1 || (Tick-m_LastKeyFrame) > SERVER_TICK_SPEED*5) { // write full tickmarker WriteTickMarker(Tick, 1); // write snapshot Write(CHUNKTYPE_SNAPSHOT, pData, Size); m_LastKeyFrame = Tick; mem_copy(m_aLastSnapshotData, pData, Size); } else { // create delta, prepend tick char aDeltaData[CSnapshot::MAX_SIZE+sizeof(int)]; int DeltaSize; // write tickmarker WriteTickMarker(Tick, 0); DeltaSize = m_pSnapshotDelta->CreateDelta((CSnapshot*)m_aLastSnapshotData, (CSnapshot*)pData, &aDeltaData); if(DeltaSize) { // record delta Write(CHUNKTYPE_DELTA, aDeltaData, DeltaSize); mem_copy(m_aLastSnapshotData, pData, Size); } } } void CDemoRecorder::RecordMessage(const void *pData, int Size) { Write(CHUNKTYPE_MESSAGE, pData, Size); } int CDemoRecorder::Stop() { if(!m_File) return -1; // add the demo length to the header io_seek(m_File, gs_LengthOffset, IOSEEK_START); int DemoLength = Length(); char aLength[4]; aLength[0] = (DemoLength>>24)&0xff; aLength[1] = (DemoLength>>16)&0xff; aLength[2] = (DemoLength>>8)&0xff; aLength[3] = (DemoLength)&0xff; io_write(m_File, aLength, sizeof(aLength)); // add the timeline markers to the header io_seek(m_File, gs_NumMarkersOffset, IOSEEK_START); char aNumMarkers[4]; aNumMarkers[0] = (m_NumTimelineMarkers>>24)&0xff; aNumMarkers[1] = (m_NumTimelineMarkers>>16)&0xff; aNumMarkers[2] = (m_NumTimelineMarkers>>8)&0xff; aNumMarkers[3] = (m_NumTimelineMarkers)&0xff; io_write(m_File, aNumMarkers, sizeof(aNumMarkers)); for(int i = 0; i < m_NumTimelineMarkers; i++) { int Marker = m_aTimelineMarkers[i]; char aMarker[4]; aMarker[0] = (Marker>>24)&0xff; aMarker[1] = (Marker>>16)&0xff; aMarker[2] = (Marker>>8)&0xff; aMarker[3] = (Marker)&0xff; io_write(m_File, aMarker, sizeof(aMarker)); } io_close(m_File); m_File = 0; m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "demo_recorder", "Stopped recording"); return 0; } void CDemoRecorder::AddDemoMarker() { if(m_LastTickMarker < 0 || m_NumTimelineMarkers >= MAX_TIMELINE_MARKERS) return; // not more than 1 marker in a second if(m_NumTimelineMarkers > 0) { int Diff = m_LastTickMarker - m_aTimelineMarkers[m_NumTimelineMarkers-1]; if(Diff < SERVER_TICK_SPEED*1.0f) return; } m_aTimelineMarkers[m_NumTimelineMarkers++] = m_LastTickMarker; m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "demo_recorder", "Added timeline marker"); } CDemoPlayer::CDemoPlayer(class CSnapshotDelta *pSnapshotDelta) { m_File = 0; m_aErrorMsg[0] = 0; m_pKeyFrames = 0; m_pSnapshotDelta = pSnapshotDelta; m_LastSnapshotDataSize = -1; } void CDemoPlayer::SetListner(IListner *pListner) { m_pListner = pListner; } int CDemoPlayer::ReadChunkHeader(int *pType, int *pSize, int *pTick) { unsigned char Chunk = 0; *pSize = 0; *pType = 0; if(io_read(m_File, &Chunk, sizeof(Chunk)) != sizeof(Chunk)) return -1; if(Chunk&CHUNKTYPEFLAG_TICKMARKER) { // decode tick marker int Tickdelta = Chunk&(CHUNKMASK_TICK); *pType = Chunk&(CHUNKTYPEFLAG_TICKMARKER|CHUNKTICKFLAG_KEYFRAME); if(Tickdelta == 0) { unsigned char aTickdata[4]; if(io_read(m_File, aTickdata, sizeof(aTickdata)) != sizeof(aTickdata)) return -1; *pTick = (aTickdata[0]<<24) | (aTickdata[1]<<16) | (aTickdata[2]<<8) | aTickdata[3]; } else { *pTick += Tickdelta; } } else { // decode normal chunk *pType = (Chunk&CHUNKMASK_TYPE)>>5; *pSize = Chunk&CHUNKMASK_SIZE; if(*pSize == 30) { unsigned char aSizedata[1]; if(io_read(m_File, aSizedata, sizeof(aSizedata)) != sizeof(aSizedata)) return -1; *pSize = aSizedata[0]; } else if(*pSize == 31) { unsigned char aSizedata[2]; if(io_read(m_File, aSizedata, sizeof(aSizedata)) != sizeof(aSizedata)) return -1; *pSize = (aSizedata[1]<<8) | aSizedata[0]; } } return 0; } void CDemoPlayer::ScanFile() { long StartPos; CHeap Heap; CKeyFrameSearch *pFirstKey = 0; CKeyFrameSearch *pCurrentKey = 0; //DEMOREC_CHUNK chunk; int ChunkSize, ChunkType, ChunkTick = 0; int i; StartPos = io_tell(m_File); m_Info.m_SeekablePoints = 0; while(1) { long CurrentPos = io_tell(m_File); if(ReadChunkHeader(&ChunkType, &ChunkSize, &ChunkTick)) break; // read the chunk if(ChunkType&CHUNKTYPEFLAG_TICKMARKER) { if(ChunkType&CHUNKTICKFLAG_KEYFRAME) { CKeyFrameSearch *pKey; // save the position pKey = (CKeyFrameSearch *)Heap.Allocate(sizeof(CKeyFrameSearch)); pKey->m_Frame.m_Filepos = CurrentPos; pKey->m_Frame.m_Tick = ChunkTick; pKey->m_pNext = 0; if(pCurrentKey) pCurrentKey->m_pNext = pKey; if(!pFirstKey) pFirstKey = pKey; pCurrentKey = pKey; m_Info.m_SeekablePoints++; } if(m_Info.m_Info.m_FirstTick == -1) m_Info.m_Info.m_FirstTick = ChunkTick; m_Info.m_Info.m_LastTick = ChunkTick; } else if(ChunkSize) io_skip(m_File, ChunkSize); } // copy all the frames to an array instead for fast access m_pKeyFrames = (CKeyFrame*)mem_alloc(m_Info.m_SeekablePoints*sizeof(CKeyFrame), 1); for(pCurrentKey = pFirstKey, i = 0; pCurrentKey; pCurrentKey = pCurrentKey->m_pNext, i++) m_pKeyFrames[i] = pCurrentKey->m_Frame; // destroy the temporary heap and seek back to the start io_seek(m_File, StartPos, IOSEEK_START); } void CDemoPlayer::DoTick() { static char aCompresseddata[CSnapshot::MAX_SIZE]; static char aDecompressed[CSnapshot::MAX_SIZE]; static char aData[CSnapshot::MAX_SIZE]; int ChunkType, ChunkTick, ChunkSize; int DataSize = 0; int GotSnapshot = 0; // update ticks m_Info.m_PreviousTick = m_Info.m_Info.m_CurrentTick; m_Info.m_Info.m_CurrentTick = m_Info.m_NextTick; ChunkTick = m_Info.m_Info.m_CurrentTick; while(1) { if(ReadChunkHeader(&ChunkType, &ChunkSize, &ChunkTick)) { // stop on error or eof m_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "demo_player", "end of file"); if(m_Info.m_PreviousTick == -1) { m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "demo_player", "empty demo"); Stop(); } else Pause(); break; } // read the chunk if(ChunkSize) { if(io_read(m_File, aCompresseddata, ChunkSize) != (unsigned)ChunkSize) { // stop on error or eof m_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "demo_player", "error reading chunk"); Stop(); break; } DataSize = CNetBase::Decompress(aCompresseddata, ChunkSize, aDecompressed, sizeof(aDecompressed)); if(DataSize < 0) { // stop on error or eof m_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "demo_player", "error during network decompression"); Stop(); break; } DataSize = CVariableInt::Decompress(aDecompressed, DataSize, aData); if(DataSize < 0) { m_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "demo_player", "error during intpack decompression"); Stop(); break; } } if(ChunkType == CHUNKTYPE_DELTA) { // process delta snapshot static char aNewsnap[CSnapshot::MAX_SIZE]; GotSnapshot = 1; DataSize = m_pSnapshotDelta->UnpackDelta((CSnapshot*)m_aLastSnapshotData, (CSnapshot*)aNewsnap, aData, DataSize); if(DataSize >= 0) { if(m_pListner) m_pListner->OnDemoPlayerSnapshot(aNewsnap, DataSize); m_LastSnapshotDataSize = DataSize; mem_copy(m_aLastSnapshotData, aNewsnap, DataSize); } else { char aBuf[256]; str_format(aBuf, sizeof(aBuf), "error during unpacking of delta, err=%d", DataSize); m_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "demo_player", aBuf); } } else if(ChunkType == CHUNKTYPE_SNAPSHOT) { // process full snapshot GotSnapshot = 1; m_LastSnapshotDataSize = DataSize; mem_copy(m_aLastSnapshotData, aData, DataSize); if(m_pListner) m_pListner->OnDemoPlayerSnapshot(aData, DataSize); } else { // if there were no snapshots in this tick, replay the last one if(!GotSnapshot && m_pListner && m_LastSnapshotDataSize != -1) { GotSnapshot = 1; m_pListner->OnDemoPlayerSnapshot(m_aLastSnapshotData, m_LastSnapshotDataSize); } // check the remaining types if(ChunkType&CHUNKTYPEFLAG_TICKMARKER) { m_Info.m_NextTick = ChunkTick; break; } else if(ChunkType == CHUNKTYPE_MESSAGE) { if(m_pListner) m_pListner->OnDemoPlayerMessage(aData, DataSize); } } } } void CDemoPlayer::Pause() { m_Info.m_Info.m_Paused = 1; } void CDemoPlayer::Unpause() { if(m_Info.m_Info.m_Paused) { /*m_Info.start_tick = m_Info.current_tick; m_Info.start_time = time_get();*/ m_Info.m_Info.m_Paused = 0; } } const char *CDemoPlayer::Load(class IStorage *pStorage, class IConsole *pConsole, const char *pFilename, int StorageType, const char *pNetversion) { m_pConsole = pConsole; m_aErrorMsg[0] = 0; m_File = pStorage->OpenFile(pFilename, IOFLAG_READ, StorageType); if(!m_File) { str_format(m_aErrorMsg, sizeof(m_aErrorMsg), "could not open '%s'", pFilename); m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "demo_player", m_aErrorMsg); return m_aErrorMsg; } // store the filename str_copy(m_aFilename, pFilename, sizeof(m_aFilename)); // clear the playback info mem_zero(&m_Info, sizeof(m_Info)); m_Info.m_Info.m_FirstTick = -1; m_Info.m_Info.m_LastTick = -1; m_Info.m_NextTick = -1; m_Info.m_Info.m_CurrentTick = -1; m_Info.m_PreviousTick = -1; m_Info.m_Info.m_Speed = 1; m_LastSnapshotDataSize = -1; // read the header io_read(m_File, &m_Info.m_Header, sizeof(m_Info.m_Header)); if(mem_comp(m_Info.m_Header.m_aMarker, gs_aHeaderMarker, sizeof(gs_aHeaderMarker)) != 0) { str_format(m_aErrorMsg, sizeof(m_aErrorMsg), "'%s' is not a demo file", pFilename); m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "demo_player", m_aErrorMsg); io_close(m_File); m_File = 0; return m_aErrorMsg; } if(m_Info.m_Header.m_Version < gs_ActVersion) { str_format(m_aErrorMsg, sizeof(m_aErrorMsg), "demo version %d is not supported", m_Info.m_Header.m_Version); m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "demo_player", m_aErrorMsg); io_close(m_File); m_File = 0; return m_aErrorMsg; } if(str_comp(m_Info.m_Header.m_aNetversion, pNetversion) != 0) { str_format(m_aErrorMsg, sizeof(m_aErrorMsg), "net version '%s' is not supported", m_Info.m_Header.m_aNetversion); m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "demo_player", m_aErrorMsg); io_close(m_File); m_File = 0; return m_aErrorMsg; } // get demo type if(!str_comp(m_Info.m_Header.m_aType, "client")) m_DemoType = DEMOTYPE_CLIENT; else if(!str_comp(m_Info.m_Header.m_aType, "server")) m_DemoType = DEMOTYPE_SERVER; else m_DemoType = DEMOTYPE_INVALID; // read map unsigned MapSize = (m_Info.m_Header.m_aMapSize[0]<<24) | (m_Info.m_Header.m_aMapSize[1]<<16) | (m_Info.m_Header.m_aMapSize[2]<<8) | (m_Info.m_Header.m_aMapSize[3]); // check if we already have the map // TODO: improve map checking (maps folder, check crc) unsigned Crc = (m_Info.m_Header.m_aMapCrc[0]<<24) | (m_Info.m_Header.m_aMapCrc[1]<<16) | (m_Info.m_Header.m_aMapCrc[2]<<8) | (m_Info.m_Header.m_aMapCrc[3]); char aMapFilename[128]; str_format(aMapFilename, sizeof(aMapFilename), "downloadedmaps/%s_%08x.map", m_Info.m_Header.m_aMapName, Crc); IOHANDLE MapFile = pStorage->OpenFile(aMapFilename, IOFLAG_READ, IStorage::TYPE_ALL); if(MapFile) { io_skip(m_File, MapSize); io_close(MapFile); } else if(MapSize > 0) { // get map data unsigned char *pMapData = (unsigned char *)mem_alloc(MapSize, 1); io_read(m_File, pMapData, MapSize); // save map MapFile = pStorage->OpenFile(aMapFilename, IOFLAG_WRITE, IStorage::TYPE_SAVE); io_write(MapFile, pMapData, MapSize); io_close(MapFile); // free data mem_free(pMapData); } // get timeline markers int Num = ((m_Info.m_Header.m_aNumTimelineMarkers[0]<<24)&0xFF000000) | ((m_Info.m_Header.m_aNumTimelineMarkers[1]<<16)&0xFF0000) | ((m_Info.m_Header.m_aNumTimelineMarkers[2]<<8)&0xFF00) | (m_Info.m_Header.m_aNumTimelineMarkers[3]&0xFF); m_Info.m_Info.m_NumTimelineMarkers = Num; for(int i = 0; i < Num && i < MAX_TIMELINE_MARKERS; i++) { char *pTimelineMarker = m_Info.m_Header.m_aTimelineMarkers[i]; m_Info.m_Info.m_aTimelineMarkers[i] = ((pTimelineMarker[0]<<24)&0xFF000000) | ((pTimelineMarker[1]<<16)&0xFF0000) | ((pTimelineMarker[2]<<8)&0xFF00) | (pTimelineMarker[3]&0xFF); } // scan the file for interessting points ScanFile(); // ready for playback return 0; } int CDemoPlayer::NextFrame() { DoTick(); return IsPlaying(); } int CDemoPlayer::Play() { // fill in previous and next tick while(m_Info.m_PreviousTick == -1 && IsPlaying()) DoTick(); // set start info /*m_Info.start_tick = m_Info.previous_tick; m_Info.start_time = time_get();*/ m_Info.m_CurrentTime = m_Info.m_PreviousTick*time_freq()/SERVER_TICK_SPEED; m_Info.m_LastUpdate = time_get(); return 0; } int CDemoPlayer::SetPos(float Percent) { int Keyframe; int WantedTick; if(!m_File) return -1; // -5 because we have to have a current tick and previous tick when we do the playback WantedTick = m_Info.m_Info.m_FirstTick + (int)((m_Info.m_Info.m_LastTick-m_Info.m_Info.m_FirstTick)*Percent) - 5; Keyframe = (int)(m_Info.m_SeekablePoints*Percent); if(Keyframe < 0 || Keyframe >= m_Info.m_SeekablePoints) return -1; // get correct key frame if(m_pKeyFrames[Keyframe].m_Tick < WantedTick) while(Keyframe < m_Info.m_SeekablePoints-1 && m_pKeyFrames[Keyframe].m_Tick < WantedTick) Keyframe++; while(Keyframe && m_pKeyFrames[Keyframe].m_Tick > WantedTick) Keyframe--; // seek to the correct keyframe io_seek(m_File, m_pKeyFrames[Keyframe].m_Filepos, IOSEEK_START); //m_Info.start_tick = -1; m_Info.m_NextTick = -1; m_Info.m_Info.m_CurrentTick = -1; m_Info.m_PreviousTick = -1; // playback everything until we hit our tick while(m_Info.m_PreviousTick < WantedTick) DoTick(); Play(); return 0; } void CDemoPlayer::SetSpeed(float Speed) { m_Info.m_Info.m_Speed = Speed; } int CDemoPlayer::Update() { int64 Now = time_get(); int64 Deltatime = Now-m_Info.m_LastUpdate; m_Info.m_LastUpdate = Now; if(!IsPlaying()) return 0; if(m_Info.m_Info.m_Paused) { } else { int64 Freq = time_freq(); m_Info.m_CurrentTime += (int64)(Deltatime*(double)m_Info.m_Info.m_Speed); while(1) { int64 CurtickStart = (m_Info.m_Info.m_CurrentTick)*Freq/SERVER_TICK_SPEED; // break if we are ready if(CurtickStart > m_Info.m_CurrentTime) break; // do one more tick DoTick(); if(m_Info.m_Info.m_Paused) return 0; } // update intratick { int64 CurtickStart = (m_Info.m_Info.m_CurrentTick)*Freq/SERVER_TICK_SPEED; int64 PrevtickStart = (m_Info.m_PreviousTick)*Freq/SERVER_TICK_SPEED; m_Info.m_IntraTick = (m_Info.m_CurrentTime - PrevtickStart) / (float)(CurtickStart-PrevtickStart); m_Info.m_TickTime = (m_Info.m_CurrentTime - PrevtickStart) / (float)Freq; } if(m_Info.m_Info.m_CurrentTick == m_Info.m_PreviousTick || m_Info.m_Info.m_CurrentTick == m_Info.m_NextTick) { char aBuf[256]; str_format(aBuf, sizeof(aBuf), "tick error prev=%d cur=%d next=%d", m_Info.m_PreviousTick, m_Info.m_Info.m_CurrentTick, m_Info.m_NextTick); m_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "demo_player", aBuf); } } return 0; } int CDemoPlayer::Stop() { if(!m_File) return -1; m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "demo_player", "Stopped playback"); io_close(m_File); m_File = 0; mem_free(m_pKeyFrames); m_pKeyFrames = 0; str_copy(m_aFilename, "", sizeof(m_aFilename)); return 0; } void CDemoPlayer::GetDemoName(char *pBuffer, int BufferSize) const { const char *pFileName = m_aFilename; const char *pExtractedName = pFileName; const char *pEnd = 0; for(; *pFileName; ++pFileName) { if(*pFileName == '/' || *pFileName == '\\') pExtractedName = pFileName+1; else if(*pFileName == '.') pEnd = pFileName; } int Length = pEnd > pExtractedName ? min(BufferSize, (int)(pEnd-pExtractedName+1)) : BufferSize; str_copy(pBuffer, pExtractedName, Length); } bool CDemoPlayer::GetDemoInfo(class IStorage *pStorage, const char *pFilename, int StorageType, CDemoHeader *pDemoHeader) const { if(!pDemoHeader) return false; mem_zero(pDemoHeader, sizeof(CDemoHeader)); IOHANDLE File = pStorage->OpenFile(pFilename, IOFLAG_READ, StorageType); if(!File) return false; io_read(File, pDemoHeader, sizeof(CDemoHeader)); if(mem_comp(pDemoHeader->m_aMarker, gs_aHeaderMarker, sizeof(gs_aHeaderMarker)) || pDemoHeader->m_Version < gs_ActVersion) { io_close(File); return false; } io_close(File); return true; } int CDemoPlayer::GetDemoType() const { if(m_File) return m_DemoType; return DEMOTYPE_INVALID; } ================================================ FILE: src/engine/shared/demo.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef ENGINE_SHARED_DEMO_H #define ENGINE_SHARED_DEMO_H #include <engine/demo.h> #include <engine/shared/protocol.h> #include "snapshot.h" class CDemoRecorder : public IDemoRecorder { class IConsole *m_pConsole; IOHANDLE m_File; int m_LastTickMarker; int m_LastKeyFrame; int m_FirstTick; unsigned char m_aLastSnapshotData[CSnapshot::MAX_SIZE]; class CSnapshotDelta *m_pSnapshotDelta; int m_NumTimelineMarkers; int m_aTimelineMarkers[MAX_TIMELINE_MARKERS]; void WriteTickMarker(int Tick, int Keyframe); void Write(int Type, const void *pData, int Size); public: CDemoRecorder(class CSnapshotDelta *pSnapshotDelta); int Start(class IStorage *pStorage, class IConsole *pConsole, const char *pFilename, const char *pNetversion, const char *pMap, unsigned MapCrc, const char *pType); int Stop(); void AddDemoMarker(); void RecordSnapshot(int Tick, const void *pData, int Size); void RecordMessage(const void *pData, int Size); bool IsRecording() const { return m_File != 0; } int Length() const { return (m_LastTickMarker - m_FirstTick)/SERVER_TICK_SPEED; } }; class CDemoPlayer : public IDemoPlayer { public: class IListner { public: virtual ~IListner() {} virtual void OnDemoPlayerSnapshot(void *pData, int Size) = 0; virtual void OnDemoPlayerMessage(void *pData, int Size) = 0; }; struct CPlaybackInfo { CDemoHeader m_Header; IDemoPlayer::CInfo m_Info; int64 m_LastUpdate; int64 m_CurrentTime; int m_SeekablePoints; int m_NextTick; int m_PreviousTick; float m_IntraTick; float m_TickTime; }; private: IListner *m_pListner; // Playback struct CKeyFrame { long m_Filepos; int m_Tick; }; struct CKeyFrameSearch { CKeyFrame m_Frame; CKeyFrameSearch *m_pNext; }; class IConsole *m_pConsole; IOHANDLE m_File; char m_aFilename[256]; char m_aErrorMsg[256]; CKeyFrame *m_pKeyFrames; CPlaybackInfo m_Info; int m_DemoType; unsigned char m_aLastSnapshotData[CSnapshot::MAX_SIZE]; int m_LastSnapshotDataSize; class CSnapshotDelta *m_pSnapshotDelta; int ReadChunkHeader(int *pType, int *pSize, int *pTick); void DoTick(); void ScanFile(); int NextFrame(); public: CDemoPlayer(class CSnapshotDelta *m_pSnapshotDelta); void SetListner(IListner *pListner); const char *Load(class IStorage *pStorage, class IConsole *pConsole, const char *pFilename, int StorageType, const char *pNetversion); int Play(); void Pause(); void Unpause(); int Stop(); void SetSpeed(float Speed); int SetPos(float Percent); const CInfo *BaseInfo() const { return &m_Info.m_Info; } void GetDemoName(char *pBuffer, int BufferSize) const; bool GetDemoInfo(class IStorage *pStorage, const char *pFilename, int StorageType, CDemoHeader *pDemoHeader) const; int GetDemoType() const; int Update(); const CPlaybackInfo *Info() const { return &m_Info; } int IsPlaying() const { return m_File != 0; } }; #endif ================================================ FILE: src/engine/shared/econ.cpp ================================================ #include <engine/console.h> #include <engine/shared/config.h> #include "econ.h" #include "netban.h" int CEcon::NewClientCallback(int ClientID, void *pUser) { CEcon *pThis = (CEcon *)pUser; char aAddrStr[NETADDR_MAXSTRSIZE]; net_addr_str(pThis->m_NetConsole.ClientAddr(ClientID), aAddrStr, sizeof(aAddrStr), true); char aBuf[128]; str_format(aBuf, sizeof(aBuf), "client accepted. cid=%d addr=%s'", ClientID, aAddrStr); pThis->Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "econ", aBuf); pThis->m_aClients[ClientID].m_State = CClient::STATE_CONNECTED; pThis->m_aClients[ClientID].m_TimeConnected = time_get(); pThis->m_aClients[ClientID].m_AuthTries = 0; pThis->m_NetConsole.Send(ClientID, "Enter password:"); return 0; } int CEcon::DelClientCallback(int ClientID, const char *pReason, void *pUser) { CEcon *pThis = (CEcon *)pUser; char aAddrStr[NETADDR_MAXSTRSIZE]; net_addr_str(pThis->m_NetConsole.ClientAddr(ClientID), aAddrStr, sizeof(aAddrStr), true); char aBuf[256]; str_format(aBuf, sizeof(aBuf), "client dropped. cid=%d addr=%s reason='%s'", ClientID, aAddrStr, pReason); pThis->Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "econ", aBuf); pThis->m_aClients[ClientID].m_State = CClient::STATE_EMPTY; return 0; } void CEcon::SendLineCB(const char *pLine, void *pUserData) { static_cast<CEcon *>(pUserData)->Send(-1, pLine); } void CEcon::ConchainEconOutputLevelUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData) { pfnCallback(pResult, pCallbackUserData); if(pResult->NumArguments() == 1) { CEcon *pThis = static_cast<CEcon *>(pUserData); pThis->Console()->SetPrintOutputLevel(pThis->m_PrintCBIndex, pResult->GetInteger(0)); } } void CEcon::ConLogout(IConsole::IResult *pResult, void *pUserData) { CEcon *pThis = static_cast<CEcon *>(pUserData); if(pThis->m_UserClientID >= 0 && pThis->m_UserClientID < NET_MAX_CONSOLE_CLIENTS && pThis->m_aClients[pThis->m_UserClientID].m_State != CClient::STATE_EMPTY) pThis->m_NetConsole.Drop(pThis->m_UserClientID, "Logout"); } void CEcon::Init(IConsole *pConsole, CNetBan *pNetBan) { m_pConsole = pConsole; for(int i = 0; i < NET_MAX_CONSOLE_CLIENTS; i++) m_aClients[i].m_State = CClient::STATE_EMPTY; m_Ready = false; m_UserClientID = -1; if(g_Config.m_EcPort == 0 || g_Config.m_EcPassword[0] == 0) return; NETADDR BindAddr; if(g_Config.m_EcBindaddr[0] && net_host_lookup(g_Config.m_EcBindaddr, &BindAddr, NETTYPE_ALL) == 0) { // got bindaddr BindAddr.type = NETTYPE_ALL; BindAddr.port = g_Config.m_EcPort; } else { mem_zero(&BindAddr, sizeof(BindAddr)); BindAddr.type = NETTYPE_ALL; BindAddr.port = g_Config.m_EcPort; } if(m_NetConsole.Open(BindAddr, pNetBan, 0)) { m_NetConsole.SetCallbacks(NewClientCallback, DelClientCallback, this); m_Ready = true; char aBuf[128]; str_format(aBuf, sizeof(aBuf), "bound to %s:%d", g_Config.m_EcBindaddr, g_Config.m_EcPort); Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD,"econ", aBuf); Console()->Chain("ec_output_level", ConchainEconOutputLevelUpdate, this); m_PrintCBIndex = Console()->RegisterPrintCallback(g_Config.m_EcOutputLevel, SendLineCB, this); Console()->Register("logout", "", CFGFLAG_ECON, ConLogout, this, "Logout of econ"); } else Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD,"econ", "couldn't open socket. port might already be in use"); } void CEcon::Update() { if(!m_Ready) return; m_NetConsole.Update(); char aBuf[NET_MAX_PACKETSIZE]; int ClientID; while(m_NetConsole.Recv(aBuf, (int)(sizeof(aBuf))-1, &ClientID)) { dbg_assert(m_aClients[ClientID].m_State != CClient::STATE_EMPTY, "got message from empty slot"); if(m_aClients[ClientID].m_State == CClient::STATE_CONNECTED) { if(str_comp(aBuf, g_Config.m_EcPassword) == 0) { m_aClients[ClientID].m_State = CClient::STATE_AUTHED; m_NetConsole.Send(ClientID, "Authentication successful. External console access granted."); str_format(aBuf, sizeof(aBuf), "cid=%d authed", ClientID); Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "econ", aBuf); } else { m_aClients[ClientID].m_AuthTries++; char aMsg[128]; str_format(aMsg, sizeof(aMsg), "Wrong password %d/%d.", m_aClients[ClientID].m_AuthTries, MAX_AUTH_TRIES); m_NetConsole.Send(ClientID, aMsg); if(m_aClients[ClientID].m_AuthTries >= MAX_AUTH_TRIES) { if(!g_Config.m_EcBantime) m_NetConsole.Drop(ClientID, "Too many authentication tries"); else m_NetConsole.NetBan()->BanAddr(m_NetConsole.ClientAddr(ClientID), g_Config.m_EcBantime*60, "Too many authentication tries"); } } } else if(m_aClients[ClientID].m_State == CClient::STATE_AUTHED) { char aFormatted[256]; str_format(aFormatted, sizeof(aFormatted), "cid=%d cmd='%s'", ClientID, aBuf); Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "server", aFormatted); m_UserClientID = ClientID; Console()->ExecuteLine(aBuf); m_UserClientID = -1; } } for(int i = 0; i < NET_MAX_CONSOLE_CLIENTS; ++i) { if(m_aClients[i].m_State == CClient::STATE_CONNECTED && time_get() > m_aClients[i].m_TimeConnected + g_Config.m_EcAuthTimeout * time_freq()) m_NetConsole.Drop(i, "authentication timeout"); } } void CEcon::Send(int ClientID, const char *pLine) { if(!m_Ready) return; if(ClientID == -1) { for(int i = 0; i < NET_MAX_CONSOLE_CLIENTS; i++) { if(m_aClients[i].m_State == CClient::STATE_AUTHED) m_NetConsole.Send(i, pLine); } } else if(ClientID >= 0 && ClientID < NET_MAX_CONSOLE_CLIENTS && m_aClients[ClientID].m_State == CClient::STATE_AUTHED) m_NetConsole.Send(ClientID, pLine); } void CEcon::Shutdown() { if(!m_Ready) return; m_NetConsole.Close(); } ================================================ FILE: src/engine/shared/econ.h ================================================ #ifndef ENGINE_SHARED_ECON_H #define ENGINE_SHARED_ECON_H #include "network.h" class CEcon { enum { MAX_AUTH_TRIES=3, }; class CClient { public: enum { STATE_EMPTY=0, STATE_CONNECTED, STATE_AUTHED, }; int m_State; int64 m_TimeConnected; int m_AuthTries; }; CClient m_aClients[NET_MAX_CONSOLE_CLIENTS]; IConsole *m_pConsole; CNetConsole m_NetConsole; bool m_Ready; int m_PrintCBIndex; int m_UserClientID; static void SendLineCB(const char *pLine, void *pUserData); static void ConchainEconOutputLevelUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData); static void ConLogout(IConsole::IResult *pResult, void *pUserData); static int NewClientCallback(int ClientID, void *pUser); static int DelClientCallback(int ClientID, const char *pReason, void *pUser); public: IConsole *Console() { return m_pConsole; } void Init(IConsole *pConsole, class CNetBan *pNetBan); void Update(); void Send(int ClientID, const char *pLine); void Shutdown(); }; #endif ================================================ FILE: src/engine/shared/engine.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <base/system.h> #include <engine/console.h> #include <engine/engine.h> #include <engine/storage.h> #include <engine/shared/config.h> #include <engine/shared/network.h> static int HostLookupThread(void *pUser) { CHostLookup *pLookup = (CHostLookup *)pUser; return net_host_lookup(pLookup->m_aHostname, &pLookup->m_Addr, pLookup->m_Nettype); } class CEngine : public IEngine { public: IConsole *m_pConsole; IStorage *m_pStorage; bool m_Logging; static void Con_DbgDumpmem(IConsole::IResult *pResult, void *pUserData) { CEngine *pEngine = static_cast<CEngine *>(pUserData); char aBuf[32]; str_timestamp(aBuf, sizeof(aBuf)); char aFilename[128]; str_format(aFilename, sizeof(aFilename), "dumps/memory_%s.txt", aBuf); mem_debug_dump(pEngine->m_pStorage->OpenFile(aFilename, IOFLAG_WRITE, IStorage::TYPE_SAVE)); } static void Con_DbgLognetwork(IConsole::IResult *pResult, void *pUserData) { CEngine *pEngine = static_cast<CEngine *>(pUserData); if(pEngine->m_Logging) { CNetBase::CloseLog(); pEngine->m_Logging = false; } else { char aBuf[32]; str_timestamp(aBuf, sizeof(aBuf)); char aFilenameSent[128], aFilenameRecv[128]; str_format(aFilenameSent, sizeof(aFilenameSent), "dumps/network_sent_%s.txt", aBuf); str_format(aFilenameRecv, sizeof(aFilenameRecv), "dumps/network_recv_%s.txt", aBuf); CNetBase::OpenLog(pEngine->m_pStorage->OpenFile(aFilenameSent, IOFLAG_WRITE, IStorage::TYPE_SAVE), pEngine->m_pStorage->OpenFile(aFilenameRecv, IOFLAG_WRITE, IStorage::TYPE_SAVE)); pEngine->m_Logging = true; } } CEngine(const char *pAppname) { dbg_logger_stdout(); dbg_logger_debugger(); // dbg_msg("engine", "running on %s-%s-%s", CONF_FAMILY_STRING, CONF_PLATFORM_STRING, CONF_ARCH_STRING); #ifdef CONF_ARCH_ENDIAN_LITTLE dbg_msg("engine", "arch is little endian"); #elif defined(CONF_ARCH_ENDIAN_BIG) dbg_msg("engine", "arch is big endian"); #else dbg_msg("engine", "unknown endian"); #endif // init the network net_init(); CNetBase::Init(); m_JobPool.Init(1); m_Logging = false; } void Init() { m_pConsole = Kernel()->RequestInterface<IConsole>(); m_pStorage = Kernel()->RequestInterface<IStorage>(); if(!m_pConsole || !m_pStorage) return; m_pConsole->Register("dbg_dumpmem", "", CFGFLAG_SERVER|CFGFLAG_CLIENT, Con_DbgDumpmem, this, "Dump the memory"); m_pConsole->Register("dbg_lognetwork", "", CFGFLAG_SERVER|CFGFLAG_CLIENT, Con_DbgLognetwork, this, "Log the network"); } void InitLogfile() { // open logfile if needed if(g_Config.m_Logfile[0]) dbg_logger_file(g_Config.m_Logfile); } void HostLookup(CHostLookup *pLookup, const char *pHostname, int Nettype) { str_copy(pLookup->m_aHostname, pHostname, sizeof(pLookup->m_aHostname)); pLookup->m_Nettype = Nettype; AddJob(&pLookup->m_Job, HostLookupThread, pLookup); } void AddJob(CJob *pJob, JOBFUNC pfnFunc, void *pData) { if(g_Config.m_Debug) dbg_msg("engine", "job added"); m_JobPool.Add(pJob, pfnFunc, pData); } }; IEngine *CreateEngine(const char *pAppname) { return new CEngine(pAppname); } ================================================ FILE: src/engine/shared/filecollection.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <base/math.h> #include <engine/storage.h> #include "filecollection.h" bool CFileCollection::IsFilenameValid(const char *pFilename) { if(str_length(pFilename) != m_FileDescLength+TIMESTAMP_LENGTH+m_FileExtLength || str_comp_num(pFilename, m_aFileDesc, m_FileDescLength) || str_comp(pFilename+m_FileDescLength+TIMESTAMP_LENGTH, m_aFileExt)) return false; pFilename += m_FileDescLength; if(pFilename[0] == '_' && pFilename[1] >= '0' && pFilename[1] <= '9' && pFilename[2] >= '0' && pFilename[2] <= '9' && pFilename[3] >= '0' && pFilename[3] <= '9' && pFilename[4] >= '0' && pFilename[4] <= '9' && pFilename[5] == '-' && pFilename[6] >= '0' && pFilename[6] <= '9' && pFilename[7] >= '0' && pFilename[7] <= '9' && pFilename[8] == '-' && pFilename[9] >= '0' && pFilename[9] <= '9' && pFilename[10] >= '0' && pFilename[10] <= '9' && pFilename[11] == '_' && pFilename[12] >= '0' && pFilename[12] <= '9' && pFilename[13] >= '0' && pFilename[13] <= '9' && pFilename[14] == '-' && pFilename[15] >= '0' && pFilename[15] <= '9' && pFilename[16] >= '0' && pFilename[16] <= '9' && pFilename[17] == '-' && pFilename[18] >= '0' && pFilename[18] <= '9' && pFilename[19] >= '0' && pFilename[19] <= '9') return true; return false; } int64 CFileCollection::ExtractTimestamp(const char *pTimestring) { int64 Timestamp = pTimestring[0]-'0'; Timestamp <<= 4; Timestamp += pTimestring[1]-'0'; Timestamp <<= 4; Timestamp += pTimestring[2]-'0'; Timestamp <<= 4; Timestamp += pTimestring[3]-'0'; Timestamp <<= 4; Timestamp += pTimestring[5]-'0'; Timestamp <<= 4; Timestamp += pTimestring[6]-'0'; Timestamp <<= 4; Timestamp += pTimestring[8]-'0'; Timestamp <<= 4; Timestamp += pTimestring[9]-'0'; Timestamp <<= 4; Timestamp += pTimestring[11]-'0'; Timestamp <<= 4; Timestamp += pTimestring[12]-'0'; Timestamp <<= 4; Timestamp += pTimestring[14]-'0'; Timestamp <<= 4; Timestamp += pTimestring[15]-'0'; Timestamp <<= 4; Timestamp += pTimestring[17]-'0'; Timestamp <<= 4; Timestamp += pTimestring[18]-'0'; return Timestamp; } void CFileCollection::BuildTimestring(int64 Timestamp, char *pTimestring) { pTimestring[19] = 0; pTimestring[18] = (Timestamp&0xF)+'0'; Timestamp >>= 4; pTimestring[17] = (Timestamp&0xF)+'0'; Timestamp >>= 4; pTimestring[16] = '-'; pTimestring[15] = (Timestamp&0xF)+'0'; Timestamp >>= 4; pTimestring[14] = (Timestamp&0xF)+'0'; Timestamp >>= 4; pTimestring[13] = '-'; pTimestring[12] = (Timestamp&0xF)+'0'; Timestamp >>= 4; pTimestring[11] = (Timestamp&0xF)+'0'; Timestamp >>= 4; pTimestring[10] = '_'; pTimestring[9] = (Timestamp&0xF)+'0'; Timestamp >>= 4; pTimestring[8] = (Timestamp&0xF)+'0'; Timestamp >>= 4; pTimestring[7] = '-'; pTimestring[6] = (Timestamp&0xF)+'0'; Timestamp >>= 4; pTimestring[5] = (Timestamp&0xF)+'0'; Timestamp >>= 4; pTimestring[4] = '-'; pTimestring[3] = (Timestamp&0xF)+'0'; Timestamp >>= 4; pTimestring[2] = (Timestamp&0xF)+'0'; Timestamp >>= 4; pTimestring[1] = (Timestamp&0xF)+'0'; Timestamp >>= 4; pTimestring[0] = (Timestamp&0xF)+'0'; } void CFileCollection::Init(IStorage *pStorage, const char *pPath, const char *pFileDesc, const char *pFileExt, int MaxEntries) { mem_zero(m_aTimestamps, sizeof(m_aTimestamps)); m_NumTimestamps = 0; m_MaxEntries = clamp(MaxEntries, 1, static_cast<int>(MAX_ENTRIES)); str_copy(m_aFileDesc, pFileDesc, sizeof(m_aFileDesc)); m_FileDescLength = str_length(m_aFileDesc); str_copy(m_aFileExt, pFileExt, sizeof(m_aFileExt)); m_FileExtLength = str_length(m_aFileExt); str_copy(m_aPath, pPath, sizeof(m_aPath)); m_pStorage = pStorage; m_pStorage->ListDirectory(IStorage::TYPE_SAVE, m_aPath, FilelistCallback, this); } void CFileCollection::AddEntry(int64 Timestamp) { if(m_NumTimestamps == 0) { // empty list m_aTimestamps[m_NumTimestamps++] = Timestamp; } else { // remove old file if(m_NumTimestamps == m_MaxEntries) { char aBuf[512]; char aTimestring[TIMESTAMP_LENGTH]; BuildTimestring(m_aTimestamps[0], aTimestring); str_format(aBuf, sizeof(aBuf), "%s/%s_%s%s", m_aPath, m_aFileDesc, aTimestring, m_aFileExt); m_pStorage->RemoveFile(aBuf, IStorage::TYPE_SAVE); } // add entry to the sorted list if(m_aTimestamps[0] > Timestamp) { // first entry if(m_NumTimestamps < m_MaxEntries) { mem_move(m_aTimestamps+1, m_aTimestamps, m_NumTimestamps*sizeof(int64)); m_aTimestamps[0] = Timestamp; ++m_NumTimestamps; } } else if(m_aTimestamps[m_NumTimestamps-1] <= Timestamp) { // last entry if(m_NumTimestamps == m_MaxEntries) { mem_move(m_aTimestamps, m_aTimestamps+1, (m_NumTimestamps-1)*sizeof(int64)); m_aTimestamps[m_NumTimestamps-1] = Timestamp; } else m_aTimestamps[m_NumTimestamps++] = Timestamp; } else { // middle entry int Left = 0, Right = m_NumTimestamps-1; while(Right-Left > 1) { int Mid = (Left+Right)/2; if(m_aTimestamps[Mid] > Timestamp) Right = Mid; else Left = Mid; } if(m_NumTimestamps == m_MaxEntries) { mem_move(m_aTimestamps, m_aTimestamps+1, (Right-1)*sizeof(int64)); m_aTimestamps[Right-1] = Timestamp; } else { mem_move(m_aTimestamps+Right+1, m_aTimestamps+Right, (m_NumTimestamps-Right)*sizeof(int64)); m_aTimestamps[Right] = Timestamp; ++m_NumTimestamps; } } } } int CFileCollection::FilelistCallback(const char *pFilename, int IsDir, int StorageType, void *pUser) { CFileCollection *pThis = static_cast<CFileCollection *>(pUser); // check for valid file name format if(IsDir || !pThis->IsFilenameValid(pFilename)) return 0; // extract the timestamp int64 Timestamp = pThis->ExtractTimestamp(pFilename+pThis->m_FileDescLength+1); // add the entry pThis->AddEntry(Timestamp); return 0; } ================================================ FILE: src/engine/shared/filecollection.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef ENGINE_SHARED_FILECOLLECTION_H #define ENGINE_SHARED_FILECOLLECTION_H class CFileCollection { enum { MAX_ENTRIES=1000, TIMESTAMP_LENGTH=20, // _YYYY-MM-DD_HH-MM-SS }; int64 m_aTimestamps[MAX_ENTRIES]; int m_NumTimestamps; int m_MaxEntries; char m_aFileDesc[128]; int m_FileDescLength; char m_aFileExt[32]; int m_FileExtLength; char m_aPath[512]; IStorage *m_pStorage; bool IsFilenameValid(const char *pFilename); int64 ExtractTimestamp(const char *pTimestring); void BuildTimestring(int64 Timestamp, char *pTimestring); public: void Init(IStorage *pStorage, const char *pPath, const char *pFileDesc, const char *pFileExt, int MaxEntries); void AddEntry(int64 Timestamp); static int FilelistCallback(const char *pFilename, int IsDir, int StorageType, void *pUser); }; #endif ================================================ FILE: src/engine/shared/huffman.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <base/system.h> #include "huffman.h" struct CHuffmanConstructNode { unsigned short m_NodeId; int m_Frequency; }; void CHuffman::Setbits_r(CNode *pNode, int Bits, unsigned Depth) { if(pNode->m_aLeafs[1] != 0xffff) Setbits_r(&m_aNodes[pNode->m_aLeafs[1]], Bits|(1<<Depth), Depth+1); if(pNode->m_aLeafs[0] != 0xffff) Setbits_r(&m_aNodes[pNode->m_aLeafs[0]], Bits, Depth+1); if(pNode->m_NumBits) { pNode->m_Bits = Bits; pNode->m_NumBits = Depth; } } // TODO: this should be something faster, but it's enough for now static void BubbleSort(CHuffmanConstructNode **ppList, int Size) { int Changed = 1; CHuffmanConstructNode *pTemp; while(Changed) { Changed = 0; for(int i = 0; i < Size-1; i++) { if(ppList[i]->m_Frequency < ppList[i+1]->m_Frequency) { pTemp = ppList[i]; ppList[i] = ppList[i+1]; ppList[i+1] = pTemp; Changed = 1; } } Size--; } } void CHuffman::ConstructTree(const unsigned *pFrequencies) { CHuffmanConstructNode aNodesLeftStorage[HUFFMAN_MAX_SYMBOLS]; CHuffmanConstructNode *apNodesLeft[HUFFMAN_MAX_SYMBOLS]; int NumNodesLeft = HUFFMAN_MAX_SYMBOLS; // add the symbols for(int i = 0; i < HUFFMAN_MAX_SYMBOLS; i++) { m_aNodes[i].m_NumBits = 0xFFFFFFFF; m_aNodes[i].m_Symbol = i; m_aNodes[i].m_aLeafs[0] = 0xffff; m_aNodes[i].m_aLeafs[1] = 0xffff; if(i == HUFFMAN_EOF_SYMBOL) aNodesLeftStorage[i].m_Frequency = 1; else aNodesLeftStorage[i].m_Frequency = pFrequencies[i]; aNodesLeftStorage[i].m_NodeId = i; apNodesLeft[i] = &aNodesLeftStorage[i]; } m_NumNodes = HUFFMAN_MAX_SYMBOLS; // construct the table while(NumNodesLeft > 1) { // we can't rely on stdlib's qsort for this, it can generate different results on different implementations BubbleSort(apNodesLeft, NumNodesLeft); m_aNodes[m_NumNodes].m_NumBits = 0; m_aNodes[m_NumNodes].m_aLeafs[0] = apNodesLeft[NumNodesLeft-1]->m_NodeId; m_aNodes[m_NumNodes].m_aLeafs[1] = apNodesLeft[NumNodesLeft-2]->m_NodeId; apNodesLeft[NumNodesLeft-2]->m_NodeId = m_NumNodes; apNodesLeft[NumNodesLeft-2]->m_Frequency = apNodesLeft[NumNodesLeft-1]->m_Frequency + apNodesLeft[NumNodesLeft-2]->m_Frequency; m_NumNodes++; NumNodesLeft--; } // set start node m_pStartNode = &m_aNodes[m_NumNodes-1]; // build symbol bits Setbits_r(m_pStartNode, 0, 0); } void CHuffman::Init(const unsigned *pFrequencies) { int i; // make sure to cleanout every thing mem_zero(this, sizeof(*this)); // construct the tree ConstructTree(pFrequencies); // build decode LUT for(i = 0; i < HUFFMAN_LUTSIZE; i++) { unsigned Bits = i; int k; CNode *pNode = m_pStartNode; for(k = 0; k < HUFFMAN_LUTBITS; k++) { pNode = &m_aNodes[pNode->m_aLeafs[Bits&1]]; Bits >>= 1; if(!pNode) break; if(pNode->m_NumBits) { m_apDecodeLut[i] = pNode; break; } } if(k == HUFFMAN_LUTBITS) m_apDecodeLut[i] = pNode; } } //*************************************************************** int CHuffman::Compress(const void *pInput, int InputSize, void *pOutput, int OutputSize) { // this macro loads a symbol for a byte into bits and bitcount #define HUFFMAN_MACRO_LOADSYMBOL(Sym) \ Bits |= m_aNodes[Sym].m_Bits << Bitcount; \ Bitcount += m_aNodes[Sym].m_NumBits; // this macro writes the symbol stored in bits and bitcount to the dst pointer #define HUFFMAN_MACRO_WRITE() \ while(Bitcount >= 8) \ { \ *pDst++ = (unsigned char)(Bits&0xff); \ if(pDst == pDstEnd) \ return -1; \ Bits >>= 8; \ Bitcount -= 8; \ } // setup buffer pointers const unsigned char *pSrc = (const unsigned char *)pInput; const unsigned char *pSrcEnd = pSrc + InputSize; unsigned char *pDst = (unsigned char *)pOutput; unsigned char *pDstEnd = pDst + OutputSize; // symbol variables unsigned Bits = 0; unsigned Bitcount = 0; // make sure that we have data that we want to compress if(InputSize) { // {A} load the first symbol int Symbol = *pSrc++; while(pSrc != pSrcEnd) { // {B} load the symbol HUFFMAN_MACRO_LOADSYMBOL(Symbol) // {C} fetch next symbol, this is done here because it will reduce dependency in the code Symbol = *pSrc++; // {B} write the symbol loaded at HUFFMAN_MACRO_WRITE() } // write the last symbol loaded from {C} or {A} in the case of only 1 byte input buffer HUFFMAN_MACRO_LOADSYMBOL(Symbol) HUFFMAN_MACRO_WRITE() } // write EOF symbol HUFFMAN_MACRO_LOADSYMBOL(HUFFMAN_EOF_SYMBOL) HUFFMAN_MACRO_WRITE() // write out the last bits *pDst++ = Bits; // return the size of the output return (int)(pDst - (const unsigned char *)pOutput); // remove macros #undef HUFFMAN_MACRO_LOADSYMBOL #undef HUFFMAN_MACRO_WRITE } //*************************************************************** int CHuffman::Decompress(const void *pInput, int InputSize, void *pOutput, int OutputSize) { // setup buffer pointers unsigned char *pDst = (unsigned char *)pOutput; unsigned char *pSrc = (unsigned char *)pInput; unsigned char *pDstEnd = pDst + OutputSize; unsigned char *pSrcEnd = pSrc + InputSize; unsigned Bits = 0; unsigned Bitcount = 0; CNode *pEof = &m_aNodes[HUFFMAN_EOF_SYMBOL]; CNode *pNode = 0; while(1) { // {A} try to load a node now, this will reduce dependency at location {D} pNode = 0; if(Bitcount >= HUFFMAN_LUTBITS) pNode = m_apDecodeLut[Bits&HUFFMAN_LUTMASK]; // {B} fill with new bits while(Bitcount < 24 && pSrc != pSrcEnd) { Bits |= (*pSrc++) << Bitcount; Bitcount += 8; } // {C} load symbol now if we didn't that earlier at location {A} if(!pNode) pNode = m_apDecodeLut[Bits&HUFFMAN_LUTMASK]; if(!pNode) return -1; // {D} check if we hit a symbol already if(pNode->m_NumBits) { // remove the bits for that symbol Bits >>= pNode->m_NumBits; Bitcount -= pNode->m_NumBits; } else { // remove the bits that the lut checked up for us Bits >>= HUFFMAN_LUTBITS; Bitcount -= HUFFMAN_LUTBITS; // walk the tree bit by bit while(1) { // traverse tree pNode = &m_aNodes[pNode->m_aLeafs[Bits&1]]; // remove bit Bitcount--; Bits >>= 1; // check if we hit a symbol if(pNode->m_NumBits) break; // no more bits, decoding error if(Bitcount == 0) return -1; } } // check for eof if(pNode == pEof) break; // output character if(pDst == pDstEnd) return -1; *pDst++ = pNode->m_Symbol; } // return the size of the decompressed buffer return (int)(pDst - (const unsigned char *)pOutput); } ================================================ FILE: src/engine/shared/huffman.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef ENGINE_SHARED_HUFFMAN_H #define ENGINE_SHARED_HUFFMAN_H class CHuffman { enum { HUFFMAN_EOF_SYMBOL = 256, HUFFMAN_MAX_SYMBOLS=HUFFMAN_EOF_SYMBOL+1, HUFFMAN_MAX_NODES=HUFFMAN_MAX_SYMBOLS*2-1, HUFFMAN_LUTBITS = 10, HUFFMAN_LUTSIZE = (1<<HUFFMAN_LUTBITS), HUFFMAN_LUTMASK = (HUFFMAN_LUTSIZE-1) }; struct CNode { // symbol unsigned m_Bits; unsigned m_NumBits; // don't use pointers for this. shorts are smaller so we can fit more data into the cache unsigned short m_aLeafs[2]; // what the symbol represents unsigned char m_Symbol; }; CNode m_aNodes[HUFFMAN_MAX_NODES]; CNode *m_apDecodeLut[HUFFMAN_LUTSIZE]; CNode *m_pStartNode; int m_NumNodes; void Setbits_r(CNode *pNode, int Bits, unsigned Depth); void ConstructTree(const unsigned *pFrequencies); public: /* Function: huffman_init Inits the compressor/decompressor. Parameters: huff - Pointer to the state to init frequencies - A pointer to an array of 256 entries of the frequencies of the bytes Remarks: - Does no allocation what so ever. - You don't have to call any cleanup functions when you are done with it */ void Init(const unsigned *pFrequencies); /* Function: huffman_compress Compresses a buffer and outputs a compressed buffer. Parameters: huff - Pointer to the huffman state input - Buffer to compress input_size - Size of the buffer to compress output - Buffer to put the compressed data into output_size - Size of the output buffer Returns: Returns the size of the compressed data. Negative value on failure. */ int Compress(const void *pInput, int InputSize, void *pOutput, int OutputSize); /* Function: huffman_decompress Decompresses a buffer Parameters: huff - Pointer to the huffman state input - Buffer to decompress input_size - Size of the buffer to decompress output - Buffer to put the uncompressed data into output_size - Size of the output buffer Returns: Returns the size of the uncompressed data. Negative value on failure. */ int Decompress(const void *pInput, int InputSize, void *pOutput, int OutputSize); }; #endif // __HUFFMAN_HEADER__ ================================================ FILE: src/engine/shared/jobs.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <base/system.h> #include "jobs.h" CJobPool::CJobPool() { // empty the pool m_NumThreads = 0; m_Shutdown = false; m_Lock = lock_create(); m_pFirstJob = 0; m_pLastJob = 0; } CJobPool::~CJobPool() { m_Shutdown = true; for(int i = 0; i < m_NumThreads; i++) { thread_wait(m_apThreads[i]); thread_destroy(m_apThreads[i]); } } void CJobPool::WorkerThread(void *pUser) { CJobPool *pPool = (CJobPool *)pUser; while(!pPool->m_Shutdown) { CJob *pJob = 0; // fetch job from queue lock_wait(pPool->m_Lock); if(pPool->m_pFirstJob) { pJob = pPool->m_pFirstJob; pPool->m_pFirstJob = pPool->m_pFirstJob->m_pNext; if(pPool->m_pFirstJob) pPool->m_pFirstJob->m_pPrev = 0; else pPool->m_pLastJob = 0; } lock_release(pPool->m_Lock); // do the job if we have one if(pJob) { pJob->m_Status = CJob::STATE_RUNNING; pJob->m_Result = pJob->m_pfnFunc(pJob->m_pFuncData); pJob->m_Status = CJob::STATE_DONE; } else thread_sleep(10); } } int CJobPool::Init(int NumThreads) { // start threads m_NumThreads = NumThreads > MAX_THREADS ? MAX_THREADS : NumThreads; for(int i = 0; i < m_NumThreads; i++) m_apThreads[i] = thread_create(WorkerThread, this); return 0; } int CJobPool::Add(CJob *pJob, JOBFUNC pfnFunc, void *pData) { mem_zero(pJob, sizeof(CJob)); pJob->m_pfnFunc = pfnFunc; pJob->m_pFuncData = pData; lock_wait(m_Lock); // add job to queue pJob->m_pPrev = m_pLastJob; if(m_pLastJob) m_pLastJob->m_pNext = pJob; m_pLastJob = pJob; if(!m_pFirstJob) m_pFirstJob = pJob; lock_release(m_Lock); return 0; } ================================================ FILE: src/engine/shared/jobs.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef ENGINE_SHARED_JOBS_H #define ENGINE_SHARED_JOBS_H typedef int (*JOBFUNC)(void *pData); class CJobPool; class CJob { friend class CJobPool; CJobPool *m_pPool; CJob *m_pPrev; CJob *m_pNext; volatile int m_Status; volatile int m_Result; JOBFUNC m_pfnFunc; void *m_pFuncData; public: CJob() { m_Status = STATE_DONE; m_pFuncData = 0; } enum { STATE_PENDING=0, STATE_RUNNING, STATE_DONE }; int Status() const { return m_Status; } int Result() const {return m_Result; } }; class CJobPool { enum { MAX_THREADS=32 }; int m_NumThreads; void *m_apThreads[MAX_THREADS]; volatile bool m_Shutdown; LOCK m_Lock; CJob *m_pFirstJob; CJob *m_pLastJob; static void WorkerThread(void *pUser); public: CJobPool(); ~CJobPool(); int Init(int NumThreads); int Add(CJob *pJob, JOBFUNC pfnFunc, void *pData); }; #endif ================================================ FILE: src/engine/shared/kernel.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <base/system.h> #include <engine/kernel.h> class CKernel : public IKernel { enum { MAX_INTERFACES=32, }; class CInterfaceInfo { public: CInterfaceInfo() { m_aName[0] = 0; m_pInterface = 0x0; } char m_aName[64]; IInterface *m_pInterface; }; CInterfaceInfo m_aInterfaces[MAX_INTERFACES]; int m_NumInterfaces; CInterfaceInfo *FindInterfaceInfo(const char *pName) { for(int i = 0; i < m_NumInterfaces; i++) { if(str_comp(pName, m_aInterfaces[i].m_aName) == 0) return &m_aInterfaces[i]; } return 0x0; } public: CKernel() { m_NumInterfaces = 0; } virtual bool RegisterInterfaceImpl(const char *pName, IInterface *pInterface) { // TODO: More error checks here if(!pInterface) { dbg_msg("kernel", "ERROR: couldn't register interface %s. null pointer given", pName); return false; } if(m_NumInterfaces == MAX_INTERFACES) { dbg_msg("kernel", "ERROR: couldn't register interface '%s'. maximum of interfaces reached", pName); return false; } if(FindInterfaceInfo(pName) != 0) { dbg_msg("kernel", "ERROR: couldn't register interface '%s'. interface already exists", pName); return false; } pInterface->m_pKernel = this; m_aInterfaces[m_NumInterfaces].m_pInterface = pInterface; str_copy(m_aInterfaces[m_NumInterfaces].m_aName, pName, sizeof(m_aInterfaces[m_NumInterfaces].m_aName)); m_NumInterfaces++; return true; } virtual bool ReregisterInterfaceImpl(const char *pName, IInterface *pInterface) { if(FindInterfaceInfo(pName) == 0) { dbg_msg("kernel", "ERROR: couldn't reregister interface '%s'. interface doesn't exist"); return false; } pInterface->m_pKernel = this; return true; } virtual IInterface *RequestInterfaceImpl(const char *pName) { CInterfaceInfo *pInfo = FindInterfaceInfo(pName); if(!pInfo) { dbg_msg("kernel", "failed to find interface with the name '%s'", pName); return 0; } return pInfo->m_pInterface; } }; IKernel *IKernel::Create() { return new CKernel; } ================================================ FILE: src/engine/shared/linereader.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include "linereader.h" void CLineReader::Init(IOHANDLE io) { m_BufferMaxSize = sizeof(m_aBuffer); m_BufferSize = 0; m_BufferPos = 0; m_IO = io; } char *CLineReader::Get() { unsigned LineStart = m_BufferPos; bool CRLFBreak = false; while(1) { if(m_BufferPos >= m_BufferSize) { // fetch more // move the remaining part to the front unsigned Read; unsigned Left = m_BufferSize - LineStart; if(LineStart > m_BufferSize) Left = 0; if(Left) mem_move(m_aBuffer, &m_aBuffer[LineStart], Left); m_BufferPos = Left; // fill the buffer Read = io_read(m_IO, &m_aBuffer[m_BufferPos], m_BufferMaxSize-m_BufferPos); m_BufferSize = Left + Read; LineStart = 0; if(!Read) { if(Left) { m_aBuffer[Left] = 0; // return the last line m_BufferPos = Left; m_BufferSize = Left; return m_aBuffer; } else return 0x0; // we are done! } } else { if(m_aBuffer[m_BufferPos] == '\n' || m_aBuffer[m_BufferPos] == '\r') { // line found if(m_aBuffer[m_BufferPos] == '\r') { if(m_BufferPos+1 >= m_BufferSize) { // read more to get the connected '\n' CRLFBreak = true; ++m_BufferPos; continue; } else if(m_aBuffer[m_BufferPos+1] == '\n') m_aBuffer[m_BufferPos++] = 0; } m_aBuffer[m_BufferPos++] = 0; return &m_aBuffer[LineStart]; } else if(CRLFBreak) { if(m_aBuffer[m_BufferPos] == '\n') m_aBuffer[m_BufferPos++] = 0; return &m_aBuffer[LineStart]; } else m_BufferPos++; } } } ================================================ FILE: src/engine/shared/linereader.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef ENGINE_SHARED_LINEREADER_H #define ENGINE_SHARED_LINEREADER_H #include <base/system.h> // buffered stream for reading lines, should perhaps be something smaller class CLineReader { char m_aBuffer[4*1024]; unsigned m_BufferPos; unsigned m_BufferSize; unsigned m_BufferMaxSize; IOHANDLE m_IO; public: void Init(IOHANDLE IoHandle); char *Get(); }; #endif ================================================ FILE: src/engine/shared/map.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <base/system.h> #include <engine/map.h> #include <engine/storage.h> #include <game/mapitems.h> #include "datafile.h" class CMap : public IEngineMap { CDataFileReader m_DataFile; public: CMap() {} virtual void *GetData(int Index) { return m_DataFile.GetData(Index); } virtual void *GetDataSwapped(int Index) { return m_DataFile.GetDataSwapped(Index); } virtual void UnloadData(int Index) { m_DataFile.UnloadData(Index); } virtual void *GetItem(int Index, int *pType, int *pID) { return m_DataFile.GetItem(Index, pType, pID); } virtual void GetType(int Type, int *pStart, int *pNum) { m_DataFile.GetType(Type, pStart, pNum); } virtual void *FindItem(int Type, int ID) { return m_DataFile.FindItem(Type, ID); } virtual int NumItems() { return m_DataFile.NumItems(); } virtual void Unload() { m_DataFile.Close(); } virtual bool Load(const char *pMapName, IStorage *pStorage) { if(!pStorage) pStorage = Kernel()->RequestInterface<IStorage>(); if(!pStorage) return false; if(!m_DataFile.Open(pStorage, pMapName, IStorage::TYPE_ALL)) return false; // check version CMapItemVersion *pItem = (CMapItemVersion *)m_DataFile.FindItem(MAPITEMTYPE_VERSION, 0); if(!pItem || pItem->m_Version != CMapItemVersion::CURRENT_VERSION) return false; return true; } virtual bool IsLoaded() { return m_DataFile.IsOpen(); } virtual unsigned Crc() { return m_DataFile.Crc(); } }; extern IEngineMap *CreateEngineMap() { return new CMap; } ================================================ FILE: src/engine/shared/mapchecker.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <base/math.h> #include <base/system.h> #include <engine/storage.h> #include <versionsrv/versionsrv.h> #include <versionsrv/mapversions.h> #include "datafile.h" #include "memheap.h" #include "mapchecker.h" CMapChecker::CMapChecker() { Init(); SetDefaults(); } void CMapChecker::Init() { m_Whitelist.Reset(); m_pFirst = 0; m_RemoveDefaultList = false; } void CMapChecker::SetDefaults() { AddMaplist(s_aMapVersionList, s_NumMapVersionItems); m_RemoveDefaultList = true; } void CMapChecker::AddMaplist(CMapVersion *pMaplist, int Num) { if(m_RemoveDefaultList) Init(); for(int i = 0; i < Num; ++i) { CWhitelistEntry *pEntry = (CWhitelistEntry *)m_Whitelist.Allocate(sizeof(CWhitelistEntry)); pEntry->m_pNext = m_pFirst; m_pFirst = pEntry; str_copy(pEntry->m_aMapName, pMaplist[i].m_aName, sizeof(pEntry->m_aMapName)); pEntry->m_MapCrc = (pMaplist[i].m_aCrc[0]<<24) | (pMaplist[i].m_aCrc[1]<<16) | (pMaplist[i].m_aCrc[2]<<8) | pMaplist[i].m_aCrc[3]; pEntry->m_MapSize = (pMaplist[i].m_aSize[0]<<24) | (pMaplist[i].m_aSize[1]<<16) | (pMaplist[i].m_aSize[2]<<8) | pMaplist[i].m_aSize[3]; } } bool CMapChecker::IsMapValid(const char *pMapName, unsigned MapCrc, unsigned MapSize) { return true; /*bool StandardMap = false; for(CWhitelistEntry *pCurrent = m_pFirst; pCurrent; pCurrent = pCurrent->m_pNext) { if(str_comp(pCurrent->m_aMapName, pMapName) == 0) { StandardMap = true; if(pCurrent->m_MapCrc == MapCrc && pCurrent->m_MapSize == MapSize) return true; } } return StandardMap?false:true;*/ } bool CMapChecker::ReadAndValidateMap(IStorage *pStorage, const char *pFilename, int StorageType) { return true; /*bool LoadedMapInfo = false; bool StandardMap = false; unsigned MapCrc = 0; unsigned MapSize = 0; // extract map name char aMapName[MAX_MAP_LENGTH]; const char *pExtractedName = pFilename; const char *pEnd = 0; for(const char *pSrc = pFilename; *pSrc; ++pSrc) { if(*pSrc == '/' || *pSrc == '\\') pExtractedName = pSrc+1; else if(*pSrc == '.') pEnd = pSrc; } int Length = (int)(pEnd - pExtractedName); if(Length <= 0 || Length >= MAX_MAP_LENGTH) return true; str_copy(aMapName, pExtractedName, min((int)MAX_MAP_LENGTH, (int)(pEnd-pExtractedName+1))); // check for valid map for(CWhitelistEntry *pCurrent = m_pFirst; pCurrent; pCurrent = pCurrent->m_pNext) { if(str_comp(pCurrent->m_aMapName, aMapName) == 0) { StandardMap = true; if(!LoadedMapInfo) { if(!CDataFileReader::GetCrcSize(pStorage, pFilename, StorageType, &MapCrc, &MapSize)) return true; LoadedMapInfo = true; } if(pCurrent->m_MapCrc == MapCrc && pCurrent->m_MapSize == MapSize) return true; } } return StandardMap?false:true;*/ } ================================================ FILE: src/engine/shared/mapchecker.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef ENGINE_SHARED_MAPCHECKER_H #define ENGINE_SHARED_MAPCHECKER_H #include "memheap.h" class CMapChecker { enum { MAX_MAP_LENGTH=8, }; struct CWhitelistEntry { char m_aMapName[MAX_MAP_LENGTH]; unsigned m_MapCrc; unsigned m_MapSize; CWhitelistEntry *m_pNext; }; class CHeap m_Whitelist; CWhitelistEntry *m_pFirst; bool m_RemoveDefaultList; void Init(); void SetDefaults(); public: CMapChecker(); void AddMaplist(struct CMapVersion *pMaplist, int Num); bool IsMapValid(const char *pMapName, unsigned MapCrc, unsigned MapSize); bool ReadAndValidateMap(class IStorage *pStorage, const char *pFilename, int StorageType); }; #endif ================================================ FILE: src/engine/shared/masterserver.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <stdio.h> // sscanf #include <base/system.h> #include <engine/engine.h> #include <engine/masterserver.h> #include <engine/storage.h> #include "linereader.h" class CMasterServer : public IEngineMasterServer { public: // master server functions struct CMasterInfo { char m_aHostname[128]; NETADDR m_Addr; bool m_Valid; CHostLookup m_Lookup; }; enum { STATE_INIT, STATE_UPDATE, STATE_READY, }; CMasterInfo m_aMasterServers[MAX_MASTERSERVERS]; int m_State; IEngine *m_pEngine; IStorage *m_pStorage; CMasterServer() { SetDefault(); m_State = STATE_INIT; m_pEngine = 0; m_pStorage = 0; } virtual int RefreshAddresses(int Nettype) { if(m_State != STATE_INIT && m_State != STATE_READY) return -1; dbg_msg("engine/mastersrv", "refreshing master server addresses"); // add lookup jobs for(int i = 0; i < MAX_MASTERSERVERS; i++) { m_pEngine->HostLookup(&m_aMasterServers[i].m_Lookup, m_aMasterServers[i].m_aHostname, Nettype); m_aMasterServers[i].m_Valid = false; } m_State = STATE_UPDATE; return 0; } virtual void Update() { // check if we need to update if(m_State != STATE_UPDATE) return; m_State = STATE_READY; for(int i = 0; i < MAX_MASTERSERVERS; i++) { if(m_aMasterServers[i].m_Lookup.m_Job.Status() != CJob::STATE_DONE) m_State = STATE_UPDATE; else { if(m_aMasterServers[i].m_Lookup.m_Job.Result() == 0) { m_aMasterServers[i].m_Addr = m_aMasterServers[i].m_Lookup.m_Addr; m_aMasterServers[i].m_Addr.port = 8300; m_aMasterServers[i].m_Valid = true; } else m_aMasterServers[i].m_Valid = false; } } if(m_State == STATE_READY) { dbg_msg("engine/mastersrv", "saving addresses"); Save(); } } virtual int IsRefreshing() { return m_State != STATE_READY; } virtual NETADDR GetAddr(int Index) { return m_aMasterServers[Index].m_Addr; } virtual const char *GetName(int Index) { return m_aMasterServers[Index].m_aHostname; } virtual bool IsValid(int Index) { return m_aMasterServers[Index].m_Valid; } virtual void Init() { m_pEngine = Kernel()->RequestInterface<IEngine>(); m_pStorage = Kernel()->RequestInterface<IStorage>(); } virtual void SetDefault() { mem_zero(m_aMasterServers, sizeof(m_aMasterServers)); for(int i = 0; i < MAX_MASTERSERVERS; i++) str_format(m_aMasterServers[i].m_aHostname, sizeof(m_aMasterServers[i].m_aHostname), "master%d.teeworlds.com", i+1); } virtual int Load() { if(!m_pStorage) return -1; // try to open file IOHANDLE File = m_pStorage->OpenFile("masters.cfg", IOFLAG_READ, IStorage::TYPE_SAVE); if(!File) return -1; CLineReader LineReader; LineReader.Init(File); while(1) { CMasterInfo Info = {{0}}; const char *pLine = LineReader.Get(); if(!pLine) break; // parse line char aAddrStr[NETADDR_MAXSTRSIZE]; if(sscanf(pLine, "%127s %47s", Info.m_aHostname, aAddrStr) == 2 && net_addr_from_str(&Info.m_Addr, aAddrStr) == 0) { Info.m_Addr.port = 8300; bool Added = false; for(int i = 0; i < MAX_MASTERSERVERS; ++i) if(str_comp(m_aMasterServers[i].m_aHostname, Info.m_aHostname) == 0) { m_aMasterServers[i] = Info; Added = true; break; } if(!Added) { for(int i = 0; i < MAX_MASTERSERVERS; ++i) if(m_aMasterServers[i].m_Addr.type == NETTYPE_INVALID) { m_aMasterServers[i] = Info; Added = true; break; } } if(!Added) break; } } io_close(File); return 0; } virtual int Save() { if(!m_pStorage) return -1; // try to open file IOHANDLE File = m_pStorage->OpenFile("masters.cfg", IOFLAG_WRITE, IStorage::TYPE_SAVE); if(!File) return -1; for(int i = 0; i < MAX_MASTERSERVERS; i++) { char aAddrStr[NETADDR_MAXSTRSIZE]; if(m_aMasterServers[i].m_Addr.type != NETTYPE_INVALID) net_addr_str(&m_aMasterServers[i].m_Addr, aAddrStr, sizeof(aAddrStr), true); else aAddrStr[0] = 0; char aBuf[256]; str_format(aBuf, sizeof(aBuf), "%s %s", m_aMasterServers[i].m_aHostname, aAddrStr); io_write(File, aBuf, str_length(aBuf)); io_write_newline(File); } io_close(File); return 0; } }; IEngineMasterServer *CreateEngineMasterServer() { return new CMasterServer; } ================================================ FILE: src/engine/shared/memheap.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <base/system.h> #include "memheap.h" // allocates a new chunk to be used void CHeap::NewChunk() { CChunk *pChunk; char *pMem; // allocate memory pMem = (char*)mem_alloc(sizeof(CChunk)+CHUNK_SIZE, 1); if(!pMem) return; // the chunk structure is located in the begining of the chunk // init it and return the chunk pChunk = (CChunk*)pMem; pChunk->m_pMemory = (char*)(pChunk+1); pChunk->m_pCurrent = pChunk->m_pMemory; pChunk->m_pEnd = pChunk->m_pMemory + CHUNK_SIZE; pChunk->m_pNext = (CChunk *)0x0; pChunk->m_pNext = m_pCurrent; m_pCurrent = pChunk; } //**************** void *CHeap::AllocateFromChunk(unsigned int Size) { char *pMem; // check if we need can fit the allocation if(m_pCurrent->m_pCurrent + Size > m_pCurrent->m_pEnd) return (void*)0x0; // get memory and move the pointer forward pMem = m_pCurrent->m_pCurrent; m_pCurrent->m_pCurrent += Size; return pMem; } // creates a heap CHeap::CHeap() { m_pCurrent = 0x0; Reset(); } CHeap::~CHeap() { Clear(); } void CHeap::Reset() { Clear(); NewChunk(); } // destroys the heap void CHeap::Clear() { CChunk *pChunk = m_pCurrent; CChunk *pNext; while(pChunk) { pNext = pChunk->m_pNext; mem_free(pChunk); pChunk = pNext; } m_pCurrent = 0x0; } // void *CHeap::Allocate(unsigned Size) { char *pMem; // try to allocate from current chunk pMem = (char *)AllocateFromChunk(Size); if(!pMem) { // allocate new chunk and add it to the heap NewChunk(); // try to allocate again pMem = (char *)AllocateFromChunk(Size); } return pMem; } ================================================ FILE: src/engine/shared/memheap.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef ENGINE_SHARED_MEMHEAP_H #define ENGINE_SHARED_MEMHEAP_H class CHeap { struct CChunk { char *m_pMemory; char *m_pCurrent; char *m_pEnd; CChunk *m_pNext; }; enum { // how large each chunk should be CHUNK_SIZE = 1024*64, }; CChunk *m_pCurrent; void Clear(); void NewChunk(); void *AllocateFromChunk(unsigned int Size); public: CHeap(); ~CHeap(); void Reset(); void *Allocate(unsigned Size); }; #endif ================================================ FILE: src/engine/shared/message.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef ENGINE_SHARED_MESSAGE_H #define ENGINE_SHARED_MESSAGE_H class CMessage { public: virtual bool Pack(void *pData, unsigned MaxDataSize); virtual bool Unpack(const void *pData, unsigned DataSize); }; #endif ================================================ FILE: src/engine/shared/netban.cpp ================================================ #include <base/math.h> #include <engine/console.h> #include <engine/storage.h> #include <engine/shared/config.h> #include "netban.h" bool CNetBan::StrAllnum(const char *pStr) { while(*pStr) { if(!(*pStr >= '0' && *pStr <= '9')) return false; pStr++; } return true; } CNetBan::CNetHash::CNetHash(const NETADDR *pAddr) { if(pAddr->type==NETTYPE_IPV4) m_Hash = (pAddr->ip[0]+pAddr->ip[1]+pAddr->ip[2]+pAddr->ip[3])&0xFF; else m_Hash = (pAddr->ip[0]+pAddr->ip[1]+pAddr->ip[2]+pAddr->ip[3]+pAddr->ip[4]+pAddr->ip[5]+pAddr->ip[6]+pAddr->ip[7]+ pAddr->ip[8]+pAddr->ip[9]+pAddr->ip[10]+pAddr->ip[11]+pAddr->ip[12]+pAddr->ip[13]+pAddr->ip[14]+pAddr->ip[15])&0xFF; m_HashIndex = 0; } CNetBan::CNetHash::CNetHash(const CNetRange *pRange) { m_Hash = 0; m_HashIndex = 0; for(int i = 0; pRange->m_LB.ip[i] == pRange->m_UB.ip[i]; ++i) { m_Hash += pRange->m_LB.ip[i]; ++m_HashIndex; } m_Hash &= 0xFF; } int CNetBan::CNetHash::MakeHashArray(const NETADDR *pAddr, CNetHash aHash[17]) { int Length = pAddr->type==NETTYPE_IPV4 ? 4 : 16; aHash[0].m_Hash = 0; aHash[0].m_HashIndex = 0; for(int i = 1, Sum = 0; i <= Length; ++i) { Sum += pAddr->ip[i-1]; aHash[i].m_Hash = Sum&0xFF; aHash[i].m_HashIndex = i%Length; } return Length; } template<class T, int HashCount> typename CNetBan::CBan<T> *CNetBan::CBanPool<T, HashCount>::Add(const T *pData, const CBanInfo *pInfo, const CNetHash *pNetHash) { if(!m_pFirstFree) return 0; // create new ban CBan<T> *pBan = m_pFirstFree; pBan->m_Data = *pData; pBan->m_Info = *pInfo; pBan->m_NetHash = *pNetHash; if(pBan->m_pNext) pBan->m_pNext->m_pPrev = pBan->m_pPrev; if(pBan->m_pPrev) pBan->m_pPrev->m_pNext = pBan->m_pNext; else m_pFirstFree = pBan->m_pNext; // add it to the hash list if(m_paaHashList[pNetHash->m_HashIndex][pNetHash->m_Hash]) m_paaHashList[pNetHash->m_HashIndex][pNetHash->m_Hash]->m_pHashPrev = pBan; pBan->m_pHashPrev = 0; pBan->m_pHashNext = m_paaHashList[pNetHash->m_HashIndex][pNetHash->m_Hash]; m_paaHashList[pNetHash->m_HashIndex][pNetHash->m_Hash] = pBan; // insert it into the used list if(m_pFirstUsed) { for(CBan<T> *p = m_pFirstUsed; ; p = p->m_pNext) { if(p->m_Info.m_Expires == CBanInfo::EXPIRES_NEVER || (pInfo->m_Expires != CBanInfo::EXPIRES_NEVER && pInfo->m_Expires <= p->m_Info.m_Expires)) { // insert before pBan->m_pNext = p; pBan->m_pPrev = p->m_pPrev; if(p->m_pPrev) p->m_pPrev->m_pNext = pBan; else m_pFirstUsed = pBan; p->m_pPrev = pBan; break; } if(!p->m_pNext) { // last entry p->m_pNext = pBan; pBan->m_pPrev = p; pBan->m_pNext = 0; break; } } } else { m_pFirstUsed = pBan; pBan->m_pNext = pBan->m_pPrev = 0; } // update ban count ++m_CountUsed; return pBan; } template<class T, int HashCount> int CNetBan::CBanPool<T, HashCount>::Remove(CBan<T> *pBan) { if(pBan == 0) return -1; // remove from hash list if(pBan->m_pHashNext) pBan->m_pHashNext->m_pHashPrev = pBan->m_pHashPrev; if(pBan->m_pHashPrev) pBan->m_pHashPrev->m_pHashNext = pBan->m_pHashNext; else m_paaHashList[pBan->m_NetHash.m_HashIndex][pBan->m_NetHash.m_Hash] = pBan->m_pHashNext; pBan->m_pHashNext = pBan->m_pHashPrev = 0; // remove from used list if(pBan->m_pNext) pBan->m_pNext->m_pPrev = pBan->m_pPrev; if(pBan->m_pPrev) pBan->m_pPrev->m_pNext = pBan->m_pNext; else m_pFirstUsed = pBan->m_pNext; // add to recycle list if(m_pFirstFree) m_pFirstFree->m_pPrev = pBan; pBan->m_pPrev = 0; pBan->m_pNext = m_pFirstFree; m_pFirstFree = pBan; // update ban count --m_CountUsed; return 0; } template<class T, int HashCount> void CNetBan::CBanPool<T, HashCount>::Update(CBan<CDataType> *pBan, const CBanInfo *pInfo) { pBan->m_Info = *pInfo; // remove from used list if(pBan->m_pNext) pBan->m_pNext->m_pPrev = pBan->m_pPrev; if(pBan->m_pPrev) pBan->m_pPrev->m_pNext = pBan->m_pNext; else m_pFirstUsed = pBan->m_pNext; // insert it into the used list if(m_pFirstUsed) { for(CBan<T> *p = m_pFirstUsed; ; p = p->m_pNext) { if(p->m_Info.m_Expires == CBanInfo::EXPIRES_NEVER || (pInfo->m_Expires != CBanInfo::EXPIRES_NEVER && pInfo->m_Expires <= p->m_Info.m_Expires)) { // insert before pBan->m_pNext = p; pBan->m_pPrev = p->m_pPrev; if(p->m_pPrev) p->m_pPrev->m_pNext = pBan; else m_pFirstUsed = pBan; p->m_pPrev = pBan; break; } if(!p->m_pNext) { // last entry p->m_pNext = pBan; pBan->m_pPrev = p; pBan->m_pNext = 0; break; } } } else { m_pFirstUsed = pBan; pBan->m_pNext = pBan->m_pPrev = 0; } } template<class T, int HashCount> void CNetBan::CBanPool<T, HashCount>::Reset() { mem_zero(m_paaHashList, sizeof(m_paaHashList)); mem_zero(m_aBans, sizeof(m_aBans)); m_pFirstUsed = 0; m_CountUsed = 0; for(int i = 1; i < MAX_BANS-1; ++i) { m_aBans[i].m_pNext = &m_aBans[i+1]; m_aBans[i].m_pPrev = &m_aBans[i-1]; } m_aBans[0].m_pNext = &m_aBans[1]; m_aBans[MAX_BANS-1].m_pPrev = &m_aBans[MAX_BANS-2]; m_pFirstFree = &m_aBans[0]; } template<class T, int HashCount> typename CNetBan::CBan<T> *CNetBan::CBanPool<T, HashCount>::Get(int Index) const { if(Index < 0 || Index >= Num()) return 0; for(CNetBan::CBan<T> *pBan = m_pFirstUsed; pBan; pBan = pBan->m_pNext, --Index) { if(Index == 0) return pBan; } return 0; } template<class T> void CNetBan::MakeBanInfo(const CBan<T> *pBan, char *pBuf, unsigned BuffSize, int Type) const { if(pBan == 0 || pBuf == 0) { if(BuffSize > 0) pBuf[0] = 0; return; } // build type based part char aBuf[256]; if(Type == MSGTYPE_PLAYER) str_copy(aBuf, "You have been banned", sizeof(aBuf)); else { char aTemp[256]; switch(Type) { case MSGTYPE_LIST: str_format(aBuf, sizeof(aBuf), "%s banned", NetToString(&pBan->m_Data, aTemp, sizeof(aTemp))); break; case MSGTYPE_BANADD: str_format(aBuf, sizeof(aBuf), "banned %s", NetToString(&pBan->m_Data, aTemp, sizeof(aTemp))); break; case MSGTYPE_BANREM: str_format(aBuf, sizeof(aBuf), "unbanned %s", NetToString(&pBan->m_Data, aTemp, sizeof(aTemp))); break; default: aBuf[0] = 0; } } // add info part if(pBan->m_Info.m_Expires != CBanInfo::EXPIRES_NEVER) { int Mins = ((pBan->m_Info.m_Expires-time_timestamp()) + 59) / 60; if(Mins <= 1) str_format(pBuf, BuffSize, "%s for 1 minute (%s)", aBuf, pBan->m_Info.m_aReason); else str_format(pBuf, BuffSize, "%s for %d minutes (%s)", aBuf, Mins, pBan->m_Info.m_aReason); } else str_format(pBuf, BuffSize, "%s for life (%s)", aBuf, pBan->m_Info.m_aReason); } template<class T> int CNetBan::Ban(T *pBanPool, const typename T::CDataType *pData, int Seconds, const char *pReason) { // do not ban localhost if(NetMatch(pData, &m_LocalhostIPV4) || NetMatch(pData, &m_LocalhostIPV6)) { Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban failed (localhost)"); return -1; } int Stamp = Seconds > 0 ? time_timestamp()+Seconds : CBanInfo::EXPIRES_NEVER; // set up info CBanInfo Info = {0}; Info.m_Expires = Stamp; str_copy(Info.m_aReason, pReason, sizeof(Info.m_aReason)); // check if it already exists CNetHash NetHash(pData); CBan<typename T::CDataType> *pBan = pBanPool->Find(pData, &NetHash); if(pBan) { // adjust the ban pBanPool->Update(pBan, &Info); char aBuf[128]; MakeBanInfo(pBan, aBuf, sizeof(aBuf), MSGTYPE_LIST); Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", aBuf); return 1; } // add ban and print result pBan = pBanPool->Add(pData, &Info, &NetHash); if(pBan) { char aBuf[128]; MakeBanInfo(pBan, aBuf, sizeof(aBuf), MSGTYPE_BANADD); Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", aBuf); return 0; } else Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban failed (full banlist)"); return -1; } template<class T> int CNetBan::Unban(T *pBanPool, const typename T::CDataType *pData) { CNetHash NetHash(pData); CBan<typename T::CDataType> *pBan = pBanPool->Find(pData, &NetHash); if(pBan) { char aBuf[256]; MakeBanInfo(pBan, aBuf, sizeof(aBuf), MSGTYPE_BANREM); pBanPool->Remove(pBan); Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", aBuf); return 0; } else Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "unban failed (invalid entry)"); return -1; } void CNetBan::Init(IConsole *pConsole, IStorage *pStorage) { m_pConsole = pConsole; m_pStorage = pStorage; m_BanAddrPool.Reset(); m_BanRangePool.Reset(); net_host_lookup("localhost", &m_LocalhostIPV4, NETTYPE_IPV4); net_host_lookup("localhost", &m_LocalhostIPV6, NETTYPE_IPV6); Console()->Register("ban", "s?ir", CFGFLAG_SERVER|CFGFLAG_MASTER|CFGFLAG_STORE, ConBan, this, "Ban ip for x minutes for any reason"); Console()->Register("ban_range", "ss?ir", CFGFLAG_SERVER|CFGFLAG_MASTER|CFGFLAG_STORE, ConBanRange, this, "Ban ip range for x minutes for any reason"); Console()->Register("unban", "s", CFGFLAG_SERVER|CFGFLAG_MASTER|CFGFLAG_STORE, ConUnban, this, "Unban ip/banlist entry"); Console()->Register("unban_range", "ss", CFGFLAG_SERVER|CFGFLAG_MASTER|CFGFLAG_STORE, ConUnbanRange, this, "Unban ip range"); Console()->Register("unban_all", "", CFGFLAG_SERVER|CFGFLAG_MASTER|CFGFLAG_STORE, ConUnbanAll, this, "Unban all entries"); Console()->Register("bans", "", CFGFLAG_SERVER|CFGFLAG_MASTER|CFGFLAG_STORE, ConBans, this, "Show banlist"); Console()->Register("bans_save", "s", CFGFLAG_SERVER|CFGFLAG_MASTER|CFGFLAG_STORE, ConBansSave, this, "Save banlist in a file"); } void CNetBan::Update() { int Now = time_timestamp(); // remove expired bans char aBuf[256], aNetStr[256]; while(m_BanAddrPool.First() && m_BanAddrPool.First()->m_Info.m_Expires != CBanInfo::EXPIRES_NEVER && m_BanAddrPool.First()->m_Info.m_Expires < Now) { str_format(aBuf, sizeof(aBuf), "ban %s expired", NetToString(&m_BanAddrPool.First()->m_Data, aNetStr, sizeof(aNetStr))); Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", aBuf); m_BanAddrPool.Remove(m_BanAddrPool.First()); } while(m_BanRangePool.First() && m_BanRangePool.First()->m_Info.m_Expires != CBanInfo::EXPIRES_NEVER && m_BanRangePool.First()->m_Info.m_Expires < Now) { str_format(aBuf, sizeof(aBuf), "ban %s expired", NetToString(&m_BanRangePool.First()->m_Data, aNetStr, sizeof(aNetStr))); Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", aBuf); m_BanRangePool.Remove(m_BanRangePool.First()); } } int CNetBan::BanAddr(const NETADDR *pAddr, int Seconds, const char *pReason) { return Ban(&m_BanAddrPool, pAddr, Seconds, pReason); } int CNetBan::BanRange(const CNetRange *pRange, int Seconds, const char *pReason) { if(pRange->IsValid()) return Ban(&m_BanRangePool, pRange, Seconds, pReason); Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban failed (invalid range)"); return -1; } int CNetBan::UnbanByAddr(const NETADDR *pAddr) { return Unban(&m_BanAddrPool, pAddr); } int CNetBan::UnbanByRange(const CNetRange *pRange) { if(pRange->IsValid()) return Unban(&m_BanRangePool, pRange); Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban failed (invalid range)"); return -1; } int CNetBan::UnbanByIndex(int Index) { int Result; char aBuf[256]; CBanAddr *pBan = m_BanAddrPool.Get(Index); if(pBan) { NetToString(&pBan->m_Data, aBuf, sizeof(aBuf)); Result = m_BanAddrPool.Remove(pBan); } else { CBanRange *pBan = m_BanRangePool.Get(Index-m_BanAddrPool.Num()); if(pBan) { NetToString(&pBan->m_Data, aBuf, sizeof(aBuf)); Result = m_BanRangePool.Remove(pBan); } else { Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "unban failed (invalid index)"); return -1; } } char aMsg[256]; str_format(aMsg, sizeof(aMsg), "unbanned index %i (%s)", Index, aBuf); Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", aMsg); return Result; } bool CNetBan::IsBanned(const NETADDR *pAddr, char *pBuf, unsigned BufferSize) const { CNetHash aHash[17]; int Length = CNetHash::MakeHashArray(pAddr, aHash); // check ban adresses CBanAddr *pBan = m_BanAddrPool.Find(pAddr, &aHash[Length]); if(pBan) { MakeBanInfo(pBan, pBuf, BufferSize, MSGTYPE_PLAYER); return true; } // check ban ranges for(int i = Length-1; i >= 0; --i) { for(CBanRange *pBan = m_BanRangePool.First(&aHash[i]); pBan; pBan = pBan->m_pHashNext) { if(NetMatch(&pBan->m_Data, pAddr, i, Length)) { MakeBanInfo(pBan, pBuf, BufferSize, MSGTYPE_PLAYER); return true; } } } return false; } void CNetBan::ConBan(IConsole::IResult *pResult, void *pUser) { CNetBan *pThis = static_cast<CNetBan *>(pUser); const char *pStr = pResult->GetString(0); int Minutes = pResult->NumArguments()>1 ? clamp(pResult->GetInteger(1), 0, 44640) : 30; const char *pReason = pResult->NumArguments()>2 ? pResult->GetString(2) : "No reason given"; NETADDR Addr; if(net_addr_from_str(&Addr, pStr) == 0) pThis->BanAddr(&Addr, Minutes*60, pReason); else pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban error (invalid network address)"); } void CNetBan::ConBanRange(IConsole::IResult *pResult, void *pUser) { CNetBan *pThis = static_cast<CNetBan *>(pUser); const char *pStr1 = pResult->GetString(0); const char *pStr2 = pResult->GetString(1); int Minutes = pResult->NumArguments()>2 ? clamp(pResult->GetInteger(2), 0, 44640) : 30; const char *pReason = pResult->NumArguments()>3 ? pResult->GetString(3) : "No reason given"; CNetRange Range; if(net_addr_from_str(&Range.m_LB, pStr1) == 0 && net_addr_from_str(&Range.m_UB, pStr2) == 0) pThis->BanRange(&Range, Minutes*60, pReason); else pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban error (invalid range)"); } void CNetBan::ConUnban(IConsole::IResult *pResult, void *pUser) { CNetBan *pThis = static_cast<CNetBan *>(pUser); const char *pStr = pResult->GetString(0); if(StrAllnum(pStr)) pThis->UnbanByIndex(str_toint(pStr)); else { NETADDR Addr; if(net_addr_from_str(&Addr, pStr) == 0) pThis->UnbanByAddr(&Addr); else pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "unban error (invalid network address)"); } } void CNetBan::ConUnbanRange(IConsole::IResult *pResult, void *pUser) { CNetBan *pThis = static_cast<CNetBan *>(pUser); const char *pStr1 = pResult->GetString(0); const char *pStr2 = pResult->GetString(1); CNetRange Range; if(net_addr_from_str(&Range.m_LB, pStr1) == 0 && net_addr_from_str(&Range.m_UB, pStr2) == 0) pThis->UnbanByRange(&Range); else pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "unban error (invalid range)"); } void CNetBan::ConUnbanAll(IConsole::IResult *pResult, void *pUser) { CNetBan *pThis = static_cast<CNetBan *>(pUser); pThis->UnbanAll(); pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "unbanned all entries"); } void CNetBan::ConBans(IConsole::IResult *pResult, void *pUser) { CNetBan *pThis = static_cast<CNetBan *>(pUser); int Count = 0; char aBuf[256], aMsg[256]; for(CBanAddr *pBan = pThis->m_BanAddrPool.First(); pBan; pBan = pBan->m_pNext) { pThis->MakeBanInfo(pBan, aBuf, sizeof(aBuf), MSGTYPE_LIST); str_format(aMsg, sizeof(aMsg), "#%i %s", Count++, aBuf); pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", aMsg); } for(CBanRange *pBan = pThis->m_BanRangePool.First(); pBan; pBan = pBan->m_pNext) { pThis->MakeBanInfo(pBan, aBuf, sizeof(aBuf), MSGTYPE_LIST); str_format(aMsg, sizeof(aMsg), "#%i %s", Count++, aBuf); pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", aMsg); } str_format(aMsg, sizeof(aMsg), "%d %s", Count, Count==1?"ban":"bans"); pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", aMsg); } void CNetBan::ConBansSave(IConsole::IResult *pResult, void *pUser) { CNetBan *pThis = static_cast<CNetBan *>(pUser); char aBuf[256]; IOHANDLE File = pThis->Storage()->OpenFile(pResult->GetString(0), IOFLAG_WRITE, IStorage::TYPE_SAVE); if(!File) { str_format(aBuf, sizeof(aBuf), "failed to save banlist to '%s'", pResult->GetString(0)); pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", aBuf); return; } int Now = time_timestamp(); char aAddrStr1[NETADDR_MAXSTRSIZE], aAddrStr2[NETADDR_MAXSTRSIZE]; for(CBanAddr *pBan = pThis->m_BanAddrPool.First(); pBan; pBan = pBan->m_pNext) { int Min = pBan->m_Info.m_Expires>-1 ? (pBan->m_Info.m_Expires-Now+59)/60 : -1; net_addr_str(&pBan->m_Data, aAddrStr1, sizeof(aAddrStr1), false); str_format(aBuf, sizeof(aBuf), "ban %s %i %s", aAddrStr1, Min, pBan->m_Info.m_aReason); io_write(File, aBuf, str_length(aBuf)); io_write_newline(File); } for(CBanRange *pBan = pThis->m_BanRangePool.First(); pBan; pBan = pBan->m_pNext) { int Min = pBan->m_Info.m_Expires>-1 ? (pBan->m_Info.m_Expires-Now+59)/60 : -1; net_addr_str(&pBan->m_Data.m_LB, aAddrStr1, sizeof(aAddrStr1), false); net_addr_str(&pBan->m_Data.m_UB, aAddrStr2, sizeof(aAddrStr2), false); str_format(aBuf, sizeof(aBuf), "ban_range %s %s %i %s", aAddrStr1, aAddrStr2, Min, pBan->m_Info.m_aReason); io_write(File, aBuf, str_length(aBuf)); io_write_newline(File); } io_close(File); str_format(aBuf, sizeof(aBuf), "saved banlist to '%s'", pResult->GetString(0)); pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", aBuf); } ================================================ FILE: src/engine/shared/netban.h ================================================ #ifndef ENGINE_SHARED_NETBAN_H #define ENGINE_SHARED_NETBAN_H #include <base/system.h> inline int NetComp(const NETADDR *pAddr1, const NETADDR *pAddr2) { return mem_comp(pAddr1, pAddr2, pAddr1->type==NETTYPE_IPV4 ? 8 : 20); } class CNetRange { public: NETADDR m_LB; NETADDR m_UB; bool IsValid() const { return m_LB.type == m_UB.type && NetComp(&m_LB, &m_UB) < 0; } }; inline int NetComp(const CNetRange *pRange1, const CNetRange *pRange2) { return NetComp(&pRange1->m_LB, &pRange2->m_LB) || NetComp(&pRange1->m_UB, &pRange2->m_UB); } class CNetBan { protected: bool NetMatch(const NETADDR *pAddr1, const NETADDR *pAddr2) const { return NetComp(pAddr1, pAddr2) == 0; } bool NetMatch(const CNetRange *pRange, const NETADDR *pAddr, int Start, int Length) const { return pRange->m_LB.type == pAddr->type && (Start == 0 || mem_comp(&pRange->m_LB.ip[0], &pAddr->ip[0], Start) == 0) && mem_comp(&pRange->m_LB.ip[Start], &pAddr->ip[Start], Length-Start) <= 0 && mem_comp(&pRange->m_UB.ip[Start], &pAddr->ip[Start], Length-Start) >= 0; } bool NetMatch(const CNetRange *pRange, const NETADDR *pAddr) const { return NetMatch(pRange, pAddr, 0, pRange->m_LB.type==NETTYPE_IPV4 ? 4 : 16); } const char *NetToString(const NETADDR *pData, char *pBuffer, unsigned BufferSize) const { char aAddrStr[NETADDR_MAXSTRSIZE]; net_addr_str(pData, aAddrStr, sizeof(aAddrStr), false); str_format(pBuffer, BufferSize, "'%s'", aAddrStr); return pBuffer; } const char *NetToString(const CNetRange *pData, char *pBuffer, unsigned BufferSize) const { char aAddrStr1[NETADDR_MAXSTRSIZE], aAddrStr2[NETADDR_MAXSTRSIZE]; net_addr_str(&pData->m_LB, aAddrStr1, sizeof(aAddrStr1), false); net_addr_str(&pData->m_UB, aAddrStr2, sizeof(aAddrStr2), false); str_format(pBuffer, BufferSize, "'%s' - '%s'", aAddrStr1, aAddrStr2); return pBuffer; } // todo: move? static bool StrAllnum(const char *pStr); class CNetHash { public: int m_Hash; int m_HashIndex; // matching parts for ranges, 0 for addr CNetHash() {} CNetHash(const NETADDR *pAddr); CNetHash(const CNetRange *pRange); static int MakeHashArray(const NETADDR *pAddr, CNetHash aHash[17]); }; struct CBanInfo { enum { EXPIRES_NEVER=-1, REASON_LENGTH=64, }; int m_Expires; char m_aReason[REASON_LENGTH]; }; template<class T> struct CBan { T m_Data; CBanInfo m_Info; CNetHash m_NetHash; // hash list CBan *m_pHashNext; CBan *m_pHashPrev; // used or free list CBan *m_pNext; CBan *m_pPrev; }; template<class T, int HashCount> class CBanPool { public: typedef T CDataType; CBan<CDataType> *Add(const CDataType *pData, const CBanInfo *pInfo, const CNetHash *pNetHash); int Remove(CBan<CDataType> *pBan); void Update(CBan<CDataType> *pBan, const CBanInfo *pInfo); void Reset(); int Num() const { return m_CountUsed; } bool IsFull() const { return m_CountUsed == MAX_BANS; } CBan<CDataType> *First() const { return m_pFirstUsed; } CBan<CDataType> *First(const CNetHash *pNetHash) const { return m_paaHashList[pNetHash->m_HashIndex][pNetHash->m_Hash]; } CBan<CDataType> *Find(const CDataType *pData, const CNetHash *pNetHash) const { for(CBan<CDataType> *pBan = m_paaHashList[pNetHash->m_HashIndex][pNetHash->m_Hash]; pBan; pBan = pBan->m_pHashNext) { if(NetComp(&pBan->m_Data, pData) == 0) return pBan; } return 0; } CBan<CDataType> *Get(int Index) const; private: enum { MAX_BANS=1024, }; CBan<CDataType> *m_paaHashList[HashCount][256]; CBan<CDataType> m_aBans[MAX_BANS]; CBan<CDataType> *m_pFirstFree; CBan<CDataType> *m_pFirstUsed; int m_CountUsed; }; typedef CBanPool<NETADDR, 1> CBanAddrPool; typedef CBanPool<CNetRange, 16> CBanRangePool; typedef CBan<NETADDR> CBanAddr; typedef CBan<CNetRange> CBanRange; template<class T> void MakeBanInfo(const CBan<T> *pBan, char *pBuf, unsigned BuffSize, int Type) const; template<class T> int Ban(T *pBanPool, const typename T::CDataType *pData, int Seconds, const char *pReason); template<class T> int Unban(T *pBanPool, const typename T::CDataType *pData); class IConsole *m_pConsole; class IStorage *m_pStorage; CBanAddrPool m_BanAddrPool; CBanRangePool m_BanRangePool; NETADDR m_LocalhostIPV4, m_LocalhostIPV6; public: enum { MSGTYPE_PLAYER=0, MSGTYPE_LIST, MSGTYPE_BANADD, MSGTYPE_BANREM, }; class IConsole *Console() const { return m_pConsole; } class IStorage *Storage() const { return m_pStorage; } virtual ~CNetBan() {} void Init(class IConsole *pConsole, class IStorage *pStorage); void Update(); virtual int BanAddr(const NETADDR *pAddr, int Seconds, const char *pReason); virtual int BanRange(const CNetRange *pRange, int Seconds, const char *pReason); int UnbanByAddr(const NETADDR *pAddr); int UnbanByRange(const CNetRange *pRange); int UnbanByIndex(int Index); void UnbanAll() { m_BanAddrPool.Reset(); m_BanRangePool.Reset(); } bool IsBanned(const NETADDR *pAddr, char *pBuf, unsigned BufferSize) const; static void ConBan(class IConsole::IResult *pResult, void *pUser); static void ConBanRange(class IConsole::IResult *pResult, void *pUser); static void ConUnban(class IConsole::IResult *pResult, void *pUser); static void ConUnbanRange(class IConsole::IResult *pResult, void *pUser); static void ConUnbanAll(class IConsole::IResult *pResult, void *pUser); static void ConBans(class IConsole::IResult *pResult, void *pUser); static void ConBansSave(class IConsole::IResult *pResult, void *pUser); }; #endif ================================================ FILE: src/engine/shared/network.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <base/system.h> #include "config.h" #include "network.h" #include "huffman.h" void CNetRecvUnpacker::Clear() { m_Valid = false; } void CNetRecvUnpacker::Start(const NETADDR *pAddr, CNetConnection *pConnection, int ClientID) { m_Addr = *pAddr; m_pConnection = pConnection; m_ClientID = ClientID; m_CurrentChunk = 0; m_Valid = true; } // TODO: rename this function int CNetRecvUnpacker::FetchChunk(CNetChunk *pChunk) { CNetChunkHeader Header; unsigned char *pEnd = m_Data.m_aChunkData + m_Data.m_DataSize; while(1) { unsigned char *pData = m_Data.m_aChunkData; // check for old data to unpack if(!m_Valid || m_CurrentChunk >= m_Data.m_NumChunks) { Clear(); return 0; } // TODO: add checking here so we don't read too far for(int i = 0; i < m_CurrentChunk; i++) { pData = Header.Unpack(pData); pData += Header.m_Size; } // unpack the header pData = Header.Unpack(pData); m_CurrentChunk++; if(pData+Header.m_Size > pEnd) { Clear(); return 0; } // handle sequence stuff if(m_pConnection && (Header.m_Flags&NET_CHUNKFLAG_VITAL)) { if(Header.m_Sequence == (m_pConnection->m_Ack+1)%NET_MAX_SEQUENCE) { // in sequence m_pConnection->m_Ack = (m_pConnection->m_Ack+1)%NET_MAX_SEQUENCE; } else { // old packet that we already got if(CNetBase::IsSeqInBackroom(Header.m_Sequence, m_pConnection->m_Ack)) continue; // out of sequence, request resend if(g_Config.m_Debug) dbg_msg("conn", "asking for resend %d %d", Header.m_Sequence, (m_pConnection->m_Ack+1)%NET_MAX_SEQUENCE); m_pConnection->SignalResend(); continue; // take the next chunk in the packet } } // fill in the info pChunk->m_ClientID = m_ClientID; pChunk->m_Address = m_Addr; pChunk->m_Flags = 0; pChunk->m_DataSize = Header.m_Size; pChunk->m_pData = pData; return 1; } } // packs the data tight and sends it void CNetBase::SendPacketConnless(NETSOCKET Socket, NETADDR *pAddr, const void *pData, int DataSize) { unsigned char aBuffer[NET_MAX_PACKETSIZE]; aBuffer[0] = 0xff; aBuffer[1] = 0xff; aBuffer[2] = 0xff; aBuffer[3] = 0xff; aBuffer[4] = 0xff; aBuffer[5] = 0xff; mem_copy(&aBuffer[6], pData, DataSize); net_udp_send(Socket, pAddr, aBuffer, 6+DataSize); } void CNetBase::SendPacket(NETSOCKET Socket, NETADDR *pAddr, CNetPacketConstruct *pPacket) { unsigned char aBuffer[NET_MAX_PACKETSIZE]; int CompressedSize = -1; int FinalSize = -1; // log the data if(ms_DataLogSent) { int Type = 1; io_write(ms_DataLogSent, &Type, sizeof(Type)); io_write(ms_DataLogSent, &pPacket->m_DataSize, sizeof(pPacket->m_DataSize)); io_write(ms_DataLogSent, &pPacket->m_aChunkData, pPacket->m_DataSize); io_flush(ms_DataLogSent); } // compress CompressedSize = ms_Huffman.Compress(pPacket->m_aChunkData, pPacket->m_DataSize, &aBuffer[3], NET_MAX_PACKETSIZE-4); // check if the compression was enabled, successful and good enough if(CompressedSize > 0 && CompressedSize < pPacket->m_DataSize) { FinalSize = CompressedSize; pPacket->m_Flags |= NET_PACKETFLAG_COMPRESSION; } else { // use uncompressed data FinalSize = pPacket->m_DataSize; mem_copy(&aBuffer[3], pPacket->m_aChunkData, pPacket->m_DataSize); pPacket->m_Flags &= ~NET_PACKETFLAG_COMPRESSION; } // set header and send the packet if all things are good if(FinalSize >= 0) { FinalSize += NET_PACKETHEADERSIZE; aBuffer[0] = ((pPacket->m_Flags<<4)&0xf0)|((pPacket->m_Ack>>8)&0xf); aBuffer[1] = pPacket->m_Ack&0xff; aBuffer[2] = pPacket->m_NumChunks; net_udp_send(Socket, pAddr, aBuffer, FinalSize); // log raw socket data if(ms_DataLogSent) { int Type = 0; io_write(ms_DataLogSent, &Type, sizeof(Type)); io_write(ms_DataLogSent, &FinalSize, sizeof(FinalSize)); io_write(ms_DataLogSent, aBuffer, FinalSize); io_flush(ms_DataLogSent); } } } // TODO: rename this function int CNetBase::UnpackPacket(unsigned char *pBuffer, int Size, CNetPacketConstruct *pPacket) { // check the size if(Size < NET_PACKETHEADERSIZE || Size > NET_MAX_PACKETSIZE) { if(g_Config.m_Debug) dbg_msg("network", "packet too small, %d", Size); return -1; } // log the data if(ms_DataLogRecv) { int Type = 0; io_write(ms_DataLogRecv, &Type, sizeof(Type)); io_write(ms_DataLogRecv, &Size, sizeof(Size)); io_write(ms_DataLogRecv, pBuffer, Size); io_flush(ms_DataLogRecv); } // read the packet pPacket->m_Flags = pBuffer[0]>>4; if(pPacket->m_Flags&NET_PACKETFLAG_CONNLESS) { if(Size < 6) { if(g_Config.m_Debug) dbg_msg("network", "connection less packet too small, %d", Size); return -1; } pPacket->m_Flags = NET_PACKETFLAG_CONNLESS; pPacket->m_Ack = 0; pPacket->m_NumChunks = 0; pPacket->m_DataSize = Size - 6; mem_copy(pPacket->m_aChunkData, &pBuffer[6], pPacket->m_DataSize); } else { if(Size-NET_PACKETHEADERSIZE > NET_MAX_PAYLOAD) { if(g_Config.m_Debug) dbg_msg("network", "packet too big, %d", Size); return -1; } pPacket->m_Ack = ((pBuffer[0]&0xf)<<8) | pBuffer[1]; pPacket->m_NumChunks = pBuffer[2]; pPacket->m_DataSize = Size - NET_PACKETHEADERSIZE; if(pPacket->m_Flags&NET_PACKETFLAG_COMPRESSION) pPacket->m_DataSize = ms_Huffman.Decompress(&pBuffer[3], pPacket->m_DataSize, pPacket->m_aChunkData, sizeof(pPacket->m_aChunkData)); else mem_copy(pPacket->m_aChunkData, &pBuffer[3], pPacket->m_DataSize); } // check for errors if(pPacket->m_DataSize < 0) { if(g_Config.m_Debug) dbg_msg("network", "error during packet decoding"); return -1; } // log the data if(ms_DataLogRecv) { int Type = 1; io_write(ms_DataLogRecv, &Type, sizeof(Type)); io_write(ms_DataLogRecv, &pPacket->m_DataSize, sizeof(pPacket->m_DataSize)); io_write(ms_DataLogRecv, pPacket->m_aChunkData, pPacket->m_DataSize); io_flush(ms_DataLogRecv); } // return success return 0; } void CNetBase::SendControlMsg(NETSOCKET Socket, NETADDR *pAddr, int Ack, int ControlMsg, const void *pExtra, int ExtraSize) { CNetPacketConstruct Construct; Construct.m_Flags = NET_PACKETFLAG_CONTROL; Construct.m_Ack = Ack; Construct.m_NumChunks = 0; Construct.m_DataSize = 1+ExtraSize; Construct.m_aChunkData[0] = ControlMsg; mem_copy(&Construct.m_aChunkData[1], pExtra, ExtraSize); // send the control message CNetBase::SendPacket(Socket, pAddr, &Construct); } unsigned char *CNetChunkHeader::Pack(unsigned char *pData) { pData[0] = ((m_Flags&0x03)<<6) | ((m_Size>>6)&0x3F); pData[1] = (m_Size&0x3F); if(m_Flags&NET_CHUNKFLAG_VITAL) { pData[1] |= (m_Sequence>>2)&0xC0; pData[2] = m_Sequence&0xFF; return pData + 3; } return pData + 2; } unsigned char *CNetChunkHeader::Unpack(unsigned char *pData) { m_Flags = (pData[0]>>6)&0x03; m_Size = ((pData[0]&0x3F)<<6) | (pData[1]&0x3F); m_Sequence = -1; if(m_Flags&NET_CHUNKFLAG_VITAL) { m_Sequence = ((pData[1]&0xC0)<<2) | pData[2]; return pData + 3; } return pData + 2; } int CNetBase::IsSeqInBackroom(int Seq, int Ack) { int Bottom = (Ack-NET_MAX_SEQUENCE/2); if(Bottom < 0) { if(Seq <= Ack) return 1; if(Seq >= (Bottom + NET_MAX_SEQUENCE)) return 1; } else { if(Seq <= Ack && Seq >= Bottom) return 1; } return 0; } IOHANDLE CNetBase::ms_DataLogSent = 0; IOHANDLE CNetBase::ms_DataLogRecv = 0; CHuffman CNetBase::ms_Huffman; void CNetBase::OpenLog(IOHANDLE DataLogSent, IOHANDLE DataLogRecv) { if(DataLogSent) { ms_DataLogSent = DataLogSent; dbg_msg("network", "logging sent packages"); } else dbg_msg("network", "failed to start logging sent packages"); if(DataLogRecv) { ms_DataLogRecv = DataLogRecv; dbg_msg("network", "logging recv packages"); } else dbg_msg("network", "failed to start logging recv packages"); } void CNetBase::CloseLog() { if(ms_DataLogSent) { dbg_msg("network", "stopped logging sent packages"); io_close(ms_DataLogSent); ms_DataLogSent = 0; } if(ms_DataLogRecv) { dbg_msg("network", "stopped logging recv packages"); io_close(ms_DataLogRecv); ms_DataLogRecv = 0; } } int CNetBase::Compress(const void *pData, int DataSize, void *pOutput, int OutputSize) { return ms_Huffman.Compress(pData, DataSize, pOutput, OutputSize); } int CNetBase::Decompress(const void *pData, int DataSize, void *pOutput, int OutputSize) { return ms_Huffman.Decompress(pData, DataSize, pOutput, OutputSize); } static const unsigned gs_aFreqTable[256+1] = { 1<<30,4545,2657,431,1950,919,444,482,2244,617,838,542,715,1814,304,240,754,212,647,186, 283,131,146,166,543,164,167,136,179,859,363,113,157,154,204,108,137,180,202,176, 872,404,168,134,151,111,113,109,120,126,129,100,41,20,16,22,18,18,17,19, 16,37,13,21,362,166,99,78,95,88,81,70,83,284,91,187,77,68,52,68, 59,66,61,638,71,157,50,46,69,43,11,24,13,19,10,12,12,20,14,9, 20,20,10,10,15,15,12,12,7,19,15,14,13,18,35,19,17,14,8,5, 15,17,9,15,14,18,8,10,2173,134,157,68,188,60,170,60,194,62,175,71, 148,67,167,78,211,67,156,69,1674,90,174,53,147,89,181,51,174,63,163,80, 167,94,128,122,223,153,218,77,200,110,190,73,174,69,145,66,277,143,141,60, 136,53,180,57,142,57,158,61,166,112,152,92,26,22,21,28,20,26,30,21, 32,27,20,17,23,21,30,22,22,21,27,25,17,27,23,18,39,26,15,21, 12,18,18,27,20,18,15,19,11,17,33,12,18,15,19,18,16,26,17,18, 9,10,25,22,22,17,20,16,6,16,15,20,14,18,24,335,1517}; void CNetBase::Init() { ms_Huffman.Init(gs_aFreqTable); } ================================================ FILE: src/engine/shared/network.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef ENGINE_SHARED_NETWORK_H #define ENGINE_SHARED_NETWORK_H #include "ringbuffer.h" #include "huffman.h" /* CURRENT: packet header: 3 bytes unsigned char flags_ack; // 4bit flags, 4bit ack unsigned char ack; // 8 bit ack unsigned char num_chunks; // 8 bit chunks (unsigned char padding[3]) // 24 bit extra incase it's a connection less packet // this is to make sure that it's compatible with the // old protocol chunk header: 2-3 bytes unsigned char flags_size; // 2bit flags, 6 bit size unsigned char size_seq; // 6bit size, 2bit seq (unsigned char seq;) // 8bit seq, if vital flag is set */ enum { NETFLAG_ALLOWSTATELESS=1, NETSENDFLAG_VITAL=1, NETSENDFLAG_CONNLESS=2, NETSENDFLAG_FLUSH=4, NETSTATE_OFFLINE=0, NETSTATE_CONNECTING, NETSTATE_ONLINE, NETBANTYPE_SOFT=1, NETBANTYPE_DROP=2 }; enum { NET_VERSION = 2, NET_MAX_PACKETSIZE = 1400, NET_MAX_PAYLOAD = NET_MAX_PACKETSIZE-6, NET_MAX_CHUNKHEADERSIZE = 3, NET_PACKETHEADERSIZE = 3, NET_MAX_CLIENTS = 16, NET_MAX_CONSOLE_CLIENTS = 4, NET_MAX_SEQUENCE = 1<<10, NET_SEQUENCE_MASK = NET_MAX_SEQUENCE-1, NET_CONNSTATE_OFFLINE=0, NET_CONNSTATE_CONNECT=1, NET_CONNSTATE_PENDING=2, NET_CONNSTATE_ONLINE=3, NET_CONNSTATE_ERROR=4, NET_PACKETFLAG_CONTROL=1, NET_PACKETFLAG_CONNLESS=2, NET_PACKETFLAG_RESEND=4, NET_PACKETFLAG_COMPRESSION=8, NET_CHUNKFLAG_VITAL=1, NET_CHUNKFLAG_RESEND=2, NET_CTRLMSG_KEEPALIVE=0, NET_CTRLMSG_CONNECT=1, NET_CTRLMSG_CONNECTACCEPT=2, NET_CTRLMSG_ACCEPT=3, NET_CTRLMSG_CLOSE=4, NET_CONN_BUFFERSIZE=1024*32, NET_ENUM_TERMINATOR }; typedef int (*NETFUNC_DELCLIENT)(int ClientID, const char* pReason, void *pUser); typedef int (*NETFUNC_NEWCLIENT)(int ClientID, void *pUser); struct CNetChunk { // -1 means that it's a stateless packet // 0 on the client means the server int m_ClientID; NETADDR m_Address; // only used when client_id == -1 int m_Flags; int m_DataSize; const void *m_pData; }; class CNetChunkHeader { public: int m_Flags; int m_Size; int m_Sequence; unsigned char *Pack(unsigned char *pData); unsigned char *Unpack(unsigned char *pData); }; class CNetChunkResend { public: int m_Flags; int m_DataSize; unsigned char *m_pData; int m_Sequence; int64 m_LastSendTime; int64 m_FirstSendTime; }; class CNetPacketConstruct { public: int m_Flags; int m_Ack; int m_NumChunks; int m_DataSize; unsigned char m_aChunkData[NET_MAX_PAYLOAD]; }; class CNetConnection { // TODO: is this needed because this needs to be aware of // the ack sequencing number and is also responible for updating // that. this should be fixed. friend class CNetRecvUnpacker; private: unsigned short m_Sequence; unsigned short m_Ack; unsigned m_State; int m_Token; int m_RemoteClosed; bool m_BlockCloseMsg; TStaticRingBuffer<CNetChunkResend, NET_CONN_BUFFERSIZE> m_Buffer; int64 m_LastUpdateTime; int64 m_LastRecvTime; int64 m_LastSendTime; char m_ErrorString[256]; CNetPacketConstruct m_Construct; NETADDR m_PeerAddr; NETSOCKET m_Socket; NETSTATS m_Stats; // void Reset(); void ResetStats(); void SetError(const char *pString); void AckChunks(int Ack); int QueueChunkEx(int Flags, int DataSize, const void *pData, int Sequence); void SendControl(int ControlMsg, const void *pExtra, int ExtraSize); void ResendChunk(CNetChunkResend *pResend); void Resend(); public: void Init(NETSOCKET Socket, bool BlockCloseMsg); int Connect(NETADDR *pAddr); void Disconnect(const char *pReason); int Update(); int Flush(); int Feed(CNetPacketConstruct *pPacket, NETADDR *pAddr); int QueueChunk(int Flags, int DataSize, const void *pData); const char *ErrorString(); void SignalResend(); int State() const { return m_State; } const NETADDR *PeerAddress() const { return &m_PeerAddr; } void ResetErrorString() { m_ErrorString[0] = 0; } const char *ErrorString() const { return m_ErrorString; } // Needed for GotProblems in NetClient int64 LastRecvTime() const { return m_LastRecvTime; } int AckSequence() const { return m_Ack; } }; class CConsoleNetConnection { private: int m_State; NETADDR m_PeerAddr; NETSOCKET m_Socket; char m_aBuffer[NET_MAX_PACKETSIZE]; int m_BufferOffset; char m_aErrorString[256]; bool m_LineEndingDetected; char m_aLineEnding[3]; public: void Init(NETSOCKET Socket, const NETADDR *pAddr); void Disconnect(const char *pReason); int State() const { return m_State; } const NETADDR *PeerAddress() const { return &m_PeerAddr; } const char *ErrorString() const { return m_aErrorString; } void Reset(); int Update(); int Send(const char *pLine); int Recv(char *pLine, int MaxLength); }; class CNetRecvUnpacker { public: bool m_Valid; NETADDR m_Addr; CNetConnection *m_pConnection; int m_CurrentChunk; int m_ClientID; CNetPacketConstruct m_Data; unsigned char m_aBuffer[NET_MAX_PACKETSIZE]; CNetRecvUnpacker() { Clear(); } void Clear(); void Start(const NETADDR *pAddr, CNetConnection *pConnection, int ClientID); int FetchChunk(CNetChunk *pChunk); }; // server side class CNetServer { struct CSlot { public: CNetConnection m_Connection; }; NETSOCKET m_Socket; class CNetBan *m_pNetBan; CSlot m_aSlots[NET_MAX_CLIENTS]; int m_MaxClients; int m_MaxClientsPerIP; NETFUNC_NEWCLIENT m_pfnNewClient; NETFUNC_DELCLIENT m_pfnDelClient; void *m_UserPtr; CNetRecvUnpacker m_RecvUnpacker; public: int SetCallbacks(NETFUNC_NEWCLIENT pfnNewClient, NETFUNC_DELCLIENT pfnDelClient, void *pUser); // bool Open(NETADDR BindAddr, class CNetBan *pNetBan, int MaxClients, int MaxClientsPerIP, int Flags); int Close(); // int Recv(CNetChunk *pChunk); int Send(CNetChunk *pChunk); int Update(); // int Drop(int ClientID, const char *pReason); // status requests const NETADDR *ClientAddr(int ClientID) const { return m_aSlots[ClientID].m_Connection.PeerAddress(); } NETSOCKET Socket() const { return m_Socket; } class CNetBan *NetBan() const { return m_pNetBan; } int NetType() const { return m_Socket.type; } int MaxClients() const { return m_MaxClients; } // void SetMaxClientsPerIP(int Max); }; class CNetConsole { struct CSlot { CConsoleNetConnection m_Connection; }; NETSOCKET m_Socket; class CNetBan *m_pNetBan; CSlot m_aSlots[NET_MAX_CONSOLE_CLIENTS]; NETFUNC_NEWCLIENT m_pfnNewClient; NETFUNC_DELCLIENT m_pfnDelClient; void *m_UserPtr; CNetRecvUnpacker m_RecvUnpacker; public: void SetCallbacks(NETFUNC_NEWCLIENT pfnNewClient, NETFUNC_DELCLIENT pfnDelClient, void *pUser); // bool Open(NETADDR BindAddr, class CNetBan *pNetBan, int Flags); int Close(); // int Recv(char *pLine, int MaxLength, int *pClientID = 0); int Send(int ClientID, const char *pLine); int Update(); // int AcceptClient(NETSOCKET Socket, const NETADDR *pAddr); int Drop(int ClientID, const char *pReason); // status requests const NETADDR *ClientAddr(int ClientID) const { return m_aSlots[ClientID].m_Connection.PeerAddress(); } class CNetBan *NetBan() const { return m_pNetBan; } }; // client side class CNetClient { NETADDR m_ServerAddr; CNetConnection m_Connection; CNetRecvUnpacker m_RecvUnpacker; NETSOCKET m_Socket; public: // openness bool Open(NETADDR BindAddr, int Flags); int Close(); // connection state int Disconnect(const char *Reason); int Connect(NETADDR *Addr); // communication int Recv(CNetChunk *Chunk); int Send(CNetChunk *Chunk); // pumping int Update(); int Flush(); int ResetErrorString(); // error and state int NetType() const { return m_Socket.type; } int State(); int GotProblems(); const char *ErrorString(); }; // TODO: both, fix these. This feels like a junk class for stuff that doesn't fit anywere class CNetBase { static IOHANDLE ms_DataLogSent; static IOHANDLE ms_DataLogRecv; static CHuffman ms_Huffman; public: static void OpenLog(IOHANDLE DataLogSent, IOHANDLE DataLogRecv); static void CloseLog(); static void Init(); static int Compress(const void *pData, int DataSize, void *pOutput, int OutputSize); static int Decompress(const void *pData, int DataSize, void *pOutput, int OutputSize); static void SendControlMsg(NETSOCKET Socket, NETADDR *pAddr, int Ack, int ControlMsg, const void *pExtra, int ExtraSize); static void SendPacketConnless(NETSOCKET Socket, NETADDR *pAddr, const void *pData, int DataSize); static void SendPacket(NETSOCKET Socket, NETADDR *pAddr, CNetPacketConstruct *pPacket); static int UnpackPacket(unsigned char *pBuffer, int Size, CNetPacketConstruct *pPacket); // The backroom is ack-NET_MAX_SEQUENCE/2. Used for knowing if we acked a packet or not static int IsSeqInBackroom(int Seq, int Ack); }; #endif ================================================ FILE: src/engine/shared/network_client.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <base/system.h> #include "network.h" bool CNetClient::Open(NETADDR BindAddr, int Flags) { // open socket NETSOCKET Socket; Socket = net_udp_create(BindAddr); if(!Socket.type) return false; // clean it mem_zero(this, sizeof(*this)); // init m_Socket = Socket; m_Connection.Init(m_Socket, false); return true; } int CNetClient::Close() { // TODO: implement me return 0; } int CNetClient::Disconnect(const char *pReason) { //dbg_msg("netclient", "disconnected. reason=\"%s\"", pReason); m_Connection.Disconnect(pReason); return 0; } int CNetClient::Update() { m_Connection.Update(); if(m_Connection.State() == NET_CONNSTATE_ERROR) Disconnect(m_Connection.ErrorString()); return 0; } int CNetClient::Connect(NETADDR *pAddr) { m_Connection.Connect(pAddr); return 0; } int CNetClient::ResetErrorString() { m_Connection.ResetErrorString(); return 0; } int CNetClient::Recv(CNetChunk *pChunk) { while(1) { // check for a chunk if(m_RecvUnpacker.FetchChunk(pChunk)) return 1; // TODO: empty the recvinfo NETADDR Addr; int Bytes = net_udp_recv(m_Socket, &Addr, m_RecvUnpacker.m_aBuffer, NET_MAX_PACKETSIZE); // no more packets for now if(Bytes <= 0) break; if(CNetBase::UnpackPacket(m_RecvUnpacker.m_aBuffer, Bytes, &m_RecvUnpacker.m_Data) == 0) { if(m_RecvUnpacker.m_Data.m_Flags&NET_PACKETFLAG_CONNLESS) { pChunk->m_Flags = NETSENDFLAG_CONNLESS; pChunk->m_ClientID = -1; pChunk->m_Address = Addr; pChunk->m_DataSize = m_RecvUnpacker.m_Data.m_DataSize; pChunk->m_pData = m_RecvUnpacker.m_Data.m_aChunkData; return 1; } else { if(m_Connection.Feed(&m_RecvUnpacker.m_Data, &Addr)) m_RecvUnpacker.Start(&Addr, &m_Connection, 0); } } } return 0; } int CNetClient::Send(CNetChunk *pChunk) { if(pChunk->m_Flags&NETSENDFLAG_CONNLESS) { if(pChunk->m_DataSize >= NET_MAX_PAYLOAD) { dbg_msg("netserver", "packet payload too big. %d. dropping packet", pChunk->m_DataSize); return -1; } // send connectionless packet CNetBase::SendPacketConnless(m_Socket, &pChunk->m_Address, pChunk->m_pData, pChunk->m_DataSize); } else { if(pChunk->m_DataSize+NET_MAX_CHUNKHEADERSIZE >= NET_MAX_PAYLOAD) { dbg_msg("netclient", "chunk payload too big. %d. dropping chunk", pChunk->m_DataSize); return -1; } int Flags = 0; dbg_assert(pChunk->m_ClientID == 0, "errornous client id"); if(pChunk->m_Flags&NETSENDFLAG_VITAL) Flags = NET_CHUNKFLAG_VITAL; m_Connection.QueueChunk(Flags, pChunk->m_DataSize, pChunk->m_pData); if(pChunk->m_Flags&NETSENDFLAG_FLUSH) m_Connection.Flush(); } return 0; } int CNetClient::State() { if(m_Connection.State() == NET_CONNSTATE_ONLINE) return NETSTATE_ONLINE; if(m_Connection.State() == NET_CONNSTATE_OFFLINE) return NETSTATE_OFFLINE; return NETSTATE_CONNECTING; } int CNetClient::Flush() { return m_Connection.Flush(); } int CNetClient::GotProblems() { if(time_get() - m_Connection.LastRecvTime() > time_freq()) return 1; return 0; } const char *CNetClient::ErrorString() { return m_Connection.ErrorString(); } ================================================ FILE: src/engine/shared/network_conn.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <base/system.h> #include "config.h" #include "network.h" void CNetConnection::ResetStats() { mem_zero(&m_Stats, sizeof(m_Stats)); } void CNetConnection::Reset() { m_Sequence = 0; m_Ack = 0; m_RemoteClosed = 0; m_State = NET_CONNSTATE_OFFLINE; m_LastSendTime = 0; m_LastRecvTime = 0; m_LastUpdateTime = 0; m_Token = -1; mem_zero(&m_PeerAddr, sizeof(m_PeerAddr)); m_Buffer.Init(); mem_zero(&m_Construct, sizeof(m_Construct)); } const char *CNetConnection::ErrorString() { return m_ErrorString; } void CNetConnection::SetError(const char *pString) { str_copy(m_ErrorString, pString, sizeof(m_ErrorString)); } void CNetConnection::Init(NETSOCKET Socket, bool BlockCloseMsg) { Reset(); ResetStats(); m_Socket = Socket; m_BlockCloseMsg = BlockCloseMsg; mem_zero(m_ErrorString, sizeof(m_ErrorString)); } void CNetConnection::AckChunks(int Ack) { while(1) { CNetChunkResend *pResend = m_Buffer.First(); if(!pResend) break; if(CNetBase::IsSeqInBackroom(pResend->m_Sequence, Ack)) m_Buffer.PopFirst(); else break; } } void CNetConnection::SignalResend() { m_Construct.m_Flags |= NET_PACKETFLAG_RESEND; } int CNetConnection::Flush() { int NumChunks = m_Construct.m_NumChunks; if(!NumChunks && !m_Construct.m_Flags) return 0; // send of the packets m_Construct.m_Ack = m_Ack; CNetBase::SendPacket(m_Socket, &m_PeerAddr, &m_Construct); // update send times m_LastSendTime = time_get(); // clear construct so we can start building a new package mem_zero(&m_Construct, sizeof(m_Construct)); return NumChunks; } int CNetConnection::QueueChunkEx(int Flags, int DataSize, const void *pData, int Sequence) { unsigned char *pChunkData; // check if we have space for it, if not, flush the connection if(m_Construct.m_DataSize + DataSize + NET_MAX_CHUNKHEADERSIZE > (int)sizeof(m_Construct.m_aChunkData)) Flush(); // pack all the data CNetChunkHeader Header; Header.m_Flags = Flags; Header.m_Size = DataSize; Header.m_Sequence = Sequence; pChunkData = &m_Construct.m_aChunkData[m_Construct.m_DataSize]; pChunkData = Header.Pack(pChunkData); mem_copy(pChunkData, pData, DataSize); pChunkData += DataSize; // m_Construct.m_NumChunks++; m_Construct.m_DataSize = (int)(pChunkData-m_Construct.m_aChunkData); // set packet flags aswell if(Flags&NET_CHUNKFLAG_VITAL && !(Flags&NET_CHUNKFLAG_RESEND)) { // save packet if we need to resend CNetChunkResend *pResend = m_Buffer.Allocate(sizeof(CNetChunkResend)+DataSize); if(pResend) { pResend->m_Sequence = Sequence; pResend->m_Flags = Flags; pResend->m_DataSize = DataSize; pResend->m_pData = (unsigned char *)(pResend+1); pResend->m_FirstSendTime = time_get(); pResend->m_LastSendTime = pResend->m_FirstSendTime; mem_copy(pResend->m_pData, pData, DataSize); } else { // out of buffer Disconnect("too weak connection (out of buffer)"); return -1; } } return 0; } int CNetConnection::QueueChunk(int Flags, int DataSize, const void *pData) { if(Flags&NET_CHUNKFLAG_VITAL) m_Sequence = (m_Sequence+1)%NET_MAX_SEQUENCE; return QueueChunkEx(Flags, DataSize, pData, m_Sequence); } void CNetConnection::SendControl(int ControlMsg, const void *pExtra, int ExtraSize) { // send the control message m_LastSendTime = time_get(); CNetBase::SendControlMsg(m_Socket, &m_PeerAddr, m_Ack, ControlMsg, pExtra, ExtraSize); } void CNetConnection::ResendChunk(CNetChunkResend *pResend) { QueueChunkEx(pResend->m_Flags|NET_CHUNKFLAG_RESEND, pResend->m_DataSize, pResend->m_pData, pResend->m_Sequence); pResend->m_LastSendTime = time_get(); } void CNetConnection::Resend() { for(CNetChunkResend *pResend = m_Buffer.First(); pResend; pResend = m_Buffer.Next(pResend)) ResendChunk(pResend); } int CNetConnection::Connect(NETADDR *pAddr) { if(State() != NET_CONNSTATE_OFFLINE) return -1; // init connection Reset(); m_PeerAddr = *pAddr; mem_zero(m_ErrorString, sizeof(m_ErrorString)); m_State = NET_CONNSTATE_CONNECT; SendControl(NET_CTRLMSG_CONNECT, 0, 0); return 0; } void CNetConnection::Disconnect(const char *pReason) { if(State() == NET_CONNSTATE_OFFLINE) return; if(m_RemoteClosed == 0) { if(pReason) SendControl(NET_CTRLMSG_CLOSE, pReason, str_length(pReason)+1); else SendControl(NET_CTRLMSG_CLOSE, 0, 0); m_ErrorString[0] = 0; if(pReason) str_copy(m_ErrorString, pReason, sizeof(m_ErrorString)); } Reset(); } int CNetConnection::Feed(CNetPacketConstruct *pPacket, NETADDR *pAddr) { int64 Now = time_get(); // check if resend is requested if(pPacket->m_Flags&NET_PACKETFLAG_RESEND) Resend(); // if(pPacket->m_Flags&NET_PACKETFLAG_CONTROL) { int CtrlMsg = pPacket->m_aChunkData[0]; if(CtrlMsg == NET_CTRLMSG_CLOSE) { if(net_addr_comp(&m_PeerAddr, pAddr) == 0) { m_State = NET_CONNSTATE_ERROR; m_RemoteClosed = 1; char Str[128] = {0}; if(pPacket->m_DataSize > 1) { // make sure to sanitize the error string form the other party if(pPacket->m_DataSize < 128) str_copy(Str, (char *)&pPacket->m_aChunkData[1], pPacket->m_DataSize); else str_copy(Str, (char *)&pPacket->m_aChunkData[1], sizeof(Str)); str_sanitize_strong(Str); } if(!m_BlockCloseMsg) { // set the error string SetError(Str); } if(g_Config.m_Debug) dbg_msg("conn", "closed reason='%s'", Str); } return 0; } else { if(State() == NET_CONNSTATE_OFFLINE) { if(CtrlMsg == NET_CTRLMSG_CONNECT) { // send response and init connection Reset(); m_State = NET_CONNSTATE_PENDING; m_PeerAddr = *pAddr; mem_zero(m_ErrorString, sizeof(m_ErrorString)); m_LastSendTime = Now; m_LastRecvTime = Now; m_LastUpdateTime = Now; SendControl(NET_CTRLMSG_CONNECTACCEPT, 0, 0); if(g_Config.m_Debug) dbg_msg("connection", "got connection, sending connect+accept"); } } else if(State() == NET_CONNSTATE_CONNECT) { // connection made if(CtrlMsg == NET_CTRLMSG_CONNECTACCEPT) { m_LastRecvTime = Now; SendControl(NET_CTRLMSG_ACCEPT, 0, 0); m_State = NET_CONNSTATE_ONLINE; if(g_Config.m_Debug) dbg_msg("connection", "got connect+accept, sending accept. connection online"); } } } } else { if(State() == NET_CONNSTATE_PENDING) { m_LastRecvTime = Now; m_State = NET_CONNSTATE_ONLINE; if(g_Config.m_Debug) dbg_msg("connection", "connecting online"); } } if(State() == NET_CONNSTATE_ONLINE) { m_LastRecvTime = Now; AckChunks(pPacket->m_Ack); } return 1; } int CNetConnection::Update() { int64 Now = time_get(); if(State() == NET_CONNSTATE_OFFLINE || State() == NET_CONNSTATE_ERROR) return 0; // check for timeout if(State() != NET_CONNSTATE_OFFLINE && State() != NET_CONNSTATE_CONNECT && (Now-m_LastRecvTime) > time_freq()*10) { m_State = NET_CONNSTATE_ERROR; SetError("Timeout"); } // fix resends if(m_Buffer.First()) { CNetChunkResend *pResend = m_Buffer.First(); // check if we have some really old stuff laying around and abort if not acked if(Now-pResend->m_FirstSendTime > time_freq()*10) { m_State = NET_CONNSTATE_ERROR; SetError("Too weak connection (not acked for 10 seconds)"); } else { // resend packet if we havn't got it acked in 1 second if(Now-pResend->m_LastSendTime > time_freq()) ResendChunk(pResend); } } // send keep alives if nothing has happend for 250ms if(State() == NET_CONNSTATE_ONLINE) { if(time_get()-m_LastSendTime > time_freq()/2) // flush connection after 500ms if needed { int NumFlushedChunks = Flush(); if(NumFlushedChunks && g_Config.m_Debug) dbg_msg("connection", "flushed connection due to timeout. %d chunks.", NumFlushedChunks); } if(time_get()-m_LastSendTime > time_freq()) SendControl(NET_CTRLMSG_KEEPALIVE, 0, 0); } else if(State() == NET_CONNSTATE_CONNECT) { if(time_get()-m_LastSendTime > time_freq()/2) // send a new connect every 500ms SendControl(NET_CTRLMSG_CONNECT, 0, 0); } else if(State() == NET_CONNSTATE_PENDING) { if(time_get()-m_LastSendTime > time_freq()/2) // send a new connect/accept every 500ms SendControl(NET_CTRLMSG_CONNECTACCEPT, 0, 0); } return 0; } ================================================ FILE: src/engine/shared/network_console.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <base/system.h> #include <engine/console.h> #include "netban.h" #include "network.h" bool CNetConsole::Open(NETADDR BindAddr, CNetBan *pNetBan, int Flags) { // zero out the whole structure mem_zero(this, sizeof(*this)); m_Socket.type = NETTYPE_INVALID; m_Socket.ipv4sock = -1; m_Socket.ipv6sock = -1; m_pNetBan = pNetBan; // open socket m_Socket = net_tcp_create(BindAddr); if(!m_Socket.type) return false; if(net_tcp_listen(m_Socket, NET_MAX_CONSOLE_CLIENTS)) return false; net_set_non_blocking(m_Socket); for(int i = 0; i < NET_MAX_CONSOLE_CLIENTS; i++) m_aSlots[i].m_Connection.Reset(); return true; } void CNetConsole::SetCallbacks(NETFUNC_NEWCLIENT pfnNewClient, NETFUNC_DELCLIENT pfnDelClient, void *pUser) { m_pfnNewClient = pfnNewClient; m_pfnDelClient = pfnDelClient; m_UserPtr = pUser; } int CNetConsole::Close() { for(int i = 0; i < NET_MAX_CONSOLE_CLIENTS; i++) m_aSlots[i].m_Connection.Disconnect("closing console"); net_tcp_close(m_Socket); return 0; } int CNetConsole::Drop(int ClientID, const char *pReason) { if(m_pfnDelClient) m_pfnDelClient(ClientID, pReason, m_UserPtr); m_aSlots[ClientID].m_Connection.Disconnect(pReason); return 0; } int CNetConsole::AcceptClient(NETSOCKET Socket, const NETADDR *pAddr) { char aError[256] = { 0 }; int FreeSlot = -1; // look for free slot or multiple client for(int i = 0; i < NET_MAX_CONSOLE_CLIENTS; i++) { if(FreeSlot == -1 && m_aSlots[i].m_Connection.State() == NET_CONNSTATE_OFFLINE) FreeSlot = i; if(m_aSlots[i].m_Connection.State() != NET_CONNSTATE_OFFLINE) { if(net_addr_comp(pAddr, m_aSlots[i].m_Connection.PeerAddress()) == 0) { str_copy(aError, "only one client per IP allowed", sizeof(aError)); break; } } } // accept client if(!aError[0] && FreeSlot != -1) { m_aSlots[FreeSlot].m_Connection.Init(Socket, pAddr); if(m_pfnNewClient) m_pfnNewClient(FreeSlot, m_UserPtr); return 0; } // reject client if(!aError[0]) str_copy(aError, "no free slot available", sizeof(aError)); net_tcp_send(Socket, aError, str_length(aError)); net_tcp_close(Socket); return -1; } int CNetConsole::Update() { NETSOCKET Socket; NETADDR Addr; if(net_tcp_accept(m_Socket, &Socket, &Addr) > 0) { // check if we just should drop the packet char aBuf[128]; if(NetBan() && NetBan()->IsBanned(&Addr, aBuf, sizeof(aBuf))) { // banned, reply with a message and drop net_tcp_send(Socket, aBuf, str_length(aBuf)); net_tcp_close(Socket); } else AcceptClient(Socket, &Addr); } for(int i = 0; i < NET_MAX_CONSOLE_CLIENTS; i++) { if(m_aSlots[i].m_Connection.State() == NET_CONNSTATE_ONLINE) m_aSlots[i].m_Connection.Update(); if(m_aSlots[i].m_Connection.State() == NET_CONNSTATE_ERROR) Drop(i, m_aSlots[i].m_Connection.ErrorString()); } return 0; } int CNetConsole::Recv(char *pLine, int MaxLength, int *pClientID) { for(int i = 0; i < NET_MAX_CONSOLE_CLIENTS; i++) { if(m_aSlots[i].m_Connection.State() == NET_CONNSTATE_ONLINE && m_aSlots[i].m_Connection.Recv(pLine, MaxLength)) { if(pClientID) *pClientID = i; return 1; } } return 0; } int CNetConsole::Send(int ClientID, const char *pLine) { if(m_aSlots[ClientID].m_Connection.State() == NET_CONNSTATE_ONLINE) return m_aSlots[ClientID].m_Connection.Send(pLine); else return -1; } ================================================ FILE: src/engine/shared/network_console_conn.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <base/system.h> #include "network.h" void CConsoleNetConnection::Reset() { m_State = NET_CONNSTATE_OFFLINE; mem_zero(&m_PeerAddr, sizeof(m_PeerAddr)); m_aErrorString[0] = 0; m_Socket.type = NETTYPE_INVALID; m_Socket.ipv4sock = -1; m_Socket.ipv6sock = -1; m_aBuffer[0] = 0; m_BufferOffset = 0; m_LineEndingDetected = false; #if defined(CONF_FAMILY_WINDOWS) m_aLineEnding[0] = '\r'; m_aLineEnding[1] = '\n'; m_aLineEnding[2] = 0; #else m_aLineEnding[0] = '\n'; m_aLineEnding[1] = 0; m_aLineEnding[2] = 0; #endif } void CConsoleNetConnection::Init(NETSOCKET Socket, const NETADDR *pAddr) { Reset(); m_Socket = Socket; net_set_non_blocking(m_Socket); m_PeerAddr = *pAddr; m_State = NET_CONNSTATE_ONLINE; } void CConsoleNetConnection::Disconnect(const char *pReason) { if(State() == NET_CONNSTATE_OFFLINE) return; if(pReason && pReason[0]) Send(pReason); net_tcp_close(m_Socket); Reset(); } int CConsoleNetConnection::Update() { if(State() == NET_CONNSTATE_ONLINE) { if((int)(sizeof(m_aBuffer)) <= m_BufferOffset) { m_State = NET_CONNSTATE_ERROR; str_copy(m_aErrorString, "too weak connection (out of buffer)", sizeof(m_aErrorString)); return -1; } int Bytes = net_tcp_recv(m_Socket, m_aBuffer+m_BufferOffset, (int)(sizeof(m_aBuffer))-m_BufferOffset); if(Bytes > 0) { m_BufferOffset += Bytes; } else if(Bytes < 0) { if(net_would_block()) // no data received return 0; m_State = NET_CONNSTATE_ERROR; // error str_copy(m_aErrorString, "connection failure", sizeof(m_aErrorString)); return -1; } else { m_State = NET_CONNSTATE_ERROR; str_copy(m_aErrorString, "remote end closed the connection", sizeof(m_aErrorString)); return -1; } } return 0; } int CConsoleNetConnection::Recv(char *pLine, int MaxLength) { if(State() == NET_CONNSTATE_ONLINE) { if(m_BufferOffset) { // find message start int StartOffset = 0; while(m_aBuffer[StartOffset] == '\r' || m_aBuffer[StartOffset] == '\n') { // detect clients line ending format if(!m_LineEndingDetected) { m_aLineEnding[0] = m_aBuffer[StartOffset]; if(StartOffset+1 < m_BufferOffset && (m_aBuffer[StartOffset+1] == '\r' || m_aBuffer[StartOffset+1] == '\n') && m_aBuffer[StartOffset] != m_aBuffer[StartOffset+1]) m_aLineEnding[1] = m_aBuffer[StartOffset+1]; m_LineEndingDetected = true; } if(++StartOffset >= m_BufferOffset) { m_BufferOffset = 0; return 0; } } // find message end int EndOffset = StartOffset; while(m_aBuffer[EndOffset] != '\r' && m_aBuffer[EndOffset] != '\n') { if(++EndOffset >= m_BufferOffset) { if(StartOffset > 0) { mem_move(m_aBuffer, m_aBuffer+StartOffset, m_BufferOffset-StartOffset); m_BufferOffset -= StartOffset; } return 0; } } // extract message and update buffer if(MaxLength-1 < EndOffset-StartOffset) { if(StartOffset > 0) { mem_move(m_aBuffer, m_aBuffer+StartOffset, m_BufferOffset-StartOffset); m_BufferOffset -= StartOffset; } return 0; } mem_copy(pLine, m_aBuffer+StartOffset, EndOffset-StartOffset); pLine[EndOffset-StartOffset] = 0; str_sanitize_cc(pLine); mem_move(m_aBuffer, m_aBuffer+EndOffset, m_BufferOffset-EndOffset); m_BufferOffset -= EndOffset; return 1; } } return 0; } int CConsoleNetConnection::Send(const char *pLine) { if(State() != NET_CONNSTATE_ONLINE) return -1; char aBuf[1024]; str_copy(aBuf, pLine, (int)(sizeof(aBuf))-2); int Length = str_length(aBuf); aBuf[Length] = m_aLineEnding[0]; aBuf[Length+1] = m_aLineEnding[1]; aBuf[Length+2] = m_aLineEnding[2]; Length += 3; const char *pData = aBuf; while(true) { int Send = net_tcp_send(m_Socket, pData, Length); if(Send < 0) { m_State = NET_CONNSTATE_ERROR; str_copy(m_aErrorString, "failed to send packet", sizeof(m_aErrorString)); return -1; } if(Send >= Length) break; pData += Send; Length -= Send; } return 0; } ================================================ FILE: src/engine/shared/network_server.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <base/system.h> #include <engine/console.h> #include "netban.h" #include "network.h" bool CNetServer::Open(NETADDR BindAddr, CNetBan *pNetBan, int MaxClients, int MaxClientsPerIP, int Flags) { // zero out the whole structure mem_zero(this, sizeof(*this)); // open socket m_Socket = net_udp_create(BindAddr); if(!m_Socket.type) return false; m_pNetBan = pNetBan; // clamp clients m_MaxClients = MaxClients; if(m_MaxClients > NET_MAX_CLIENTS) m_MaxClients = NET_MAX_CLIENTS; if(m_MaxClients < 1) m_MaxClients = 1; m_MaxClientsPerIP = MaxClientsPerIP; for(int i = 0; i < NET_MAX_CLIENTS; i++) m_aSlots[i].m_Connection.Init(m_Socket, true); return true; } int CNetServer::SetCallbacks(NETFUNC_NEWCLIENT pfnNewClient, NETFUNC_DELCLIENT pfnDelClient, void *pUser) { m_pfnNewClient = pfnNewClient; m_pfnDelClient = pfnDelClient; m_UserPtr = pUser; return 0; } int CNetServer::Close() { // TODO: implement me return 0; } int CNetServer::Drop(int ClientID, const char *pReason) { // TODO: insert lots of checks here /*NETADDR Addr = ClientAddr(ClientID); dbg_msg("net_server", "client dropped. cid=%d ip=%d.%d.%d.%d reason=\"%s\"", ClientID, Addr.ip[0], Addr.ip[1], Addr.ip[2], Addr.ip[3], pReason );*/ if(m_pfnDelClient) m_pfnDelClient(ClientID, pReason, m_UserPtr); m_aSlots[ClientID].m_Connection.Disconnect(pReason); return 0; } int CNetServer::Update() { for(int i = 0; i < MaxClients(); i++) { m_aSlots[i].m_Connection.Update(); if(m_aSlots[i].m_Connection.State() == NET_CONNSTATE_ERROR) Drop(i, m_aSlots[i].m_Connection.ErrorString()); } return 0; } /* TODO: chopp up this function into smaller working parts */ int CNetServer::Recv(CNetChunk *pChunk) { while(1) { NETADDR Addr; // check for a chunk if(m_RecvUnpacker.FetchChunk(pChunk)) return 1; // TODO: empty the recvinfo int Bytes = net_udp_recv(m_Socket, &Addr, m_RecvUnpacker.m_aBuffer, NET_MAX_PACKETSIZE); // no more packets for now if(Bytes <= 0) break; if(CNetBase::UnpackPacket(m_RecvUnpacker.m_aBuffer, Bytes, &m_RecvUnpacker.m_Data) == 0) { // check if we just should drop the packet char aBuf[128]; if(NetBan() && NetBan()->IsBanned(&Addr, aBuf, sizeof(aBuf))) { // banned, reply with a message CNetBase::SendControlMsg(m_Socket, &Addr, 0, NET_CTRLMSG_CLOSE, aBuf, str_length(aBuf)+1); continue; } if(m_RecvUnpacker.m_Data.m_Flags&NET_PACKETFLAG_CONNLESS) { pChunk->m_Flags = NETSENDFLAG_CONNLESS; pChunk->m_ClientID = -1; pChunk->m_Address = Addr; pChunk->m_DataSize = m_RecvUnpacker.m_Data.m_DataSize; pChunk->m_pData = m_RecvUnpacker.m_Data.m_aChunkData; return 1; } else { // TODO: check size here if(m_RecvUnpacker.m_Data.m_Flags&NET_PACKETFLAG_CONTROL && m_RecvUnpacker.m_Data.m_aChunkData[0] == NET_CTRLMSG_CONNECT) { bool Found = false; // check if we already got this client for(int i = 0; i < MaxClients(); i++) { if(m_aSlots[i].m_Connection.State() != NET_CONNSTATE_OFFLINE && net_addr_comp(m_aSlots[i].m_Connection.PeerAddress(), &Addr) == 0) { Found = true; // silent ignore.. we got this client already break; } } // client that wants to connect if(!Found) { // only allow a specific number of players with the same ip NETADDR ThisAddr = Addr, OtherAddr; int FoundAddr = 1; ThisAddr.port = 0; for(int i = 0; i < MaxClients(); ++i) { if(m_aSlots[i].m_Connection.State() == NET_CONNSTATE_OFFLINE) continue; OtherAddr = *m_aSlots[i].m_Connection.PeerAddress(); OtherAddr.port = 0; if(!net_addr_comp(&ThisAddr, &OtherAddr)) { if(FoundAddr++ >= m_MaxClientsPerIP) { char aBuf[128]; str_format(aBuf, sizeof(aBuf), "Only %d players with the same IP are allowed", m_MaxClientsPerIP); CNetBase::SendControlMsg(m_Socket, &Addr, 0, NET_CTRLMSG_CLOSE, aBuf, sizeof(aBuf)); return 0; } } } for(int i = 0; i < MaxClients(); i++) { if(m_aSlots[i].m_Connection.State() == NET_CONNSTATE_OFFLINE) { Found = true; m_aSlots[i].m_Connection.Feed(&m_RecvUnpacker.m_Data, &Addr); if(m_pfnNewClient) m_pfnNewClient(i, m_UserPtr); break; } } if(!Found) { const char FullMsg[] = "This server is full"; CNetBase::SendControlMsg(m_Socket, &Addr, 0, NET_CTRLMSG_CLOSE, FullMsg, sizeof(FullMsg)); } } } else { // normal packet, find matching slot for(int i = 0; i < MaxClients(); i++) { if(net_addr_comp(m_aSlots[i].m_Connection.PeerAddress(), &Addr) == 0) { if(m_aSlots[i].m_Connection.Feed(&m_RecvUnpacker.m_Data, &Addr)) { if(m_RecvUnpacker.m_Data.m_DataSize) m_RecvUnpacker.Start(&Addr, &m_aSlots[i].m_Connection, i); } } } } } } } return 0; } int CNetServer::Send(CNetChunk *pChunk) { if(pChunk->m_Flags&NETSENDFLAG_CONNLESS) { if(pChunk->m_DataSize >= NET_MAX_PAYLOAD) { dbg_msg("netserver", "packet payload too big. %d. dropping packet", pChunk->m_DataSize); return -1; } // send connectionless packet CNetBase::SendPacketConnless(m_Socket, &pChunk->m_Address, pChunk->m_pData, pChunk->m_DataSize); } else { if(pChunk->m_DataSize+NET_MAX_CHUNKHEADERSIZE >= NET_MAX_PAYLOAD) { dbg_msg("netclient", "chunk payload too big. %d. dropping chunk", pChunk->m_DataSize); return -1; } int Flags = 0; dbg_assert(pChunk->m_ClientID >= 0, "errornous client id"); dbg_assert(pChunk->m_ClientID < MaxClients(), "errornous client id"); if(pChunk->m_Flags&NETSENDFLAG_VITAL) Flags = NET_CHUNKFLAG_VITAL; if(m_aSlots[pChunk->m_ClientID].m_Connection.QueueChunk(Flags, pChunk->m_DataSize, pChunk->m_pData) == 0) { if(pChunk->m_Flags&NETSENDFLAG_FLUSH) m_aSlots[pChunk->m_ClientID].m_Connection.Flush(); } else { Drop(pChunk->m_ClientID, "Error sending data"); } } return 0; } void CNetServer::SetMaxClientsPerIP(int Max) { // clamp if(Max < 1) Max = 1; else if(Max > NET_MAX_CLIENTS) Max = NET_MAX_CLIENTS; m_MaxClientsPerIP = Max; } ================================================ FILE: src/engine/shared/packer.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <base/system.h> #include "packer.h" #include "compression.h" #include "config.h" void CPacker::Reset() { m_Error = 0; m_pCurrent = m_aBuffer; m_pEnd = m_pCurrent + PACKER_BUFFER_SIZE; } void CPacker::AddInt(int i) { if(m_Error) return; // make sure that we have space enough if(m_pEnd - m_pCurrent < 6) { dbg_break(); m_Error = 1; } else m_pCurrent = CVariableInt::Pack(m_pCurrent, i); } void CPacker::AddString(const char *pStr, int Limit) { if(m_Error) return; // if(Limit > 0) { while(*pStr && Limit != 0) { *m_pCurrent++ = *pStr++; Limit--; if(m_pCurrent >= m_pEnd) { m_Error = 1; break; } } *m_pCurrent++ = 0; } else { while(*pStr) { *m_pCurrent++ = *pStr++; if(m_pCurrent >= m_pEnd) { m_Error = 1; break; } } *m_pCurrent++ = 0; } } void CPacker::AddRaw(const void *pData, int Size) { if(m_Error) return; if(m_pCurrent+Size >= m_pEnd) { m_Error = 1; return; } const unsigned char *pSrc = (const unsigned char *)pData; while(Size) { *m_pCurrent++ = *pSrc++; Size--; } } void CUnpacker::Reset(const void *pData, int Size) { m_Error = 0; m_pStart = (const unsigned char *)pData; m_pEnd = m_pStart + Size; m_pCurrent = m_pStart; } int CUnpacker::GetInt() { if(m_Error) return 0; if(m_pCurrent >= m_pEnd) { m_Error = 1; return 0; } int i; m_pCurrent = CVariableInt::Unpack(m_pCurrent, &i); if(m_pCurrent > m_pEnd) { m_Error = 1; return 0; } return i; } const char *CUnpacker::GetString(int SanitizeType) { if(m_Error || m_pCurrent >= m_pEnd) return ""; char *pPtr = (char *)m_pCurrent; while(*m_pCurrent) // skip the string { m_pCurrent++; if(m_pCurrent == m_pEnd) { m_Error = 1;; return ""; } } m_pCurrent++; // sanitize all strings if(SanitizeType&SANITIZE) str_sanitize(pPtr); else if(SanitizeType&SANITIZE_CC) str_sanitize_cc(pPtr); return SanitizeType&SKIP_START_WHITESPACES ? str_skip_whitespaces(pPtr) : pPtr; } const unsigned char *CUnpacker::GetRaw(int Size) { const unsigned char *pPtr = m_pCurrent; if(m_Error) return 0; // check for nasty sizes if(Size < 0 || m_pCurrent+Size > m_pEnd) { m_Error = 1; return 0; } // "unpack" the data m_pCurrent += Size; return pPtr; } ================================================ FILE: src/engine/shared/packer.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef ENGINE_SHARED_PACKER_H #define ENGINE_SHARED_PACKER_H class CPacker { enum { PACKER_BUFFER_SIZE=1024*2 }; unsigned char m_aBuffer[PACKER_BUFFER_SIZE]; unsigned char *m_pCurrent; unsigned char *m_pEnd; int m_Error; public: void Reset(); void AddInt(int i); void AddString(const char *pStr, int Limit); void AddRaw(const void *pData, int Size); int Size() const { return (int)(m_pCurrent-m_aBuffer); } const unsigned char *Data() const { return m_aBuffer; } bool Error() const { return m_Error; } }; class CUnpacker { const unsigned char *m_pStart; const unsigned char *m_pCurrent; const unsigned char *m_pEnd; int m_Error; public: enum { SANITIZE=1, SANITIZE_CC=2, SKIP_START_WHITESPACES=4 }; void Reset(const void *pData, int Size); int GetInt(); const char *GetString(int SanitizeType = SANITIZE); const unsigned char *GetRaw(int Size); bool Error() const { return m_Error; } }; #endif ================================================ FILE: src/engine/shared/protocol.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef ENGINE_SHARED_PROTOCOL_H #define ENGINE_SHARED_PROTOCOL_H #include <base/system.h> /* Connection diagram - How the initilization works. Client -> INFO -> Server Contains version info, name, and some other info. Client <- MAP <- Server Contains current map. Client -> READY -> Server The client has loaded the map and is ready to go, but the mod needs to send it's information aswell. modc_connected is called on the client and mods_connected is called on the server. The client should call client_entergame when the mod has done it's initilization. Client -> ENTERGAME -> Server Tells the server to start sending snapshots. client_entergame and server_client_enter is called. */ enum { NETMSG_NULL=0, // the first thing sent by the client // contains the version info for the client NETMSG_INFO=1, // sent by server NETMSG_MAP_CHANGE, // sent when client should switch map NETMSG_MAP_DATA, // map transfer, contains a chunk of the map file NETMSG_CON_READY, // connection is ready, client should send start info NETMSG_SNAP, // normal snapshot, multiple parts NETMSG_SNAPEMPTY, // empty snapshot NETMSG_SNAPSINGLE, // ? NETMSG_SNAPSMALL, // NETMSG_INPUTTIMING, // reports how off the input was NETMSG_RCON_AUTH_ON, // rcon authentication enabled NETMSG_RCON_AUTH_OFF, // rcon authentication disabled NETMSG_RCON_LINE, // line that should be printed to the remote console NETMSG_RCON_CMD_ADD, NETMSG_RCON_CMD_REM, NETMSG_AUTH_CHALLANGE, // NETMSG_AUTH_RESULT, // // sent by client NETMSG_READY, // NETMSG_ENTERGAME, NETMSG_INPUT, // contains the inputdata from the client NETMSG_RCON_CMD, // NETMSG_RCON_AUTH, // NETMSG_REQUEST_MAP_DATA,// NETMSG_AUTH_START, // NETMSG_AUTH_RESPONSE, // // sent by both NETMSG_PING, NETMSG_PING_REPLY, NETMSG_ERROR, }; // this should be revised enum { SERVER_TICK_SPEED=50, SERVERINFO_FLAG_PASSWORD = 0x1, SERVERINFO_LEVEL_MIN=0, SERVERINFO_LEVEL_MAX=2, MAX_CLIENTS=16, MAX_INPUT_SIZE=128, MAX_SNAPSHOT_PACKSIZE=900, MAX_NAME_LENGTH=16, MAX_CLAN_LENGTH=12, // message packing MSGFLAG_VITAL=1, MSGFLAG_FLUSH=2, MSGFLAG_NORECORD=4, MSGFLAG_RECORD=8, MSGFLAG_NOSEND=16 }; #endif ================================================ FILE: src/engine/shared/ringbuffer.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <base/system.h> #include "ringbuffer.h" CRingBufferBase::CItem *CRingBufferBase::NextBlock(CItem *pItem) { if(pItem->m_pNext) return pItem->m_pNext; return m_pFirst; } CRingBufferBase::CItem *CRingBufferBase::PrevBlock(CItem *pItem) { if(pItem->m_pPrev) return pItem->m_pPrev; return m_pLast; } CRingBufferBase::CItem *CRingBufferBase::MergeBack(CItem *pItem) { // make sure that this block and previous block is free if(!pItem->m_Free || !pItem->m_pPrev || !pItem->m_pPrev->m_Free) return pItem; // merge the blocks pItem->m_pPrev->m_Size += pItem->m_Size; pItem->m_pPrev->m_pNext = pItem->m_pNext; // fixup pointers if(pItem->m_pNext) pItem->m_pNext->m_pPrev = pItem->m_pPrev; else m_pLast = pItem->m_pPrev; if(pItem == m_pProduce) m_pProduce = pItem->m_pPrev; if(pItem == m_pConsume) m_pConsume = pItem->m_pPrev; // return the current block return pItem->m_pPrev; } void CRingBufferBase::Init(void *pMemory, int Size, int Flags) { mem_zero(pMemory, Size); m_Size = (Size)/sizeof(CItem)*sizeof(CItem); m_pFirst = (CItem *)pMemory; m_pFirst->m_Free = 1; m_pFirst->m_Size = m_Size; m_pLast = m_pFirst; m_pProduce = m_pFirst; m_pConsume = m_pFirst; m_Flags = Flags; } void *CRingBufferBase::Allocate(int Size) { int WantedSize = (Size+sizeof(CItem)+sizeof(CItem)-1)/sizeof(CItem)*sizeof(CItem); CItem *pBlock = 0; // check if we even can fit this block if(WantedSize > m_Size) return 0; while(1) { // check for space if(m_pProduce->m_Free) { if(m_pProduce->m_Size >= WantedSize) pBlock = m_pProduce; else { // wrap around to try to find a block if(m_pFirst->m_Free && m_pFirst->m_Size >= WantedSize) pBlock = m_pFirst; } } if(pBlock) break; else { // we have no block, check our policy and see what todo if(m_Flags&FLAG_RECYCLE) { if(!PopFirst()) return 0; } else return 0; } } // okey, we have our block // split the block if needed if(pBlock->m_Size > WantedSize+(int)sizeof(CItem)) { CItem *pNewItem = (CItem *)((char *)pBlock + WantedSize); pNewItem->m_pPrev = pBlock; pNewItem->m_pNext = pBlock->m_pNext; if(pNewItem->m_pNext) pNewItem->m_pNext->m_pPrev = pNewItem; pBlock->m_pNext = pNewItem; pNewItem->m_Free = 1; pNewItem->m_Size = pBlock->m_Size - WantedSize; pBlock->m_Size = WantedSize; if(!pNewItem->m_pNext) m_pLast = pNewItem; } // set next block m_pProduce = NextBlock(pBlock); // set as used and return the item pointer pBlock->m_Free = 0; return (void *)(pBlock+1); } int CRingBufferBase::PopFirst() { if(m_pConsume->m_Free) return 0; // set the free flag m_pConsume->m_Free = 1; // previous block is also free, merge them m_pConsume = MergeBack(m_pConsume); // advance the consume pointer m_pConsume = NextBlock(m_pConsume); while(m_pConsume->m_Free && m_pConsume != m_pProduce) { m_pConsume = MergeBack(m_pConsume); m_pConsume = NextBlock(m_pConsume); } // in the case that we have catched up with the produce pointer // we might stand on a free block so merge em MergeBack(m_pConsume); return 1; } void *CRingBufferBase::Prev(void *pCurrent) { CItem *pItem = ((CItem *)pCurrent) - 1; while(1) { pItem = PrevBlock(pItem); if(pItem == m_pProduce) return 0; if(!pItem->m_Free) return pItem+1; } } void *CRingBufferBase::Next(void *pCurrent) { CItem *pItem = ((CItem *)pCurrent) - 1; while(1) { pItem = NextBlock(pItem); if(pItem == m_pProduce) return 0; if(!pItem->m_Free) return pItem+1; } } void *CRingBufferBase::First() { if(m_pConsume->m_Free) return 0; return (void *)(m_pConsume+1); } void *CRingBufferBase::Last() { return Prev(m_pProduce+1); } ================================================ FILE: src/engine/shared/ringbuffer.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef ENGINE_SHARED_RINGBUFFER_H #define ENGINE_SHARED_RINGBUFFER_H typedef struct RINGBUFFER RINGBUFFER; class CRingBufferBase { class CItem { public: CItem *m_pPrev; CItem *m_pNext; int m_Free; int m_Size; }; CItem *m_pProduce; CItem *m_pConsume; CItem *m_pFirst; CItem *m_pLast; void *m_pMemory; int m_Size; int m_Flags; CItem *NextBlock(CItem *pItem); CItem *PrevBlock(CItem *pItem); CItem *MergeBack(CItem *pItem); protected: void *Allocate(int Size); void *Prev(void *pCurrent); void *Next(void *pCurrent); void *First(); void *Last(); void Init(void *pMemory, int Size, int Flags); int PopFirst(); public: enum { // Will start to destroy items to try to fit the next one FLAG_RECYCLE=1 }; }; template<typename T, int TSIZE, int TFLAGS=0> class TStaticRingBuffer : public CRingBufferBase { unsigned char m_aBuffer[TSIZE]; public: TStaticRingBuffer() { Init(); } void Init() { CRingBufferBase::Init(m_aBuffer, TSIZE, TFLAGS); } T *Allocate(int Size) { return (T*)CRingBufferBase::Allocate(Size); } int PopFirst() { return CRingBufferBase::PopFirst(); } T *Prev(T *pCurrent) { return (T*)CRingBufferBase::Prev(pCurrent); } T *Next(T *pCurrent) { return (T*)CRingBufferBase::Next(pCurrent); } T *First() { return (T*)CRingBufferBase::First(); } T *Last() { return (T*)CRingBufferBase::Last(); } }; #endif ================================================ FILE: src/engine/shared/snapshot.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include "snapshot.h" #include "compression.h" // CSnapshot CSnapshotItem *CSnapshot::GetItem(int Index) { return (CSnapshotItem *)(DataStart() + Offsets()[Index]); } int CSnapshot::GetItemSize(int Index) { if(Index == m_NumItems-1) return (m_DataSize - Offsets()[Index]) - sizeof(CSnapshotItem); return (Offsets()[Index+1] - Offsets()[Index]) - sizeof(CSnapshotItem); } int CSnapshot::GetItemIndex(int Key) { // TODO: OPT: this should not be a linear search. very bad for(int i = 0; i < m_NumItems; i++) { if(GetItem(i)->Key() == Key) return i; } return -1; } int CSnapshot::Crc() { int Crc = 0; for(int i = 0; i < m_NumItems; i++) { CSnapshotItem *pItem = GetItem(i); int Size = GetItemSize(i); for(int b = 0; b < Size/4; b++) Crc += pItem->Data()[b]; } return Crc; } void CSnapshot::DebugDump() { dbg_msg("snapshot", "data_size=%d num_items=%d", m_DataSize, m_NumItems); for(int i = 0; i < m_NumItems; i++) { CSnapshotItem *pItem = GetItem(i); int Size = GetItemSize(i); dbg_msg("snapshot", "\ttype=%d id=%d", pItem->Type(), pItem->ID()); for(int b = 0; b < Size/4; b++) dbg_msg("snapshot", "\t\t%3d %12d\t%08x", b, pItem->Data()[b], pItem->Data()[b]); } } // CSnapshotDelta struct CItemList { int m_Num; int m_aKeys[64]; int m_aIndex[64]; }; enum { HASHLIST_SIZE = 256, }; static void GenerateHash(CItemList *pHashlist, CSnapshot *pSnapshot) { for(int i = 0; i < HASHLIST_SIZE; i++) pHashlist[i].m_Num = 0; for(int i = 0; i < pSnapshot->NumItems(); i++) { int Key = pSnapshot->GetItem(i)->Key(); int HashID = ((Key>>12)&0xf0) | (Key&0xf); if(pHashlist[HashID].m_Num != 64) { pHashlist[HashID].m_aIndex[pHashlist[HashID].m_Num] = i; pHashlist[HashID].m_aKeys[pHashlist[HashID].m_Num] = Key; pHashlist[HashID].m_Num++; } } } static int GetItemIndexHashed(int Key, const CItemList *pHashlist) { int HashID = ((Key>>12)&0xf0) | (Key&0xf); for(int i = 0; i < pHashlist[HashID].m_Num; i++) { if(pHashlist[HashID].m_aKeys[i] == Key) return pHashlist[HashID].m_aIndex[i]; } return -1; } static int DiffItem(int *pPast, int *pCurrent, int *pOut, int Size) { int Needed = 0; while(Size) { *pOut = *pCurrent-*pPast; Needed |= *pOut; pOut++; pPast++; pCurrent++; Size--; } return Needed; } void CSnapshotDelta::UndiffItem(int *pPast, int *pDiff, int *pOut, int Size) { while(Size) { *pOut = *pPast+*pDiff; if(*pDiff == 0) m_aSnapshotDataRate[m_SnapshotCurrent] += 1; else { unsigned char aBuf[16]; unsigned char *pEnd = CVariableInt::Pack(aBuf, *pDiff); m_aSnapshotDataRate[m_SnapshotCurrent] += (int)(pEnd - (unsigned char*)aBuf) * 8; } pOut++; pPast++; pDiff++; Size--; } } CSnapshotDelta::CSnapshotDelta() { mem_zero(m_aItemSizes, sizeof(m_aItemSizes)); mem_zero(m_aSnapshotDataRate, sizeof(m_aSnapshotDataRate)); mem_zero(m_aSnapshotDataUpdates, sizeof(m_aSnapshotDataUpdates)); m_SnapshotCurrent = 0; mem_zero(&m_Empty, sizeof(m_Empty)); } void CSnapshotDelta::SetStaticsize(int ItemType, int Size) { m_aItemSizes[ItemType] = Size; } CSnapshotDelta::CData *CSnapshotDelta::EmptyDelta() { return &m_Empty; } // TODO: OPT: this should be made much faster int CSnapshotDelta::CreateDelta(CSnapshot *pFrom, CSnapshot *pTo, void *pDstData) { CData *pDelta = (CData *)pDstData; int *pData = (int *)pDelta->m_pData; int i, ItemSize, PastIndex; CSnapshotItem *pFromItem; CSnapshotItem *pCurItem; CSnapshotItem *pPastItem; int Count = 0; int SizeCount = 0; pDelta->m_NumDeletedItems = 0; pDelta->m_NumUpdateItems = 0; pDelta->m_NumTempItems = 0; CItemList Hashlist[HASHLIST_SIZE]; GenerateHash(Hashlist, pTo); // pack deleted stuff for(i = 0; i < pFrom->NumItems(); i++) { pFromItem = pFrom->GetItem(i); if(GetItemIndexHashed(pFromItem->Key(), Hashlist) == -1) { // deleted pDelta->m_NumDeletedItems++; *pData = pFromItem->Key(); pData++; } } GenerateHash(Hashlist, pFrom); int aPastIndecies[1024]; // fetch previous indices // we do this as a separate pass because it helps the cache const int NumItems = pTo->NumItems(); for(i = 0; i < NumItems; i++) { pCurItem = pTo->GetItem(i); // O(1) .. O(n) aPastIndecies[i] = GetItemIndexHashed(pCurItem->Key(), Hashlist); // O(n) .. O(n^n) } for(i = 0; i < NumItems; i++) { // do delta ItemSize = pTo->GetItemSize(i); // O(1) .. O(n) pCurItem = pTo->GetItem(i); // O(1) .. O(n) PastIndex = aPastIndecies[i]; if(PastIndex != -1) { int *pItemDataDst = pData+3; pPastItem = pFrom->GetItem(PastIndex); if(m_aItemSizes[pCurItem->Type()]) pItemDataDst = pData+2; if(DiffItem((int*)pPastItem->Data(), (int*)pCurItem->Data(), pItemDataDst, ItemSize/4)) { *pData++ = pCurItem->Type(); *pData++ = pCurItem->ID(); if(!m_aItemSizes[pCurItem->Type()]) *pData++ = ItemSize/4; pData += ItemSize/4; pDelta->m_NumUpdateItems++; } } else { *pData++ = pCurItem->Type(); *pData++ = pCurItem->ID(); if(!m_aItemSizes[pCurItem->Type()]) *pData++ = ItemSize/4; mem_copy(pData, pCurItem->Data(), ItemSize); SizeCount += ItemSize; pData += ItemSize/4; pDelta->m_NumUpdateItems++; Count++; } } if(0) { dbg_msg("snapshot", "%d %d %d", pDelta->m_NumDeletedItems, pDelta->m_NumUpdateItems, pDelta->m_NumTempItems); } /* // TODO: pack temp stuff // finish //mem_copy(pDelta->offsets, deleted, pDelta->num_deleted_items*sizeof(int)); //mem_copy(&(pDelta->offsets[pDelta->num_deleted_items]), update, pDelta->num_update_items*sizeof(int)); //mem_copy(&(pDelta->offsets[pDelta->num_deleted_items+pDelta->num_update_items]), temp, pDelta->num_temp_items*sizeof(int)); //mem_copy(pDelta->data_start(), data, data_size); //pDelta->data_size = data_size; * */ if(!pDelta->m_NumDeletedItems && !pDelta->m_NumUpdateItems && !pDelta->m_NumTempItems) return 0; return (int)((char*)pData-(char*)pDstData); } static int RangeCheck(void *pEnd, void *pPtr, int Size) { if((const char *)pPtr + Size > (const char *)pEnd) return -1; return 0; } int CSnapshotDelta::UnpackDelta(CSnapshot *pFrom, CSnapshot *pTo, void *pSrcData, int DataSize) { CSnapshotBuilder Builder; CData *pDelta = (CData *)pSrcData; int *pData = (int *)pDelta->m_pData; int *pEnd = (int *)(((char *)pSrcData + DataSize)); CSnapshotItem *pFromItem; int Keep, ItemSize; int *pDeleted; int ID, Type, Key; int FromIndex; int *pNewData; Builder.Init(); // unpack deleted stuff pDeleted = pData; pData += pDelta->m_NumDeletedItems; if(pData > pEnd) return -1; // copy all non deleted stuff for(int i = 0; i < pFrom->NumItems(); i++) { // dbg_assert(0, "fail!"); pFromItem = pFrom->GetItem(i); ItemSize = pFrom->GetItemSize(i); Keep = 1; for(int d = 0; d < pDelta->m_NumDeletedItems; d++) { if(pDeleted[d] == pFromItem->Key()) { Keep = 0; break; } } if(Keep) { // keep it mem_copy( Builder.NewItem(pFromItem->Type(), pFromItem->ID(), ItemSize), pFromItem->Data(), ItemSize); } } // unpack updated stuff for(int i = 0; i < pDelta->m_NumUpdateItems; i++) { if(pData+2 > pEnd) return -1; Type = *pData++; ID = *pData++; if(m_aItemSizes[Type]) ItemSize = m_aItemSizes[Type]; else { if(pData+1 > pEnd) return -2; ItemSize = (*pData++) * 4; } m_SnapshotCurrent = Type; if(RangeCheck(pEnd, pData, ItemSize) || ItemSize < 0) return -3; Key = (Type<<16)|ID; // create the item if needed pNewData = Builder.GetItemData(Key); if(!pNewData) pNewData = (int *)Builder.NewItem(Key>>16, Key&0xffff, ItemSize); //if(range_check(pEnd, pNewData, ItemSize)) return -4; FromIndex = pFrom->GetItemIndex(Key); if(FromIndex != -1) { // we got an update so we need pTo apply the diff UndiffItem((int *)pFrom->GetItem(FromIndex)->Data(), pData, pNewData, ItemSize/4); m_aSnapshotDataUpdates[m_SnapshotCurrent]++; } else // no previous, just copy the pData { mem_copy(pNewData, pData, ItemSize); m_aSnapshotDataRate[m_SnapshotCurrent] += ItemSize*8; m_aSnapshotDataUpdates[m_SnapshotCurrent]++; } pData += ItemSize/4; } // finish up return Builder.Finish(pTo); } // CSnapshotStorage void CSnapshotStorage::Init() { m_pFirst = 0; m_pLast = 0; } void CSnapshotStorage::PurgeAll() { CHolder *pHolder = m_pFirst; CHolder *pNext; while(pHolder) { pNext = pHolder->m_pNext; mem_free(pHolder); pHolder = pNext; } // no more snapshots in storage m_pFirst = 0; m_pLast = 0; } void CSnapshotStorage::PurgeUntil(int Tick) { CHolder *pHolder = m_pFirst; CHolder *pNext; while(pHolder) { pNext = pHolder->m_pNext; if(pHolder->m_Tick >= Tick) return; // no more to remove mem_free(pHolder); // did we come to the end of the list? if (!pNext) break; m_pFirst = pNext; pNext->m_pPrev = 0x0; pHolder = pNext; } // no more snapshots in storage m_pFirst = 0; m_pLast = 0; } void CSnapshotStorage::Add(int Tick, int64 Tagtime, int DataSize, void *pData, int CreateAlt) { // allocate memory for holder + snapshot_data int TotalSize = sizeof(CHolder)+DataSize; if(CreateAlt) TotalSize += DataSize; CHolder *pHolder = (CHolder *)mem_alloc(TotalSize, 1); // set data pHolder->m_Tick = Tick; pHolder->m_Tagtime = Tagtime; pHolder->m_SnapSize = DataSize; pHolder->m_pSnap = (CSnapshot*)(pHolder+1); mem_copy(pHolder->m_pSnap, pData, DataSize); if(CreateAlt) // create alternative if wanted { pHolder->m_pAltSnap = (CSnapshot*)(((char *)pHolder->m_pSnap) + DataSize); mem_copy(pHolder->m_pAltSnap, pData, DataSize); } else pHolder->m_pAltSnap = 0; // link pHolder->m_pNext = 0; pHolder->m_pPrev = m_pLast; if(m_pLast) m_pLast->m_pNext = pHolder; else m_pFirst = pHolder; m_pLast = pHolder; } int CSnapshotStorage::Get(int Tick, int64 *pTagtime, CSnapshot **ppData, CSnapshot **ppAltData) { CHolder *pHolder = m_pFirst; while(pHolder) { if(pHolder->m_Tick == Tick) { if(pTagtime) *pTagtime = pHolder->m_Tagtime; if(ppData) *ppData = pHolder->m_pSnap; if(ppAltData) *ppAltData = pHolder->m_pAltSnap; return pHolder->m_SnapSize; } pHolder = pHolder->m_pNext; } return -1; } // CSnapshotBuilder void CSnapshotBuilder::Init() { m_DataSize = 0; m_NumItems = 0; } void CSnapshotBuilder::Init(const CSnapshot *pSnapshot) { if(pSnapshot->m_DataSize > CSnapshot::MAX_SIZE || pSnapshot->m_NumItems > MAX_ITEMS) { dbg_assert(m_DataSize < CSnapshot::MAX_SIZE, "too much data"); dbg_assert(m_NumItems < MAX_ITEMS, "too many items"); dbg_msg("snapshot", "invalid snapshot"); // remove me m_DataSize = 0; m_NumItems = 0; return; } m_DataSize = pSnapshot->m_DataSize; m_NumItems = pSnapshot->m_NumItems; mem_copy(m_aOffsets, pSnapshot->Offsets(), sizeof(int)*m_NumItems); mem_copy(m_aData, pSnapshot->DataStart(), m_DataSize); } CSnapshotItem *CSnapshotBuilder::GetItem(int Index) { return (CSnapshotItem *)&(m_aData[m_aOffsets[Index]]); } int *CSnapshotBuilder::GetItemData(int Key) { int i; for(i = 0; i < m_NumItems; i++) { if(GetItem(i)->Key() == Key) return (int *)GetItem(i)->Data(); } return 0; } int CSnapshotBuilder::Finish(void *SpnapData) { // flattern and make the snapshot CSnapshot *pSnap = (CSnapshot *)SpnapData; int OffsetSize = sizeof(int)*m_NumItems; pSnap->m_DataSize = m_DataSize; pSnap->m_NumItems = m_NumItems; mem_copy(pSnap->Offsets(), m_aOffsets, OffsetSize); mem_copy(pSnap->DataStart(), m_aData, m_DataSize); return sizeof(CSnapshot) + OffsetSize + m_DataSize; } void *CSnapshotBuilder::NewItem(int Type, int ID, int Size) { if(m_DataSize + sizeof(CSnapshotItem) + Size >= CSnapshot::MAX_SIZE || m_NumItems+1 >= MAX_ITEMS) { dbg_assert(m_DataSize < CSnapshot::MAX_SIZE, "too much data"); dbg_assert(m_NumItems < MAX_ITEMS, "too many items"); return 0; } CSnapshotItem *pObj = (CSnapshotItem *)(m_aData + m_DataSize); mem_zero(pObj, sizeof(CSnapshotItem) + Size); pObj->m_TypeAndID = (Type<<16)|ID; m_aOffsets[m_NumItems] = m_DataSize; m_DataSize += sizeof(CSnapshotItem) + Size; m_NumItems++; return pObj->Data(); } ================================================ FILE: src/engine/shared/snapshot.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef ENGINE_SHARED_SNAPSHOT_H #define ENGINE_SHARED_SNAPSHOT_H #include <base/system.h> // CSnapshot class CSnapshotItem { public: int m_TypeAndID; int *Data() { return (int *)(this+1); } int Type() { return m_TypeAndID>>16; } int ID() { return m_TypeAndID&0xffff; } int Key() { return m_TypeAndID; } }; class CSnapshot { friend class CSnapshotBuilder; int m_DataSize; int m_NumItems; int *Offsets() const { return (int *)(this+1); } char *DataStart() const { return (char*)(Offsets()+m_NumItems); } public: enum { MAX_SIZE=64*1024 }; void Clear() { m_DataSize = 0; m_NumItems = 0; } int NumItems() const { return m_NumItems; } CSnapshotItem *GetItem(int Index); int GetItemSize(int Index); int GetItemIndex(int Key); int Crc(); void DebugDump(); }; // CSnapshotDelta class CSnapshotDelta { public: class CData { public: int m_NumDeletedItems; int m_NumUpdateItems; int m_NumTempItems; // needed? int m_pData[1]; }; private: // TODO: strange arbitrary number short m_aItemSizes[64]; int m_aSnapshotDataRate[0xffff]; int m_aSnapshotDataUpdates[0xffff]; int m_SnapshotCurrent; CData m_Empty; void UndiffItem(int *pPast, int *pDiff, int *pOut, int Size); public: CSnapshotDelta(); int GetDataRate(int Index) { return m_aSnapshotDataRate[Index]; } int GetDataUpdates(int Index) { return m_aSnapshotDataUpdates[Index]; } void SetStaticsize(int ItemType, int Size); CData *EmptyDelta(); int CreateDelta(class CSnapshot *pFrom, class CSnapshot *pTo, void *pData); int UnpackDelta(class CSnapshot *pFrom, class CSnapshot *pTo, void *pData, int DataSize); }; // CSnapshotStorage class CSnapshotStorage { public: class CHolder { public: CHolder *m_pPrev; CHolder *m_pNext; int64 m_Tagtime; int m_Tick; int m_SnapSize; CSnapshot *m_pSnap; CSnapshot *m_pAltSnap; }; CHolder *m_pFirst; CHolder *m_pLast; void Init(); void PurgeAll(); void PurgeUntil(int Tick); void Add(int Tick, int64 Tagtime, int DataSize, void *pData, int CreateAlt); int Get(int Tick, int64 *Tagtime, CSnapshot **pData, CSnapshot **ppAltData); }; class CSnapshotBuilder { enum { MAX_ITEMS = 1024 }; char m_aData[CSnapshot::MAX_SIZE]; int m_DataSize; int m_aOffsets[MAX_ITEMS]; int m_NumItems; public: void Init(); void Init(const CSnapshot *pSnapshot); void *NewItem(int Type, int ID, int Size); CSnapshotItem *GetItem(int Index); int *GetItemData(int Key); int Finish(void *Snapdata); }; #endif // ENGINE_SNAPSHOT_H ================================================ FILE: src/engine/shared/storage.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <base/system.h> #include <engine/storage.h> #include "linereader.h" // compiled-in data-dir path #define DATA_DIR "data" class CStorage : public IStorage { public: enum { MAX_PATHS = 16, MAX_PATH_LENGTH = 512 }; char m_aaStoragePaths[MAX_PATHS][MAX_PATH_LENGTH]; int m_NumPaths; char m_aDatadir[MAX_PATH_LENGTH]; char m_aUserdir[MAX_PATH_LENGTH]; char m_aCurrentdir[MAX_PATH_LENGTH]; CStorage() { mem_zero(m_aaStoragePaths, sizeof(m_aaStoragePaths)); m_NumPaths = 0; m_aDatadir[0] = 0; m_aUserdir[0] = 0; } int Init(const char *pApplicationName, int StorageType, int NumArgs, const char **ppArguments) { // get userdir fs_storage_path(pApplicationName, m_aUserdir, sizeof(m_aUserdir)); // get datadir FindDatadir(ppArguments[0]); // get currentdir if(!fs_getcwd(m_aCurrentdir, sizeof(m_aCurrentdir))) m_aCurrentdir[0] = 0; // load paths from storage.cfg LoadPaths(ppArguments[0]); if(!m_NumPaths) { dbg_msg("storage", "using standard paths"); AddDefaultPaths(); } // add save directories if(StorageType != STORAGETYPE_BASIC) { if(m_NumPaths && (!m_aaStoragePaths[TYPE_SAVE][0] || !fs_makedir(m_aaStoragePaths[TYPE_SAVE]))) { char aPath[MAX_PATH_LENGTH]; if(StorageType == STORAGETYPE_CLIENT) { fs_makedir(GetPath(TYPE_SAVE, "screenshots", aPath, sizeof(aPath))); fs_makedir(GetPath(TYPE_SAVE, "screenshots/auto", aPath, sizeof(aPath))); fs_makedir(GetPath(TYPE_SAVE, "maps", aPath, sizeof(aPath))); fs_makedir(GetPath(TYPE_SAVE, "downloadedmaps", aPath, sizeof(aPath))); fs_makedir(GetPath(TYPE_SAVE, "skins", aPath, sizeof(aPath))); } fs_makedir(GetPath(TYPE_SAVE, "dumps", aPath, sizeof(aPath))); fs_makedir(GetPath(TYPE_SAVE, "demos", aPath, sizeof(aPath))); fs_makedir(GetPath(TYPE_SAVE, "demos/auto", aPath, sizeof(aPath))); } else { dbg_msg("storage", "unable to create save directory"); return 1; } } return m_NumPaths ? 0 : 1; } void LoadPaths(const char *pArgv0) { // check current directory IOHANDLE File = io_open("storage.cfg", IOFLAG_READ); if(!File) { // check usable path in argv[0] unsigned int Pos = ~0U; for(unsigned i = 0; pArgv0[i]; i++) if(pArgv0[i] == '/' || pArgv0[i] == '\\') Pos = i; if(Pos < MAX_PATH_LENGTH) { char aBuffer[MAX_PATH_LENGTH]; str_copy(aBuffer, pArgv0, Pos+1); str_append(aBuffer, "/storage.cfg", sizeof(aBuffer)); File = io_open(aBuffer, IOFLAG_READ); } if(Pos >= MAX_PATH_LENGTH || !File) { dbg_msg("storage", "couldn't open storage.cfg"); return; } } char *pLine; CLineReader LineReader; LineReader.Init(File); while((pLine = LineReader.Get())) { if(str_length(pLine) > 9 && !str_comp_num(pLine, "add_path ", 9)) AddPath(pLine+9); } io_close(File); if(!m_NumPaths) dbg_msg("storage", "no paths found in storage.cfg"); } void AddDefaultPaths() { AddPath("$USERDIR"); AddPath("$DATADIR"); AddPath("$CURRENTDIR"); } void AddPath(const char *pPath) { if(m_NumPaths >= MAX_PATHS || !pPath[0]) return; if(!str_comp(pPath, "$USERDIR")) { if(m_aUserdir[0]) { str_copy(m_aaStoragePaths[m_NumPaths++], m_aUserdir, MAX_PATH_LENGTH); dbg_msg("storage", "added path '$USERDIR' ('%s')", m_aUserdir); } } else if(!str_comp(pPath, "$DATADIR")) { if(m_aDatadir[0]) { str_copy(m_aaStoragePaths[m_NumPaths++], m_aDatadir, MAX_PATH_LENGTH); dbg_msg("storage", "added path '$DATADIR' ('%s')", m_aDatadir); } } else if(!str_comp(pPath, "$CURRENTDIR")) { m_aaStoragePaths[m_NumPaths++][0] = 0; dbg_msg("storage", "added path '$CURRENTDIR' ('%s')", m_aCurrentdir); } else { if(fs_is_dir(pPath)) { str_copy(m_aaStoragePaths[m_NumPaths++], pPath, MAX_PATH_LENGTH); dbg_msg("storage", "added path '%s'", pPath); } } } void FindDatadir(const char *pArgv0) { // 1) use data-dir in PWD if present if(fs_is_dir("data/mapres")) { str_copy(m_aDatadir, "data", sizeof(m_aDatadir)); return; } // 2) use compiled-in data-dir if present if(fs_is_dir(DATA_DIR "/mapres")) { str_copy(m_aDatadir, DATA_DIR, sizeof(m_aDatadir)); return; } // 3) check for usable path in argv[0] { unsigned int Pos = ~0U; for(unsigned i = 0; pArgv0[i]; i++) if(pArgv0[i] == '/' || pArgv0[i] == '\\') Pos = i; if(Pos < MAX_PATH_LENGTH) { char aBaseDir[MAX_PATH_LENGTH]; str_copy(aBaseDir, pArgv0, Pos+1); str_format(m_aDatadir, sizeof(m_aDatadir), "%s/data", aBaseDir); str_append(aBaseDir, "/data/mapres", sizeof(aBaseDir)); if(fs_is_dir(aBaseDir)) return; else m_aDatadir[0] = 0; } } #if defined(CONF_FAMILY_UNIX) // 4) check for all default locations { const char *aDirs[] = { "/usr/share/teeworlds/data", "/usr/share/games/teeworlds/data", "/usr/local/share/teeworlds/data", "/usr/local/share/games/teeworlds/data", "/opt/teeworlds/data" }; const int DirsCount = sizeof(aDirs) / sizeof(aDirs[0]); int i; for (i = 0; i < DirsCount; i++) { char aBuf[128]; str_format(aBuf, sizeof(aBuf), "%s/mapres", aDirs[i]); if(fs_is_dir(aBuf)) { str_copy(m_aDatadir, aDirs[i], sizeof(m_aDatadir)); return; } } } #endif // no data-dir found dbg_msg("storage", "warning no data directory found"); } virtual void ListDirectory(int Type, const char *pPath, FS_LISTDIR_CALLBACK pfnCallback, void *pUser) { char aBuffer[MAX_PATH_LENGTH]; if(Type == TYPE_ALL) { // list all available directories for(int i = 0; i < m_NumPaths; ++i) fs_listdir(GetPath(i, pPath, aBuffer, sizeof(aBuffer)), pfnCallback, i, pUser); } else if(Type >= 0 && Type < m_NumPaths) { // list wanted directory fs_listdir(GetPath(Type, pPath, aBuffer, sizeof(aBuffer)), pfnCallback, Type, pUser); } } const char *GetPath(int Type, const char *pDir, char *pBuffer, unsigned BufferSize) { str_format(pBuffer, BufferSize, "%s%s%s", m_aaStoragePaths[Type], !m_aaStoragePaths[Type][0] ? "" : "/", pDir); return pBuffer; } virtual IOHANDLE OpenFile(const char *pFilename, int Flags, int Type, char *pBuffer = 0, int BufferSize = 0) { char aBuffer[MAX_PATH_LENGTH]; if(!pBuffer) { pBuffer = aBuffer; BufferSize = sizeof(aBuffer); } if(Flags&IOFLAG_WRITE) { return io_open(GetPath(TYPE_SAVE, pFilename, pBuffer, BufferSize), Flags); } else { IOHANDLE Handle = 0; if(Type == TYPE_ALL) { // check all available directories for(int i = 0; i < m_NumPaths; ++i) { Handle = io_open(GetPath(i, pFilename, pBuffer, BufferSize), Flags); if(Handle) return Handle; } } else if(Type >= 0 && Type < m_NumPaths) { // check wanted directory Handle = io_open(GetPath(Type, pFilename, pBuffer, BufferSize), Flags); if(Handle) return Handle; } } pBuffer[0] = 0; return 0; } struct CFindCBData { CStorage *pStorage; const char *pFilename; const char *pPath; char *pBuffer; int BufferSize; }; static int FindFileCallback(const char *pName, int IsDir, int Type, void *pUser) { CFindCBData Data = *static_cast<CFindCBData *>(pUser); if(IsDir) { if(pName[0] == '.') return 0; // search within the folder char aBuf[MAX_PATH_LENGTH]; char aPath[MAX_PATH_LENGTH]; str_format(aPath, sizeof(aPath), "%s/%s", Data.pPath, pName); Data.pPath = aPath; fs_listdir(Data.pStorage->GetPath(Type, aPath, aBuf, sizeof(aBuf)), FindFileCallback, Type, &Data); if(Data.pBuffer[0]) return 1; } else if(!str_comp(pName, Data.pFilename)) { // found the file = end str_format(Data.pBuffer, Data.BufferSize, "%s/%s", Data.pPath, Data.pFilename); return 1; } return 0; } virtual bool FindFile(const char *pFilename, const char *pPath, int Type, char *pBuffer, int BufferSize) { if(BufferSize < 1) return false; pBuffer[0] = 0; char aBuf[MAX_PATH_LENGTH]; CFindCBData Data; Data.pStorage = this; Data.pFilename = pFilename; Data.pPath = pPath; Data.pBuffer = pBuffer; Data.BufferSize = BufferSize; if(Type == TYPE_ALL) { // search within all available directories for(int i = 0; i < m_NumPaths; ++i) { fs_listdir(GetPath(i, pPath, aBuf, sizeof(aBuf)), FindFileCallback, i, &Data); if(pBuffer[0]) return true; } } else if(Type >= 0 && Type < m_NumPaths) { // search within wanted directory fs_listdir(GetPath(Type, pPath, aBuf, sizeof(aBuf)), FindFileCallback, Type, &Data); } return pBuffer[0] != 0; } virtual bool RemoveFile(const char *pFilename, int Type) { if(Type < 0 || Type >= m_NumPaths) return false; char aBuffer[MAX_PATH_LENGTH]; return !fs_remove(GetPath(Type, pFilename, aBuffer, sizeof(aBuffer))); } virtual bool RenameFile(const char* pOldFilename, const char* pNewFilename, int Type) { if(Type < 0 || Type >= m_NumPaths) return false; char aOldBuffer[MAX_PATH_LENGTH]; char aNewBuffer[MAX_PATH_LENGTH]; return !fs_rename(GetPath(Type, pOldFilename, aOldBuffer, sizeof(aOldBuffer)), GetPath(Type, pNewFilename, aNewBuffer, sizeof (aNewBuffer))); } virtual bool CreateFolder(const char *pFoldername, int Type) { if(Type < 0 || Type >= m_NumPaths) return false; char aBuffer[MAX_PATH_LENGTH]; return !fs_makedir(GetPath(Type, pFoldername, aBuffer, sizeof(aBuffer))); } virtual void GetCompletePath(int Type, const char *pDir, char *pBuffer, unsigned BufferSize) { if(Type < 0 || Type >= m_NumPaths) { if(BufferSize > 0) pBuffer[0] = 0; return; } GetPath(Type, pDir, pBuffer, BufferSize); } static IStorage *Create(const char *pApplicationName, int StorageType, int NumArgs, const char **ppArguments) { CStorage *p = new CStorage(); if(p && p->Init(pApplicationName, StorageType, NumArgs, ppArguments)) { dbg_msg("storage", "initialisation failed"); delete p; p = 0; } return p; } }; IStorage *CreateStorage(const char *pApplicationName, int StorageType, int NumArgs, const char **ppArguments) { return CStorage::Create(pApplicationName, StorageType, NumArgs, ppArguments); } ================================================ FILE: src/engine/sound.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef ENGINE_SOUND_H #define ENGINE_SOUND_H #include "kernel.h" class ISound : public IInterface { MACRO_INTERFACE("sound", 0) public: enum { FLAG_LOOP=1, FLAG_POS=2, FLAG_ALL=3 }; class CSampleHandle { friend class ISound; int m_Id; public: CSampleHandle() : m_Id(-1) {} bool IsValid() const { return Id() >= 0; } int Id() const { return m_Id; } }; virtual bool IsSoundEnabled() = 0; virtual CSampleHandle LoadWV(const char *pFilename) = 0; virtual void SetChannel(int ChannelID, float Volume, float Panning) = 0; virtual void SetListenerPos(float x, float y) = 0; virtual int PlayAt(int ChannelID, CSampleHandle Sound, int Flags, float x, float y) = 0; virtual int Play(int ChannelID, CSampleHandle Sound, int Flags) = 0; virtual void Stop(CSampleHandle Sound) = 0; virtual void StopAll() = 0; protected: inline CSampleHandle CreateSampleHandle(int Index) { CSampleHandle Tex; Tex.m_Id = Index; return Tex; } }; class IEngineSound : public ISound { MACRO_INTERFACE("enginesound", 0) public: virtual int Init() = 0; virtual int Update() = 0; virtual int Shutdown() = 0; }; extern IEngineSound *CreateEngineSound(); #endif ================================================ FILE: src/engine/storage.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef ENGINE_STORAGE_H #define ENGINE_STORAGE_H #include "kernel.h" class IStorage : public IInterface { MACRO_INTERFACE("storage", 0) public: enum { TYPE_SAVE = 0, TYPE_ALL = -1, STORAGETYPE_BASIC = 0, STORAGETYPE_SERVER, STORAGETYPE_CLIENT, }; virtual void ListDirectory(int Type, const char *pPath, FS_LISTDIR_CALLBACK pfnCallback, void *pUser) = 0; virtual IOHANDLE OpenFile(const char *pFilename, int Flags, int Type, char *pBuffer = 0, int BufferSize = 0) = 0; virtual bool FindFile(const char *pFilename, const char *pPath, int Type, char *pBuffer, int BufferSize) = 0; virtual bool RemoveFile(const char *pFilename, int Type) = 0; virtual bool RenameFile(const char* pOldFilename, const char* pNewFilename, int Type) = 0; virtual bool CreateFolder(const char *pFoldername, int Type) = 0; virtual void GetCompletePath(int Type, const char *pDir, char *pBuffer, unsigned BufferSize) = 0; }; extern IStorage *CreateStorage(const char *pApplicationName, int StorageType, int NumArgs, const char **ppArguments); #endif ================================================ FILE: src/engine/textrender.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef ENGINE_TEXTRENDER_H #define ENGINE_TEXTRENDER_H #include "kernel.h" enum { TEXTFLAG_RENDER=1, TEXTFLAG_ALLOW_NEWLINE=2, TEXTFLAG_STOP_AT_END=4 }; class CFont; class CTextCursor { public: int m_Flags; int m_LineCount; int m_CharCount; int m_MaxLines; float m_StartX; float m_StartY; float m_LineWidth; float m_X, m_Y; CFont *m_pFont; float m_FontSize; }; class ITextRender : public IInterface { MACRO_INTERFACE("textrender", 0) public: virtual void SetCursor(CTextCursor *pCursor, float x, float y, float FontSize, int Flags) = 0; virtual CFont *LoadFont(const char *pFilename) = 0; virtual void DestroyFont(CFont *pFont) = 0; virtual void SetDefaultFont(CFont *pFont) = 0; // virtual void TextEx(CTextCursor *pCursor, const char *pText, int Length) = 0; // old foolish interface virtual void TextColor(float r, float g, float b, float a) = 0; virtual void TextOutlineColor(float r, float g, float b, float a) = 0; virtual void Text(void *pFontSetV, float x, float y, float Size, const char *pText, int MaxWidth) = 0; virtual float TextWidth(void *pFontSetV, float Size, const char *pText, int Length) = 0; virtual int TextLineCount(void *pFontSetV, float Size, const char *pText, float LineWidth) = 0; }; class IEngineTextRender : public ITextRender { MACRO_INTERFACE("enginetextrender", 0) public: virtual void Init() = 0; }; extern IEngineTextRender *CreateEngineTextRender(); #endif ================================================ FILE: src/game/client/animstate.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <base/math.h> #include <game/generated/protocol.h> #include <game/generated/client_data.h> #include "animstate.h" static void AnimSeqEval(CAnimSequence *pSeq, float Time, CAnimKeyframe *pFrame) { if(pSeq->m_NumFrames == 0) { pFrame->m_Time = 0; pFrame->m_X = 0; pFrame->m_Y = 0; pFrame->m_Angle = 0; } else if(pSeq->m_NumFrames == 1) { *pFrame = pSeq->m_aFrames[0]; } else { //time = max(0.0f, min(1.0f, time / duration)); // TODO: use clamp CAnimKeyframe *pFrame1 = 0; CAnimKeyframe *pFrame2 = 0; float Blend = 0.0f; // TODO: make this smarter.. binary search for (int i = 1; i < pSeq->m_NumFrames; i++) { if (pSeq->m_aFrames[i-1].m_Time <= Time && pSeq->m_aFrames[i].m_Time >= Time) { pFrame1 = &pSeq->m_aFrames[i-1]; pFrame2 = &pSeq->m_aFrames[i]; Blend = (Time - pFrame1->m_Time) / (pFrame2->m_Time - pFrame1->m_Time); break; } } if (pFrame1 && pFrame2) { pFrame->m_Time = Time; pFrame->m_X = mix(pFrame1->m_X, pFrame2->m_X, Blend); pFrame->m_Y = mix(pFrame1->m_Y, pFrame2->m_Y, Blend); pFrame->m_Angle = mix(pFrame1->m_Angle, pFrame2->m_Angle, Blend); } } } static void AnimAddKeyframe(CAnimKeyframe *pSeq, CAnimKeyframe *pAdded, float Amount) { pSeq->m_X += pAdded->m_X*Amount; pSeq->m_Y += pAdded->m_Y*Amount; pSeq->m_Angle += pAdded->m_Angle*Amount; } static void AnimAdd(CAnimState *pState, CAnimState *pAdded, float Amount) { AnimAddKeyframe(pState->GetBody(), pAdded->GetBody(), Amount); AnimAddKeyframe(pState->GetBackFoot(), pAdded->GetBackFoot(), Amount); AnimAddKeyframe(pState->GetFrontFoot(), pAdded->GetFrontFoot(), Amount); AnimAddKeyframe(pState->GetAttach(), pAdded->GetAttach(), Amount); } void CAnimState::Set(CAnimation *pAnim, float Time) { AnimSeqEval(&pAnim->m_Body, Time, &m_Body); AnimSeqEval(&pAnim->m_BackFoot, Time, &m_BackFoot); AnimSeqEval(&pAnim->m_FrontFoot, Time, &m_FrontFoot); AnimSeqEval(&pAnim->m_Attach, Time, &m_Attach); } void CAnimState::Add(CAnimation *pAnim, float Time, float Amount) { CAnimState Add; Add.Set(pAnim, Time); AnimAdd(this, &Add, Amount); } CAnimState *CAnimState::GetIdle() { static CAnimState State; static bool Init = true; if(Init) { State.Set(&g_pData->m_aAnimations[ANIM_BASE], 0); State.Add(&g_pData->m_aAnimations[ANIM_IDLE], 0, 1.0f); Init = false; } return &State; } ================================================ FILE: src/game/client/animstate.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_CLIENT_ANIMSTATE_H #define GAME_CLIENT_ANIMSTATE_H class CAnimState { CAnimKeyframe m_Body; CAnimKeyframe m_BackFoot; CAnimKeyframe m_FrontFoot; CAnimKeyframe m_Attach; public: CAnimKeyframe *GetBody() { return &m_Body; }; CAnimKeyframe *GetBackFoot() { return &m_BackFoot; }; CAnimKeyframe *GetFrontFoot() { return &m_FrontFoot; }; CAnimKeyframe *GetAttach() { return &m_Attach; }; void Set(CAnimation *pAnim, float Time); void Add(CAnimation *pAdded, float Time, float Amount); static CAnimState *GetIdle(); }; #endif ================================================ FILE: src/game/client/component.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_CLIENT_COMPONENT_H #define GAME_CLIENT_COMPONENT_H #include <engine/input.h> #include "gameclient.h" class CComponent { protected: friend class CGameClient; CGameClient *m_pClient; // perhaps propagte pointers for these as well class IKernel *Kernel() const { return m_pClient->Kernel(); } class IGraphics *Graphics() const { return m_pClient->Graphics(); } class ITextRender *TextRender() const { return m_pClient->TextRender(); } class IClient *Client() const { return m_pClient->Client(); } class IInput *Input() const { return m_pClient->Input(); } class IStorage *Storage() const { return m_pClient->Storage(); } class CUI *UI() const { return m_pClient->UI(); } class ISound *Sound() const { return m_pClient->Sound(); } class CRenderTools *RenderTools() const { return m_pClient->RenderTools(); } class IConsole *Console() const { return m_pClient->Console(); } class IDemoPlayer *DemoPlayer() const { return m_pClient->DemoPlayer(); } class IDemoRecorder *DemoRecorder() const { return m_pClient->DemoRecorder(); } class IServerBrowser *ServerBrowser() const { return m_pClient->ServerBrowser(); } class CLayers *Layers() const { return m_pClient->Layers(); } class CCollision *Collision() const { return m_pClient->Collision(); } public: virtual ~CComponent() {} virtual void OnStateChange(int NewState, int OldState) {}; virtual void OnConsoleInit() {}; virtual void OnInit() {}; virtual void OnReset() {}; virtual void OnRender() {}; virtual void OnRelease() {}; virtual void OnMapLoad() {}; virtual void OnMessage(int Msg, void *pRawMsg) {} virtual bool OnMouseMove(float x, float y) { return false; } virtual bool OnInput(IInput::CEvent e) { return false; } }; #endif ================================================ FILE: src/game/client/components/binds.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <engine/config.h> #include <engine/shared/config.h> #include "binds.h" bool CBinds::CBindsSpecial::OnInput(IInput::CEvent Event) { // don't handle invalid events and keys that arn't set to anything if(Event.m_Key >= KEY_F1 && Event.m_Key <= KEY_F15 && m_pBinds->m_aaKeyBindings[Event.m_Key][0] != 0) { int Stroke = 0; if(Event.m_Flags&IInput::FLAG_PRESS) Stroke = 1; m_pBinds->GetConsole()->ExecuteLineStroked(Stroke, m_pBinds->m_aaKeyBindings[Event.m_Key]); return true; } return false; } CBinds::CBinds() { mem_zero(m_aaKeyBindings, sizeof(m_aaKeyBindings)); m_SpecialBinds.m_pBinds = this; } void CBinds::Bind(int KeyID, const char *pStr) { if(KeyID < 0 || KeyID >= KEY_LAST) return; str_copy(m_aaKeyBindings[KeyID], pStr, sizeof(m_aaKeyBindings[KeyID])); char aBuf[256]; if(!m_aaKeyBindings[KeyID][0]) str_format(aBuf, sizeof(aBuf), "unbound %s (%d)", Input()->KeyName(KeyID), KeyID); else str_format(aBuf, sizeof(aBuf), "bound %s (%d) = %s", Input()->KeyName(KeyID), KeyID, m_aaKeyBindings[KeyID]); Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "binds", aBuf); } bool CBinds::OnInput(IInput::CEvent e) { // don't handle invalid events and keys that arn't set to anything if(e.m_Key <= 0 || e.m_Key >= KEY_LAST || m_aaKeyBindings[e.m_Key][0] == 0) return false; int Stroke = 0; if(e.m_Flags&IInput::FLAG_PRESS) Stroke = 1; Console()->ExecuteLineStroked(Stroke, m_aaKeyBindings[e.m_Key]); return true; } void CBinds::UnbindAll() { for(int i = 0; i < KEY_LAST; i++) m_aaKeyBindings[i][0] = 0; } const char *CBinds::Get(int KeyID) { if(KeyID > 0 && KeyID < KEY_LAST) return m_aaKeyBindings[KeyID]; return ""; } const char *CBinds::GetKey(const char *pBindStr) { for(int KeyId = 0; KeyId < KEY_LAST; KeyId++) { const char *pBind = Get(KeyId); if(!pBind[0]) continue; if(str_comp(pBind, pBindStr) == 0) return Input()->KeyName(KeyId); } return ""; } void CBinds::SetDefaults() { // set default key bindings UnbindAll(); Bind(KEY_F1, "toggle_local_console"); Bind(KEY_F2, "toggle_remote_console"); Bind(KEY_TAB, "+scoreboard"); Bind('u', "+show_chat"); Bind(KEY_F10, "screenshot"); Bind('a', "+left"); Bind('d', "+right"); Bind(KEY_SPACE, "+jump"); Bind(KEY_MOUSE_1, "+fire"); Bind(KEY_MOUSE_2, "+hook"); Bind(KEY_LSHIFT, "+emote"); Bind(KEY_RSHIFT, "+spectate"); Bind(KEY_RIGHT, "spectate_next"); Bind(KEY_LEFT, "spectate_previous"); Bind('1', "+weapon1"); Bind('2', "+weapon2"); Bind('3', "+weapon3"); Bind('4', "+weapon4"); Bind('5', "+weapon5"); Bind(KEY_MOUSE_WHEEL_UP, "+prevweapon"); Bind(KEY_MOUSE_WHEEL_DOWN, "+nextweapon"); Bind('t', "chat all"); Bind('y', "chat team"); Bind(KEY_F3, "vote yes"); Bind(KEY_F4, "vote no"); Bind('r', "ready_change"); } void CBinds::OnConsoleInit() { // bindings IConfig *pConfig = Kernel()->RequestInterface<IConfig>(); if(pConfig) pConfig->RegisterCallback(ConfigSaveCallback, this); Console()->Register("bind", "sr", CFGFLAG_CLIENT, ConBind, this, "Bind key to execute the command"); Console()->Register("unbind", "s", CFGFLAG_CLIENT, ConUnbind, this, "Unbind key"); Console()->Register("unbindall", "", CFGFLAG_CLIENT, ConUnbindAll, this, "Unbind all keys"); Console()->Register("dump_binds", "", CFGFLAG_CLIENT, ConDumpBinds, this, "Dump binds"); // default bindings SetDefaults(); } void CBinds::ConBind(IConsole::IResult *pResult, void *pUserData) { CBinds *pBinds = (CBinds *)pUserData; const char *pKeyName = pResult->GetString(0); int id = pBinds->GetKeyID(pKeyName); if(!id) { char aBuf[256]; str_format(aBuf, sizeof(aBuf), "key %s not found", pKeyName); pBinds->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "binds", aBuf); return; } pBinds->Bind(id, pResult->GetString(1)); } void CBinds::ConUnbind(IConsole::IResult *pResult, void *pUserData) { CBinds *pBinds = (CBinds *)pUserData; const char *pKeyName = pResult->GetString(0); int id = pBinds->GetKeyID(pKeyName); if(!id) { char aBuf[256]; str_format(aBuf, sizeof(aBuf), "key %s not found", pKeyName); pBinds->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "binds", aBuf); return; } pBinds->Bind(id, ""); } void CBinds::ConUnbindAll(IConsole::IResult *pResult, void *pUserData) { CBinds *pBinds = (CBinds *)pUserData; pBinds->UnbindAll(); } void CBinds::ConDumpBinds(IConsole::IResult *pResult, void *pUserData) { CBinds *pBinds = (CBinds *)pUserData; char aBuf[1024]; for(int i = 0; i < KEY_LAST; i++) { if(pBinds->m_aaKeyBindings[i][0] == 0) continue; str_format(aBuf, sizeof(aBuf), "%s (%d) = %s", pBinds->Input()->KeyName(i), i, pBinds->m_aaKeyBindings[i]); pBinds->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "binds", aBuf); } } int CBinds::GetKeyID(const char *pKeyName) { // check for numeric if(pKeyName[0] == '&') { int i = str_toint(pKeyName+1); if(i > 0 && i < KEY_LAST) return i; // numeric } // search for key for(int i = 0; i < KEY_LAST; i++) { if(str_comp(pKeyName, Input()->KeyName(i)) == 0) return i; } return 0; } void CBinds::ConfigSaveCallback(IConfig *pConfig, void *pUserData) { CBinds *pSelf = (CBinds *)pUserData; char aBuffer[256]; char *pEnd = aBuffer+sizeof(aBuffer)-8; pConfig->WriteLine("unbindall"); for(int i = 0; i < KEY_LAST; i++) { if(pSelf->m_aaKeyBindings[i][0] == 0) continue; str_format(aBuffer, sizeof(aBuffer), "bind %s ", pSelf->Input()->KeyName(i)); // process the string. we need to escape some characters const char *pSrc = pSelf->m_aaKeyBindings[i]; char *pDst = aBuffer + str_length(aBuffer); *pDst++ = '"'; while(*pSrc && pDst < pEnd) { if(*pSrc == '"' || *pSrc == '\\') // escape \ and " *pDst++ = '\\'; *pDst++ = *pSrc++; } *pDst++ = '"'; *pDst++ = 0; pConfig->WriteLine(aBuffer); } } ================================================ FILE: src/game/client/components/binds.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_CLIENT_COMPONENTS_BINDS_H #define GAME_CLIENT_COMPONENTS_BINDS_H #include <game/client/component.h> #include <engine/keys.h> class CBinds : public CComponent { char m_aaKeyBindings[KEY_LAST][128]; int GetKeyID(const char *pKeyName); static void ConBind(IConsole::IResult *pResult, void *pUserData); static void ConUnbind(IConsole::IResult *pResult, void *pUserData); static void ConUnbindAll(IConsole::IResult *pResult, void *pUserData); static void ConDumpBinds(IConsole::IResult *pResult, void *pUserData); class IConsole *GetConsole() const { return Console(); } static void ConfigSaveCallback(class IConfig *pConfig, void *pUserData); public: CBinds(); class CBindsSpecial : public CComponent { public: CBinds *m_pBinds; virtual bool OnInput(IInput::CEvent Event); }; CBindsSpecial m_SpecialBinds; void Bind(int KeyID, const char *pStr); void SetDefaults(); void UnbindAll(); const char *Get(int KeyID); const char *GetKey(const char *pBindStr); virtual void OnConsoleInit(); virtual bool OnInput(IInput::CEvent Event); }; #endif ================================================ FILE: src/game/client/components/broadcast.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <engine/shared/config.h> #include <engine/graphics.h> #include <engine/textrender.h> #include <game/generated/protocol.h> #include <game/generated/client_data.h> #include <game/client/gameclient.h> #include <game/client/components/motd.h> #include <game/client/components/scoreboard.h> #include "broadcast.h" CBroadcast::CBroadcast() { OnReset(); } void CBroadcast::DoBroadcast(const char *pText) { str_copy(m_aBroadcastText, pText, sizeof(m_aBroadcastText)); CTextCursor Cursor; TextRender()->SetCursor(&Cursor, 0, 0, 12.0f, TEXTFLAG_STOP_AT_END); Cursor.m_LineWidth = 300*Graphics()->ScreenAspect(); TextRender()->TextEx(&Cursor, m_aBroadcastText, -1); m_BroadcastRenderOffset = 150*Graphics()->ScreenAspect()-Cursor.m_X/2; m_BroadcastTime = time_get()+time_freq()*10; } void CBroadcast::OnReset() { m_BroadcastTime = 0; } void CBroadcast::OnRender() { if(m_pClient->m_pScoreboard->Active() || m_pClient->m_pMotd->IsActive()) return; Graphics()->MapScreen(0, 0, 300*Graphics()->ScreenAspect(), 300); if(time_get() < m_BroadcastTime) { CTextCursor Cursor; TextRender()->SetCursor(&Cursor, m_BroadcastRenderOffset, 40.0f, 12.0f, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); Cursor.m_LineWidth = 300*Graphics()->ScreenAspect()-m_BroadcastRenderOffset; TextRender()->TextEx(&Cursor, m_aBroadcastText, -1); } } ================================================ FILE: src/game/client/components/broadcast.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_CLIENT_COMPONENTS_BROADCAST_H #define GAME_CLIENT_COMPONENTS_BROADCAST_H #include <game/client/component.h> class CBroadcast : public CComponent { char m_aBroadcastText[128]; int64 m_BroadcastTime; float m_BroadcastRenderOffset; public: CBroadcast(); void DoBroadcast(const char *pText); virtual void OnReset(); virtual void OnRender(); }; #endif ================================================ FILE: src/game/client/components/camera.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <engine/shared/config.h> #include <base/math.h> #include <game/collision.h> #include <game/client/gameclient.h> #include <game/client/component.h> #include "camera.h" #include "controls.h" CCamera::CCamera() { m_CamType = CAMTYPE_UNDEFINED; m_RotationCenter = vec2(0.0f, 0.0f); m_MenuCenter = vec2(0.0f, 0.0f); m_Positions[POS_START] = vec2(500.0f, 500.0f); m_Positions[POS_INTERNET] = vec2(500.0f, 500.0f); m_Positions[POS_LAN] = vec2(1000.0f, 1000.0f); m_Positions[POS_FAVORITES] = vec2(2000.0f, 500.0f); m_Positions[POS_DEMOS] = vec2(1500.0f, 1000.0f); m_Positions[POS_SETTINGS] = vec2(1000.0f, 500.0f); m_CurrentPosition = -1; } void CCamera::OnRender() { if(Client()->State() == IClient::STATE_ONLINE || Client()->State() == IClient::STATE_DEMOPLAYBACK) { m_Zoom = 1.0f; // update camera center if(m_pClient->m_Snap.m_SpecInfo.m_Active && !m_pClient->m_Snap.m_SpecInfo.m_UsePosition) { if(m_CamType != CAMTYPE_SPEC) { m_pClient->m_pControls->m_MousePos = m_PrevCenter; m_pClient->m_pControls->ClampMousePos(); m_CamType = CAMTYPE_SPEC; } m_Center = m_pClient->m_pControls->m_MousePos; } else { if(m_CamType != CAMTYPE_PLAYER) { m_pClient->m_pControls->ClampMousePos(); m_CamType = CAMTYPE_PLAYER; } vec2 CameraOffset(0, 0); float l = length(m_pClient->m_pControls->m_MousePos); if(l > 0.0001f) // make sure that this isn't 0 { float DeadZone = g_Config.m_ClMouseDeadzone; float FollowFactor = g_Config.m_ClMouseFollowfactor/100.0f; float OffsetAmount = max(l-DeadZone, 0.0f) * FollowFactor; CameraOffset = normalize(m_pClient->m_pControls->m_MousePos)*OffsetAmount; } if(m_pClient->m_Snap.m_SpecInfo.m_Active) m_Center = m_pClient->m_Snap.m_SpecInfo.m_Position + CameraOffset; else m_Center = m_pClient->m_LocalCharacterPos + CameraOffset; } } else { m_Zoom = 0.7f; static vec2 Dir = vec2(1.0f, 0.0f); if(distance(m_Center, m_RotationCenter) <= (float)g_Config.m_ClRotationRadius+0.5f) { // do little rotation float RotPerTick = 360.0f/(float)g_Config.m_ClRotationSpeed * Client()->RenderFrameTime(); Dir = rotate(Dir, RotPerTick); m_Center = m_RotationCenter+Dir*(float)g_Config.m_ClRotationRadius; } else { Dir = normalize(m_RotationCenter-m_Center); m_Center += Dir*(500.0f*Client()->RenderFrameTime()); Dir = normalize(m_Center-m_RotationCenter); } } m_PrevCenter = m_Center; } void CCamera::ChangePosition(int PositionNumber) { m_RotationCenter = m_Positions[PositionNumber]; m_CurrentPosition = PositionNumber; } int CCamera::GetCurrentPosition() { return m_CurrentPosition; } void CCamera::ConSetPosition(IConsole::IResult *pResult, void *pUserData) { CCamera *pSelf = (CCamera *)pUserData; int PositionNumber = clamp(pResult->GetInteger(0), 0, 4); vec2 Position = vec2(pResult->GetInteger(1)*32.0f+16.0f, pResult->GetInteger(2)*32.0f+16.0f); pSelf->m_Positions[PositionNumber] = Position; // update if(pSelf->GetCurrentPosition() == PositionNumber) pSelf->ChangePosition(PositionNumber); } void CCamera::OnConsoleInit() { Console()->Register("set_position", "iii", CFGFLAG_CLIENT, ConSetPosition, this, "Sets the rotation position"); } void CCamera::OnStateChange(int NewState, int OldState) { if(OldState == IClient::STATE_OFFLINE) m_MenuCenter = m_Center; else if(NewState != IClient::STATE_ONLINE && Client()->State() != IClient::STATE_DEMOPLAYBACK) m_Center = m_MenuCenter; } ================================================ FILE: src/game/client/components/camera.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_CLIENT_COMPONENTS_CAMERA_H #define GAME_CLIENT_COMPONENTS_CAMERA_H #include <base/vmath.h> #include <game/client/component.h> class CCamera : public CComponent { public: enum { POS_START=0, POS_INTERNET, POS_LAN, POS_FAVORITES, POS_DEMOS, POS_SETTINGS, NUM_POS, }; vec2 m_Center; vec2 m_MenuCenter; vec2 m_RotationCenter; float m_Zoom; CCamera(); virtual void OnRender(); void ChangePosition(int PositionNumber); int GetCurrentPosition(); static void ConSetPosition(IConsole::IResult *pResult, void *pUserData); virtual void OnConsoleInit(); virtual void OnStateChange(int NewState, int OldState); public: enum { CAMTYPE_UNDEFINED=-1, CAMTYPE_SPEC, CAMTYPE_PLAYER, }; int m_CamType; vec2 m_PrevCenter; vec2 m_Positions[NUM_POS]; int m_CurrentPosition; }; #endif ================================================ FILE: src/game/client/components/chat.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <engine/engine.h> #include <engine/graphics.h> #include <engine/textrender.h> #include <engine/keys.h> #include <engine/shared/config.h> #include <game/generated/protocol.h> #include <game/generated/client_data.h> #include <game/client/gameclient.h> #include <game/client/localization.h> #include <game/client/components/scoreboard.h> #include <game/client/components/sounds.h> #include "menus.h" #include "chat.h" CChat::CChat() { OnReset(); } void CChat::OnReset() { for(int i = 0; i < MAX_LINES; i++) { m_aLines[i].m_Time = 0; m_aLines[i].m_aText[0] = 0; m_aLines[i].m_aName[0] = 0; } m_Show = false; m_InputUpdate = false; m_ChatStringOffset = 0; m_CompletionChosen = -1; m_aCompletionBuffer[0] = 0; m_PlaceholderOffset = 0; m_PlaceholderLength = 0; m_pHistoryEntry = 0x0; m_PendingChatCounter = 0; m_LastChatSend = 0; for(int i = 0; i < CHAT_NUM; ++i) m_aLastSoundPlayed[i] = 0; } void CChat::OnRelease() { m_Show = false; } void CChat::OnStateChange(int NewState, int OldState) { if(OldState <= IClient::STATE_CONNECTING) { m_Mode = MODE_NONE; for(int i = 0; i < MAX_LINES; i++) m_aLines[i].m_Time = 0; m_CurrentLine = 0; } } void CChat::ConSay(IConsole::IResult *pResult, void *pUserData) { ((CChat*)pUserData)->Say(0, pResult->GetString(0)); } void CChat::ConSayTeam(IConsole::IResult *pResult, void *pUserData) { ((CChat*)pUserData)->Say(1, pResult->GetString(0)); } void CChat::ConChat(IConsole::IResult *pResult, void *pUserData) { const char *pMode = pResult->GetString(0); if(str_comp(pMode, "all") == 0) ((CChat*)pUserData)->EnableMode(0); else if(str_comp(pMode, "team") == 0) ((CChat*)pUserData)->EnableMode(1); else ((CChat*)pUserData)->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "console", "expected all or team as mode"); } void CChat::ConShowChat(IConsole::IResult *pResult, void *pUserData) { ((CChat *)pUserData)->m_Show = pResult->GetInteger(0) != 0; } void CChat::OnConsoleInit() { Console()->Register("say", "r", CFGFLAG_CLIENT, ConSay, this, "Say in chat"); Console()->Register("say_team", "r", CFGFLAG_CLIENT, ConSayTeam, this, "Say in team chat"); Console()->Register("chat", "s", CFGFLAG_CLIENT, ConChat, this, "Enable chat with all/team mode"); Console()->Register("+show_chat", "", CFGFLAG_CLIENT, ConShowChat, this, "Show chat"); } bool CChat::OnInput(IInput::CEvent Event) { if(m_Mode == MODE_NONE) return false; if(Event.m_Flags&IInput::FLAG_PRESS && Event.m_Key == KEY_ESCAPE) { m_Mode = MODE_NONE; m_pClient->OnRelease(); } else if(Event.m_Flags&IInput::FLAG_PRESS && (Event.m_Key == KEY_RETURN || Event.m_Key == KEY_KP_ENTER)) { if(m_Input.GetString()[0]) { bool AddEntry = false; if(m_LastChatSend+time_freq() < time_get()) { Say(m_Mode == MODE_ALL ? 0 : 1, m_Input.GetString()); AddEntry = true; } else if(m_PendingChatCounter < 3) { ++m_PendingChatCounter; AddEntry = true; } if(AddEntry) { CHistoryEntry *pEntry = m_History.Allocate(sizeof(CHistoryEntry)+m_Input.GetLength()); pEntry->m_Team = m_Mode == MODE_ALL ? 0 : 1; mem_copy(pEntry->m_aText, m_Input.GetString(), m_Input.GetLength()+1); } } m_pHistoryEntry = 0x0; m_Mode = MODE_NONE; m_pClient->OnRelease(); } if(Event.m_Flags&IInput::FLAG_PRESS && Event.m_Key == KEY_TAB) { // fill the completion buffer if(m_CompletionChosen < 0) { const char *pCursor = m_Input.GetString()+m_Input.GetCursorOffset(); for(int Count = 0; Count < m_Input.GetCursorOffset() && *(pCursor-1) != ' '; --pCursor, ++Count); m_PlaceholderOffset = pCursor-m_Input.GetString(); for(m_PlaceholderLength = 0; *pCursor && *pCursor != ' '; ++pCursor) ++m_PlaceholderLength; str_copy(m_aCompletionBuffer, m_Input.GetString()+m_PlaceholderOffset, min(static_cast<int>(sizeof(m_aCompletionBuffer)), m_PlaceholderLength+1)); } // find next possible name const char *pCompletionString = 0; m_CompletionChosen = (m_CompletionChosen+1)%(2*MAX_CLIENTS); for(int i = 0; i < 2*MAX_CLIENTS; ++i) { int SearchType = ((m_CompletionChosen+i)%(2*MAX_CLIENTS))/MAX_CLIENTS; int Index = (m_CompletionChosen+i)%MAX_CLIENTS; if(!m_pClient->m_aClients[Index].m_Active) continue; bool Found = false; if(SearchType == 1) { if(str_comp_nocase_num(m_pClient->m_aClients[Index].m_aName, m_aCompletionBuffer, str_length(m_aCompletionBuffer)) && str_find_nocase(m_pClient->m_aClients[Index].m_aName, m_aCompletionBuffer)) Found = true; } else if(!str_comp_nocase_num(m_pClient->m_aClients[Index].m_aName, m_aCompletionBuffer, str_length(m_aCompletionBuffer))) Found = true; if(Found) { pCompletionString = m_pClient->m_aClients[Index].m_aName; m_CompletionChosen = Index+SearchType*MAX_CLIENTS; break; } } // insert the name if(pCompletionString) { char aBuf[256]; // add part before the name str_copy(aBuf, m_Input.GetString(), min(static_cast<int>(sizeof(aBuf)), m_PlaceholderOffset+1)); // add the name str_append(aBuf, pCompletionString, sizeof(aBuf)); // add seperator const char *pSeparator = ""; if(*(m_Input.GetString()+m_PlaceholderOffset+m_PlaceholderLength) != ' ') pSeparator = m_PlaceholderOffset == 0 ? ": " : " "; else if(m_PlaceholderOffset == 0) pSeparator = ":"; if(*pSeparator) str_append(aBuf, pSeparator, sizeof(aBuf)); // add part after the name str_append(aBuf, m_Input.GetString()+m_PlaceholderOffset+m_PlaceholderLength, sizeof(aBuf)); m_PlaceholderLength = str_length(pSeparator)+str_length(pCompletionString); m_OldChatStringLength = m_Input.GetLength(); m_Input.Set(aBuf); m_Input.SetCursorOffset(m_PlaceholderOffset+m_PlaceholderLength); m_InputUpdate = true; } } else { // reset name completion process if(Event.m_Flags&IInput::FLAG_PRESS && Event.m_Key != KEY_TAB) m_CompletionChosen = -1; m_OldChatStringLength = m_Input.GetLength(); m_Input.ProcessInput(Event); m_InputUpdate = true; } if(Event.m_Flags&IInput::FLAG_PRESS && Event.m_Key == KEY_UP) { if(m_pHistoryEntry) { CHistoryEntry *pTest = m_History.Prev(m_pHistoryEntry); if(pTest) m_pHistoryEntry = pTest; } else m_pHistoryEntry = m_History.Last(); if(m_pHistoryEntry) m_Input.Set(m_pHistoryEntry->m_aText); } else if (Event.m_Flags&IInput::FLAG_PRESS && Event.m_Key == KEY_DOWN) { if(m_pHistoryEntry) m_pHistoryEntry = m_History.Next(m_pHistoryEntry); if (m_pHistoryEntry) m_Input.Set(m_pHistoryEntry->m_aText); else m_Input.Clear(); } return true; } void CChat::EnableMode(int Team) { if(Client()->State() == IClient::STATE_DEMOPLAYBACK) return; if(m_Mode == MODE_NONE) { if(Team) m_Mode = MODE_TEAM; else m_Mode = MODE_ALL; m_Input.Clear(); Input()->ClearEvents(); m_CompletionChosen = -1; } } void CChat::OnMessage(int MsgType, void *pRawMsg) { if(MsgType == NETMSGTYPE_SV_CHAT) { CNetMsg_Sv_Chat *pMsg = (CNetMsg_Sv_Chat *)pRawMsg; AddLine(pMsg->m_ClientID, pMsg->m_Team, pMsg->m_pMessage); } } void CChat::AddLine(int ClientID, int Team, const char *pLine) { if(*pLine == 0 || (ClientID != -1 && (m_pClient->m_aClients[ClientID].m_aName[0] == '\0' || // unknown client m_pClient->m_aClients[ClientID].m_ChatIgnore || (m_pClient->m_LocalClientID != ClientID && g_Config.m_ClShowChatFriends && !m_pClient->m_aClients[ClientID].m_Friend)))) return; bool Highlighted = false; char *p = const_cast<char*>(pLine); while(*p) { Highlighted = false; pLine = p; // find line seperator and strip multiline while(*p) { if(*p++ == '\n') { *(p-1) = 0; break; } } m_CurrentLine = (m_CurrentLine+1)%MAX_LINES; m_aLines[m_CurrentLine].m_Time = time_get(); m_aLines[m_CurrentLine].m_YOffset[0] = -1.0f; m_aLines[m_CurrentLine].m_YOffset[1] = -1.0f; m_aLines[m_CurrentLine].m_ClientID = ClientID; m_aLines[m_CurrentLine].m_Team = Team; m_aLines[m_CurrentLine].m_NameColor = -2; // check for highlighted name const char *pHL = str_find_nocase(pLine, m_pClient->m_aClients[m_pClient->m_LocalClientID].m_aName); if(pHL) { int Length = str_length(m_pClient->m_aClients[m_pClient->m_LocalClientID].m_aName); if((pLine == pHL || pHL[-1] == ' ') && (pHL[Length] == 0 || pHL[Length] == ' ' || (pHL[Length] == ':' && pHL[Length+1] == ' '))) Highlighted = true; } m_aLines[m_CurrentLine].m_Highlighted = Highlighted; if(ClientID == -1) // server message { str_copy(m_aLines[m_CurrentLine].m_aName, "*** ", sizeof(m_aLines[m_CurrentLine].m_aName)); str_format(m_aLines[m_CurrentLine].m_aText, sizeof(m_aLines[m_CurrentLine].m_aText), "%s", pLine); } else { if(m_pClient->m_aClients[ClientID].m_Team == TEAM_SPECTATORS) m_aLines[m_CurrentLine].m_NameColor = TEAM_SPECTATORS; if(m_pClient->m_GameInfo.m_GameFlags&GAMEFLAG_TEAMS) { if(m_pClient->m_aClients[ClientID].m_Team == TEAM_RED) m_aLines[m_CurrentLine].m_NameColor = TEAM_RED; else if(m_pClient->m_aClients[ClientID].m_Team == TEAM_BLUE) m_aLines[m_CurrentLine].m_NameColor = TEAM_BLUE; } str_copy(m_aLines[m_CurrentLine].m_aName, m_pClient->m_aClients[ClientID].m_aName, sizeof(m_aLines[m_CurrentLine].m_aName)); str_format(m_aLines[m_CurrentLine].m_aText, sizeof(m_aLines[m_CurrentLine].m_aText), ": %s", pLine); } char aBuf[1024]; str_format(aBuf, sizeof(aBuf), "%s%s", m_aLines[m_CurrentLine].m_aName, m_aLines[m_CurrentLine].m_aText); Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, m_aLines[m_CurrentLine].m_Team?"teamchat":"chat", aBuf); } // play sound int64 Now = time_get(); if(ClientID == -1) { if(Now-m_aLastSoundPlayed[CHAT_SERVER] >= time_freq()*3/10) { m_pClient->m_pSounds->Play(CSounds::CHN_GUI, SOUND_CHAT_SERVER, 0); m_aLastSoundPlayed[CHAT_SERVER] = Now; } } else if(Highlighted) { if(Now-m_aLastSoundPlayed[CHAT_HIGHLIGHT] >= time_freq()*3/10) { m_pClient->m_pSounds->Play(CSounds::CHN_GUI, SOUND_CHAT_HIGHLIGHT, 0); m_aLastSoundPlayed[CHAT_HIGHLIGHT] = Now; } } else { if(Now-m_aLastSoundPlayed[CHAT_CLIENT] >= time_freq()*3/10) { m_pClient->m_pSounds->Play(CSounds::CHN_GUI, SOUND_CHAT_CLIENT, 0); m_aLastSoundPlayed[CHAT_CLIENT] = Now; } } } void CChat::OnRender() { // send pending chat messages if(m_PendingChatCounter > 0 && m_LastChatSend+time_freq() < time_get()) { CHistoryEntry *pEntry = m_History.Last(); for(int i = m_PendingChatCounter-1; pEntry; --i, pEntry = m_History.Prev(pEntry)) { if(i == 0) { Say(pEntry->m_Team, pEntry->m_aText); break; } } --m_PendingChatCounter; } // dont render chat if the menu is active if(m_pClient->m_pMenus->IsActive()) return; float Width = 300.0f*Graphics()->ScreenAspect(); Graphics()->MapScreen(0.0f, 0.0f, Width, 300.0f); float x = 5.0f; float y = 300.0f-20.0f; if(m_Mode != MODE_NONE) { // render chat input CTextCursor Cursor; TextRender()->SetCursor(&Cursor, x, y, 8.0f, TEXTFLAG_RENDER); Cursor.m_LineWidth = Width-190.0f; Cursor.m_MaxLines = 2; if(m_Mode == MODE_ALL) TextRender()->TextEx(&Cursor, Localize("All"), -1); else if(m_Mode == MODE_TEAM) TextRender()->TextEx(&Cursor, Localize("Team"), -1); else TextRender()->TextEx(&Cursor, Localize("Chat"), -1); TextRender()->TextEx(&Cursor, ": ", -1); // check if the visible text has to be moved if(m_InputUpdate) { if(m_ChatStringOffset > 0 && m_Input.GetLength() < m_OldChatStringLength) m_ChatStringOffset = max(0, m_ChatStringOffset-(m_OldChatStringLength-m_Input.GetLength())); if(m_ChatStringOffset > m_Input.GetCursorOffset()) m_ChatStringOffset -= m_ChatStringOffset-m_Input.GetCursorOffset(); else { CTextCursor Temp = Cursor; Temp.m_Flags = 0; TextRender()->TextEx(&Temp, m_Input.GetString()+m_ChatStringOffset, m_Input.GetCursorOffset()-m_ChatStringOffset); TextRender()->TextEx(&Temp, "|", -1); while(Temp.m_LineCount > 2) { ++m_ChatStringOffset; Temp = Cursor; Temp.m_Flags = 0; TextRender()->TextEx(&Temp, m_Input.GetString()+m_ChatStringOffset, m_Input.GetCursorOffset()-m_ChatStringOffset); TextRender()->TextEx(&Temp, "|", -1); } } m_InputUpdate = false; } TextRender()->TextEx(&Cursor, m_Input.GetString()+m_ChatStringOffset, m_Input.GetCursorOffset()-m_ChatStringOffset); static float MarkerOffset = TextRender()->TextWidth(0, 8.0f, "|", -1)/3; CTextCursor Marker = Cursor; Marker.m_X -= MarkerOffset; TextRender()->TextEx(&Marker, "|", -1); TextRender()->TextEx(&Cursor, m_Input.GetString()+m_Input.GetCursorOffset(), -1); } y -= 8.0f; int64 Now = time_get(); float LineWidth = m_pClient->m_pScoreboard->Active() ? 90.0f : 200.0f; float HeightLimit = m_pClient->m_pScoreboard->Active() ? 230.0f : m_Show ? 50.0f : 200.0f; float Begin = x; float FontSize = 6.0f; CTextCursor Cursor; int OffsetType = m_pClient->m_pScoreboard->Active() ? 1 : 0; for(int i = 0; i < MAX_LINES; i++) { int r = ((m_CurrentLine-i)+MAX_LINES)%MAX_LINES; if(Now > m_aLines[r].m_Time+16*time_freq() && !m_Show) break; // get the y offset (calculate it if we haven't done that yet) if(m_aLines[r].m_YOffset[OffsetType] < 0.0f) { TextRender()->SetCursor(&Cursor, Begin, 0.0f, FontSize, 0); Cursor.m_LineWidth = LineWidth; TextRender()->TextEx(&Cursor, m_aLines[r].m_aName, -1); TextRender()->TextEx(&Cursor, m_aLines[r].m_aText, -1); m_aLines[r].m_YOffset[OffsetType] = Cursor.m_Y + Cursor.m_FontSize; } y -= m_aLines[r].m_YOffset[OffsetType]; // cut off if msgs waste too much space if(y < HeightLimit) break; float Blend = Now > m_aLines[r].m_Time+14*time_freq() && !m_Show ? 1.0f-(Now-m_aLines[r].m_Time-14*time_freq())/(2.0f*time_freq()) : 1.0f; // reset the cursor TextRender()->SetCursor(&Cursor, Begin, y, FontSize, TEXTFLAG_RENDER); Cursor.m_LineWidth = LineWidth; // render name if(m_aLines[r].m_ClientID == -1) TextRender()->TextColor(1.0f, 1.0f, 0.5f, Blend); // system else if(m_aLines[r].m_Team) TextRender()->TextColor(0.45f, 0.9f, 0.45f, Blend); // team message else if(m_aLines[r].m_NameColor == TEAM_RED) TextRender()->TextColor(1.0f, 0.5f, 0.5f, Blend); // red else if(m_aLines[r].m_NameColor == TEAM_BLUE) TextRender()->TextColor(0.7f, 0.7f, 1.0f, Blend); // blue else if(m_aLines[r].m_NameColor == TEAM_SPECTATORS) TextRender()->TextColor(0.75f, 0.5f, 0.75f, Blend); // spectator else TextRender()->TextColor(0.8f, 0.8f, 0.8f, Blend); TextRender()->TextEx(&Cursor, m_aLines[r].m_aName, -1); // render line if(m_aLines[r].m_ClientID == -1) TextRender()->TextColor(1.0f, 1.0f, 0.5f, Blend); // system else if(m_aLines[r].m_Highlighted) TextRender()->TextColor(1.0f, 0.5f, 0.5f, Blend); // highlighted else if(m_aLines[r].m_Team) TextRender()->TextColor(0.65f, 1.0f, 0.65f, Blend); // team message else TextRender()->TextColor(1.0f, 1.0f, 1.0f, Blend); TextRender()->TextEx(&Cursor, m_aLines[r].m_aText, -1); } TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); } void CChat::Say(int Team, const char *pLine) { m_LastChatSend = time_get(); // send chat message CNetMsg_Cl_Say Msg; Msg.m_Team = Team; Msg.m_pMessage = pLine; Client()->SendPackMsg(&Msg, MSGFLAG_VITAL); } ================================================ FILE: src/game/client/components/chat.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_CLIENT_COMPONENTS_CHAT_H #define GAME_CLIENT_COMPONENTS_CHAT_H #include <engine/shared/ringbuffer.h> #include <game/client/component.h> #include <game/client/lineinput.h> class CChat : public CComponent { CLineInput m_Input; enum { MAX_LINES = 25, }; struct CLine { int64 m_Time; float m_YOffset[2]; int m_ClientID; int m_Team; int m_NameColor; char m_aName[64]; char m_aText[512]; bool m_Highlighted; }; CLine m_aLines[MAX_LINES]; int m_CurrentLine; // chat enum { MODE_NONE=0, MODE_ALL, MODE_TEAM, CHAT_SERVER=0, CHAT_HIGHLIGHT, CHAT_CLIENT, CHAT_NUM, }; int m_Mode; bool m_Show; bool m_InputUpdate; int m_ChatStringOffset; int m_OldChatStringLength; int m_CompletionChosen; char m_aCompletionBuffer[256]; int m_PlaceholderOffset; int m_PlaceholderLength; struct CHistoryEntry { int m_Team; char m_aText[1]; }; CHistoryEntry *m_pHistoryEntry; TStaticRingBuffer<CHistoryEntry, 64*1024, CRingBufferBase::FLAG_RECYCLE> m_History; int m_PendingChatCounter; int64 m_LastChatSend; int64 m_aLastSoundPlayed[CHAT_NUM]; static void ConSay(IConsole::IResult *pResult, void *pUserData); static void ConSayTeam(IConsole::IResult *pResult, void *pUserData); static void ConChat(IConsole::IResult *pResult, void *pUserData); static void ConShowChat(IConsole::IResult *pResult, void *pUserData); public: CChat(); bool IsActive() const { return m_Mode != MODE_NONE; } void AddLine(int ClientID, int Team, const char *pLine); void EnableMode(int Team); void Say(int Team, const char *pLine); virtual void OnReset(); virtual void OnConsoleInit(); virtual void OnStateChange(int NewState, int OldState); virtual void OnRender(); virtual void OnRelease(); virtual void OnMessage(int MsgType, void *pRawMsg); virtual bool OnInput(IInput::CEvent Event); }; #endif ================================================ FILE: src/game/client/components/console.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <math.h> #include <game/generated/client_data.h> #include <base/system.h> #include <engine/shared/ringbuffer.h> #include <engine/shared/config.h> #include <engine/graphics.h> #include <engine/textrender.h> #include <engine/storage.h> #include <engine/keys.h> #include <engine/console.h> #include <cstring> #include <cstdio> #include <game/client/ui.h> #include <game/version.h> #include <game/client/lineinput.h> #include <game/client/render.h> #include <game/client/components/controls.h> #include <game/client/components/menus.h> #include "console.h" enum { CONSOLE_CLOSED, CONSOLE_OPENING, CONSOLE_OPEN, CONSOLE_CLOSING, }; CGameConsole::CInstance::CInstance(int Type) { m_pHistoryEntry = 0x0; m_Type = Type; if(Type == CGameConsole::CONSOLETYPE_LOCAL) m_CompletionFlagmask = CFGFLAG_CLIENT; else m_CompletionFlagmask = CFGFLAG_SERVER; m_aCompletionBuffer[0] = 0; m_CompletionChosen = -1; m_CompletionRenderOffset = 0.0f; m_IsCommand = false; } void CGameConsole::CInstance::Init(CGameConsole *pGameConsole) { m_pGameConsole = pGameConsole; }; void CGameConsole::CInstance::ClearBacklog() { m_Backlog.Init(); m_BacklogActPage = 0; } void CGameConsole::CInstance::ClearHistory() { m_History.Init(); m_pHistoryEntry = 0; } void CGameConsole::CInstance::ExecuteLine(const char *pLine) { if(m_Type == CGameConsole::CONSOLETYPE_LOCAL) m_pGameConsole->m_pConsole->ExecuteLine(pLine); else { if(m_pGameConsole->Client()->RconAuthed()) m_pGameConsole->Client()->Rcon(pLine); else m_pGameConsole->Client()->RconAuth("", pLine); } } void CGameConsole::CInstance::PossibleCommandsCompleteCallback(const char *pStr, void *pUser) { CGameConsole::CInstance *pInstance = (CGameConsole::CInstance *)pUser; if(pInstance->m_CompletionChosen == pInstance->m_CompletionEnumerationCount) pInstance->m_Input.Set(pStr); pInstance->m_CompletionEnumerationCount++; } void CGameConsole::CInstance::OnInput(IInput::CEvent Event) { bool Handled = false; if(Event.m_Flags&IInput::FLAG_PRESS) { if(Event.m_Key == KEY_RETURN || Event.m_Key == KEY_KP_ENTER) { if(m_Input.GetString()[0]) { if(m_Type == CONSOLETYPE_LOCAL || m_pGameConsole->Client()->RconAuthed()) { char *pEntry = m_History.Allocate(m_Input.GetLength()+1); mem_copy(pEntry, m_Input.GetString(), m_Input.GetLength()+1); } ExecuteLine(m_Input.GetString()); m_Input.Clear(); m_pHistoryEntry = 0x0; } Handled = true; } else if (Event.m_Key == KEY_UP) { if (m_pHistoryEntry) { char *pTest = m_History.Prev(m_pHistoryEntry); if (pTest) m_pHistoryEntry = pTest; } else m_pHistoryEntry = m_History.Last(); if (m_pHistoryEntry) m_Input.Set(m_pHistoryEntry); Handled = true; } else if (Event.m_Key == KEY_DOWN) { if (m_pHistoryEntry) m_pHistoryEntry = m_History.Next(m_pHistoryEntry); if (m_pHistoryEntry) m_Input.Set(m_pHistoryEntry); else m_Input.Clear(); Handled = true; } else if(Event.m_Key == KEY_TAB) { if(m_Type == CGameConsole::CONSOLETYPE_LOCAL || m_pGameConsole->Client()->RconAuthed()) { m_CompletionChosen++; m_CompletionEnumerationCount = 0; m_pGameConsole->m_pConsole->PossibleCommands(m_aCompletionBuffer, m_CompletionFlagmask, m_Type != CGameConsole::CONSOLETYPE_LOCAL && m_pGameConsole->Client()->RconAuthed() && m_pGameConsole->Client()->UseTempRconCommands(), PossibleCommandsCompleteCallback, this); // handle wrapping if(m_CompletionEnumerationCount && m_CompletionChosen >= m_CompletionEnumerationCount) { m_CompletionChosen %= m_CompletionEnumerationCount; m_CompletionEnumerationCount = 0; m_pGameConsole->m_pConsole->PossibleCommands(m_aCompletionBuffer, m_CompletionFlagmask, m_Type != CGameConsole::CONSOLETYPE_LOCAL && m_pGameConsole->Client()->RconAuthed() && m_pGameConsole->Client()->UseTempRconCommands(), PossibleCommandsCompleteCallback, this); } } } else if(Event.m_Key == KEY_PAGEUP) { ++m_BacklogActPage; } else if(Event.m_Key == KEY_PAGEDOWN) { --m_BacklogActPage; if(m_BacklogActPage < 0) m_BacklogActPage = 0; } } if(!Handled) m_Input.ProcessInput(Event); if(Event.m_Flags&IInput::FLAG_PRESS) { if(Event.m_Key != KEY_TAB) { m_CompletionChosen = -1; str_copy(m_aCompletionBuffer, m_Input.GetString(), sizeof(m_aCompletionBuffer)); } // find the current command { char aBuf[64] = {0}; const char *pSrc = GetString(); int i = 0; for(; i < (int)sizeof(aBuf)-1 && *pSrc && *pSrc != ' '; i++, pSrc++) aBuf[i] = *pSrc; aBuf[i] = 0; const IConsole::CCommandInfo *pCommand = m_pGameConsole->m_pConsole->GetCommandInfo(aBuf, m_CompletionFlagmask, m_Type != CGameConsole::CONSOLETYPE_LOCAL && m_pGameConsole->Client()->RconAuthed() && m_pGameConsole->Client()->UseTempRconCommands()); if(pCommand) { m_IsCommand = true; str_copy(m_aCommandName, pCommand->m_pName, IConsole::TEMPCMD_NAME_LENGTH); str_copy(m_aCommandHelp, pCommand->m_pHelp, IConsole::TEMPCMD_HELP_LENGTH); str_copy(m_aCommandParams, pCommand->m_pParams, IConsole::TEMPCMD_PARAMS_LENGTH); } else m_IsCommand = false; } } } void CGameConsole::CInstance::PrintLine(const char *pLine) { int Len = str_length(pLine); if (Len > 255) Len = 255; CBacklogEntry *pEntry = m_Backlog.Allocate(sizeof(CBacklogEntry)+Len); pEntry->m_YOffset = -1.0f; mem_copy(pEntry->m_aText, pLine, Len); pEntry->m_aText[Len] = 0; } CGameConsole::CGameConsole() : m_LocalConsole(CONSOLETYPE_LOCAL), m_RemoteConsole(CONSOLETYPE_REMOTE) { m_ConsoleType = CONSOLETYPE_LOCAL; m_ConsoleState = CONSOLE_CLOSED; m_StateChangeEnd = 0.0f; m_StateChangeDuration = 0.1f; } float CGameConsole::TimeNow() { static long long s_TimeStart = time_get(); return float(time_get()-s_TimeStart)/float(time_freq()); } CGameConsole::CInstance *CGameConsole::CurrentConsole() { if(m_ConsoleType == CONSOLETYPE_REMOTE) return &m_RemoteConsole; return &m_LocalConsole; } void CGameConsole::OnReset() { } // only defined for 0<=t<=1 static float ConsoleScaleFunc(float t) { //return t; return sinf(acosf(1.0f-t)); } struct CRenderInfo { CGameConsole *m_pSelf; CTextCursor m_Cursor; const char *m_pCurrentCmd; int m_WantedCompletion; int m_EnumCount; float m_Offset; float m_Width; }; void CGameConsole::PossibleCommandsRenderCallback(const char *pStr, void *pUser) { CRenderInfo *pInfo = static_cast<CRenderInfo *>(pUser); if(pInfo->m_EnumCount == pInfo->m_WantedCompletion) { float tw = pInfo->m_pSelf->TextRender()->TextWidth(pInfo->m_Cursor.m_pFont, pInfo->m_Cursor.m_FontSize, pStr, -1); pInfo->m_pSelf->Graphics()->TextureClear(); pInfo->m_pSelf->Graphics()->QuadsBegin(); pInfo->m_pSelf->Graphics()->SetColor(229.0f/255.0f,185.0f/255.0f,4.0f/255.0f,0.85f); pInfo->m_pSelf->RenderTools()->DrawRoundRect(pInfo->m_Cursor.m_X-3, pInfo->m_Cursor.m_Y, tw+5, pInfo->m_Cursor.m_FontSize+4, pInfo->m_Cursor.m_FontSize/3); pInfo->m_pSelf->Graphics()->QuadsEnd(); // scroll when out of sight if(pInfo->m_Cursor.m_X < 3.0f) pInfo->m_Offset = 0.0f; else if(pInfo->m_Cursor.m_X+tw > pInfo->m_Width) pInfo->m_Offset -= pInfo->m_Width/2; pInfo->m_pSelf->TextRender()->TextColor(0.05f, 0.05f, 0.05f,1); pInfo->m_pSelf->TextRender()->TextEx(&pInfo->m_Cursor, pStr, -1); } else { const char *pMatchStart = str_find_nocase(pStr, pInfo->m_pCurrentCmd); if(pMatchStart) { pInfo->m_pSelf->TextRender()->TextColor(0.5f,0.5f,0.5f,1); pInfo->m_pSelf->TextRender()->TextEx(&pInfo->m_Cursor, pStr, pMatchStart-pStr); pInfo->m_pSelf->TextRender()->TextColor(229.0f/255.0f,185.0f/255.0f,4.0f/255.0f,1); pInfo->m_pSelf->TextRender()->TextEx(&pInfo->m_Cursor, pMatchStart, str_length(pInfo->m_pCurrentCmd)); pInfo->m_pSelf->TextRender()->TextColor(0.5f,0.5f,0.5f,1); pInfo->m_pSelf->TextRender()->TextEx(&pInfo->m_Cursor, pMatchStart+str_length(pInfo->m_pCurrentCmd), -1); } else { pInfo->m_pSelf->TextRender()->TextColor(0.75f,0.75f,0.75f,1); pInfo->m_pSelf->TextRender()->TextEx(&pInfo->m_Cursor, pStr, -1); } } pInfo->m_EnumCount++; pInfo->m_Cursor.m_X += 7.0f; } void CGameConsole::OnRender() { CUIRect Screen = *UI()->Screen(); float ConsoleMaxHeight = Screen.h*3/5.0f; float ConsoleHeight; float Progress = (TimeNow()-(m_StateChangeEnd-m_StateChangeDuration))/float(m_StateChangeDuration); if (Progress >= 1.0f) { if (m_ConsoleState == CONSOLE_CLOSING) m_ConsoleState = CONSOLE_CLOSED; else if (m_ConsoleState == CONSOLE_OPENING) m_ConsoleState = CONSOLE_OPEN; Progress = 1.0f; } if (m_ConsoleState == CONSOLE_OPEN && g_Config.m_ClEditor) Toggle(CONSOLETYPE_LOCAL); if (m_ConsoleState == CONSOLE_CLOSED) return; if (m_ConsoleState == CONSOLE_OPEN) Input()->MouseModeAbsolute(); float ConsoleHeightScale; if (m_ConsoleState == CONSOLE_OPENING) ConsoleHeightScale = ConsoleScaleFunc(Progress); else if (m_ConsoleState == CONSOLE_CLOSING) ConsoleHeightScale = ConsoleScaleFunc(1.0f-Progress); else //if (console_state == CONSOLE_OPEN) ConsoleHeightScale = ConsoleScaleFunc(1.0f); ConsoleHeight = ConsoleHeightScale*ConsoleMaxHeight; Graphics()->MapScreen(Screen.x, Screen.y, Screen.w, Screen.h); // do console shadow Graphics()->TextureClear(); Graphics()->QuadsBegin(); IGraphics::CColorVertex Array[4] = { IGraphics::CColorVertex(0, 0,0,0, 0.5f), IGraphics::CColorVertex(1, 0,0,0, 0.5f), IGraphics::CColorVertex(2, 0,0,0, 0.0f), IGraphics::CColorVertex(3, 0,0,0, 0.0f)}; Graphics()->SetColorVertex(Array, 4); IGraphics::CQuadItem QuadItem(0, ConsoleHeight, Screen.w, 10.0f); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); // do background Graphics()->TextureSet(g_pData->m_aImages[IMAGE_CONSOLE_BG].m_Id); Graphics()->QuadsBegin(); Graphics()->SetColor(0.2f, 0.2f, 0.2f,0.9f); if(m_ConsoleType == CONSOLETYPE_REMOTE) Graphics()->SetColor(0.4f, 0.2f, 0.2f,0.9f); Graphics()->QuadsSetSubset(0,-ConsoleHeight*0.075f,Screen.w*0.075f*0.5f,0); QuadItem = IGraphics::CQuadItem(0, 0, Screen.w, ConsoleHeight); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); // do small bar shadow Graphics()->TextureClear(); Graphics()->QuadsBegin(); Array[0] = IGraphics::CColorVertex(0, 0,0,0, 0.0f); Array[1] = IGraphics::CColorVertex(1, 0,0,0, 0.0f); Array[2] = IGraphics::CColorVertex(2, 0,0,0, 0.25f); Array[3] = IGraphics::CColorVertex(3, 0,0,0, 0.25f); Graphics()->SetColorVertex(Array, 4); QuadItem = IGraphics::CQuadItem(0, ConsoleHeight-20, Screen.w, 10); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); // do the lower bar Graphics()->TextureSet(g_pData->m_aImages[IMAGE_CONSOLE_BAR].m_Id); Graphics()->QuadsBegin(); Graphics()->SetColor(1.0f, 1.0f, 1.0f, 0.9f); Graphics()->QuadsSetSubset(0,0.1f,Screen.w*0.015f,1-0.1f); QuadItem = IGraphics::CQuadItem(0,ConsoleHeight-10.0f,Screen.w,10.0f); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); ConsoleHeight -= 22.0f; CInstance *pConsole = CurrentConsole(); { float FontSize = 10.0f; float RowHeight = FontSize*1.25f; float x = 3; float y = ConsoleHeight - RowHeight - 5.0f; CRenderInfo Info; Info.m_pSelf = this; Info.m_WantedCompletion = pConsole->m_CompletionChosen; Info.m_EnumCount = 0; Info.m_Offset = pConsole->m_CompletionRenderOffset; Info.m_Width = Screen.w; Info.m_pCurrentCmd = pConsole->m_aCompletionBuffer; TextRender()->SetCursor(&Info.m_Cursor, x+Info.m_Offset, y+RowHeight+2.0f, FontSize, TEXTFLAG_RENDER); // render prompt CTextCursor Cursor; TextRender()->SetCursor(&Cursor, x, y, FontSize, TEXTFLAG_RENDER); const char *pPrompt = "> "; if(m_ConsoleType == CONSOLETYPE_REMOTE) { if(Client()->State() == IClient::STATE_ONLINE) { if(Client()->RconAuthed()) pPrompt = "rcon> "; else pPrompt = "ENTER PASSWORD> "; } else pPrompt = "NOT CONNECTED> "; } TextRender()->TextEx(&Cursor, pPrompt, -1); x = Cursor.m_X; //hide rcon password char aInputString[256]; str_copy(aInputString, pConsole->m_Input.GetString(), sizeof(aInputString)); if(m_ConsoleType == CONSOLETYPE_REMOTE && Client()->State() == IClient::STATE_ONLINE && !Client()->RconAuthed()) { for(int i = 0; i < pConsole->m_Input.GetLength(); ++i) aInputString[i] = '*'; } // render console input (wrap line) TextRender()->SetCursor(&Cursor, x, y, FontSize, 0); Cursor.m_LineWidth = Screen.w - 10.0f - x; TextRender()->TextEx(&Cursor, aInputString, pConsole->m_Input.GetCursorOffset()); TextRender()->TextEx(&Cursor, aInputString+pConsole->m_Input.GetCursorOffset(), -1); int Lines = Cursor.m_LineCount; y -= (Lines - 1) * FontSize; TextRender()->SetCursor(&Cursor, x, y, FontSize, TEXTFLAG_RENDER); Cursor.m_LineWidth = Screen.w - 10.0f - x; TextRender()->TextEx(&Cursor, aInputString, pConsole->m_Input.GetCursorOffset()); static float MarkerOffset = TextRender()->TextWidth(0, FontSize, "|", -1)/3; CTextCursor Marker = Cursor; Marker.m_X -= MarkerOffset; Marker.m_LineWidth = -1; TextRender()->TextEx(&Marker, "|", -1); TextRender()->TextEx(&Cursor, aInputString+pConsole->m_Input.GetCursorOffset(), -1); // render possible commands if(m_ConsoleType == CONSOLETYPE_LOCAL || Client()->RconAuthed()) { if(pConsole->m_Input.GetString()[0] != 0) { m_pConsole->PossibleCommands(pConsole->m_aCompletionBuffer, pConsole->m_CompletionFlagmask, m_ConsoleType != CGameConsole::CONSOLETYPE_LOCAL && Client()->RconAuthed() && Client()->UseTempRconCommands(), PossibleCommandsRenderCallback, &Info); pConsole->m_CompletionRenderOffset = Info.m_Offset; if(Info.m_EnumCount <= 0) { if(pConsole->m_IsCommand) { char aBuf[512]; str_format(aBuf, sizeof(aBuf), "Help: %s ", pConsole->m_aCommandHelp); TextRender()->TextEx(&Info.m_Cursor, aBuf, -1); TextRender()->TextColor(0.75f, 0.75f, 0.75f, 1); str_format(aBuf, sizeof(aBuf), "Syntax: %s %s", pConsole->m_aCommandName, pConsole->m_aCommandParams); TextRender()->TextEx(&Info.m_Cursor, aBuf, -1); } } } } TextRender()->TextColor(1,1,1,1); // render log (actual page, wrap lines) CInstance::CBacklogEntry *pEntry = pConsole->m_Backlog.Last(); float OffsetY = 0.0f; float LineOffset = 1.0f; for(int Page = 0; Page <= pConsole->m_BacklogActPage; ++Page, OffsetY = 0.0f) { while(pEntry) { // get y offset (calculate it if we haven't yet) if(pEntry->m_YOffset < 0.0f) { TextRender()->SetCursor(&Cursor, 0.0f, 0.0f, FontSize, 0); Cursor.m_LineWidth = Screen.w-10; TextRender()->TextEx(&Cursor, pEntry->m_aText, -1); pEntry->m_YOffset = Cursor.m_Y+Cursor.m_FontSize+LineOffset; } OffsetY += pEntry->m_YOffset; // next page when lines reach the top if(y-OffsetY <= RowHeight) break; // just render output from actual backlog page (render bottom up) if(Page == pConsole->m_BacklogActPage) { TextRender()->SetCursor(&Cursor, 0.0f, y-OffsetY, FontSize, TEXTFLAG_RENDER); Cursor.m_LineWidth = Screen.w-10.0f; TextRender()->TextEx(&Cursor, pEntry->m_aText, -1); } pEntry = pConsole->m_Backlog.Prev(pEntry); } // actual backlog page number is too high, render last available page (current checked one, render top down) if(!pEntry && Page < pConsole->m_BacklogActPage) { pConsole->m_BacklogActPage = Page; pEntry = pConsole->m_Backlog.First(); while(OffsetY > 0.0f && pEntry) { TextRender()->SetCursor(&Cursor, 0.0f, y-OffsetY, FontSize, TEXTFLAG_RENDER); Cursor.m_LineWidth = Screen.w-10.0f; TextRender()->TextEx(&Cursor, pEntry->m_aText, -1); OffsetY -= pEntry->m_YOffset; pEntry = pConsole->m_Backlog.Next(pEntry); } break; } } // render page char aBuf[128]; str_format(aBuf, sizeof(aBuf), Localize("-Page %d-"), pConsole->m_BacklogActPage+1); TextRender()->Text(0, 10.0f, 0.0f, FontSize, aBuf, -1); // render version str_format(aBuf, sizeof(aBuf), "v%s", GAME_VERSION); float Width = TextRender()->TextWidth(0, FontSize, aBuf, -1); TextRender()->Text(0, Screen.w-Width-10.0f, 0.0f, FontSize, aBuf, -1); } } void CGameConsole::OnMessage(int MsgType, void *pRawMsg) { } bool CGameConsole::OnInput(IInput::CEvent Event) { if(m_ConsoleState == CONSOLE_CLOSED) return false; if(Event.m_Key >= KEY_F1 && Event.m_Key <= KEY_F15) return false; if(Event.m_Key == KEY_ESCAPE && (Event.m_Flags&IInput::FLAG_PRESS)) Toggle(m_ConsoleType); else CurrentConsole()->OnInput(Event); return true; } void CGameConsole::Toggle(int Type) { if(m_ConsoleType != Type && (m_ConsoleState == CONSOLE_OPEN || m_ConsoleState == CONSOLE_OPENING)) { // don't toggle console, just switch what console to use } else { if (m_ConsoleState == CONSOLE_CLOSED || m_ConsoleState == CONSOLE_OPEN) { m_StateChangeEnd = TimeNow()+m_StateChangeDuration; } else { float Progress = m_StateChangeEnd-TimeNow(); float ReversedProgress = m_StateChangeDuration-Progress; m_StateChangeEnd = TimeNow()+ReversedProgress; } if (m_ConsoleState == CONSOLE_CLOSED || m_ConsoleState == CONSOLE_CLOSING) { Input()->MouseModeAbsolute(); m_pClient->m_pMenus->UseMouseButtons(false); m_ConsoleState = CONSOLE_OPENING; // reset controls m_pClient->m_pControls->OnReset(); } else { Input()->MouseModeRelative(); m_pClient->m_pMenus->UseMouseButtons(true); m_pClient->OnRelease(); m_ConsoleState = CONSOLE_CLOSING; } } m_ConsoleType = Type; } void CGameConsole::Dump(int Type) { CInstance *pConsole = Type == CONSOLETYPE_REMOTE ? &m_RemoteConsole : &m_LocalConsole; char aFilename[128]; char aDate[20]; str_timestamp(aDate, sizeof(aDate)); str_format(aFilename, sizeof(aFilename), "dumps/%s_dump_%s.txt", Type==CONSOLETYPE_REMOTE?"remote_console":"local_console", aDate); IOHANDLE io = Storage()->OpenFile(aFilename, IOFLAG_WRITE, IStorage::TYPE_SAVE); if(io) { for(CInstance::CBacklogEntry *pEntry = pConsole->m_Backlog.First(); pEntry; pEntry = pConsole->m_Backlog.Next(pEntry)) { io_write(io, pEntry->m_aText, str_length(pEntry->m_aText)); io_write_newline(io); } io_close(io); } } void CGameConsole::ConToggleLocalConsole(IConsole::IResult *pResult, void *pUserData) { ((CGameConsole *)pUserData)->Toggle(CONSOLETYPE_LOCAL); } void CGameConsole::ConToggleRemoteConsole(IConsole::IResult *pResult, void *pUserData) { ((CGameConsole *)pUserData)->Toggle(CONSOLETYPE_REMOTE); } void CGameConsole::ConClearLocalConsole(IConsole::IResult *pResult, void *pUserData) { ((CGameConsole *)pUserData)->m_LocalConsole.ClearBacklog(); } void CGameConsole::ConClearRemoteConsole(IConsole::IResult *pResult, void *pUserData) { ((CGameConsole *)pUserData)->m_RemoteConsole.ClearBacklog(); } void CGameConsole::ConDumpLocalConsole(IConsole::IResult *pResult, void *pUserData) { ((CGameConsole *)pUserData)->Dump(CONSOLETYPE_LOCAL); } void CGameConsole::ConDumpRemoteConsole(IConsole::IResult *pResult, void *pUserData) { ((CGameConsole *)pUserData)->Dump(CONSOLETYPE_REMOTE); } void CGameConsole::ClientConsolePrintCallback(const char *pStr, void *pUserData) { ((CGameConsole *)pUserData)->m_LocalConsole.PrintLine(pStr); } void CGameConsole::ConchainConsoleOutputLevelUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData) { pfnCallback(pResult, pCallbackUserData); if(pResult->NumArguments() == 1) { CGameConsole *pThis = static_cast<CGameConsole *>(pUserData); pThis->Console()->SetPrintOutputLevel(pThis->m_PrintCBIndex, pResult->GetInteger(0)); } } void CGameConsole::PrintLine(int Type, const char *pLine) { if(Type == CONSOLETYPE_LOCAL) m_LocalConsole.PrintLine(pLine); else if(Type == CONSOLETYPE_REMOTE) m_RemoteConsole.PrintLine(pLine); } void CGameConsole::OnConsoleInit() { // init console instances m_LocalConsole.Init(this); m_RemoteConsole.Init(this); m_pConsole = Kernel()->RequestInterface<IConsole>(); // m_PrintCBIndex = Console()->RegisterPrintCallback(g_Config.m_ConsoleOutputLevel, ClientConsolePrintCallback, this); Console()->Register("toggle_local_console", "", CFGFLAG_CLIENT, ConToggleLocalConsole, this, "Toggle local console"); Console()->Register("toggle_remote_console", "", CFGFLAG_CLIENT, ConToggleRemoteConsole, this, "Toggle remote console"); Console()->Register("clear_local_console", "", CFGFLAG_CLIENT, ConClearLocalConsole, this, "Clear local console"); Console()->Register("clear_remote_console", "", CFGFLAG_CLIENT, ConClearRemoteConsole, this, "Clear remote console"); Console()->Register("dump_local_console", "", CFGFLAG_CLIENT, ConDumpLocalConsole, this, "Dump local console"); Console()->Register("dump_remote_console", "", CFGFLAG_CLIENT, ConDumpRemoteConsole, this, "Dump remote console"); Console()->Chain("console_output_level", ConchainConsoleOutputLevelUpdate, this); } void CGameConsole::OnStateChange(int NewState, int OldState) { if(NewState == IClient::STATE_OFFLINE) m_RemoteConsole.ClearHistory(); } ================================================ FILE: src/game/client/components/console.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_CLIENT_COMPONENTS_CONSOLE_H #define GAME_CLIENT_COMPONENTS_CONSOLE_H #include <engine/shared/ringbuffer.h> #include <game/client/component.h> #include <game/client/lineinput.h> class CGameConsole : public CComponent { class CInstance { public: struct CBacklogEntry { float m_YOffset; char m_aText[1]; }; TStaticRingBuffer<CBacklogEntry, 64*1024, CRingBufferBase::FLAG_RECYCLE> m_Backlog; TStaticRingBuffer<char, 64*1024, CRingBufferBase::FLAG_RECYCLE> m_History; char *m_pHistoryEntry; CLineInput m_Input; int m_Type; int m_CompletionEnumerationCount; int m_BacklogActPage; public: CGameConsole *m_pGameConsole; char m_aCompletionBuffer[128]; int m_CompletionChosen; int m_CompletionFlagmask; float m_CompletionRenderOffset; bool m_IsCommand; char m_aCommandName[IConsole::TEMPCMD_NAME_LENGTH]; char m_aCommandHelp[IConsole::TEMPCMD_HELP_LENGTH]; char m_aCommandParams[IConsole::TEMPCMD_PARAMS_LENGTH]; CInstance(int t); void Init(CGameConsole *pGameConsole); void ClearBacklog(); void ClearHistory(); void ExecuteLine(const char *pLine); void OnInput(IInput::CEvent Event); void PrintLine(const char *pLine); const char *GetString() const { return m_Input.GetString(); } static void PossibleCommandsCompleteCallback(const char *pStr, void *pUser); }; class IConsole *m_pConsole; CInstance m_LocalConsole; CInstance m_RemoteConsole; CInstance *CurrentConsole(); float TimeNow(); int m_PrintCBIndex; int m_ConsoleType; int m_ConsoleState; float m_StateChangeEnd; float m_StateChangeDuration; void Toggle(int Type); void Dump(int Type); static void PossibleCommandsRenderCallback(const char *pStr, void *pUser); static void ClientConsolePrintCallback(const char *pStr, void *pUserData); static void ConToggleLocalConsole(IConsole::IResult *pResult, void *pUserData); static void ConToggleRemoteConsole(IConsole::IResult *pResult, void *pUserData); static void ConClearLocalConsole(IConsole::IResult *pResult, void *pUserData); static void ConClearRemoteConsole(IConsole::IResult *pResult, void *pUserData); static void ConDumpLocalConsole(IConsole::IResult *pResult, void *pUserData); static void ConDumpRemoteConsole(IConsole::IResult *pResult, void *pUserData); static void ConchainConsoleOutputLevelUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData); public: enum { CONSOLETYPE_LOCAL=0, CONSOLETYPE_REMOTE, }; CGameConsole(); void PrintLine(int Type, const char *pLine); virtual void OnStateChange(int NewState, int OldState); virtual void OnConsoleInit(); virtual void OnReset(); virtual void OnRender(); virtual void OnMessage(int MsgType, void *pRawMsg); virtual bool OnInput(IInput::CEvent Events); }; #endif ================================================ FILE: src/game/client/components/controls.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <base/math.h> #include <engine/shared/config.h> #include <game/collision.h> #include <game/client/gameclient.h> #include <game/client/component.h> #include <game/client/components/chat.h> #include <game/client/components/menus.h> #include <game/client/components/scoreboard.h> #include "controls.h" CControls::CControls() { mem_zero(&m_LastData, sizeof(m_LastData)); } void CControls::OnReset() { m_LastData.m_Direction = 0; m_LastData.m_Hook = 0; // simulate releasing the fire button if((m_LastData.m_Fire&1) != 0) m_LastData.m_Fire++; m_LastData.m_Fire &= INPUT_STATE_MASK; m_LastData.m_Jump = 0; m_InputData = m_LastData; m_InputDirectionLeft = 0; m_InputDirectionRight = 0; } void CControls::OnRelease() { OnReset(); } void CControls::OnPlayerDeath() { m_LastData.m_WantedWeapon = m_InputData.m_WantedWeapon = 0; } static void ConKeyInputState(IConsole::IResult *pResult, void *pUserData) { ((int *)pUserData)[0] = pResult->GetInteger(0); } static void ConKeyInputCounter(IConsole::IResult *pResult, void *pUserData) { int *v = (int *)pUserData; if(((*v)&1) != pResult->GetInteger(0)) (*v)++; *v &= INPUT_STATE_MASK; } struct CInputSet { CControls *m_pControls; int *m_pVariable; int m_Value; }; static void ConKeyInputSet(IConsole::IResult *pResult, void *pUserData) { CInputSet *pSet = (CInputSet *)pUserData; if(pResult->GetInteger(0)) *pSet->m_pVariable = pSet->m_Value; } static void ConKeyInputNextPrevWeapon(IConsole::IResult *pResult, void *pUserData) { CInputSet *pSet = (CInputSet *)pUserData; ConKeyInputCounter(pResult, pSet->m_pVariable); pSet->m_pControls->m_InputData.m_WantedWeapon = 0; } void CControls::OnConsoleInit() { // game commands Console()->Register("+left", "", CFGFLAG_CLIENT, ConKeyInputState, &m_InputDirectionLeft, "Move left"); Console()->Register("+right", "", CFGFLAG_CLIENT, ConKeyInputState, &m_InputDirectionRight, "Move right"); Console()->Register("+jump", "", CFGFLAG_CLIENT, ConKeyInputState, &m_InputData.m_Jump, "Jump"); Console()->Register("+hook", "", CFGFLAG_CLIENT, ConKeyInputState, &m_InputData.m_Hook, "Hook"); Console()->Register("+fire", "", CFGFLAG_CLIENT, ConKeyInputCounter, &m_InputData.m_Fire, "Fire"); { static CInputSet s_Set = {this, &m_InputData.m_WantedWeapon, 1}; Console()->Register("+weapon1", "", CFGFLAG_CLIENT, ConKeyInputSet, (void *)&s_Set, "Switch to hammer"); } { static CInputSet s_Set = {this, &m_InputData.m_WantedWeapon, 2}; Console()->Register("+weapon2", "", CFGFLAG_CLIENT, ConKeyInputSet, (void *)&s_Set, "Switch to gun"); } { static CInputSet s_Set = {this, &m_InputData.m_WantedWeapon, 3}; Console()->Register("+weapon3", "", CFGFLAG_CLIENT, ConKeyInputSet, (void *)&s_Set, "Switch to shotgun"); } { static CInputSet s_Set = {this, &m_InputData.m_WantedWeapon, 4}; Console()->Register("+weapon4", "", CFGFLAG_CLIENT, ConKeyInputSet, (void *)&s_Set, "Switch to grenade"); } { static CInputSet s_Set = {this, &m_InputData.m_WantedWeapon, 5}; Console()->Register("+weapon5", "", CFGFLAG_CLIENT, ConKeyInputSet, (void *)&s_Set, "Switch to laser"); } { static CInputSet s_Set = {this, &m_InputData.m_NextWeapon, 0}; Console()->Register("+nextweapon", "", CFGFLAG_CLIENT, ConKeyInputNextPrevWeapon, (void *)&s_Set, "Switch to next weapon"); } { static CInputSet s_Set = {this, &m_InputData.m_PrevWeapon, 0}; Console()->Register("+prevweapon", "", CFGFLAG_CLIENT, ConKeyInputNextPrevWeapon, (void *)&s_Set, "Switch to previous weapon"); } } void CControls::OnMessage(int Msg, void *pRawMsg) { if(Msg == NETMSGTYPE_SV_WEAPONPICKUP) { CNetMsg_Sv_WeaponPickup *pMsg = (CNetMsg_Sv_WeaponPickup *)pRawMsg; if(g_Config.m_ClAutoswitchWeapons) m_InputData.m_WantedWeapon = pMsg->m_Weapon+1; } } int CControls::SnapInput(int *pData) { static int64 LastSendTime = 0; bool Send = false; // update player state if(m_pClient->m_pChat->IsActive()) m_InputData.m_PlayerFlags = PLAYERFLAG_CHATTING; else m_InputData.m_PlayerFlags = 0; if(m_pClient->m_pScoreboard->Active()) m_InputData.m_PlayerFlags |= PLAYERFLAG_SCOREBOARD; if(m_LastData.m_PlayerFlags != m_InputData.m_PlayerFlags) Send = true; m_LastData.m_PlayerFlags = m_InputData.m_PlayerFlags; // we freeze the input if chat or menu is activated if(m_pClient->m_pChat->IsActive() || m_pClient->m_pMenus->IsActive()) { OnReset(); mem_copy(pData, &m_InputData, sizeof(m_InputData)); // send once a second just to be sure if(time_get() > LastSendTime + time_freq()) Send = true; } else { m_InputData.m_TargetX = (int)m_MousePos.x; m_InputData.m_TargetY = (int)m_MousePos.y; if(!m_InputData.m_TargetX && !m_InputData.m_TargetY) { m_InputData.m_TargetX = 1; m_MousePos.x = 1; } // set direction m_InputData.m_Direction = 0; if(m_InputDirectionLeft && !m_InputDirectionRight) m_InputData.m_Direction = -1; if(!m_InputDirectionLeft && m_InputDirectionRight) m_InputData.m_Direction = 1; // stress testing if(g_Config.m_DbgStress) { float t = Client()->LocalTime(); mem_zero(&m_InputData, sizeof(m_InputData)); m_InputData.m_Direction = ((int)t/2)%3-1; m_InputData.m_Jump = ((int)t)&1; m_InputData.m_Fire = ((int)(t*10)); m_InputData.m_Hook = ((int)(t*2))&1; m_InputData.m_WantedWeapon = ((int)t)%NUM_WEAPONS; m_InputData.m_TargetX = (int)(sinf(t*3)*100.0f); m_InputData.m_TargetY = (int)(cosf(t*3)*100.0f); } // check if we need to send input if(m_InputData.m_Direction != m_LastData.m_Direction) Send = true; else if(m_InputData.m_Jump != m_LastData.m_Jump) Send = true; else if(m_InputData.m_Fire != m_LastData.m_Fire) Send = true; else if(m_InputData.m_Hook != m_LastData.m_Hook) Send = true; else if(m_InputData.m_WantedWeapon != m_LastData.m_WantedWeapon) Send = true; else if(m_InputData.m_NextWeapon != m_LastData.m_NextWeapon) Send = true; else if(m_InputData.m_PrevWeapon != m_LastData.m_PrevWeapon) Send = true; // send at at least 10hz if(time_get() > LastSendTime + time_freq()/25) Send = true; } // copy and return size m_LastData = m_InputData; if(!Send) return 0; LastSendTime = time_get(); mem_copy(pData, &m_InputData, sizeof(m_InputData)); return sizeof(m_InputData); } void CControls::OnRender() { // update target pos if(m_pClient->m_Snap.m_pGameData && !m_pClient->m_Snap.m_SpecInfo.m_Active) m_TargetPos = m_pClient->m_LocalCharacterPos + m_MousePos; else if(m_pClient->m_Snap.m_SpecInfo.m_Active && m_pClient->m_Snap.m_SpecInfo.m_UsePosition) m_TargetPos = m_pClient->m_Snap.m_SpecInfo.m_Position + m_MousePos; else m_TargetPos = m_MousePos; } bool CControls::OnMouseMove(float x, float y) { if((m_pClient->m_Snap.m_pGameData && m_pClient->m_Snap.m_pGameData->m_GameStateFlags&(GAMESTATEFLAG_PAUSED|GAMESTATEFLAG_ROUNDOVER|GAMESTATEFLAG_GAMEOVER)) || (m_pClient->m_Snap.m_SpecInfo.m_Active && m_pClient->m_pChat->IsActive())) return false; m_MousePos += vec2(x, y); // TODO: ugly ClampMousePos(); return true; } void CControls::ClampMousePos() { if(m_pClient->m_Snap.m_SpecInfo.m_Active && !m_pClient->m_Snap.m_SpecInfo.m_UsePosition) { m_MousePos.x = clamp(m_MousePos.x, 200.0f, Collision()->GetWidth()*32-200.0f); m_MousePos.y = clamp(m_MousePos.y, 200.0f, Collision()->GetHeight()*32-200.0f); } else { float CameraMaxDistance = 200.0f; float FollowFactor = g_Config.m_ClMouseFollowfactor/100.0f; float MouseMax = min(CameraMaxDistance/FollowFactor + g_Config.m_ClMouseDeadzone, (float)g_Config.m_ClMouseMaxDistance); if(length(m_MousePos) > MouseMax) m_MousePos = normalize(m_MousePos)*MouseMax; } } ================================================ FILE: src/game/client/components/controls.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_CLIENT_COMPONENTS_CONTROLS_H #define GAME_CLIENT_COMPONENTS_CONTROLS_H #include <base/vmath.h> #include <game/client/component.h> class CControls : public CComponent { public: vec2 m_MousePos; vec2 m_TargetPos; CNetObj_PlayerInput m_InputData; CNetObj_PlayerInput m_LastData; int m_InputDirectionLeft; int m_InputDirectionRight; CControls(); virtual void OnReset(); virtual void OnRelease(); virtual void OnRender(); virtual void OnMessage(int MsgType, void *pRawMsg); virtual bool OnMouseMove(float x, float y); virtual void OnConsoleInit(); virtual void OnPlayerDeath(); int SnapInput(int *pData); void ClampMousePos(); }; #endif ================================================ FILE: src/game/client/components/countryflags.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <base/math.h> #include <base/system.h> #include <engine/console.h> #include <engine/graphics.h> #include <engine/storage.h> #include <engine/textrender.h> #include <engine/external/json-parser/json.h> #include <engine/shared/config.h> #include "countryflags.h" void CCountryFlags::LoadCountryflagsIndexfile() { // read file data into buffer const char *pFilename = "countryflags/index.json"; IOHANDLE File = Storage()->OpenFile(pFilename, IOFLAG_READ, IStorage::TYPE_ALL); if(!File) { Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "countryflags", "couldn't open index file"); return; } int FileSize = (int)io_length(File); char *pFileData = (char *)mem_alloc(FileSize+1, 1); io_read(File, pFileData, FileSize); pFileData[FileSize] = 0; io_close(File); // parse json data json_settings JsonSettings; mem_zero(&JsonSettings, sizeof(JsonSettings)); char aError[256]; json_value *pJsonData = json_parse_ex(&JsonSettings, pFileData, aError); if(pJsonData == 0) { Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, pFilename, aError); mem_free(pFileData); return; } // extract data const json_value &rInit = (*pJsonData)["country codes"]; if(rInit.type == json_object) { enum { NUM_INDICES = 2, }; const char *paIndices[NUM_INDICES] = {"custom", "ISO 3166-1"}; for(int Index = 0; Index < NUM_INDICES; ++Index) { const json_value &rStart = rInit[(const char *)paIndices[Index]]; if(rStart.type == json_array) { for(unsigned i = 0; i < rStart.u.array.length; ++i) { char aBuf[64]; // validate country code int CountryCode = (long)rStart[i]["code"]; if(CountryCode < CODE_LB || CountryCode > CODE_UB) { str_format(aBuf, sizeof(aBuf), "country code '%i' not within valid code range [%i..%i]", CountryCode, CODE_LB, CODE_UB); Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "countryflags", aBuf); continue; } // add entry const char *pCountryName = rStart[i]["id"]; CCountryFlag CountryFlag; CountryFlag.m_CountryCode = CountryCode; str_copy(CountryFlag.m_aCountryCodeString, pCountryName, sizeof(CountryFlag.m_aCountryCodeString)); if(g_Config.m_ClLoadCountryFlags) { // load the graphic file CImageInfo Info; str_format(aBuf, sizeof(aBuf), "countryflags/%s.png", pCountryName); if(!Graphics()->LoadPNG(&Info, aBuf, IStorage::TYPE_ALL)) { char aMsg[64]; str_format(aMsg, sizeof(aMsg), "failed to load '%s'", aBuf); Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "countryflags", aMsg); continue; } CountryFlag.m_Texture = Graphics()->LoadTextureRaw(Info.m_Width, Info.m_Height, Info.m_Format, Info.m_pData, Info.m_Format, 0); mem_free(Info.m_pData); } m_aCountryFlags.add_unsorted(CountryFlag); // print message if(g_Config.m_Debug) { str_format(aBuf, sizeof(aBuf), "loaded country flag '%s'", pCountryName); Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "countryflags", aBuf); } } } } } // clean up json_value_free(pJsonData); mem_free(pFileData); m_aCountryFlags.sort_range(); // find index of default item int DefaultIndex = 0, Index = 0; for(sorted_array<CCountryFlag>::range r = m_aCountryFlags.all(); !r.empty(); r.pop_front(), ++Index) if(r.front().m_CountryCode == -1) { DefaultIndex = Index; break; } // init LUT if(DefaultIndex != 0) for(int i = 0; i < CODE_RANGE; ++i) m_CodeIndexLUT[i] = DefaultIndex; else mem_zero(m_CodeIndexLUT, sizeof(m_CodeIndexLUT)); for(int i = 0; i < m_aCountryFlags.size(); ++i) m_CodeIndexLUT[max(0, (m_aCountryFlags[i].m_CountryCode-CODE_LB)%CODE_RANGE)] = i; } void CCountryFlags::OnInit() { // load country flags m_aCountryFlags.clear(); LoadCountryflagsIndexfile(); if(!m_aCountryFlags.size()) { Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "countryflags", "failed to load country flags. folder='countryflags/'"); CCountryFlag DummyEntry; DummyEntry.m_CountryCode = -1; mem_zero(DummyEntry.m_aCountryCodeString, sizeof(DummyEntry.m_aCountryCodeString)); m_aCountryFlags.add(DummyEntry); } } int CCountryFlags::Num() const { return m_aCountryFlags.size(); } const CCountryFlags::CCountryFlag *CCountryFlags::GetByCountryCode(int CountryCode) const { return GetByIndex(m_CodeIndexLUT[max(0, (CountryCode-CODE_LB)%CODE_RANGE)]); } const CCountryFlags::CCountryFlag *CCountryFlags::GetByIndex(int Index) const { return &m_aCountryFlags[max(0, Index%m_aCountryFlags.size())]; } void CCountryFlags::Render(int CountryCode, const vec4 *pColor, float x, float y, float w, float h) { const CCountryFlag *pFlag = GetByCountryCode(CountryCode); if(pFlag->m_Texture.IsValid()) { Graphics()->TextureSet(pFlag->m_Texture); Graphics()->QuadsBegin(); Graphics()->SetColor(pColor->r, pColor->g, pColor->b, pColor->a); IGraphics::CQuadItem QuadItem(x, y, w, h); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); } else { CTextCursor Cursor; TextRender()->SetCursor(&Cursor, x, y, 10.0f, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); Cursor.m_LineWidth = w; TextRender()->TextEx(&Cursor, pFlag->m_aCountryCodeString, -1); } } ================================================ FILE: src/game/client/components/countryflags.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_CLIENT_COMPONENTS_COUNTRYFLAGS_H #define GAME_CLIENT_COMPONENTS_COUNTRYFLAGS_H #include <base/vmath.h> #include <base/tl/sorted_array.h> #include <game/client/component.h> class CCountryFlags : public CComponent { public: struct CCountryFlag { int m_CountryCode; char m_aCountryCodeString[8]; IGraphics::CTextureHandle m_Texture; bool operator<(const CCountryFlag &Other) { return str_comp(m_aCountryCodeString, Other.m_aCountryCodeString) < 0; } }; void OnInit(); int Num() const; const CCountryFlag *GetByCountryCode(int CountryCode) const; const CCountryFlag *GetByIndex(int Index) const; void Render(int CountryCode, const vec4 *pColor, float x, float y, float w, float h); private: enum { CODE_LB=-1, CODE_UB=999, CODE_RANGE=CODE_UB-CODE_LB+1, }; sorted_array<CCountryFlag> m_aCountryFlags; int m_CodeIndexLUT[CODE_RANGE]; void LoadCountryflagsIndexfile(); }; #endif ================================================ FILE: src/game/client/components/damageind.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <engine/demo.h> #include <engine/graphics.h> #include <game/generated/protocol.h> #include <game/generated/client_data.h> #include <game/gamecore.h> // get_angle #include <game/client/ui.h> #include <game/client/render.h> #include "damageind.h" CDamageInd::CDamageInd() { m_NumItems = 0; } CDamageInd::CItem *CDamageInd::CreateI() { if (m_NumItems < MAX_ITEMS) { CItem *p = &m_aItems[m_NumItems]; m_NumItems++; return p; } return 0; } void CDamageInd::DestroyI(CDamageInd::CItem *i) { m_NumItems--; *i = m_aItems[m_NumItems]; } void CDamageInd::Create(vec2 Pos, vec2 Dir) { CItem *i = CreateI(); if (i) { i->m_Pos = Pos; i->m_StartTime = Client()->LocalTime(); i->m_Dir = Dir*-1; i->m_StartAngle = (( (float)rand()/(float)RAND_MAX) - 1.0f) * 2.0f * pi; } } void CDamageInd::OnRender() { Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id); Graphics()->QuadsBegin(); static float s_LastLocalTime = Client()->LocalTime(); for(int i = 0; i < m_NumItems;) { if(Client()->State() == IClient::STATE_DEMOPLAYBACK) { const IDemoPlayer::CInfo *pInfo = DemoPlayer()->BaseInfo(); if(pInfo->m_Paused) m_aItems[i].m_StartTime += Client()->LocalTime()-s_LastLocalTime; else m_aItems[i].m_StartTime += (Client()->LocalTime()-s_LastLocalTime)*(1.0f-pInfo->m_Speed); } else { if(m_pClient->m_Snap.m_pGameData && m_pClient->m_Snap.m_pGameData->m_GameStateFlags&GAMESTATEFLAG_PAUSED) m_aItems[i].m_StartTime += Client()->LocalTime()-s_LastLocalTime; } float Life = 0.75f - (Client()->LocalTime() - m_aItems[i].m_StartTime); if(Life < 0.0f) DestroyI(&m_aItems[i]); else { vec2 Pos = mix(m_aItems[i].m_Pos+m_aItems[i].m_Dir*75.0f, m_aItems[i].m_Pos, clamp((Life-0.60f)/0.15f, 0.0f, 1.0f)); Graphics()->SetColor(1.0f,1.0f,1.0f, Life/0.1f); Graphics()->QuadsSetRotation(m_aItems[i].m_StartAngle + Life * 2.0f); RenderTools()->SelectSprite(SPRITE_STAR1); RenderTools()->DrawSprite(Pos.x, Pos.y, 48.0f); i++; } } s_LastLocalTime = Client()->LocalTime(); Graphics()->QuadsEnd(); } void CDamageInd::OnReset() { m_NumItems = 0; } ================================================ FILE: src/game/client/components/damageind.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_CLIENT_COMPONENTS_DAMAGEIND_H #define GAME_CLIENT_COMPONENTS_DAMAGEIND_H #include <base/vmath.h> #include <game/client/component.h> class CDamageInd : public CComponent { struct CItem { vec2 m_Pos; vec2 m_Dir; float m_StartTime; float m_StartAngle; }; enum { MAX_ITEMS=64, }; CItem m_aItems[MAX_ITEMS]; int m_NumItems; CItem *CreateI(); void DestroyI(CItem *i); public: CDamageInd(); void Create(vec2 Pos, vec2 Dir); virtual void OnRender(); virtual void OnReset(); }; #endif ================================================ FILE: src/game/client/components/debughud.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <engine/shared/config.h> #include <engine/graphics.h> #include <engine/textrender.h> #include <game/generated/protocol.h> #include <game/generated/client_data.h> #include <game/layers.h> #include <game/client/gameclient.h> #include <game/client/animstate.h> #include <game/client/render.h> //#include "controls.h" //#include "camera.h" #include "debughud.h" void CDebugHud::RenderNetCorrections() { if(!g_Config.m_Debug || g_Config.m_DbgGraphs || !m_pClient->m_Snap.m_pLocalCharacter || !m_pClient->m_Snap.m_pLocalPrevCharacter) return; float Width = 300*Graphics()->ScreenAspect(); Graphics()->MapScreen(0, 0, Width, 300); /*float speed = distance(vec2(netobjects.local_prev_character->x, netobjects.local_prev_character->y), vec2(netobjects.local_character->x, netobjects.local_character->y));*/ float Velspeed = length(vec2(m_pClient->m_Snap.m_pLocalCharacter->m_VelX/256.0f, m_pClient->m_Snap.m_pLocalCharacter->m_VelY/256.0f))*50; float Ramp = VelocityRamp(Velspeed, m_pClient->m_Tuning.m_VelrampStart, m_pClient->m_Tuning.m_VelrampRange, m_pClient->m_Tuning.m_VelrampCurvature); const char *paStrings[] = {"velspeed:", "velspeed*ramp:", "ramp:", "Pos", " x:", " y:", "netobj corrections", " num:", " on:"}; const int Num = sizeof(paStrings)/sizeof(char *); const float LineHeight = 6.0f; const float Fontsize = 5.0f; float x = Width-100.0f, y = 50.0f; for(int i = 0; i < Num; ++i) TextRender()->Text(0, x, y+i*LineHeight, Fontsize, paStrings[i], -1); x = Width-10.0f; char aBuf[128]; str_format(aBuf, sizeof(aBuf), "%.0f", Velspeed/32); float w = TextRender()->TextWidth(0, Fontsize, aBuf, -1); TextRender()->Text(0, x-w, y, Fontsize, aBuf, -1); y += LineHeight; str_format(aBuf, sizeof(aBuf), "%.0f", Velspeed/32*Ramp); w = TextRender()->TextWidth(0, Fontsize, aBuf, -1); TextRender()->Text(0, x-w, y, Fontsize, aBuf, -1); y += LineHeight; str_format(aBuf, sizeof(aBuf), "%.2f", Ramp); w = TextRender()->TextWidth(0, Fontsize, aBuf, -1); TextRender()->Text(0, x-w, y, Fontsize, aBuf, -1); y += 2*LineHeight; str_format(aBuf, sizeof(aBuf), "%d", m_pClient->m_Snap.m_pLocalCharacter->m_X/32); w = TextRender()->TextWidth(0, Fontsize, aBuf, -1); TextRender()->Text(0, x-w, y, Fontsize, aBuf, -1); y += LineHeight; str_format(aBuf, sizeof(aBuf), "%d", m_pClient->m_Snap.m_pLocalCharacter->m_Y/32); w = TextRender()->TextWidth(0, Fontsize, aBuf, -1); TextRender()->Text(0, x-w, y, Fontsize, aBuf, -1); y += 2*LineHeight; str_format(aBuf, sizeof(aBuf), "%d", m_pClient->NetobjNumCorrections()); w = TextRender()->TextWidth(0, Fontsize, aBuf, -1); TextRender()->Text(0, x-w, y, Fontsize, aBuf, -1); y += LineHeight; w = TextRender()->TextWidth(0, Fontsize, m_pClient->NetobjCorrectedOn(), -1); TextRender()->Text(0, x-w, y, Fontsize, m_pClient->NetobjCorrectedOn(), -1); } void CDebugHud::RenderTuning() { // render tuning debugging if(!g_Config.m_DbgTuning) return; CTuningParams StandardTuning; Graphics()->MapScreen(0, 0, 300*Graphics()->ScreenAspect(), 300); float y = 50.0f; int Count = 0; for(int i = 0; i < m_pClient->m_Tuning.Num(); i++) { char aBuf[128]; float Current, Standard; m_pClient->m_Tuning.Get(i, &Current); StandardTuning.Get(i, &Standard); if(Standard == Current) TextRender()->TextColor(1,1,1,1.0f); else TextRender()->TextColor(1,0.25f,0.25f,1.0f); float w; float x = 5.0f; str_format(aBuf, sizeof(aBuf), "%.2f", Standard); x += 20.0f; w = TextRender()->TextWidth(0, 5, aBuf, -1); TextRender()->Text(0x0, x-w, y+Count*6, 5, aBuf, -1); str_format(aBuf, sizeof(aBuf), "%.2f", Current); x += 20.0f; w = TextRender()->TextWidth(0, 5, aBuf, -1); TextRender()->Text(0x0, x-w, y+Count*6, 5, aBuf, -1); x += 5.0f; TextRender()->Text(0x0, x, y+Count*6, 5, m_pClient->m_Tuning.m_apNames[i], -1); Count++; } y = y+Count*6; Graphics()->TextureClear(); Graphics()->BlendNormal(); Graphics()->LinesBegin(); float Height = 50.0f; float pv = 1; IGraphics::CLineItem Array[100]; for(int i = 0; i < 100; i++) { float Speed = i/100.0f * 3000; float Ramp = VelocityRamp(Speed, m_pClient->m_Tuning.m_VelrampStart, m_pClient->m_Tuning.m_VelrampRange, m_pClient->m_Tuning.m_VelrampCurvature); float RampedSpeed = (Speed * Ramp)/1000.0f; Array[i] = IGraphics::CLineItem((i-1)*2, y+Height-pv*Height, i*2, y+Height-RampedSpeed*Height); //Graphics()->LinesDraw((i-1)*2, 200, i*2, 200); pv = RampedSpeed; } Graphics()->LinesDraw(Array, 100); Graphics()->LinesEnd(); TextRender()->TextColor(1,1,1,1); } void CDebugHud::OnRender() { RenderTuning(); RenderNetCorrections(); } ================================================ FILE: src/game/client/components/debughud.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_CLIENT_COMPONENTS_DEBUGHUD_H #define GAME_CLIENT_COMPONENTS_DEBUGHUD_H #include <game/client/component.h> class CDebugHud : public CComponent { void RenderNetCorrections(); void RenderTuning(); public: virtual void OnRender(); }; #endif ================================================ FILE: src/game/client/components/effects.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <engine/demo.h> #include <engine/engine.h> #include <engine/shared/config.h> #include <game/generated/client_data.h> #include <game/client/components/particles.h> #include <game/client/components/skins.h> #include <game/client/components/flow.h> #include <game/client/components/damageind.h> #include <game/client/components/sounds.h> #include <game/client/gameclient.h> #include "effects.h" inline vec2 RandomDir() { return normalize(vec2(frandom()-0.5f, frandom()-0.5f)); } CEffects::CEffects() { m_Add50hz = false; m_Add100hz = false; } void CEffects::AirJump(vec2 Pos) { CParticle p; p.SetDefault(); p.m_Spr = SPRITE_PART_AIRJUMP; p.m_Pos = Pos + vec2(-6.0f, 16.0f); p.m_Vel = vec2(0, -200); p.m_LifeSpan = 0.5f; p.m_StartSize = 48.0f; p.m_EndSize = 0; p.m_Rot = frandom()*pi*2; p.m_Rotspeed = pi*2; p.m_Gravity = 500; p.m_Friction = 0.7f; p.m_FlowAffected = 0.0f; m_pClient->m_pParticles->Add(CParticles::GROUP_GENERAL, &p); p.m_Pos = Pos + vec2(6.0f, 16.0f); m_pClient->m_pParticles->Add(CParticles::GROUP_GENERAL, &p); m_pClient->m_pSounds->PlayAt(CSounds::CHN_WORLD, SOUND_PLAYER_AIRJUMP, 1.0f, Pos); } void CEffects::DamageIndicator(vec2 Pos, vec2 Dir) { m_pClient->m_pDamageind->Create(Pos, Dir); } void CEffects::PowerupShine(vec2 Pos, vec2 size) { if(!m_Add50hz) return; CParticle p; p.SetDefault(); p.m_Spr = SPRITE_PART_SLICE; p.m_Pos = Pos + vec2((frandom()-0.5f)*size.x, (frandom()-0.5f)*size.y); p.m_Vel = vec2(0, 0); p.m_LifeSpan = 0.5f; p.m_StartSize = 16.0f; p.m_EndSize = 0; p.m_Rot = frandom()*pi*2; p.m_Rotspeed = pi*2; p.m_Gravity = 500; p.m_Friction = 0.9f; p.m_FlowAffected = 0.0f; m_pClient->m_pParticles->Add(CParticles::GROUP_GENERAL, &p); } void CEffects::SmokeTrail(vec2 Pos, vec2 Vel) { if(!m_Add50hz) return; CParticle p; p.SetDefault(); p.m_Spr = SPRITE_PART_SMOKE; p.m_Pos = Pos; p.m_Vel = Vel + RandomDir()*50.0f; p.m_LifeSpan = 0.5f + frandom()*0.5f; p.m_StartSize = 12.0f + frandom()*8; p.m_EndSize = 0; p.m_Friction = 0.7f; p.m_Gravity = frandom()*-500.0f; m_pClient->m_pParticles->Add(CParticles::GROUP_PROJECTILE_TRAIL, &p); } void CEffects::SkidTrail(vec2 Pos, vec2 Vel) { if(!m_Add100hz) return; CParticle p; p.SetDefault(); p.m_Spr = SPRITE_PART_SMOKE; p.m_Pos = Pos; p.m_Vel = Vel + RandomDir()*50.0f; p.m_LifeSpan = 0.5f + frandom()*0.5f; p.m_StartSize = 24.0f + frandom()*12; p.m_EndSize = 0; p.m_Friction = 0.7f; p.m_Gravity = frandom()*-500.0f; p.m_Color = vec4(0.75f,0.75f,0.75f,1.0f); m_pClient->m_pParticles->Add(CParticles::GROUP_GENERAL, &p); } void CEffects::BulletTrail(vec2 Pos) { if(!m_Add100hz) return; CParticle p; p.SetDefault(); p.m_Spr = SPRITE_PART_BALL; p.m_Pos = Pos; p.m_LifeSpan = 0.25f + frandom()*0.25f; p.m_StartSize = 8.0f; p.m_EndSize = 0; p.m_Friction = 0.7f; m_pClient->m_pParticles->Add(CParticles::GROUP_PROJECTILE_TRAIL, &p); } void CEffects::PlayerSpawn(vec2 Pos) { for(int i = 0; i < 32; i++) { CParticle p; p.SetDefault(); p.m_Spr = SPRITE_PART_SHELL; p.m_Pos = Pos; p.m_Vel = RandomDir() * (powf(frandom(), 3)*600.0f); p.m_LifeSpan = 0.3f + frandom()*0.3f; p.m_StartSize = 64.0f + frandom()*32; p.m_EndSize = 0; p.m_Rot = frandom()*pi*2; p.m_Rotspeed = frandom(); p.m_Gravity = frandom()*-400.0f; p.m_Friction = 0.7f; p.m_Color = vec4(0xb5/255.0f, 0x50/255.0f, 0xcb/255.0f, 1.0f); m_pClient->m_pParticles->Add(CParticles::GROUP_GENERAL, &p); } m_pClient->m_pSounds->PlayAt(CSounds::CHN_WORLD, SOUND_PLAYER_SPAWN, 1.0f, Pos); } void CEffects::PlayerDeath(vec2 Pos, int ClientID) { vec3 BloodColor(1.0f,1.0f,1.0f); if(ClientID >= 0) { if(m_pClient->m_aClients[ClientID].m_aUseCustomColors[CSkins::SKINPART_BODY]) BloodColor = m_pClient->m_pSkins->GetColorV3(m_pClient->m_aClients[ClientID].m_aSkinPartColors[CSkins::SKINPART_BODY]); else { const CSkins::CSkinPart *s = m_pClient->m_pSkins->GetSkinPart(CSkins::SKINPART_BODY, m_pClient->m_aClients[ClientID].m_SkinPartIDs[CSkins::SKINPART_BODY]); if(s) BloodColor = s->m_BloodColor; } } for(int i = 0; i < 64; i++) { CParticle p; p.SetDefault(); p.m_Spr = SPRITE_PART_SPLAT01 + (rand()%3); p.m_Pos = Pos; p.m_Vel = RandomDir() * ((frandom()+0.1f)*900.0f); p.m_LifeSpan = 0.3f + frandom()*0.3f; p.m_StartSize = 24.0f + frandom()*16; p.m_EndSize = 0; p.m_Rot = frandom()*pi*2; p.m_Rotspeed = (frandom()-0.5f) * pi; p.m_Gravity = 800.0f; p.m_Friction = 0.8f; vec3 c = BloodColor * (0.75f + frandom()*0.25f); p.m_Color = vec4(c.r, c.g, c.b, 0.75f); m_pClient->m_pParticles->Add(CParticles::GROUP_GENERAL, &p); } } void CEffects::Explosion(vec2 Pos) { // add to flow for(int y = -8; y <= 8; y++) for(int x = -8; x <= 8; x++) { if(x == 0 && y == 0) continue; float a = 1 - (length(vec2(x,y)) / length(vec2(8,8))); m_pClient->m_pFlow->Add(Pos+vec2(x,y)*16, normalize(vec2(x,y))*5000.0f*a, 10.0f); } // add the explosion CParticle p; p.SetDefault(); p.m_Spr = SPRITE_PART_EXPL01; p.m_Pos = Pos; p.m_LifeSpan = 0.4f; p.m_StartSize = 150.0f; p.m_EndSize = 0; p.m_Rot = frandom()*pi*2; m_pClient->m_pParticles->Add(CParticles::GROUP_EXPLOSIONS, &p); // add the smoke for(int i = 0; i < 24; i++) { CParticle p; p.SetDefault(); p.m_Spr = SPRITE_PART_SMOKE; p.m_Pos = Pos; p.m_Vel = RandomDir() * ((1.0f + frandom()*0.2f) * 1000.0f); p.m_LifeSpan = 0.5f + frandom()*0.4f; p.m_StartSize = 32.0f + frandom()*8; p.m_EndSize = 0; p.m_Gravity = frandom()*-800.0f; p.m_Friction = 0.4f; p.m_Color = mix(vec4(0.75f,0.75f,0.75f,1.0f), vec4(0.5f,0.5f,0.5f,1.0f), frandom()); m_pClient->m_pParticles->Add(CParticles::GROUP_GENERAL, &p); } } void CEffects::HammerHit(vec2 Pos) { // add the explosion CParticle p; p.SetDefault(); p.m_Spr = SPRITE_PART_HIT01; p.m_Pos = Pos; p.m_LifeSpan = 0.3f; p.m_StartSize = 120.0f; p.m_EndSize = 0; p.m_Rot = frandom()*pi*2; m_pClient->m_pParticles->Add(CParticles::GROUP_EXPLOSIONS, &p); m_pClient->m_pSounds->PlayAt(CSounds::CHN_WORLD, SOUND_HAMMER_HIT, 1.0f, Pos); } void CEffects::OnRender() { static int64 LastUpdate100hz = 0; static int64 LastUpdate50hz = 0; if(Client()->State() == IClient::STATE_DEMOPLAYBACK) { const IDemoPlayer::CInfo *pInfo = DemoPlayer()->BaseInfo(); if(time_get()-LastUpdate100hz > time_freq()/(100*pInfo->m_Speed)) { m_Add100hz = true; LastUpdate100hz = time_get(); } else m_Add100hz = false; if(time_get()-LastUpdate50hz > time_freq()/(100*pInfo->m_Speed)) { m_Add50hz = true; LastUpdate50hz = time_get(); } else m_Add50hz = false; if(m_Add50hz) m_pClient->m_pFlow->Update(); return; } if(time_get()-LastUpdate100hz > time_freq()/100) { m_Add100hz = true; LastUpdate100hz = time_get(); } else m_Add100hz = false; if(time_get()-LastUpdate50hz > time_freq()/100) { m_Add50hz = true; LastUpdate50hz = time_get(); } else m_Add50hz = false; if(m_Add50hz) m_pClient->m_pFlow->Update(); } ================================================ FILE: src/game/client/components/effects.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_CLIENT_COMPONENTS_EFFECTS_H #define GAME_CLIENT_COMPONENTS_EFFECTS_H #include <game/client/component.h> class CEffects : public CComponent { bool m_Add50hz; bool m_Add100hz; public: CEffects(); virtual void OnRender(); void BulletTrail(vec2 Pos); void SmokeTrail(vec2 Pos, vec2 Vel); void SkidTrail(vec2 Pos, vec2 Vel); void Explosion(vec2 Pos); void HammerHit(vec2 Pos); void AirJump(vec2 Pos); void DamageIndicator(vec2 Pos, vec2 Dir); void PlayerSpawn(vec2 Pos); void PlayerDeath(vec2 Pos, int ClientID); void PowerupShine(vec2 Pos, vec2 Size); void Update(); }; #endif ================================================ FILE: src/game/client/components/emoticon.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <engine/graphics.h> #include <engine/shared/config.h> #include <game/generated/protocol.h> #include <game/generated/client_data.h> #include <game/gamecore.h> // get_angle #include <game/client/ui.h> #include <game/client/render.h> #include "emoticon.h" CEmoticon::CEmoticon() { OnReset(); } void CEmoticon::ConKeyEmoticon(IConsole::IResult *pResult, void *pUserData) { CEmoticon *pSelf = (CEmoticon *)pUserData; if(!pSelf->m_pClient->m_Snap.m_SpecInfo.m_Active && pSelf->Client()->State() != IClient::STATE_DEMOPLAYBACK) pSelf->m_Active = pResult->GetInteger(0) != 0; } void CEmoticon::ConEmote(IConsole::IResult *pResult, void *pUserData) { ((CEmoticon *)pUserData)->Emote(pResult->GetInteger(0)); } void CEmoticon::OnConsoleInit() { Console()->Register("+emote", "", CFGFLAG_CLIENT, ConKeyEmoticon, this, "Open emote selector"); Console()->Register("emote", "i", CFGFLAG_CLIENT, ConEmote, this, "Use emote"); } void CEmoticon::OnReset() { m_WasActive = false; m_Active = false; m_SelectedEmote = -1; } void CEmoticon::OnRelease() { m_Active = false; } void CEmoticon::OnMessage(int MsgType, void *pRawMsg) { } bool CEmoticon::OnMouseMove(float x, float y) { if(!m_Active) return false; UI()->ConvertMouseMove(&x, &y); m_SelectorMouse += vec2(x,y); return true; } void CEmoticon::DrawCircle(float x, float y, float r, int Segments) { IGraphics::CFreeformItem Array[32]; int NumItems = 0; float FSegments = (float)Segments; for(int i = 0; i < Segments; i+=2) { float a1 = i/FSegments * 2*pi; float a2 = (i+1)/FSegments * 2*pi; float a3 = (i+2)/FSegments * 2*pi; float Ca1 = cosf(a1); float Ca2 = cosf(a2); float Ca3 = cosf(a3); float Sa1 = sinf(a1); float Sa2 = sinf(a2); float Sa3 = sinf(a3); Array[NumItems++] = IGraphics::CFreeformItem( x, y, x+Ca1*r, y+Sa1*r, x+Ca3*r, y+Sa3*r, x+Ca2*r, y+Sa2*r); if(NumItems == 32) { m_pClient->Graphics()->QuadsDrawFreeform(Array, 32); NumItems = 0; } } if(NumItems) m_pClient->Graphics()->QuadsDrawFreeform(Array, NumItems); } void CEmoticon::OnRender() { if(!m_Active) { if(m_WasActive && m_SelectedEmote != -1) Emote(m_SelectedEmote); m_WasActive = false; return; } if(m_pClient->m_Snap.m_SpecInfo.m_Active) { m_Active = false; m_WasActive = false; return; } m_WasActive = true; if (length(m_SelectorMouse) > 170.0f) m_SelectorMouse = normalize(m_SelectorMouse) * 170.0f; float SelectedAngle = GetAngle(m_SelectorMouse) + 2*pi/24; if (SelectedAngle < 0) SelectedAngle += 2*pi; if (length(m_SelectorMouse) > 110.0f) m_SelectedEmote = (int)(SelectedAngle / (2*pi) * NUM_EMOTICONS); CUIRect Screen = *UI()->Screen(); Graphics()->MapScreen(Screen.x, Screen.y, Screen.w, Screen.h); Graphics()->BlendNormal(); Graphics()->TextureClear(); Graphics()->QuadsBegin(); Graphics()->SetColor(0,0,0,0.3f); DrawCircle(Screen.w/2, Screen.h/2, 190.0f, 64); Graphics()->QuadsEnd(); Graphics()->TextureSet(g_pData->m_aImages[IMAGE_EMOTICONS].m_Id); Graphics()->QuadsBegin(); for (int i = 0; i < NUM_EMOTICONS; i++) { float Angle = 2*pi*i/NUM_EMOTICONS; if (Angle > pi) Angle -= 2*pi; bool Selected = m_SelectedEmote == i; float Size = Selected ? 80.0f : 50.0f; float NudgeX = 150.0f * cosf(Angle); float NudgeY = 150.0f * sinf(Angle); RenderTools()->SelectSprite(SPRITE_OOP + i); IGraphics::CQuadItem QuadItem(Screen.w/2 + NudgeX, Screen.h/2 + NudgeY, Size, Size); Graphics()->QuadsDraw(&QuadItem, 1); } Graphics()->QuadsEnd(); Graphics()->TextureSet(g_pData->m_aImages[IMAGE_CURSOR].m_Id); Graphics()->QuadsBegin(); Graphics()->SetColor(1,1,1,1); IGraphics::CQuadItem QuadItem(m_SelectorMouse.x+Screen.w/2,m_SelectorMouse.y+Screen.h/2,24,24); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); } void CEmoticon::Emote(int Emoticon) { CNetMsg_Cl_Emoticon Msg; Msg.m_Emoticon = Emoticon; Client()->SendPackMsg(&Msg, MSGFLAG_VITAL); } ================================================ FILE: src/game/client/components/emoticon.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_CLIENT_COMPONENTS_EMOTICON_H #define GAME_CLIENT_COMPONENTS_EMOTICON_H #include <base/vmath.h> #include <game/client/component.h> class CEmoticon : public CComponent { void DrawCircle(float x, float y, float r, int Segments); bool m_WasActive; bool m_Active; vec2 m_SelectorMouse; int m_SelectedEmote; static void ConKeyEmoticon(IConsole::IResult *pResult, void *pUserData); static void ConEmote(IConsole::IResult *pResult, void *pUserData); public: CEmoticon(); virtual void OnReset(); virtual void OnConsoleInit(); virtual void OnRender(); virtual void OnRelease(); virtual void OnMessage(int MsgType, void *pRawMsg); virtual bool OnMouseMove(float x, float y); void Emote(int Emoticon); }; #endif ================================================ FILE: src/game/client/components/flow.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <engine/graphics.h> #include <game/mapitems.h> #include <game/layers.h> #include "flow.h" CFlow::CFlow() { m_pCells = 0; m_Height = 0; m_Width = 0; m_Spacing = 16; } void CFlow::DbgRender() { if(!m_pCells) return; IGraphics::CLineItem Array[1024]; int NumItems = 0; Graphics()->TextureClear(); Graphics()->LinesBegin(); for(int y = 0; y < m_Height; y++) for(int x = 0; x < m_Width; x++) { vec2 Pos(x*m_Spacing, y*m_Spacing); vec2 Vel = m_pCells[y*m_Width+x].m_Vel * 0.01f; Array[NumItems++] = IGraphics::CLineItem(Pos.x, Pos.y, Pos.x+Vel.x, Pos.y+Vel.y); if(NumItems == 1024) { Graphics()->LinesDraw(Array, 1024); NumItems = 0; } } if(NumItems) Graphics()->LinesDraw(Array, NumItems); Graphics()->LinesEnd(); } void CFlow::Init() { if(m_pCells) { mem_free(m_pCells); m_pCells = 0; } CMapItemLayerTilemap *pTilemap = Layers()->GameLayer(); m_Width = pTilemap->m_Width*32/m_Spacing; m_Height = pTilemap->m_Height*32/m_Spacing; // allocate and clear m_pCells = (CCell *)mem_alloc(sizeof(CCell)*m_Width*m_Height, 1); for(int y = 0; y < m_Height; y++) for(int x = 0; x < m_Width; x++) m_pCells[y*m_Width+x].m_Vel = vec2(0.0f, 0.0f); } void CFlow::Update() { if(!m_pCells) return; for(int y = 0; y < m_Height; y++) for(int x = 0; x < m_Width; x++) m_pCells[y*m_Width+x].m_Vel *= 0.85f; } vec2 CFlow::Get(vec2 Pos) { if(!m_pCells) return vec2(0,0); int x = (int)(Pos.x / m_Spacing); int y = (int)(Pos.y / m_Spacing); if(x < 0 || y < 0 || x >= m_Width || y >= m_Height) return vec2(0,0); return m_pCells[y*m_Width+x].m_Vel; } void CFlow::Add(vec2 Pos, vec2 Vel, float Size) { if(!m_pCells) return; int x = (int)(Pos.x / m_Spacing); int y = (int)(Pos.y / m_Spacing); if(x < 0 || y < 0 || x >= m_Width || y >= m_Height) return; m_pCells[y*m_Width+x].m_Vel += Vel; } ================================================ FILE: src/game/client/components/flow.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_CLIENT_COMPONENTS_FLOW_H #define GAME_CLIENT_COMPONENTS_FLOW_H #include <base/vmath.h> #include <game/client/component.h> class CFlow : public CComponent { struct CCell { vec2 m_Vel; }; CCell *m_pCells; int m_Height; int m_Width; int m_Spacing; void DbgRender(); void Init(); public: CFlow(); vec2 Get(vec2 Pos); void Add(vec2 Pos, vec2 Vel, float Size); void Update(); }; #endif ================================================ FILE: src/game/client/components/hud.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <engine/graphics.h> #include <engine/textrender.h> #include <engine/shared/config.h> #include <game/generated/protocol.h> #include <game/generated/client_data.h> #include <game/layers.h> #include <game/client/gameclient.h> #include <game/client/animstate.h> #include <game/client/render.h> #include "menus.h" #include "controls.h" #include "camera.h" #include "hud.h" #include "voting.h" #include "binds.h" CHud::CHud() { // won't work if zero m_AverageFPS = 1.0f; } void CHud::OnReset() { } void CHud::RenderGameTimer() { float Half = 300.0f*Graphics()->ScreenAspect()/2.0f; if(!(m_pClient->m_Snap.m_pGameData->m_GameStateFlags&GAMESTATEFLAG_SUDDENDEATH)) { char Buf[32]; int Time = 0; if(m_pClient->m_GameInfo.m_TimeLimit && !(m_pClient->m_Snap.m_pGameData->m_GameStateFlags&GAMESTATEFLAG_WARMUP)) { Time = m_pClient->m_GameInfo.m_TimeLimit*60 - ((Client()->GameTick()-m_pClient->m_Snap.m_pGameData->m_GameStartTick)/Client()->GameTickSpeed()); if(m_pClient->m_Snap.m_pGameData->m_GameStateFlags&(GAMESTATEFLAG_ROUNDOVER|GAMESTATEFLAG_GAMEOVER)) Time = 0; } else if(m_pClient->m_Snap.m_pGameData->m_GameStateFlags&(GAMESTATEFLAG_ROUNDOVER|GAMESTATEFLAG_GAMEOVER)) Time = m_pClient->m_Snap.m_pGameData->m_GameStateEndTick/Client()->GameTickSpeed(); else Time = (Client()->GameTick()-m_pClient->m_Snap.m_pGameData->m_GameStartTick)/Client()->GameTickSpeed(); str_format(Buf, sizeof(Buf), "%d:%02d", Time/60, Time%60); float FontSize = 10.0f; float w = TextRender()->TextWidth(0, FontSize, Buf, -1); // last 60 sec red, last 10 sec blink if(m_pClient->m_GameInfo.m_TimeLimit && Time <= 60 && !(m_pClient->m_Snap.m_pGameData->m_GameStateFlags&GAMESTATEFLAG_WARMUP)) { float Alpha = Time <= 10 && (2*time_get()/time_freq()) % 2 ? 0.5f : 1.0f; TextRender()->TextColor(1.0f, 0.25f, 0.25f, Alpha); } TextRender()->Text(0, Half-w/2, 2, FontSize, Buf, -1); TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); } } void CHud::RenderPauseTimer() { if((m_pClient->m_Snap.m_pGameData->m_GameStateFlags&(GAMESTATEFLAG_STARTCOUNTDOWN|GAMESTATEFLAG_PAUSED)) == GAMESTATEFLAG_PAUSED) { char aBuf[256]; const char *pText = Localize("Game paused"); float FontSize = 20.0f; float w = TextRender()->TextWidth(0, FontSize, pText, -1); TextRender()->Text(0, 150*Graphics()->ScreenAspect()+-w/2, 50, FontSize, pText, -1); FontSize = 16.0f; if(m_pClient->m_Snap.m_pGameData->m_GameStateEndTick == 0) { if(m_pClient->m_Snap.m_NotReadyCount == 1) str_format(aBuf, sizeof(aBuf), Localize("%d player not ready"), m_pClient->m_Snap.m_NotReadyCount); else if(m_pClient->m_Snap.m_NotReadyCount > 1) str_format(aBuf, sizeof(aBuf), Localize("%d players not ready"), m_pClient->m_Snap.m_NotReadyCount); else return; } else { float Seconds = static_cast<float>(m_pClient->m_Snap.m_pGameData->m_GameStateEndTick-Client()->GameTick())/SERVER_TICK_SPEED; if(Seconds < 5) str_format(aBuf, sizeof(aBuf), "%.1f", Seconds); else str_format(aBuf, sizeof(aBuf), "%d", round(Seconds)); } w = TextRender()->TextWidth(0, FontSize, aBuf, -1); TextRender()->Text(0, 150*Graphics()->ScreenAspect()+-w/2, 75, FontSize, aBuf, -1); } } void CHud::RenderStartCountdown() { if(m_pClient->m_Snap.m_pGameData->m_GameStateFlags&GAMESTATEFLAG_STARTCOUNTDOWN) { const char *pText = Localize("Game starts in"); float FontSize = 20.0f; float w = TextRender()->TextWidth(0, FontSize, pText, -1); TextRender()->Text(0, 150*Graphics()->ScreenAspect()+-w/2, 50, FontSize, pText, -1); if(m_pClient->m_Snap.m_pGameData->m_GameStateEndTick == 0) return; FontSize = 16.0f; char aBuf[32]; int Seconds = (m_pClient->m_Snap.m_pGameData->m_GameStateEndTick-Client()->GameTick()+SERVER_TICK_SPEED-1)/SERVER_TICK_SPEED; str_format(aBuf, sizeof(aBuf), "%d", Seconds); w = TextRender()->TextWidth(0, FontSize, aBuf, -1); TextRender()->Text(0, 150*Graphics()->ScreenAspect()+-w/2, 75, FontSize, aBuf, -1); } } void CHud::RenderDeadNotification() { if(m_pClient->m_Snap.m_pGameData->m_GameStateFlags == 0 && m_pClient->m_aClients[m_pClient->m_LocalClientID].m_Team != TEAM_SPECTATORS && m_pClient->m_Snap.m_pLocalInfo && (m_pClient->m_Snap.m_pLocalInfo->m_PlayerFlags&PLAYERFLAG_DEAD)) { const char *pText = Localize("Wait for next round"); float FontSize = 16.0f; float w = TextRender()->TextWidth(0, FontSize, pText, -1); TextRender()->Text(0, 150*Graphics()->ScreenAspect()+-w/2, 50, FontSize, pText, -1); } } void CHud::RenderSuddenDeath() { if(m_pClient->m_Snap.m_pGameData->m_GameStateFlags&GAMESTATEFLAG_SUDDENDEATH) { float Half = 300.0f*Graphics()->ScreenAspect()/2.0f; const char *pText = Localize("Sudden Death"); float FontSize = 12.0f; float w = TextRender()->TextWidth(0, FontSize, pText, -1); TextRender()->Text(0, Half-w/2, 2, FontSize, pText, -1); } } void CHud::RenderScoreHud() { // render small score hud if(!(m_pClient->m_Snap.m_pGameData->m_GameStateFlags&(GAMESTATEFLAG_ROUNDOVER|GAMESTATEFLAG_GAMEOVER))) { int GameFlags = m_pClient->m_GameInfo.m_GameFlags; float Whole = 300*Graphics()->ScreenAspect(); float StartY = 229.0f; if(GameFlags&GAMEFLAG_TEAMS && m_pClient->m_Snap.m_pGameDataTeam) { char aScoreTeam[2][32]; str_format(aScoreTeam[TEAM_RED], sizeof(aScoreTeam)/2, "%d", m_pClient->m_Snap.m_pGameDataTeam->m_TeamscoreRed); str_format(aScoreTeam[TEAM_BLUE], sizeof(aScoreTeam)/2, "%d", m_pClient->m_Snap.m_pGameDataTeam->m_TeamscoreBlue); float aScoreTeamWidth[2] = { TextRender()->TextWidth(0, 14.0f, aScoreTeam[TEAM_RED], -1), TextRender()->TextWidth(0, 14.0f, aScoreTeam[TEAM_BLUE], -1) }; float ScoreWidthMax = max(max(aScoreTeamWidth[TEAM_RED], aScoreTeamWidth[TEAM_BLUE]), TextRender()->TextWidth(0, 14.0f, "100", -1)); float Split = 3.0f; float ImageSize = GameFlags&GAMEFLAG_FLAGS ? 16.0f : Split; for(int t = 0; t < NUM_TEAMS; t++) { // draw box Graphics()->BlendNormal(); Graphics()->TextureClear(); Graphics()->QuadsBegin(); if(t == 0) Graphics()->SetColor(1.0f, 0.0f, 0.0f, 0.25f); else Graphics()->SetColor(0.0f, 0.0f, 1.0f, 0.25f); RenderTools()->DrawRoundRectExt(Whole-ScoreWidthMax-ImageSize-2*Split, StartY+t*20, ScoreWidthMax+ImageSize+2*Split, 18.0f, 5.0f, CUI::CORNER_L); Graphics()->QuadsEnd(); // draw score TextRender()->Text(0, Whole-ScoreWidthMax+(ScoreWidthMax-aScoreTeamWidth[t])/2-Split, StartY+t*20, 14.0f, aScoreTeam[t], -1); if(GameFlags&GAMEFLAG_SURVIVAL) { // draw number of alive players char aBuf[32]; str_format(aBuf, sizeof(aBuf), m_pClient->m_Snap.m_AliveCount[t]==1 ? Localize("%d player left") : Localize("%d players left"), m_pClient->m_Snap.m_AliveCount[t]); float w = TextRender()->TextWidth(0, 8.0f, aBuf, -1); TextRender()->Text(0, min(Whole-w-1.0f, Whole-ScoreWidthMax-ImageSize-2*Split), StartY+(t+1)*20.0f-3.0f, 8.0f, aBuf, -1); } StartY += 8.0f; } if(GameFlags&GAMEFLAG_FLAGS && m_pClient->m_Snap.m_pGameDataFlag) { int FlagCarrier[2] = { m_pClient->m_Snap.m_pGameDataFlag->m_FlagCarrierRed, m_pClient->m_Snap.m_pGameDataFlag->m_FlagCarrierBlue }; int FlagDropTick[2] = { m_pClient->m_Snap.m_pGameDataFlag->m_FlagDropTickRed, m_pClient->m_Snap.m_pGameDataFlag->m_FlagDropTickBlue }; StartY = 229.0f; for(int t = 0; t < 2; t++) { int BlinkTimer = (FlagDropTick[t] != 0 && (Client()->GameTick()-FlagDropTick[t])/Client()->GameTickSpeed() >= 25) ? 10 : 20; if(FlagCarrier[t] == FLAG_ATSTAND || (FlagCarrier[t] == FLAG_TAKEN && ((Client()->GameTick()/BlinkTimer)&1))) { // draw flag Graphics()->BlendNormal(); Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id); Graphics()->QuadsBegin(); RenderTools()->SelectSprite(t==0?SPRITE_FLAG_RED:SPRITE_FLAG_BLUE); IGraphics::CQuadItem QuadItem(Whole-ScoreWidthMax-ImageSize, StartY+1.0f+t*20, ImageSize/2, ImageSize); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); } else if(FlagCarrier[t] >= 0) { // draw name of the flag holder int ID = FlagCarrier[t]%MAX_CLIENTS; const char *pName = m_pClient->m_aClients[ID].m_aName; float w = TextRender()->TextWidth(0, 8.0f, pName, -1); TextRender()->Text(0, min(Whole-w-1.0f, Whole-ScoreWidthMax-ImageSize-2*Split), StartY+(t+1)*20.0f-3.0f, 8.0f, pName, -1); // draw tee of the flag holder CTeeRenderInfo Info = m_pClient->m_aClients[ID].m_RenderInfo; Info.m_Size = 18.0f; RenderTools()->RenderTee(CAnimState::GetIdle(), &Info, EMOTE_NORMAL, vec2(1,0), vec2(Whole-ScoreWidthMax-Info.m_Size/2-Split, StartY+1.0f+Info.m_Size/2+t*20)); } StartY += 8.0f; } } } else { int Local = -1; int aPos[2] = { 1, 2 }; CGameClient::CPlayerInfoItem aPlayerInfo[2] = {{0}}; int i = 0; for(int t = 0; t < 2 && i < MAX_CLIENTS && m_pClient->m_Snap.m_aInfoByScore[i].m_pPlayerInfo; ++i) { if(m_pClient->m_aClients[m_pClient->m_Snap.m_aInfoByScore[i].m_ClientID].m_Team != TEAM_SPECTATORS) { aPlayerInfo[t] = m_pClient->m_Snap.m_aInfoByScore[i]; if(aPlayerInfo[t].m_ClientID == m_pClient->m_LocalClientID) Local = t; ++t; } } // search local player info if not a spectator, nor within top2 scores if(Local == -1 && m_pClient->m_aClients[m_pClient->m_LocalClientID].m_Team != TEAM_SPECTATORS) { for(; i < MAX_CLIENTS && m_pClient->m_Snap.m_aInfoByScore[i].m_pPlayerInfo; ++i) { if(m_pClient->m_aClients[m_pClient->m_Snap.m_aInfoByScore[i].m_ClientID].m_Team != TEAM_SPECTATORS) ++aPos[1]; if(m_pClient->m_Snap.m_aInfoByScore[i].m_ClientID == m_pClient->m_LocalClientID) { aPlayerInfo[1] = m_pClient->m_Snap.m_aInfoByScore[i]; Local = 1; break; } } } char aScore[2][32]; for(int t = 0; t < 2; ++t) { if(aPlayerInfo[t].m_pPlayerInfo) str_format(aScore[t], sizeof(aScore)/2, "%d", aPlayerInfo[t].m_pPlayerInfo->m_Score); else aScore[t][0] = 0; } float aScoreWidth[2] = {TextRender()->TextWidth(0, 14.0f, aScore[0], -1), TextRender()->TextWidth(0, 14.0f, aScore[1], -1)}; float ScoreWidthMax = max(max(aScoreWidth[0], aScoreWidth[1]), TextRender()->TextWidth(0, 14.0f, "10", -1)); float Split = 3.0f, ImageSize = 16.0f, PosSize = 16.0f; // todo: add core hud for LMS for(int t = 0; t < 2; t++) { // draw box Graphics()->BlendNormal(); Graphics()->TextureClear(); Graphics()->QuadsBegin(); if(t == Local) Graphics()->SetColor(1.0f, 1.0f, 1.0f, 0.25f); else Graphics()->SetColor(0.0f, 0.0f, 0.0f, 0.25f); RenderTools()->DrawRoundRectExt(Whole-ScoreWidthMax-ImageSize-2*Split-PosSize, StartY+t*20, ScoreWidthMax+ImageSize+2*Split+PosSize, 18.0f, 5.0f, CUI::CORNER_L); Graphics()->QuadsEnd(); // draw score TextRender()->Text(0, Whole-ScoreWidthMax+(ScoreWidthMax-aScoreWidth[t])/2-Split, StartY+t*20, 14.0f, aScore[t], -1); if(aPlayerInfo[t].m_pPlayerInfo) { // draw name int ID = aPlayerInfo[t].m_ClientID; const char *pName = m_pClient->m_aClients[ID].m_aName; float w = TextRender()->TextWidth(0, 8.0f, pName, -1); TextRender()->Text(0, min(Whole-w-1.0f, Whole-ScoreWidthMax-ImageSize-2*Split-PosSize), StartY+(t+1)*20.0f-3.0f, 8.0f, pName, -1); // draw tee CTeeRenderInfo Info = m_pClient->m_aClients[ID].m_RenderInfo; Info.m_Size = 18.0f; RenderTools()->RenderTee(CAnimState::GetIdle(), &Info, EMOTE_NORMAL, vec2(1,0), vec2(Whole-ScoreWidthMax-Info.m_Size/2-Split, StartY+1.0f+Info.m_Size/2+t*20)); } // draw position char aBuf[32]; str_format(aBuf, sizeof(aBuf), "%d.", aPos[t]); TextRender()->Text(0, Whole-ScoreWidthMax-ImageSize-Split-PosSize, StartY+2.0f+t*20, 10.0f, aBuf, -1); StartY += 8.0f; } } } } void CHud::RenderWarmupTimer() { // render warmup timer if(m_pClient->m_Snap.m_pGameData->m_GameStateFlags&GAMESTATEFLAG_WARMUP) { char aBuf[256]; float FontSize = 20.0f; float w = TextRender()->TextWidth(0, FontSize, Localize("Warmup"), -1); TextRender()->Text(0, 150*Graphics()->ScreenAspect()+-w/2, 50, FontSize, Localize("Warmup"), -1); FontSize = 16.0f; if(m_pClient->m_Snap.m_pGameData->m_GameStateEndTick == 0) { if(m_pClient->m_Snap.m_NotReadyCount == 1) str_format(aBuf, sizeof(aBuf), Localize("%d player not ready"), m_pClient->m_Snap.m_NotReadyCount); else if(m_pClient->m_Snap.m_NotReadyCount > 1) str_format(aBuf, sizeof(aBuf), Localize("%d players not ready"), m_pClient->m_Snap.m_NotReadyCount); else str_format(aBuf, sizeof(aBuf), Localize("wait for more players")); } else { float Seconds = static_cast<float>(m_pClient->m_Snap.m_pGameData->m_GameStateEndTick-Client()->GameTick())/SERVER_TICK_SPEED; if(Seconds < 5) str_format(aBuf, sizeof(aBuf), "%.1f", Seconds); else str_format(aBuf, sizeof(aBuf), "%d", round(Seconds)); } w = TextRender()->TextWidth(0, FontSize, aBuf, -1); TextRender()->Text(0, 150*Graphics()->ScreenAspect()+-w/2, 75, FontSize, aBuf, -1); } } void CHud::MapscreenToGroup(float CenterX, float CenterY, CMapItemGroup *pGroup) { float Points[4]; RenderTools()->MapscreenToWorld(CenterX, CenterY, pGroup->m_ParallaxX/100.0f, pGroup->m_ParallaxY/100.0f, pGroup->m_OffsetX, pGroup->m_OffsetY, Graphics()->ScreenAspect(), m_pClient->m_pCamera->m_Zoom, Points); Graphics()->MapScreen(Points[0], Points[1], Points[2], Points[3]); } void CHud::RenderFps() { if(g_Config.m_ClShowfps) { // calculate avg. fps float FPS = 1.0f / Client()->RenderFrameTime(); m_AverageFPS = (m_AverageFPS*(1.0f-(1.0f/m_AverageFPS))) + (FPS*(1.0f/m_AverageFPS)); char Buf[512]; str_format(Buf, sizeof(Buf), "%d", (int)m_AverageFPS); TextRender()->Text(0, m_Width-10-TextRender()->TextWidth(0,12,Buf,-1), 5, 12, Buf, -1); } } void CHud::RenderConnectionWarning() { if(Client()->ConnectionProblems()) { const char *pText = Localize("Connection Problems..."); float w = TextRender()->TextWidth(0, 24, pText, -1); TextRender()->Text(0, 150*Graphics()->ScreenAspect()-w/2, 50, 24, pText, -1); } } void CHud::RenderTeambalanceWarning() { // render prompt about team-balance if(m_pClient->m_GameInfo.m_GameFlags&GAMEFLAG_TEAMS && g_Config.m_ClWarningTeambalance && m_pClient->m_ServerSettings.m_TeamBalance && absolute(m_pClient->m_GameInfo.m_aTeamSize[TEAM_RED]-m_pClient->m_GameInfo.m_aTeamSize[TEAM_BLUE]) >= NUM_TEAMS) { bool Flash = time_get()/(time_freq()/2)%2 == 0; const char *pText = Localize("Please balance teams!"); if(Flash) TextRender()->TextColor(1,1,0.5f,1); else TextRender()->TextColor(0.7f,0.7f,0.2f,1.0f); TextRender()->Text(0x0, 5, 50, 6, pText, -1); TextRender()->TextColor(1,1,1,1); } } void CHud::RenderVoting() { if(!m_pClient->m_pVoting->IsVoting() || Client()->State() == IClient::STATE_DEMOPLAYBACK) return; Graphics()->TextureClear(); Graphics()->QuadsBegin(); Graphics()->SetColor(0,0,0,0.40f); RenderTools()->DrawRoundRect(-10, 60-2, 100+10+4+5, 46, 5.0f); Graphics()->QuadsEnd(); TextRender()->TextColor(1,1,1,1); CTextCursor Cursor; char aBuf[512]; str_format(aBuf, sizeof(aBuf), Localize("%ds left"), m_pClient->m_pVoting->SecondsLeft()); float tw = TextRender()->TextWidth(0x0, 6, aBuf, -1); TextRender()->SetCursor(&Cursor, 5.0f+100.0f-tw, 60.0f, 6.0f, TEXTFLAG_RENDER); TextRender()->TextEx(&Cursor, aBuf, -1); TextRender()->SetCursor(&Cursor, 5.0f, 60.0f, 6.0f, TEXTFLAG_RENDER); Cursor.m_LineWidth = 100.0f-tw; Cursor.m_MaxLines = 3; TextRender()->TextEx(&Cursor, m_pClient->m_pVoting->VoteDescription(), -1); // reason str_format(aBuf, sizeof(aBuf), "%s %s", Localize("Reason:"), m_pClient->m_pVoting->VoteReason()); TextRender()->SetCursor(&Cursor, 5.0f, 79.0f, 6.0f, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); Cursor.m_LineWidth = 100.0f; TextRender()->TextEx(&Cursor, aBuf, -1); CUIRect Base = {5, 88, 100, 4}; m_pClient->m_pVoting->RenderBars(Base, false); const char *pYesKey = m_pClient->m_pBinds->GetKey("vote yes"); const char *pNoKey = m_pClient->m_pBinds->GetKey("vote no"); str_format(aBuf, sizeof(aBuf), "%s - %s", pYesKey, Localize("Vote yes")); Base.y += Base.h+1; UI()->DoLabel(&Base, aBuf, 6.0f, -1); str_format(aBuf, sizeof(aBuf), "%s - %s", Localize("Vote no"), pNoKey); UI()->DoLabel(&Base, aBuf, 6.0f, 1); } void CHud::RenderCursor() { if(!m_pClient->m_Snap.m_pLocalCharacter || Client()->State() == IClient::STATE_DEMOPLAYBACK) return; MapscreenToGroup(m_pClient->m_pCamera->m_Center.x, m_pClient->m_pCamera->m_Center.y, Layers()->GameGroup()); Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id); Graphics()->QuadsBegin(); // render cursor RenderTools()->SelectSprite(g_pData->m_Weapons.m_aId[m_pClient->m_Snap.m_pLocalCharacter->m_Weapon%NUM_WEAPONS].m_pSpriteCursor); float CursorSize = 64; RenderTools()->DrawSprite(m_pClient->m_pControls->m_TargetPos.x, m_pClient->m_pControls->m_TargetPos.y, CursorSize); Graphics()->QuadsEnd(); } void CHud::RenderHealthAndAmmo(const CNetObj_Character *pCharacter) { if(!pCharacter) return; float x = 5; float y = 5; int i; IGraphics::CQuadItem Array[10]; // render ammo if(pCharacter->m_Weapon == WEAPON_NINJA) { Graphics()->TextureClear(); Graphics()->QuadsBegin(); Graphics()->SetColor(0.8f, 0.8f, 0.8f, 0.5f); RenderTools()->DrawRoundRectExt(x,y+24, 118.0f, 10.0f, 0.0f, 0); int Max = g_pData->m_Weapons.m_Ninja.m_Duration * Client()->GameTickSpeed() / 1000; float Width = 116.0f * clamp(pCharacter->m_AmmoCount-Client()->GameTick(), 0, Max) / Max; Graphics()->SetColor(0.9f, 0.2f, 0.2f, 0.85f); RenderTools()->DrawRoundRectExt(x+1.0f, y+25.0f, Width, 8.0f, 0.0f, 0); Graphics()->QuadsEnd(); Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id); Graphics()->QuadsBegin(); Graphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f); RenderTools()->SelectSprite(g_pData->m_Weapons.m_aId[WEAPON_NINJA].m_pSpriteBody); RenderTools()->DrawRoundRectExt(x+40.0f,y+25, 32.0f, 8.0f, 0.0f, 0); } else { Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id); Graphics()->QuadsBegin(); RenderTools()->SelectSprite(g_pData->m_Weapons.m_aId[pCharacter->m_Weapon%NUM_WEAPONS].m_pSpriteProj); for(i = 0; i < min(pCharacter->m_AmmoCount, 10); i++) Array[i] = IGraphics::CQuadItem(x+i*12,y+24,10,10); Graphics()->QuadsDrawTL(Array, i); } int h = 0; // render health RenderTools()->SelectSprite(SPRITE_HEALTH_FULL); for(; h < min(pCharacter->m_Health, 10); h++) Array[h] = IGraphics::CQuadItem(x+h*12,y,10,10); Graphics()->QuadsDrawTL(Array, h); i = 0; RenderTools()->SelectSprite(SPRITE_HEALTH_EMPTY); for(; h < 10; h++) Array[i++] = IGraphics::CQuadItem(x+h*12,y,10,10); Graphics()->QuadsDrawTL(Array, i); // render armor meter h = 0; RenderTools()->SelectSprite(SPRITE_ARMOR_FULL); for(; h < min(pCharacter->m_Armor, 10); h++) Array[h] = IGraphics::CQuadItem(x+h*12,y+12,10,10); Graphics()->QuadsDrawTL(Array, h); i = 0; RenderTools()->SelectSprite(SPRITE_ARMOR_EMPTY); for(; h < 10; h++) Array[i++] = IGraphics::CQuadItem(x+h*12,y+12,10,10); Graphics()->QuadsDrawTL(Array, i); Graphics()->QuadsEnd(); } void CHud::RenderSpectatorHud() { // draw the box Graphics()->TextureClear(); Graphics()->QuadsBegin(); Graphics()->SetColor(0.0f, 0.0f, 0.0f, 0.4f); RenderTools()->DrawRoundRectExt(m_Width-180.0f, m_Height-15.0f, 180.0f, 15.0f, 5.0f, CUI::CORNER_TL); Graphics()->QuadsEnd(); // draw the text char aBuf[128]; str_format(aBuf, sizeof(aBuf), "%s: %s", Localize("Spectate"), m_pClient->m_Snap.m_SpecInfo.m_SpectatorID != SPEC_FREEVIEW ? m_pClient->m_aClients[m_pClient->m_Snap.m_SpecInfo.m_SpectatorID].m_aName : Localize("Free-View")); TextRender()->Text(0, m_Width-174.0f, m_Height-13.0f, 8.0f, aBuf, -1); } void CHud::OnRender() { if(!m_pClient->m_Snap.m_pGameData) return; // dont render hud if the menu is active if(m_pClient->m_pMenus->IsActive()) return; m_Width = 300.0f*Graphics()->ScreenAspect(); m_Height = 300.0f; Graphics()->MapScreen(0.0f, 0.0f, m_Width, m_Height); if(g_Config.m_ClShowhud) { if(m_pClient->m_Snap.m_pLocalCharacter && !(m_pClient->m_Snap.m_pGameData->m_GameStateFlags&(GAMESTATEFLAG_ROUNDOVER|GAMESTATEFLAG_GAMEOVER))) RenderHealthAndAmmo(m_pClient->m_Snap.m_pLocalCharacter); else if(m_pClient->m_Snap.m_SpecInfo.m_Active) { if(m_pClient->m_Snap.m_SpecInfo.m_SpectatorID != SPEC_FREEVIEW) RenderHealthAndAmmo(&m_pClient->m_Snap.m_aCharacters[m_pClient->m_Snap.m_SpecInfo.m_SpectatorID].m_Cur); RenderSpectatorHud(); } RenderGameTimer(); RenderPauseTimer(); RenderStartCountdown(); RenderDeadNotification(); RenderSuddenDeath(); RenderScoreHud(); RenderWarmupTimer(); RenderFps(); if(Client()->State() != IClient::STATE_DEMOPLAYBACK) RenderConnectionWarning(); RenderTeambalanceWarning(); RenderVoting(); } RenderCursor(); } ================================================ FILE: src/game/client/components/hud.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_CLIENT_COMPONENTS_HUD_H #define GAME_CLIENT_COMPONENTS_HUD_H #include <game/client/component.h> class CHud : public CComponent { float m_Width, m_Height; float m_AverageFPS; void RenderCursor(); void RenderFps(); void RenderConnectionWarning(); void RenderTeambalanceWarning(); void RenderVoting(); void RenderHealthAndAmmo(const CNetObj_Character *pCharacter); void RenderGameTimer(); void RenderPauseTimer(); void RenderStartCountdown(); void RenderDeadNotification(); void RenderSuddenDeath(); void RenderScoreHud(); void RenderSpectatorHud(); void RenderWarmupTimer(); void MapscreenToGroup(float CenterX, float CenterY, struct CMapItemGroup *PGroup); public: CHud(); virtual void OnReset(); virtual void OnRender(); }; #endif ================================================ FILE: src/game/client/components/items.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <engine/graphics.h> #include <engine/demo.h> #include <game/generated/protocol.h> #include <game/generated/client_data.h> #include <game/gamecore.h> // get_angle #include <game/client/gameclient.h> #include <game/client/ui.h> #include <game/client/render.h> #include <game/client/components/flow.h> #include <game/client/components/effects.h> #include "items.h" void CItems::OnReset() { m_NumExtraProjectiles = 0; } void CItems::RenderProjectile(const CNetObj_Projectile *pCurrent, int ItemID) { // get positions float Curvature = 0; float Speed = 0; if(pCurrent->m_Type == WEAPON_GRENADE) { Curvature = m_pClient->m_Tuning.m_GrenadeCurvature; Speed = m_pClient->m_Tuning.m_GrenadeSpeed; } else if(pCurrent->m_Type == WEAPON_SHOTGUN) { Curvature = m_pClient->m_Tuning.m_ShotgunCurvature; Speed = m_pClient->m_Tuning.m_ShotgunSpeed; } else if(pCurrent->m_Type == WEAPON_GUN) { Curvature = m_pClient->m_Tuning.m_GunCurvature; Speed = m_pClient->m_Tuning.m_GunSpeed; } static float s_LastGameTickTime = Client()->GameTickTime(); if(m_pClient->m_Snap.m_pGameData && !(m_pClient->m_Snap.m_pGameData->m_GameStateFlags&GAMESTATEFLAG_PAUSED)) s_LastGameTickTime = Client()->GameTickTime(); float Ct = (Client()->PrevGameTick()-pCurrent->m_StartTick)/(float)SERVER_TICK_SPEED + s_LastGameTickTime; if(Ct < 0) return; // projectile havn't been shot yet vec2 StartPos(pCurrent->m_X, pCurrent->m_Y); vec2 StartVel(pCurrent->m_VelX/100.0f, pCurrent->m_VelY/100.0f); vec2 Pos = CalcPos(StartPos, StartVel, Curvature, Speed, Ct); vec2 PrevPos = CalcPos(StartPos, StartVel, Curvature, Speed, Ct-0.001f); Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id); Graphics()->QuadsBegin(); RenderTools()->SelectSprite(g_pData->m_Weapons.m_aId[clamp(pCurrent->m_Type, 0, NUM_WEAPONS-1)].m_pSpriteProj); vec2 Vel = Pos-PrevPos; //vec2 pos = mix(vec2(prev->x, prev->y), vec2(current->x, current->y), Client()->IntraGameTick()); // add particle for this projectile if(pCurrent->m_Type == WEAPON_GRENADE) { m_pClient->m_pEffects->SmokeTrail(Pos, Vel*-1); static float s_Time = 0.0f; static float s_LastLocalTime = Client()->LocalTime(); if(Client()->State() == IClient::STATE_DEMOPLAYBACK) { const IDemoPlayer::CInfo *pInfo = DemoPlayer()->BaseInfo(); if(!pInfo->m_Paused) s_Time += (Client()->LocalTime()-s_LastLocalTime)*pInfo->m_Speed; } else { if(m_pClient->m_Snap.m_pGameData && !(m_pClient->m_Snap.m_pGameData->m_GameStateFlags&GAMESTATEFLAG_PAUSED)) s_Time += Client()->LocalTime()-s_LastLocalTime; } Graphics()->QuadsSetRotation(s_Time*pi*2*2 + ItemID); s_LastLocalTime = Client()->LocalTime(); } else { m_pClient->m_pEffects->BulletTrail(Pos); if(length(Vel) > 0.00001f) Graphics()->QuadsSetRotation(GetAngle(Vel)); else Graphics()->QuadsSetRotation(0); } IGraphics::CQuadItem QuadItem(Pos.x, Pos.y, 32, 32); Graphics()->QuadsDraw(&QuadItem, 1); Graphics()->QuadsSetRotation(0); Graphics()->QuadsEnd(); } void CItems::RenderPickup(const CNetObj_Pickup *pPrev, const CNetObj_Pickup *pCurrent) { Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id); Graphics()->QuadsBegin(); vec2 Pos = mix(vec2(pPrev->m_X, pPrev->m_Y), vec2(pCurrent->m_X, pCurrent->m_Y), Client()->IntraGameTick()); float Angle = 0.0f; float Size = 64.0f; const int c[] = { SPRITE_PICKUP_HEALTH, SPRITE_PICKUP_ARMOR, SPRITE_PICKUP_GRENADE, SPRITE_PICKUP_SHOTGUN, SPRITE_PICKUP_LASER, SPRITE_PICKUP_NINJA }; RenderTools()->SelectSprite(c[pCurrent->m_Type]); switch(pCurrent->m_Type) { case PICKUP_GRENADE: Size = g_pData->m_Weapons.m_aId[WEAPON_GRENADE].m_VisualSize; break; case PICKUP_SHOTGUN: Size = g_pData->m_Weapons.m_aId[WEAPON_SHOTGUN].m_VisualSize; break; case PICKUP_LASER: Size = g_pData->m_Weapons.m_aId[WEAPON_LASER].m_VisualSize; break; case PICKUP_NINJA: m_pClient->m_pEffects->PowerupShine(Pos, vec2(96,18)); Size *= 2.0f; Pos.x -= 10.0f; } Graphics()->QuadsSetRotation(Angle); static float s_Time = 0.0f; static float s_LastLocalTime = Client()->LocalTime(); float Offset = Pos.y/32.0f + Pos.x/32.0f; if(Client()->State() == IClient::STATE_DEMOPLAYBACK) { const IDemoPlayer::CInfo *pInfo = DemoPlayer()->BaseInfo(); if(!pInfo->m_Paused) s_Time += (Client()->LocalTime()-s_LastLocalTime)*pInfo->m_Speed; } else { if(m_pClient->m_Snap.m_pGameData && !(m_pClient->m_Snap.m_pGameData->m_GameStateFlags&GAMESTATEFLAG_PAUSED)) s_Time += Client()->LocalTime()-s_LastLocalTime; } Pos.x += cosf(s_Time*2.0f+Offset)*2.5f; Pos.y += sinf(s_Time*2.0f+Offset)*2.5f; s_LastLocalTime = Client()->LocalTime(); RenderTools()->DrawSprite(Pos.x, Pos.y, Size); Graphics()->QuadsEnd(); } void CItems::RenderFlag(const CNetObj_Flag *pPrev, const CNetObj_Flag *pCurrent, const CNetObj_GameDataFlag *pPrevGameDataFlag, const CNetObj_GameDataFlag *pCurGameDataFlag) { float Angle = 0.0f; float Size = 42.0f; Graphics()->BlendNormal(); Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id); Graphics()->QuadsBegin(); if(pCurrent->m_Team == TEAM_RED) RenderTools()->SelectSprite(SPRITE_FLAG_RED); else RenderTools()->SelectSprite(SPRITE_FLAG_BLUE); Graphics()->QuadsSetRotation(Angle); vec2 Pos = mix(vec2(pPrev->m_X, pPrev->m_Y), vec2(pCurrent->m_X, pCurrent->m_Y), Client()->IntraGameTick()); if(pCurGameDataFlag) { // make sure that the flag isn't interpolated between capture and return if(pPrevGameDataFlag && ((pCurrent->m_Team == TEAM_RED && pPrevGameDataFlag->m_FlagCarrierRed != pCurGameDataFlag->m_FlagCarrierRed) || (pCurrent->m_Team == TEAM_BLUE && pPrevGameDataFlag->m_FlagCarrierBlue != pCurGameDataFlag->m_FlagCarrierBlue))) Pos = vec2(pCurrent->m_X, pCurrent->m_Y); // make sure to use predicted position if we are the carrier if(m_pClient->m_LocalClientID != -1 && ((pCurrent->m_Team == TEAM_RED && pCurGameDataFlag->m_FlagCarrierRed == m_pClient->m_LocalClientID) || (pCurrent->m_Team == TEAM_BLUE && pCurGameDataFlag->m_FlagCarrierBlue == m_pClient->m_LocalClientID))) Pos = m_pClient->m_LocalCharacterPos; } IGraphics::CQuadItem QuadItem(Pos.x, Pos.y-Size*0.75f, Size, Size*2); Graphics()->QuadsDraw(&QuadItem, 1); Graphics()->QuadsEnd(); } void CItems::RenderLaser(const struct CNetObj_Laser *pCurrent) { vec2 Pos = vec2(pCurrent->m_X, pCurrent->m_Y); vec2 From = vec2(pCurrent->m_FromX, pCurrent->m_FromY); vec2 Dir = normalize(Pos-From); float Ticks = Client()->GameTick() + Client()->IntraGameTick() - pCurrent->m_StartTick; float Ms = (Ticks/50.0f) * 1000.0f; float a = Ms / m_pClient->m_Tuning.m_LaserBounceDelay; a = clamp(a, 0.0f, 1.0f); float Ia = 1-a; vec2 Out, Border; Graphics()->BlendNormal(); Graphics()->TextureClear(); Graphics()->QuadsBegin(); //vec4 inner_color(0.15f,0.35f,0.75f,1.0f); //vec4 outer_color(0.65f,0.85f,1.0f,1.0f); // do outline vec4 OuterColor(0.075f, 0.075f, 0.25f, 1.0f); Graphics()->SetColor(OuterColor.r, OuterColor.g, OuterColor.b, 1.0f); Out = vec2(Dir.y, -Dir.x) * (7.0f*Ia); IGraphics::CFreeformItem Freeform( From.x-Out.x, From.y-Out.y, From.x+Out.x, From.y+Out.y, Pos.x-Out.x, Pos.y-Out.y, Pos.x+Out.x, Pos.y+Out.y); Graphics()->QuadsDrawFreeform(&Freeform, 1); // do inner vec4 InnerColor(0.5f, 0.5f, 1.0f, 1.0f); Out = vec2(Dir.y, -Dir.x) * (5.0f*Ia); Graphics()->SetColor(InnerColor.r, InnerColor.g, InnerColor.b, 1.0f); // center Freeform = IGraphics::CFreeformItem( From.x-Out.x, From.y-Out.y, From.x+Out.x, From.y+Out.y, Pos.x-Out.x, Pos.y-Out.y, Pos.x+Out.x, Pos.y+Out.y); Graphics()->QuadsDrawFreeform(&Freeform, 1); Graphics()->QuadsEnd(); // render head { Graphics()->BlendNormal(); Graphics()->TextureSet(g_pData->m_aImages[IMAGE_PARTICLES].m_Id); Graphics()->QuadsBegin(); int Sprites[] = {SPRITE_PART_SPLAT01, SPRITE_PART_SPLAT02, SPRITE_PART_SPLAT03}; RenderTools()->SelectSprite(Sprites[Client()->GameTick()%3]); Graphics()->QuadsSetRotation(Client()->GameTick()); Graphics()->SetColor(OuterColor.r, OuterColor.g, OuterColor.b, 1.0f); IGraphics::CQuadItem QuadItem(Pos.x, Pos.y, 24, 24); Graphics()->QuadsDraw(&QuadItem, 1); Graphics()->SetColor(InnerColor.r, InnerColor.g, InnerColor.b, 1.0f); QuadItem = IGraphics::CQuadItem(Pos.x, Pos.y, 20, 20); Graphics()->QuadsDraw(&QuadItem, 1); Graphics()->QuadsEnd(); } Graphics()->BlendNormal(); } void CItems::OnRender() { if(Client()->State() < IClient::STATE_ONLINE) return; int Num = Client()->SnapNumItems(IClient::SNAP_CURRENT); for(int i = 0; i < Num; i++) { IClient::CSnapItem Item; const void *pData = Client()->SnapGetItem(IClient::SNAP_CURRENT, i, &Item); if(Item.m_Type == NETOBJTYPE_PROJECTILE) { RenderProjectile((const CNetObj_Projectile *)pData, Item.m_ID); } else if(Item.m_Type == NETOBJTYPE_PICKUP) { const void *pPrev = Client()->SnapFindItem(IClient::SNAP_PREV, Item.m_Type, Item.m_ID); if(pPrev) RenderPickup((const CNetObj_Pickup *)pPrev, (const CNetObj_Pickup *)pData); } else if(Item.m_Type == NETOBJTYPE_LASER) { RenderLaser((const CNetObj_Laser *)pData); } } // render flag for(int i = 0; i < Num; i++) { IClient::CSnapItem Item; const void *pData = Client()->SnapGetItem(IClient::SNAP_CURRENT, i, &Item); if(Item.m_Type == NETOBJTYPE_FLAG) { const void *pPrev = Client()->SnapFindItem(IClient::SNAP_PREV, Item.m_Type, Item.m_ID); if (pPrev) { const void *pPrevGameDataFlag = Client()->SnapFindItem(IClient::SNAP_PREV, NETOBJTYPE_GAMEDATAFLAG, m_pClient->m_Snap.m_GameDataFlagSnapID); RenderFlag(static_cast<const CNetObj_Flag *>(pPrev), static_cast<const CNetObj_Flag *>(pData), static_cast<const CNetObj_GameDataFlag *>(pPrevGameDataFlag), m_pClient->m_Snap.m_pGameDataFlag); } } } // render extra projectiles for(int i = 0; i < m_NumExtraProjectiles; i++) { if(m_aExtraProjectiles[i].m_StartTick < Client()->GameTick()) { m_aExtraProjectiles[i] = m_aExtraProjectiles[m_NumExtraProjectiles-1]; m_NumExtraProjectiles--; } else RenderProjectile(&m_aExtraProjectiles[i], 0); } } void CItems::AddExtraProjectile(CNetObj_Projectile *pProj) { if(m_NumExtraProjectiles != MAX_EXTRA_PROJECTILES) { m_aExtraProjectiles[m_NumExtraProjectiles] = *pProj; m_NumExtraProjectiles++; } } ================================================ FILE: src/game/client/components/items.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_CLIENT_COMPONENTS_ITEMS_H #define GAME_CLIENT_COMPONENTS_ITEMS_H #include <game/client/component.h> class CItems : public CComponent { enum { MAX_EXTRA_PROJECTILES=32, }; CNetObj_Projectile m_aExtraProjectiles[MAX_EXTRA_PROJECTILES]; int m_NumExtraProjectiles; void RenderProjectile(const CNetObj_Projectile *pCurrent, int ItemID); void RenderPickup(const CNetObj_Pickup *pPrev, const CNetObj_Pickup *pCurrent); void RenderFlag(const CNetObj_Flag *pPrev, const CNetObj_Flag *pCurrent, const CNetObj_GameDataFlag *pPrevGameDataFlag, const CNetObj_GameDataFlag *pCurGameDataFlag); void RenderLaser(const struct CNetObj_Laser *pCurrent); public: virtual void OnReset(); virtual void OnRender(); void AddExtraProjectile(CNetObj_Projectile *pProj); }; #endif ================================================ FILE: src/game/client/components/killmessages.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <engine/graphics.h> #include <engine/textrender.h> #include <game/generated/protocol.h> #include <game/generated/client_data.h> #include <game/client/gameclient.h> #include <game/client/animstate.h> #include "killmessages.h" void CKillMessages::OnReset() { m_KillmsgCurrent = 0; for(int i = 0; i < MAX_KILLMSGS; i++) m_aKillmsgs[i].m_Tick = -100000; } void CKillMessages::OnMessage(int MsgType, void *pRawMsg) { if(MsgType == NETMSGTYPE_SV_KILLMSG) { CNetMsg_Sv_KillMsg *pMsg = (CNetMsg_Sv_KillMsg *)pRawMsg; // unpack messages CKillMsg Kill; Kill.m_VictimID = pMsg->m_Victim; Kill.m_VictimTeam = m_pClient->m_aClients[Kill.m_VictimID].m_Team; str_copy(Kill.m_aVictimName, m_pClient->m_aClients[Kill.m_VictimID].m_aName, sizeof(Kill.m_aVictimName)); Kill.m_VictimRenderInfo = m_pClient->m_aClients[Kill.m_VictimID].m_RenderInfo; Kill.m_KillerID = pMsg->m_Killer; Kill.m_KillerTeam = m_pClient->m_aClients[Kill.m_KillerID].m_Team; str_copy(Kill.m_aKillerName, m_pClient->m_aClients[Kill.m_KillerID].m_aName, sizeof(Kill.m_aKillerName)); Kill.m_KillerRenderInfo = m_pClient->m_aClients[Kill.m_KillerID].m_RenderInfo; Kill.m_Weapon = pMsg->m_Weapon; Kill.m_ModeSpecial = pMsg->m_ModeSpecial; Kill.m_Tick = Client()->GameTick(); // add the message m_KillmsgCurrent = (m_KillmsgCurrent+1)%MAX_KILLMSGS; m_aKillmsgs[m_KillmsgCurrent] = Kill; } } void CKillMessages::OnRender() { float Width = 400*3.0f*Graphics()->ScreenAspect(); float Height = 400*3.0f; Graphics()->MapScreen(0, 0, Width*1.5f, Height*1.5f); float StartX = Width*1.5f-10.0f; float y = 20.0f; for(int i = 1; i <= MAX_KILLMSGS; i++) { int r = (m_KillmsgCurrent+i)%MAX_KILLMSGS; if(Client()->GameTick() > m_aKillmsgs[r].m_Tick+50*10) continue; float FontSize = 36.0f; float KillerNameW = TextRender()->TextWidth(0, FontSize, m_aKillmsgs[r].m_aKillerName, -1); float VictimNameW = TextRender()->TextWidth(0, FontSize, m_aKillmsgs[r].m_aVictimName, -1); float x = StartX; // render victim name x -= VictimNameW; TextRender()->Text(0, x, y, FontSize, m_aKillmsgs[r].m_aVictimName, -1); // render victim tee x -= 24.0f; if(m_pClient->m_GameInfo.m_GameFlags&GAMEFLAG_FLAGS) { if(m_aKillmsgs[r].m_ModeSpecial&1) { Graphics()->BlendNormal(); Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id); Graphics()->QuadsBegin(); if(m_aKillmsgs[r].m_VictimTeam == TEAM_RED) RenderTools()->SelectSprite(SPRITE_FLAG_BLUE); else RenderTools()->SelectSprite(SPRITE_FLAG_RED); float Size = 56.0f; IGraphics::CQuadItem QuadItem(x, y-16, Size/2, Size); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); } } RenderTools()->RenderTee(CAnimState::GetIdle(), &m_aKillmsgs[r].m_VictimRenderInfo, EMOTE_PAIN, vec2(-1,0), vec2(x, y+28)); x -= 32.0f; // render weapon x -= 44.0f; if (m_aKillmsgs[r].m_Weapon >= 0) { Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id); Graphics()->QuadsBegin(); RenderTools()->SelectSprite(g_pData->m_Weapons.m_aId[m_aKillmsgs[r].m_Weapon].m_pSpriteBody); RenderTools()->DrawSprite(x, y+28, 96); Graphics()->QuadsEnd(); } x -= 52.0f; if(m_aKillmsgs[r].m_VictimID != m_aKillmsgs[r].m_KillerID) { if(m_pClient->m_GameInfo.m_GameFlags&GAMEFLAG_FLAGS) { if(m_aKillmsgs[r].m_ModeSpecial&2) { Graphics()->BlendNormal(); Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id); Graphics()->QuadsBegin(); if(m_aKillmsgs[r].m_KillerTeam == TEAM_RED) RenderTools()->SelectSprite(SPRITE_FLAG_BLUE, SPRITE_FLAG_FLIP_X); else RenderTools()->SelectSprite(SPRITE_FLAG_RED, SPRITE_FLAG_FLIP_X); float Size = 56.0f; IGraphics::CQuadItem QuadItem(x-56, y-16, Size/2, Size); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); } } // render killer tee x -= 24.0f; RenderTools()->RenderTee(CAnimState::GetIdle(), &m_aKillmsgs[r].m_KillerRenderInfo, EMOTE_ANGRY, vec2(1,0), vec2(x, y+28)); x -= 32.0f; // render killer name x -= KillerNameW; TextRender()->Text(0, x, y, FontSize, m_aKillmsgs[r].m_aKillerName, -1); } y += 46.0f; } } ================================================ FILE: src/game/client/components/killmessages.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_CLIENT_COMPONENTS_KILLMESSAGES_H #define GAME_CLIENT_COMPONENTS_KILLMESSAGES_H #include <game/client/component.h> class CKillMessages : public CComponent { public: // kill messages struct CKillMsg { int m_Weapon; int m_VictimID; int m_VictimTeam; char m_aVictimName[64]; CTeeRenderInfo m_VictimRenderInfo; int m_KillerID; int m_KillerTeam; char m_aKillerName[64]; CTeeRenderInfo m_KillerRenderInfo; int m_ModeSpecial; // for CTF, if the guy is carrying a flag for example int m_Tick; }; enum { MAX_KILLMSGS = 5, }; CKillMsg m_aKillmsgs[MAX_KILLMSGS]; int m_KillmsgCurrent; virtual void OnReset(); virtual void OnRender(); virtual void OnMessage(int MsgType, void *pRawMsg); }; #endif ================================================ FILE: src/game/client/components/mapimages.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <engine/graphics.h> #include <engine/map.h> #include <engine/storage.h> #include <game/client/component.h> #include <game/mapitems.h> #include "mapimages.h" CMapImages::CMapImages() { m_Count = 0; m_MenuCount = 0; } void CMapImages::OnMapLoad() { IMap *pMap = Kernel()->RequestInterface<IMap>(); // unload all textures for(int i = 0; i < m_Count; i++) { Graphics()->UnloadTexture(m_aTextures[i]); m_aTextures[i] = IGraphics::CTextureHandle(); } m_Count = 0; int Start; pMap->GetType(MAPITEMTYPE_IMAGE, &Start, &m_Count); // load new textures for(int i = 0; i < m_Count; i++) { CMapItemImage *pImg = (CMapItemImage *)pMap->GetItem(Start+i, 0, 0); if(pImg->m_External || (pImg->m_Version > 1 && pImg->m_Format != CImageInfo::FORMAT_RGB && pImg->m_Format != CImageInfo::FORMAT_RGBA)) { char Buf[256]; char *pName = (char *)pMap->GetData(pImg->m_ImageName); str_format(Buf, sizeof(Buf), "mapres/%s.png", pName); m_aTextures[i] = Graphics()->LoadTexture(Buf, IStorage::TYPE_ALL, CImageInfo::FORMAT_AUTO, 0); } else { void *pData = pMap->GetData(pImg->m_ImageData); m_aTextures[i] = Graphics()->LoadTextureRaw(pImg->m_Width, pImg->m_Height, pImg->m_Version == 1 ? CImageInfo::FORMAT_RGBA : pImg->m_Format, pData, CImageInfo::FORMAT_RGBA, 0); pMap->UnloadData(pImg->m_ImageData); } } } void CMapImages::OnMenuMapLoad(IMap *pMap) { // unload all textures for(int i = 0; i < m_MenuCount; i++) { Graphics()->UnloadTexture(m_aMenuTextures[i]); m_aMenuTextures[i] = IGraphics::CTextureHandle(); } m_MenuCount = 0; int Start; pMap->GetType(MAPITEMTYPE_IMAGE, &Start, &m_MenuCount); // load new textures for(int i = 0; i < m_MenuCount; i++) { CMapItemImage *pImg = (CMapItemImage *)pMap->GetItem(Start+i, 0, 0); if(pImg->m_External || (pImg->m_Version > 1 && pImg->m_Format != CImageInfo::FORMAT_RGB && pImg->m_Format != CImageInfo::FORMAT_RGBA)) { char Buf[256]; char *pName = (char *)pMap->GetData(pImg->m_ImageName); str_format(Buf, sizeof(Buf), "mapres/%s.png", pName); m_aMenuTextures[i] = Graphics()->LoadTexture(Buf, IStorage::TYPE_ALL, CImageInfo::FORMAT_AUTO, 0); } else { void *pData = pMap->GetData(pImg->m_ImageData); m_aMenuTextures[i] = Graphics()->LoadTextureRaw(pImg->m_Width, pImg->m_Height, pImg->m_Version == 1 ? CImageInfo::FORMAT_RGBA : pImg->m_Format, pData, CImageInfo::FORMAT_RGBA, 0); pMap->UnloadData(pImg->m_ImageData); } } } IGraphics::CTextureHandle CMapImages::Get(int Index) const { if(Client()->State() == IClient::STATE_ONLINE || Client()->State() == IClient::STATE_DEMOPLAYBACK) return m_aTextures[Index]; return m_aMenuTextures[Index]; } int CMapImages::Num() const { if(Client()->State() == IClient::STATE_ONLINE || Client()->State() == IClient::STATE_DEMOPLAYBACK) return m_Count; return m_MenuCount; } ================================================ FILE: src/game/client/components/mapimages.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_CLIENT_COMPONENTS_MAPIMAGES_H #define GAME_CLIENT_COMPONENTS_MAPIMAGES_H #include <game/client/component.h> class CMapImages : public CComponent { IGraphics::CTextureHandle m_aTextures[64]; IGraphics::CTextureHandle m_aMenuTextures[64]; int m_Count; int m_MenuCount; public: CMapImages(); IGraphics::CTextureHandle Get(int Index) const; int Num() const; virtual void OnMapLoad(); void OnMenuMapLoad(class IMap *pMap); }; #endif ================================================ FILE: src/game/client/components/maplayers.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <engine/graphics.h> #include <engine/keys.h> #include <engine/demo.h> #include <engine/serverbrowser.h> #include <engine/shared/config.h> #include <engine/storage.h> #include <game/layers.h> #include <game/client/gameclient.h> #include <game/client/component.h> #include <game/client/render.h> #include <game/client/components/camera.h> #include <game/client/components/mapimages.h> #include "maplayers.h" CMapLayers::CMapLayers(int t) { m_Type = t; m_CurrentLocalTick = 0; m_LastLocalTick = 0; m_EnvelopeUpdate = false; m_pMenuMap = 0; m_pMenuLayers = 0; } void CMapLayers::OnInit() { if(m_Type == TYPE_BACKGROUND) { m_pMenuLayers = new CLayers; m_pMenuMap = CreateEngineMap(); char aBuf[128]; str_format(aBuf, sizeof(aBuf), "maps/%s.map", g_Config.m_ClBackgroundMap); if(!m_pMenuMap->Load(aBuf, m_pClient->Storage())) { str_format(aBuf, sizeof(aBuf), "map '%s' not found", g_Config.m_ClBackgroundMap); Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "client", aBuf); return; } str_format(aBuf, sizeof(aBuf), "loaded map '%s'", g_Config.m_ClBackgroundMap); Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "client", aBuf); m_pMenuLayers->Init(Kernel(), m_pMenuMap); RenderTools()->RenderTilemapGenerateSkip(m_pMenuLayers); m_pClient->m_pMapimages->OnMenuMapLoad(m_pMenuMap); } } void CMapLayers::EnvelopeUpdate() { if(Client()->State() == IClient::STATE_DEMOPLAYBACK) { const IDemoPlayer::CInfo *pInfo = DemoPlayer()->BaseInfo(); m_CurrentLocalTick = pInfo->m_CurrentTick; m_LastLocalTick = pInfo->m_CurrentTick; m_EnvelopeUpdate = true; } } void CMapLayers::MapScreenToGroup(float CenterX, float CenterY, CMapItemGroup *pGroup) { float Points[4]; RenderTools()->MapscreenToWorld(CenterX, CenterY, pGroup->m_ParallaxX/100.0f, pGroup->m_ParallaxY/100.0f, pGroup->m_OffsetX, pGroup->m_OffsetY, Graphics()->ScreenAspect(), m_pClient->m_pCamera->m_Zoom, Points); Graphics()->MapScreen(Points[0], Points[1], Points[2], Points[3]); } void CMapLayers::EnvelopeEval(float TimeOffset, int Env, float *pChannels, void *pUser) { CMapLayers *pThis = (CMapLayers *)pUser; pChannels[0] = 0; pChannels[1] = 0; pChannels[2] = 0; pChannels[3] = 0; CEnvPoint *pPoints = 0; CLayers *pLayers = 0; { int Start, Num; if(pThis->Client()->State() == IClient::STATE_ONLINE || pThis->Client()->State() == IClient::STATE_DEMOPLAYBACK) pLayers = pThis->Layers(); else pLayers = pThis->m_pMenuLayers; pLayers->Map()->GetType(MAPITEMTYPE_ENVPOINTS, &Start, &Num); if(Num) pPoints = (CEnvPoint *)pLayers->Map()->GetItem(Start, 0, 0); } int Start, Num; pLayers->Map()->GetType(MAPITEMTYPE_ENVELOPE, &Start, &Num); if(Env >= Num) return; CMapItemEnvelope *pItem = (CMapItemEnvelope *)pLayers->Map()->GetItem(Start+Env, 0, 0); static float s_Time = 0.0f; static float s_LastLocalTime = pThis->Client()->LocalTime(); if(pThis->Client()->State() == IClient::STATE_DEMOPLAYBACK) { const IDemoPlayer::CInfo *pInfo = pThis->DemoPlayer()->BaseInfo(); if(!pInfo->m_Paused || pThis->m_EnvelopeUpdate) { if(pThis->m_CurrentLocalTick != pInfo->m_CurrentTick) { pThis->m_LastLocalTick = pThis->m_CurrentLocalTick; pThis->m_CurrentLocalTick = pInfo->m_CurrentTick; } s_Time = mix(pThis->m_LastLocalTick / (float)pThis->Client()->GameTickSpeed(), pThis->m_CurrentLocalTick / (float)pThis->Client()->GameTickSpeed(), pThis->Client()->IntraGameTick()); } pThis->RenderTools()->RenderEvalEnvelope(pPoints+pItem->m_StartPoint, pItem->m_NumPoints, 4, s_Time+TimeOffset, pChannels); } else if(pThis->Client()->State() != IClient::STATE_OFFLINE) { if(pThis->m_pClient->m_Snap.m_pGameData && !(pThis->m_pClient->m_Snap.m_pGameData->m_GameStateFlags&GAMESTATEFLAG_PAUSED)) { if(pItem->m_Version < 2 || pItem->m_Synchronized) { s_Time = mix((pThis->Client()->PrevGameTick()-pThis->m_pClient->m_Snap.m_pGameData->m_GameStartTick) / (float)pThis->Client()->GameTickSpeed(), (pThis->Client()->GameTick()-pThis->m_pClient->m_Snap.m_pGameData->m_GameStartTick) / (float)pThis->Client()->GameTickSpeed(), pThis->Client()->IntraGameTick()); } else s_Time += pThis->Client()->LocalTime()-s_LastLocalTime; } pThis->RenderTools()->RenderEvalEnvelope(pPoints+pItem->m_StartPoint, pItem->m_NumPoints, 4, s_Time+TimeOffset, pChannels); s_LastLocalTime = pThis->Client()->LocalTime(); } else { s_Time = pThis->Client()->LocalTime(); pThis->RenderTools()->RenderEvalEnvelope(pPoints+pItem->m_StartPoint, pItem->m_NumPoints, 4, s_Time+TimeOffset, pChannels); } } void CMapLayers::OnRender() { if((Client()->State() != IClient::STATE_ONLINE && Client()->State() != IClient::STATE_DEMOPLAYBACK && !m_pMenuMap)) return; CLayers *pLayers = 0; if(Client()->State() == IClient::STATE_ONLINE || Client()->State() == IClient::STATE_DEMOPLAYBACK) pLayers = Layers(); else if(m_pMenuMap->IsLoaded()) pLayers = m_pMenuLayers; if(!pLayers) return; CUIRect Screen; Graphics()->GetScreen(&Screen.x, &Screen.y, &Screen.w, &Screen.h); vec2 Center = m_pClient->m_pCamera->m_Center; //float center_x = gameclient.camera->center.x; //float center_y = gameclient.camera->center.y; bool PassedGameLayer = false; for(int g = 0; g < pLayers->NumGroups(); g++) { CMapItemGroup *pGroup = pLayers->GetGroup(g); if(!g_Config.m_GfxNoclip && pGroup->m_Version >= 2 && pGroup->m_UseClipping) { // set clipping float Points[4]; MapScreenToGroup(Center.x, Center.y, pLayers->GameGroup()); Graphics()->GetScreen(&Points[0], &Points[1], &Points[2], &Points[3]); float x0 = (pGroup->m_ClipX - Points[0]) / (Points[2]-Points[0]); float y0 = (pGroup->m_ClipY - Points[1]) / (Points[3]-Points[1]); float x1 = ((pGroup->m_ClipX+pGroup->m_ClipW) - Points[0]) / (Points[2]-Points[0]); float y1 = ((pGroup->m_ClipY+pGroup->m_ClipH) - Points[1]) / (Points[3]-Points[1]); Graphics()->ClipEnable((int)(x0*Graphics()->ScreenWidth()), (int)(y0*Graphics()->ScreenHeight()), (int)((x1-x0)*Graphics()->ScreenWidth()), (int)((y1-y0)*Graphics()->ScreenHeight())); } MapScreenToGroup(Center.x, Center.y, pGroup); for(int l = 0; l < pGroup->m_NumLayers; l++) { CMapItemLayer *pLayer = pLayers->GetLayer(pGroup->m_StartLayer+l); bool Render = false; bool IsGameLayer = false; if(pLayer == (CMapItemLayer*)pLayers->GameLayer()) { IsGameLayer = true; PassedGameLayer = 1; } // skip rendering if detail layers if not wanted if(pLayer->m_Flags&LAYERFLAG_DETAIL && !g_Config.m_GfxHighDetail && !IsGameLayer && (Client()->State() == IClient::STATE_ONLINE || Client()->State() == IClient::STATE_DEMOPLAYBACK)) continue; if(m_Type == -1) Render = true; else if(m_Type == 0) { if(PassedGameLayer && (Client()->State() == IClient::STATE_ONLINE || Client()->State() == IClient::STATE_DEMOPLAYBACK)) return; Render = true; } else { if(PassedGameLayer && !IsGameLayer) Render = true; } if(Render && pLayer->m_Type == LAYERTYPE_TILES && Input()->KeyPressed(KEY_LCTRL) && Input()->KeyPressed(KEY_LSHIFT) && Input()->KeyDown(KEY_KP0)) { CMapItemLayerTilemap *pTMap = (CMapItemLayerTilemap *)pLayer; CTile *pTiles = (CTile *)pLayers->Map()->GetData(pTMap->m_Data); CServerInfo CurrentServerInfo; Client()->GetServerInfo(&CurrentServerInfo); char aFilename[256]; str_format(aFilename, sizeof(aFilename), "dumps/tilelayer_dump_%s-%d-%d-%dx%d.txt", CurrentServerInfo.m_aMap, g, l, pTMap->m_Width, pTMap->m_Height); IOHANDLE File = Storage()->OpenFile(aFilename, IOFLAG_WRITE, IStorage::TYPE_SAVE); if(File) { for(int y = 0; y < pTMap->m_Height; y++) { for(int x = 0; x < pTMap->m_Width; x++) io_write(File, &(pTiles[y*pTMap->m_Width + x].m_Index), sizeof(pTiles[y*pTMap->m_Width + x].m_Index)); io_write_newline(File); } io_close(File); } } if(Render && !IsGameLayer) { //layershot_begin(); if(pLayer->m_Type == LAYERTYPE_TILES) { CMapItemLayerTilemap *pTMap = (CMapItemLayerTilemap *)pLayer; if(pTMap->m_Image == -1) Graphics()->TextureClear(); else Graphics()->TextureSet(m_pClient->m_pMapimages->Get(pTMap->m_Image)); CTile *pTiles = (CTile *)pLayers->Map()->GetData(pTMap->m_Data); Graphics()->BlendNone(); vec4 Color = vec4(pTMap->m_Color.r/255.0f, pTMap->m_Color.g/255.0f, pTMap->m_Color.b/255.0f, pTMap->m_Color.a/255.0f); RenderTools()->RenderTilemap(pTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_OPAQUE, EnvelopeEval, this, pTMap->m_ColorEnv, pTMap->m_ColorEnvOffset); Graphics()->BlendNormal(); RenderTools()->RenderTilemap(pTiles, pTMap->m_Width, pTMap->m_Height, 32.0f, Color, TILERENDERFLAG_EXTEND|LAYERRENDERFLAG_TRANSPARENT, EnvelopeEval, this, pTMap->m_ColorEnv, pTMap->m_ColorEnvOffset); } else if(pLayer->m_Type == LAYERTYPE_QUADS) { CMapItemLayerQuads *pQLayer = (CMapItemLayerQuads *)pLayer; if(pQLayer->m_Image == -1) Graphics()->TextureClear(); else Graphics()->TextureSet(m_pClient->m_pMapimages->Get(pQLayer->m_Image)); CQuad *pQuads = (CQuad *)pLayers->Map()->GetDataSwapped(pQLayer->m_Data); Graphics()->BlendNone(); RenderTools()->RenderQuads(pQuads, pQLayer->m_NumQuads, LAYERRENDERFLAG_OPAQUE, EnvelopeEval, this); Graphics()->BlendNormal(); RenderTools()->RenderQuads(pQuads, pQLayer->m_NumQuads, LAYERRENDERFLAG_TRANSPARENT, EnvelopeEval, this); } //layershot_end(); } } if(!g_Config.m_GfxNoclip) Graphics()->ClipDisable(); } if(!g_Config.m_GfxNoclip) Graphics()->ClipDisable(); // reset the screen like it was before Graphics()->MapScreen(Screen.x, Screen.y, Screen.w, Screen.h); } void CMapLayers::ConchainBackgroundMap(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData) { pfnCallback(pResult, pCallbackUserData); if(pResult->NumArguments()) ((CMapLayers*)pUserData)->BackgroundMapUpdate(); } void CMapLayers::OnConsoleInit() { Console()->Chain("cl_background_map", ConchainBackgroundMap, this); } void CMapLayers::BackgroundMapUpdate() { if(m_Type == TYPE_BACKGROUND && m_pMenuMap) { // uload map m_pMenuMap->Unload(); char aBuf[128]; str_format(aBuf, sizeof(aBuf), "maps/%s.map", g_Config.m_ClBackgroundMap); if(!m_pMenuMap->Load(aBuf, m_pClient->Storage())) { str_format(aBuf, sizeof(aBuf), "map '%s' not found", g_Config.m_ClBackgroundMap); Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "client", aBuf); return; } str_format(aBuf, sizeof(aBuf), "loaded map '%s'", g_Config.m_ClBackgroundMap); Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "client", aBuf); m_pMenuLayers->Init(Kernel(), m_pMenuMap); RenderTools()->RenderTilemapGenerateSkip(m_pMenuLayers); m_pClient->m_pMapimages->OnMenuMapLoad(m_pMenuMap); } } ================================================ FILE: src/game/client/components/maplayers.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_CLIENT_COMPONENTS_MAPLAYERS_H #define GAME_CLIENT_COMPONENTS_MAPLAYERS_H #include <game/client/component.h> class CMapLayers : public CComponent { CLayers *m_pMenuLayers; IEngineMap *m_pMenuMap; int m_Type; int m_CurrentLocalTick; int m_LastLocalTick; bool m_EnvelopeUpdate; void MapScreenToGroup(float CenterX, float CenterY, CMapItemGroup *pGroup); static void EnvelopeEval(float TimeOffset, int Env, float *pChannels, void *pUser); public: enum { TYPE_BACKGROUND=0, TYPE_FOREGROUND, }; CMapLayers(int Type); virtual void OnInit(); virtual void OnRender(); void EnvelopeUpdate(); static void ConchainBackgroundMap(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData); virtual void OnConsoleInit(); void BackgroundMapUpdate(); bool MenuMapLoaded() { return m_pMenuMap ? m_pMenuMap->IsLoaded() : false; } }; #endif ================================================ FILE: src/game/client/components/menus.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <math.h> #include <base/system.h> #include <base/math.h> #include <base/vmath.h> #include <engine/config.h> #include <engine/editor.h> #include <engine/engine.h> #include <engine/friends.h> #include <engine/keys.h> #include <engine/serverbrowser.h> #include <engine/storage.h> #include <engine/textrender.h> #include <engine/shared/config.h> #include <game/version.h> #include <game/generated/protocol.h> #include <game/generated/client_data.h> #include <game/client/components/camera.h> #include <game/client/components/sounds.h> #include <game/client/gameclient.h> #include <game/client/lineinput.h> #include <mastersrv/mastersrv.h> #include "maplayers.h" #include "countryflags.h" #include "menus.h" #include "skins.h" float CMenus::ms_ButtonHeight = 25.0f; float CMenus::ms_ListheaderHeight = 20.0f; float CMenus::ms_FontmodHeight = 0.8f; IInput::CEvent CMenus::m_aInputEvents[MAX_INPUTEVENTS]; int CMenus::m_NumInputEvents; CMenus::CMenus() { m_Popup = POPUP_NONE; m_NextPopup = POPUP_NONE; m_ActivePage = PAGE_INTERNET; m_GamePage = PAGE_GAME; m_NeedRestartGraphics = false; m_NeedRestartSound = false; m_TeePartSelected = CSkins::SKINPART_BODY; m_aSaveSkinName[0] = 0; m_RefreshSkinSelector = true; m_pSelectedSkin = 0; m_MenuActive = true; m_UseMouseButtons = true; m_MenuPage = PAGE_START; m_InfoMode = false; m_EscapePressed = false; m_EnterPressed = false; m_DeletePressed = false; m_NumInputEvents = 0; m_LastInput = time_get(); str_copy(m_aCurrentDemoFolder, "demos", sizeof(m_aCurrentDemoFolder)); m_aCallvoteReason[0] = 0; m_FriendlistSelectedIndex = -1; m_SelectedFilter = 0; m_SelectedServer.m_Filter = -1; m_SelectedServer.m_Index = -1; } float *CMenus::ButtonFade(const void *pID, float Seconds, int Checked) { float *pFade = (float*)pID; if(UI()->HotItem() == pID || Checked) *pFade = Seconds; else if(*pFade > 0.0f) { *pFade -= Client()->RenderFrameTime(); if(*pFade < 0.0f) *pFade = 0.0f; } return pFade; } int CMenus::DoIcon(int ImageId, int SpriteId, const CUIRect *pRect) { Graphics()->TextureSet(g_pData->m_aImages[ImageId].m_Id); Graphics()->QuadsBegin(); RenderTools()->SelectSprite(SpriteId); IGraphics::CQuadItem QuadItem(pRect->x, pRect->y, pRect->w, pRect->h); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); return 0; } int CMenus::DoButton_Toggle(const void *pID, int Checked, const CUIRect *pRect, bool Active) { Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GUIBUTTONS].m_Id); Graphics()->QuadsBegin(); if(!Active) Graphics()->SetColor(1.0f, 1.0f, 1.0f, 0.5f); RenderTools()->SelectSprite(Checked?SPRITE_GUIBUTTON_ON:SPRITE_GUIBUTTON_OFF); IGraphics::CQuadItem QuadItem(pRect->x, pRect->y, pRect->w, pRect->h); Graphics()->QuadsDrawTL(&QuadItem, 1); if(UI()->HotItem() == pID && Active) { RenderTools()->SelectSprite(SPRITE_GUIBUTTON_HOVER); IGraphics::CQuadItem QuadItem(pRect->x, pRect->y, pRect->w, pRect->h); Graphics()->QuadsDrawTL(&QuadItem, 1); } Graphics()->QuadsEnd(); return Active ? UI()->DoButtonLogic(pID, "", Checked, pRect) : 0; } int CMenus::DoButton_Menu(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Corners, float r, float FontFactor, vec4 ColorHot, bool TextFade) { float Seconds = 0.6f; // 0.6 seconds for fade float *pFade = ButtonFade(pID, Seconds, Checked); float FadeVal = *pFade/Seconds; vec4 Color = mix(vec4(0.0f, 0.0f, 0.0f, 0.25f), ColorHot, FadeVal); RenderTools()->DrawUIRect(pRect, Color, Corners, r); CUIRect Temp; pRect->HMargin(pRect->h>=20.0f?2.0f:1.0f, &Temp); Temp.HMargin((Temp.h*FontFactor)/2.0f, &Temp); if(TextFade) { TextRender()->TextColor(1.0f-FadeVal, 1.0f-FadeVal, 1.0f-FadeVal, 1.0f); TextRender()->TextOutlineColor(0.0f+FadeVal, 0.0f+FadeVal, 0.0f+FadeVal, 0.25f); } UI()->DoLabel(&Temp, pText, Temp.h*ms_FontmodHeight, 0); if(TextFade) { TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); TextRender()->TextOutlineColor(0.0f, 0.0f, 0.0f, 0.3f); } return UI()->DoButtonLogic(pID, pText, Checked, pRect); } int CMenus::DoButton_MenuImage(const void *pID, const char *pText, int Checked, const CUIRect *pRect, const char *pImageName, float r, float FontFactor) { float Seconds = 0.6f; // 0.6 seconds for fade float *pFade = ButtonFade(pID, Seconds); float FadeVal = *pFade/Seconds; RenderTools()->DrawUIRect(pRect, vec4(0.0f+FadeVal, 0.0f+FadeVal, 0.0f+FadeVal, 0.25f+FadeVal*0.5f), CUI::CORNER_ALL, r); CUIRect Text, Image; pRect->VSplitRight(pRect->h*4.0f, &Text, &Image); // always correct ratio for image // render image const CMenuImage *pImage = FindMenuImage(pImageName); if(pImage) { Graphics()->TextureSet(pImage->m_GreyTexture); Graphics()->QuadsBegin(); Graphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f); IGraphics::CQuadItem QuadItem(Image.x, Image.y, Image.w, Image.h); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); if(*pFade > 0.0f) { Graphics()->TextureSet(pImage->m_OrgTexture); Graphics()->QuadsBegin(); Graphics()->SetColor(1.0f, 1.0f, 1.0f, *pFade/Seconds); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); } } Text.HMargin(pRect->h>=20.0f?2.0f:1.0f, &Text); Text.HMargin((Text.h*FontFactor)/2.0f, &Text); Text.VSplitLeft(r, 0, &Text); TextRender()->TextColor(1.0f-FadeVal, 1.0f-FadeVal, 1.0f-FadeVal, 1.0f); TextRender()->TextOutlineColor(0.0f+FadeVal, 0.0f+FadeVal, 0.0f+FadeVal, 0.25f); UI()->DoLabel(&Text, pText, Text.h*ms_FontmodHeight, 0); TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); TextRender()->TextOutlineColor(0.0f, 0.0f, 0.0f, 0.3f); return UI()->DoButtonLogic(pID, pText, Checked, pRect); } void CMenus::DoButton_KeySelect(const void *pID, const char *pText, int Checked, const CUIRect *pRect) { float Seconds = 0.6f; // 0.6 seconds for fade float *pFade = ButtonFade(pID, Seconds, Checked); float FadeVal = *pFade/Seconds; RenderTools()->DrawUIRect(pRect, vec4(0.0f+FadeVal, 0.0f+FadeVal, 0.0f+FadeVal, 0.25f+FadeVal*0.5f), CUI::CORNER_ALL, 5.0f); CUIRect Temp; pRect->HMargin(1.0f, &Temp); TextRender()->TextColor(1.0f-FadeVal, 1.0f-FadeVal, 1.0f-FadeVal, 1.0f); TextRender()->TextOutlineColor(0.0f+FadeVal, 0.0f+FadeVal, 0.0f+FadeVal, 0.25f); UI()->DoLabel(&Temp, pText, Temp.h*ms_FontmodHeight, 0); TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); TextRender()->TextOutlineColor(0.0f, 0.0f, 0.0f, 0.3f); } int CMenus::DoButton_MenuTab(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Corners) { if(Checked) RenderTools()->DrawUIRect(pRect, vec4(1.0f, 1.0f, 1.0f, 0.25f), Corners, 10.0f); else { RenderTools()->DrawUIRect(pRect, vec4(0.0f, 0.0f, 0.0f, 0.25f), Corners, 10.0f); TextRender()->TextColor(1.0f, 1.0f, 1.0f, 0.7f); } CUIRect Temp; pRect->HMargin(pRect->h>=20.0f?2.0f:1.0f, &Temp); UI()->DoLabel(&Temp, pText, Temp.h*ms_FontmodHeight, 0); TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); return UI()->DoButtonLogic(pID, pText, Checked, pRect); } int CMenus::DoButton_MenuTabTop(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Corners, float r, float FontFactor) { float Seconds = 0.6f; // 0.6 seconds for fade float *pFade = ButtonFade(pID, Seconds, Checked); float FadeVal = *pFade/Seconds; RenderTools()->DrawUIRect(pRect, vec4(0.0f+FadeVal, 0.0f+FadeVal, 0.0f+FadeVal, 0.25f+FadeVal*0.5f), Corners, r); CUIRect Temp; pRect->HMargin(pRect->h>=20.0f?2.0f:1.0f, &Temp); Temp.HMargin((Temp.h*FontFactor)/2.0f, &Temp); TextRender()->TextColor(1.0f-FadeVal, 1.0f-FadeVal, 1.0f-FadeVal, 1.0f); TextRender()->TextOutlineColor(0.0f+FadeVal, 0.0f+FadeVal, 0.0f+FadeVal, 0.25f); UI()->DoLabel(&Temp, pText, Temp.h*ms_FontmodHeight, 0); TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); TextRender()->TextOutlineColor(0.0f, 0.0f, 0.0f, 0.3f); return UI()->DoButtonLogic(pID, pText, Checked, pRect); } int CMenus::DoButton_GridHeader(const void *pID, const char *pText, int Checked, const CUIRect *pRect) //void CMenus::ui_draw_grid_header(const void *id, const char *text, int checked, const CUIRect *r, const void *extra) { if(Checked) { RenderTools()->DrawUIRect(pRect, vec4(1,1,1,0.5f), CUI::CORNER_ALL, 5.0f); TextRender()->TextColor(0.0f, 0.0f, 0.0f, 1.0f); TextRender()->TextOutlineColor(1.0f, 1.0f, 1.0f, 0.25f); } CUIRect Label; pRect->VSplitLeft(5.0f, 0, &Label); Label.y+=2.0f; UI()->DoLabel(&Label, pText, pRect->h*ms_FontmodHeight*0.8f, 0); if(Checked) { TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); TextRender()->TextOutlineColor(0.0f, 0.0f, 0.0f, 0.3f); } return UI()->DoButtonLogic(pID, pText, Checked, pRect); } int CMenus::DoButton_GridHeaderIcon(const void *pID, int ImageID, int SpriteID, const CUIRect *pRect, int Corners) { float Seconds = 0.6f; // 0.6 seconds for fade float *pFade = ButtonFade(pID, Seconds); RenderTools()->DrawUIRect(pRect, vec4(1.0f, 1.0f, 1.0f, 0.5f+(*pFade/Seconds)*0.25f), Corners, 5.0f); CUIRect Image; pRect->HMargin(2.0f, &Image); pRect->VMargin((Image.w-Image.h)/2.0f, &Image); Graphics()->TextureSet(g_pData->m_aImages[ImageID].m_Id); Graphics()->QuadsBegin(); Graphics()->SetColor(1.0f, 1.0f, 1.0f, 0.5f); RenderTools()->SelectSprite(SpriteID); IGraphics::CQuadItem QuadItem(Image.x, Image.y, Image.w, Image.h); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); return UI()->DoButtonLogic(pID, "", false, pRect); } int CMenus::DoButton_CheckBox_Common(const void *pID, const char *pText, const char *pBoxText, const CUIRect *pRect, bool Checked) //void CMenus::ui_draw_checkbox_common(const void *id, const char *text, const char *boxtext, const CUIRect *r, const void *extra) { RenderTools()->DrawUIRect(pRect, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f); CUIRect c = *pRect; CUIRect t = *pRect; c.w = c.h; t.x += c.w; t.w -= c.w; t.VSplitLeft(5.0f, 0, &t); c.Margin(2.0f, &c); Graphics()->TextureSet(g_pData->m_aImages[IMAGE_MENUICONS].m_Id); Graphics()->QuadsBegin(); Graphics()->SetColor(1.0f, 1.0f, 1.0f, UI()->HotItem() == pID ? 1.0f : 0.6f); if(Checked) RenderTools()->SelectSprite(SPRITE_MENU_CHECKBOX_ACTIVE); else RenderTools()->SelectSprite(SPRITE_MENU_CHECKBOX_INACTIVE); IGraphics::CQuadItem QuadItem(c.x, c.y, c.w, c.h); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); t.y += 2.0f; // lame fix UI()->DoLabel(&c, pBoxText, pRect->h*ms_FontmodHeight*0.6f, 0); UI()->DoLabel(&t, pText, pRect->h*ms_FontmodHeight*0.8f, -1); return UI()->DoButtonLogic(pID, pText, 0, pRect); } int CMenus::DoButton_CheckBox(const void *pID, const char *pText, int Checked, const CUIRect *pRect) { return DoButton_CheckBox_Common(pID, pText, "", pRect, Checked); } int CMenus::DoButton_CheckBox_Number(const void *pID, const char *pText, int Checked, const CUIRect *pRect) { char aBuf[16]; str_format(aBuf, sizeof(aBuf), "%d", Checked); return DoButton_CheckBox_Common(pID, pText, aBuf, pRect); } int CMenus::DoButton_SpriteID(const void *pID, int ImageID, int SpriteID, const CUIRect *pRect, int Corners, float r, bool Fade) { float Seconds = 0.6f; // 0.6 seconds for fade float *pFade = ButtonFade(pID, Seconds); float FadeVal = *pFade/Seconds; CUIRect Icon = *pRect; Icon.Margin(2.0f, &Icon); if(Fade) RenderTools()->DrawUIRect(pRect, vec4(0.0f+FadeVal, 0.0f+FadeVal, 0.0f+FadeVal, 0.25f+FadeVal*0.5f), Corners, r); else RenderTools()->DrawUIRect(pRect, vec4(0.0f, 0.0f, 0.0f, 0.25f), Corners, r); Graphics()->TextureSet(g_pData->m_aImages[ImageID].m_Id); Graphics()->QuadsBegin(); Graphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f); RenderTools()->SelectSprite(SpriteID); IGraphics::CQuadItem QuadItem(Icon.x, Icon.y, Icon.w, Icon.h); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); return UI()->DoButtonLogic(pID, "", false, pRect); } int CMenus::DoButton_SpriteClean(int ImageID, int SpriteID, const CUIRect *pRect) { int Inside = UI()->MouseInside(pRect); Graphics()->TextureSet(g_pData->m_aImages[ImageID].m_Id); Graphics()->QuadsBegin(); Graphics()->SetColor(1.0f, 1.0f, 1.0f, Inside ? 1.0f : 0.6f); RenderTools()->SelectSprite(SpriteID); IGraphics::CQuadItem QuadItem(pRect->x, pRect->y, pRect->w, pRect->h); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); int ReturnValue = 0; if(Inside && Input()->KeyDown(KEY_MOUSE_1)) ReturnValue = 1; return ReturnValue; } int CMenus::DoButton_SpriteCleanID(const void *pID, int ImageID, int SpriteID, const CUIRect *pRect, bool Blend) { int Inside = UI()->MouseInside(pRect); Graphics()->TextureSet(g_pData->m_aImages[ImageID].m_Id); Graphics()->QuadsBegin(); Graphics()->SetColor(1.0f, 1.0f, 1.0f, !Blend || Inside ? 1.0f : 0.6f); RenderTools()->SelectSprite(SpriteID); IGraphics::CQuadItem QuadItem(pRect->x, pRect->y, pRect->w, pRect->h); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); return UI()->DoButtonLogic(pID, 0, 0, pRect); } int CMenus::DoButton_MouseOver(int ImageID, int SpriteID, const CUIRect *pRect) { int Inside = UI()->MouseInside(pRect); Graphics()->TextureSet(g_pData->m_aImages[ImageID].m_Id); Graphics()->QuadsBegin(); Graphics()->SetColor(1.0f, 1.0f, 1.0f, Inside ? 1.0f : 0.6f); RenderTools()->SelectSprite(SpriteID); IGraphics::CQuadItem QuadItem(pRect->x, pRect->y, pRect->w, pRect->h); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); return Inside; } int CMenus::DoEditBox(void *pID, const CUIRect *pRect, char *pStr, unsigned StrSize, float FontSize, float *pOffset, bool Hidden, int Corners) { int Inside = UI()->MouseInside(pRect); bool ReturnValue = false; bool UpdateOffset = false; static int s_AtIndex = 0; static bool s_DoScroll = false; FontSize *= UI()->Scale(); if(UI()->LastActiveItem() == pID) { static float s_ScrollStart = 0.0f; int Len = str_length(pStr); if(Len == 0) s_AtIndex = 0; if(Inside && UI()->MouseButton(0)) { s_DoScroll = true; s_ScrollStart = UI()->MouseX(); int MxRel = (int)(UI()->MouseX() - pRect->x); float Offset = pRect->w/2.0f-TextRender()->TextWidth(0, FontSize, pStr, -1)/2.0f; for(int i = 1; i <= Len; i++) { if(Offset + TextRender()->TextWidth(0, FontSize, pStr, i) - *pOffset > MxRel) { s_AtIndex = i - 1; break; } if(i == Len) s_AtIndex = Len; } } else if(!UI()->MouseButton(0)) s_DoScroll = false; else if(s_DoScroll) { // do scrolling if(UI()->MouseX() < pRect->x && s_ScrollStart-UI()->MouseX() > 10.0f) { s_AtIndex = max(0, s_AtIndex-1); s_ScrollStart = UI()->MouseX(); UpdateOffset = true; } else if(UI()->MouseX() > pRect->x+pRect->w && UI()->MouseX()-s_ScrollStart > 10.0f) { s_AtIndex = min(Len, s_AtIndex+1); s_ScrollStart = UI()->MouseX(); UpdateOffset = true; } } for(int i = 0; i < m_NumInputEvents; i++) { Len = str_length(pStr); ReturnValue |= CLineInput::Manipulate(m_aInputEvents[i], pStr, StrSize, &Len, &s_AtIndex); } } bool JustGotActive = false; if(UI()->ActiveItem() == pID) { if(!UI()->MouseButton(0)) { s_AtIndex = min(s_AtIndex, str_length(pStr)); s_DoScroll = false; UI()->SetActiveItem(0); } } else if(UI()->HotItem() == pID) { if(UI()->MouseButton(0)) { if (UI()->LastActiveItem() != pID) JustGotActive = true; UI()->SetActiveItem(pID); } } if(Inside) UI()->SetHotItem(pID); CUIRect Textbox = *pRect; RenderTools()->DrawUIRect(&Textbox, vec4(0.0f, 0.0f, 0.0f, 0.25f), Corners, 5.0f); Textbox.VMargin(2.0f, &Textbox); Textbox.HMargin(2.0f, &Textbox); const char *pDisplayStr = pStr; char aStars[128]; if(Hidden) { unsigned s = str_length(pStr); if(s >= sizeof(aStars)) s = sizeof(aStars)-1; for(unsigned int i = 0; i < s; ++i) aStars[i] = '*'; aStars[s] = 0; pDisplayStr = aStars; } // check if the text has to be moved if(UI()->LastActiveItem() == pID && !JustGotActive && (UpdateOffset || m_NumInputEvents)) { float w = TextRender()->TextWidth(0, FontSize, pDisplayStr, s_AtIndex); if(w-*pOffset > Textbox.w) { // move to the left float wt = TextRender()->TextWidth(0, FontSize, pDisplayStr, -1); do { *pOffset += min(wt-*pOffset-Textbox.w, Textbox.w/3); } while(w-*pOffset > Textbox.w); } else if(w-*pOffset < 0.0f) { // move to the right do { *pOffset = max(0.0f, *pOffset-Textbox.w/3); } while(w-*pOffset < 0.0f); } } UI()->ClipEnable(pRect); Textbox.x -= *pOffset; UI()->DoLabel(&Textbox, pDisplayStr, FontSize, 0); // render the cursor if(UI()->LastActiveItem() == pID && !JustGotActive) { float w = TextRender()->TextWidth(0, FontSize, pDisplayStr, -1); Textbox = *pRect; Textbox.x += Textbox.w/2.0f-w/2.0f; w = TextRender()->TextWidth(0, FontSize, pDisplayStr, s_AtIndex); Textbox.x += (w-*pOffset-TextRender()->TextWidth(0, FontSize, "|", -1)/2); if((2*time_get()/time_freq()) % 2) // make it blink UI()->DoLabel(&Textbox, "|", FontSize, -1); } UI()->ClipDisable(); return ReturnValue; } void CMenus::DoEditBoxOption(void *pID, char *pOption, int OptionLength, const CUIRect *pRect, const char *pStr, float VSplitVal, float *pOffset, bool Hidden) { RenderTools()->DrawUIRect(pRect, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f); CUIRect Label, EditBox; pRect->VSplitLeft(VSplitVal, &Label, &EditBox); char aBuf[32]; str_format(aBuf, sizeof(aBuf), "%s:", pStr); Label.y += 2.0f; UI()->DoLabel(&Label, aBuf, pRect->h*ms_FontmodHeight*0.8f, 0); DoEditBox(pID, &EditBox, pOption, OptionLength, pRect->h*ms_FontmodHeight*0.8f, pOffset, Hidden); } void CMenus::DoScrollbarOption(void *pID, int *pOption, const CUIRect *pRect, const char *pStr, float VSplitVal, int Min, int Max, bool infinite) { RenderTools()->DrawUIRect(pRect, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f); CUIRect Label, ScrollBar; pRect->VSplitLeft(VSplitVal, &Label, &ScrollBar); char aBuf[32]; if(*pOption || !infinite) str_format(aBuf, sizeof(aBuf), "%s: %i", pStr, *pOption); else str_format(aBuf, sizeof(aBuf), "%s: \xe2\x88\x9e", pStr); Label.VSplitLeft(Label.h+5.0f, 0, &Label); Label.y += 2.0f; UI()->DoLabel(&Label, aBuf, pRect->h*ms_FontmodHeight*0.8f, -1); ScrollBar.VMargin(4.0f, &ScrollBar); *pOption = static_cast<int>(DoScrollbarH(pOption, &ScrollBar, (float)(*pOption-Min)/(float)(Max-Min))*(float)(Max-Min)+(float)Min+0.1f); } float CMenus::DoDropdownMenu(void *pID, const CUIRect *pRect, const char *pStr, float HeaderHeight, FDropdownCallback pfnCallback) { CUIRect View = *pRect; CUIRect Header, Label; bool Active = pID == m_pActiveDropdown; int Corners = Active ? CUI::CORNER_T : CUI::CORNER_ALL; View.HSplitTop(HeaderHeight, &Header, &View); // background RenderTools()->DrawUIRect(&Header, vec4(0.0f, 0.0f, 0.0f, 0.25f), Corners, 5.0f); // render icon CUIRect Button; Header.VSplitLeft(Header.h, &Button, 0); Button.Margin(2.0f, &Button); Graphics()->TextureSet(g_pData->m_aImages[IMAGE_MENUICONS].m_Id); Graphics()->QuadsBegin(); Graphics()->SetColor(1.0f, 1.0f, 1.0f, UI()->HotItem() == pID ? 1.0f : 0.6f); if(Active) RenderTools()->SelectSprite(SPRITE_MENU_EXPANDED); else RenderTools()->SelectSprite(SPRITE_MENU_COLLAPSED); IGraphics::CQuadItem QuadItem(Button.x, Button.y, Button.w, Button.h); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f); Graphics()->QuadsEnd(); // label Label = Header; Label.y += 2.0f; UI()->DoLabel(&Label, pStr, Header.h*ms_FontmodHeight*0.8f, 0); if(UI()->DoButtonLogic(pID, 0, 0, &Header)) { if(Active) m_pActiveDropdown = 0; else m_pActiveDropdown = (int*)pID; } // render content of expanded menu if(Active) return HeaderHeight + pfnCallback(View, this); return HeaderHeight; } void CMenus::DoInfoBox(const CUIRect *pRect, const char *pLabel, const char *pValue) { RenderTools()->DrawUIRect(pRect, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f); CUIRect Label, Value; pRect->VSplitMid(&Label, &Value); RenderTools()->DrawUIRect(&Value, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f); char aBuf[32]; str_format(aBuf, sizeof(aBuf), "%s:", pLabel); Label.y += 2.0f; UI()->DoLabel(&Label, aBuf, pRect->h*ms_FontmodHeight*0.8f, 0); Value.y += 2.0f; UI()->DoLabel(&Value, pValue, pRect->h*ms_FontmodHeight*0.8f, 0); } float CMenus::DoScrollbarV(const void *pID, const CUIRect *pRect, float Current) { CUIRect Handle; static float OffsetY; pRect->HSplitTop(33, &Handle, 0); Handle.y += (pRect->h-Handle.h)*Current; // logic float ReturnValue = Current; int Inside = UI()->MouseInside(&Handle); if(UI()->ActiveItem() == pID) { if(!UI()->MouseButton(0)) UI()->SetActiveItem(0); float Min = pRect->y; float Max = pRect->h-Handle.h; float Cur = UI()->MouseY()-OffsetY; ReturnValue = (Cur-Min)/Max; if(ReturnValue < 0.0f) ReturnValue = 0.0f; if(ReturnValue > 1.0f) ReturnValue = 1.0f; } else if(UI()->HotItem() == pID) { if(UI()->MouseButton(0)) { UI()->SetActiveItem(pID); OffsetY = UI()->MouseY()-Handle.y; } } if(Inside) UI()->SetHotItem(pID); // render CUIRect Rail; pRect->VMargin(5.0f, &Rail); RenderTools()->DrawUIRect(&Rail, vec4(1.0f, 1.0f, 1.0f, 0.25f), CUI::CORNER_ALL, Rail.w/2.0f); CUIRect Slider = Handle; Slider.VMargin(5.0f, &Slider); RenderTools()->DrawUIRect(&Slider, vec4(1.0f , 1.0f, 1.0f, 1.0f), CUI::CORNER_ALL, Slider.w/2.0f); return ReturnValue; } float CMenus::DoScrollbarH(const void *pID, const CUIRect *pRect, float Current) { CUIRect Handle; static float OffsetX; pRect->VSplitLeft(33, &Handle, 0); Handle.x += (pRect->w-Handle.w)*Current; // logic float ReturnValue = Current; int Inside = UI()->MouseInside(&Handle); if(UI()->ActiveItem() == pID) { if(!UI()->MouseButton(0)) UI()->SetActiveItem(0); float Min = pRect->x; float Max = pRect->w-Handle.w; float Cur = UI()->MouseX()-OffsetX; ReturnValue = (Cur-Min)/Max; if(ReturnValue < 0.0f) ReturnValue = 0.0f; if(ReturnValue > 1.0f) ReturnValue = 1.0f; } else if(UI()->HotItem() == pID) { if(UI()->MouseButton(0)) { UI()->SetActiveItem(pID); OffsetX = UI()->MouseX()-Handle.x; } } if(Inside) UI()->SetHotItem(pID); // render CUIRect Rail; pRect->HMargin(5.0f, &Rail); RenderTools()->DrawUIRect(&Rail, vec4(1.0f, 1.0f, 1.0f, 0.25f), CUI::CORNER_ALL, Rail.h/2.0f); CUIRect Slider = Handle; Slider.HMargin(5.0f, &Slider); RenderTools()->DrawUIRect(&Slider, vec4(1.0f , 1.0f, 1.0f, 1.0f), CUI::CORNER_ALL, Slider.h/2.0f); return ReturnValue; } static CUIRect gs_ListBoxOriginalView; static CUIRect gs_ListBoxView; static float gs_ListBoxRowHeight; static int gs_ListBoxItemIndex; static int gs_ListBoxSelectedIndex; static int gs_ListBoxNewSelected; static int gs_ListBoxDoneEvents; static int gs_ListBoxNumItems; static int gs_ListBoxItemsPerRow; static float gs_ListBoxScrollValue; static bool gs_ListBoxItemActivated; void CMenus::UiDoListboxHeader(const CUIRect *pRect, const char *pTitle, float HeaderHeight, float Spacing) { CUIRect Header; CUIRect View = *pRect; // background View.HSplitTop(ms_ListheaderHeight+Spacing, &Header, 0); RenderTools()->DrawUIRect(&Header, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_T, 5.0f); // draw header View.HSplitTop(ms_ListheaderHeight, &Header, &View); Header.y += 2.0f; UI()->DoLabel(&Header, pTitle, Header.h*ms_FontmodHeight*0.8f, 0); View.HSplitTop(Spacing, &Header, &View); // setup the variables gs_ListBoxOriginalView = View; } void CMenus::UiDoListboxStart(const void *pID, float RowHeight, const char *pBottomText, int NumItems, int ItemsPerRow, int SelectedIndex, float ScrollValue, const CUIRect *pRect, bool Background) { CUIRect View, Scroll, Row; if(pRect) View = *pRect; else View = gs_ListBoxOriginalView; CUIRect Footer; // background if(Background) RenderTools()->DrawUIRect(&View, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_B, 5.0f); // draw footers if(pBottomText) { View.HSplitBottom(ms_ListheaderHeight, &View, &Footer); Footer.VSplitLeft(10.0f, 0, &Footer); Footer.y += 2.0f; UI()->DoLabel(&Footer, pBottomText, Footer.h*ms_FontmodHeight*0.8f, 0); } // prepare the scroll View.VSplitRight(20.0f, &View, &Scroll); // scroll background RenderTools()->DrawUIRect(&Scroll, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f); // list background RenderTools()->DrawUIRect(&View, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f); // setup the variables gs_ListBoxOriginalView = View; gs_ListBoxSelectedIndex = SelectedIndex; gs_ListBoxNewSelected = SelectedIndex; gs_ListBoxItemIndex = 0; gs_ListBoxRowHeight = RowHeight; gs_ListBoxNumItems = NumItems; gs_ListBoxItemsPerRow = ItemsPerRow; gs_ListBoxDoneEvents = 0; gs_ListBoxScrollValue = ScrollValue; gs_ListBoxItemActivated = false; // do the scrollbar View.HSplitTop(gs_ListBoxRowHeight, &Row, 0); int NumViewable = (int)(gs_ListBoxOriginalView.h/Row.h) + 1; int Num = (NumItems+gs_ListBoxItemsPerRow-1)/gs_ListBoxItemsPerRow-NumViewable+1; if(Num < 0) Num = 0; if(Num > 0) { if(Input()->KeyPresses(KEY_MOUSE_WHEEL_UP) && UI()->MouseInside(&View)) gs_ListBoxScrollValue -= 3.0f/Num; if(Input()->KeyPresses(KEY_MOUSE_WHEEL_DOWN) && UI()->MouseInside(&View)) gs_ListBoxScrollValue += 3.0f/Num; if(gs_ListBoxScrollValue < 0.0f) gs_ListBoxScrollValue = 0.0f; if(gs_ListBoxScrollValue > 1.0f) gs_ListBoxScrollValue = 1.0f; } Scroll.HMargin(5.0f, &Scroll); gs_ListBoxScrollValue = DoScrollbarV(pID, &Scroll, gs_ListBoxScrollValue); // the list gs_ListBoxView = gs_ListBoxOriginalView; UI()->ClipEnable(&gs_ListBoxView); gs_ListBoxView.y -= gs_ListBoxScrollValue*Num*Row.h; } CMenus::CListboxItem CMenus::UiDoListboxNextRow() { static CUIRect s_RowView; CListboxItem Item = {0}; if(gs_ListBoxItemIndex%gs_ListBoxItemsPerRow == 0) gs_ListBoxView.HSplitTop(gs_ListBoxRowHeight /*-2.0f*/, &s_RowView, &gs_ListBoxView); s_RowView.VSplitLeft(s_RowView.w/(gs_ListBoxItemsPerRow-gs_ListBoxItemIndex%gs_ListBoxItemsPerRow)/(UI()->Scale()), &Item.m_Rect, &s_RowView); Item.m_Visible = 1; //item.rect = row; Item.m_HitRect = Item.m_Rect; //CUIRect select_hit_box = item.rect; if(gs_ListBoxSelectedIndex == gs_ListBoxItemIndex) Item.m_Selected = 1; // make sure that only those in view can be selected if(Item.m_Rect.y+Item.m_Rect.h > gs_ListBoxOriginalView.y) { if(Item.m_HitRect.y < Item.m_HitRect.y) // clip the selection { Item.m_HitRect.h -= gs_ListBoxOriginalView.y-Item.m_HitRect.y; Item.m_HitRect.y = gs_ListBoxOriginalView.y; } } else Item.m_Visible = 0; // check if we need to do more if(Item.m_Rect.y > gs_ListBoxOriginalView.y+gs_ListBoxOriginalView.h) Item.m_Visible = 0; gs_ListBoxItemIndex++; return Item; } CMenus::CListboxItem CMenus::UiDoListboxNextItem(const void *pId, bool Selected) { int ThisItemIndex = gs_ListBoxItemIndex; if(Selected) { if(gs_ListBoxSelectedIndex == gs_ListBoxNewSelected) gs_ListBoxNewSelected = ThisItemIndex; gs_ListBoxSelectedIndex = ThisItemIndex; } CListboxItem Item = UiDoListboxNextRow(); if(Item.m_Visible && UI()->DoButtonLogic(pId, "", gs_ListBoxSelectedIndex == gs_ListBoxItemIndex, &Item.m_HitRect)) gs_ListBoxNewSelected = ThisItemIndex; // process input, regard selected index if(gs_ListBoxSelectedIndex == ThisItemIndex) { if(!gs_ListBoxDoneEvents) { gs_ListBoxDoneEvents = 1; if(m_EnterPressed || (UI()->ActiveItem() == pId && Input()->MouseDoubleClick())) { gs_ListBoxItemActivated = true; UI()->SetActiveItem(0); } else { for(int i = 0; i < m_NumInputEvents; i++) { int NewIndex = -1; if(m_aInputEvents[i].m_Flags&IInput::FLAG_PRESS) { if(m_aInputEvents[i].m_Key == KEY_DOWN) NewIndex = gs_ListBoxNewSelected + 1; if(m_aInputEvents[i].m_Key == KEY_UP) NewIndex = gs_ListBoxNewSelected - 1; } if(NewIndex > -1 && NewIndex < gs_ListBoxNumItems) { // scroll float Offset = (NewIndex/gs_ListBoxItemsPerRow-gs_ListBoxNewSelected/gs_ListBoxItemsPerRow)*gs_ListBoxRowHeight; int Scroll = gs_ListBoxOriginalView.y > Item.m_Rect.y+Offset ? -1 : gs_ListBoxOriginalView.y+gs_ListBoxOriginalView.h < Item.m_Rect.y+Item.m_Rect.h+Offset ? 1 : 0; if(Scroll) { int NumViewable = (int)(gs_ListBoxOriginalView.h/gs_ListBoxRowHeight) + 1; int ScrollNum = (gs_ListBoxNumItems+gs_ListBoxItemsPerRow-1)/gs_ListBoxItemsPerRow-NumViewable+1; if(Scroll < 0) { int Num = (gs_ListBoxOriginalView.y-Item.m_Rect.y-Offset+gs_ListBoxRowHeight-1.0f)/gs_ListBoxRowHeight; gs_ListBoxScrollValue -= (1.0f/ScrollNum)*Num; } else { int Num = (Item.m_Rect.y+Item.m_Rect.h+Offset-(gs_ListBoxOriginalView.y+gs_ListBoxOriginalView.h)+gs_ListBoxRowHeight-1.0f)/ gs_ListBoxRowHeight; gs_ListBoxScrollValue += (1.0f/ScrollNum)*Num; } if(gs_ListBoxScrollValue < 0.0f) gs_ListBoxScrollValue = 0.0f; if(gs_ListBoxScrollValue > 1.0f) gs_ListBoxScrollValue = 1.0f; } gs_ListBoxNewSelected = NewIndex; } } } } //selected_index = i; CUIRect r = Item.m_Rect; RenderTools()->DrawUIRect(&r, vec4(1,1,1,0.5f), CUI::CORNER_ALL, 5.0f); } return Item; } int CMenus::UiDoListboxEnd(float *pScrollValue, bool *pItemActivated) { UI()->ClipDisable(); if(pScrollValue) *pScrollValue = gs_ListBoxScrollValue; if(pItemActivated) *pItemActivated = gs_ListBoxItemActivated; return gs_ListBoxNewSelected; } int CMenus::DoKeyReader(void *pID, const CUIRect *pRect, int Key) { // process static void *pGrabbedID = 0; static bool MouseReleased = true; static int ButtonUsed = 0; int Inside = UI()->MouseInside(pRect); int NewKey = Key; if(!UI()->MouseButton(0) && !UI()->MouseButton(1) && pGrabbedID == pID) MouseReleased = true; if(UI()->ActiveItem() == pID) { if(m_Binder.m_GotKey) { // abort with escape key if(m_Binder.m_Key.m_Key != KEY_ESCAPE) NewKey = m_Binder.m_Key.m_Key; m_Binder.m_GotKey = false; UI()->SetActiveItem(0); MouseReleased = false; pGrabbedID = pID; } if(ButtonUsed == 1 && !UI()->MouseButton(1)) { if(Inside) NewKey = 0; UI()->SetActiveItem(0); } } else if(UI()->HotItem() == pID) { if(MouseReleased) { if(UI()->MouseButton(0)) { m_Binder.m_TakeKey = true; m_Binder.m_GotKey = false; UI()->SetActiveItem(pID); ButtonUsed = 0; } if(UI()->MouseButton(1)) { UI()->SetActiveItem(pID); ButtonUsed = 1; } } } if(Inside) UI()->SetHotItem(pID); // draw if (UI()->ActiveItem() == pID && ButtonUsed == 0) DoButton_KeySelect(pID, "???", 0, pRect); else { if(Key == 0) DoButton_KeySelect(pID, "", 0, pRect); else DoButton_KeySelect(pID, Input()->KeyName(Key), 0, pRect); } return NewKey; } void CMenus::RenderMenubar(CUIRect r) { CUIRect Box = r; CUIRect Button; m_ActivePage = m_MenuPage; int NewPage = -1; if(Client()->State() != IClient::STATE_OFFLINE) m_ActivePage = m_GamePage; if(m_MenuPage == PAGE_SETTINGS || m_GamePage == PAGE_SETTINGS) { float Spacing = 3.0f; float ButtonWidth = (Box.w/6.0f)-(Spacing*5.0)/6.0f; // render header background RenderTools()->DrawUIRect4(&Box, vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_B, 5.0f); Box.HSplitBottom(25.0f, 0, &Box); Box.VSplitLeft(ButtonWidth, &Button, &Box); static int s_GeneralButton=0; if(DoButton_MenuTabTop(&s_GeneralButton, Localize("General"), g_Config.m_UiSettingsPage==SETTINGS_GENERAL, &Button)) { g_Config.m_UiSettingsPage = SETTINGS_GENERAL; } Box.VSplitLeft(Spacing, 0, &Box); // little space Box.VSplitLeft(ButtonWidth, &Button, &Box); static int s_PlayerButton=0; if(DoButton_MenuTabTop(&s_PlayerButton, Localize("Player"), g_Config.m_UiSettingsPage==SETTINGS_PLAYER, &Button)) { g_Config.m_UiSettingsPage = SETTINGS_PLAYER; } Box.VSplitLeft(Spacing, 0, &Box); // little space Box.VSplitLeft(ButtonWidth, &Button, &Box); static int s_TeeButton=0; if(DoButton_MenuTabTop(&s_TeeButton, Localize("Tee"), g_Config.m_UiSettingsPage==SETTINGS_TEE, &Button)) { g_Config.m_UiSettingsPage = SETTINGS_TEE; } Box.VSplitLeft(Spacing, 0, &Box); // little space Box.VSplitLeft(ButtonWidth, &Button, &Box); static int s_ControlsButton=0; if(DoButton_MenuTabTop(&s_ControlsButton, Localize("Controls"), g_Config.m_UiSettingsPage==SETTINGS_CONTROLS, &Button)) { g_Config.m_UiSettingsPage = SETTINGS_CONTROLS; } Box.VSplitLeft(Spacing, 0, &Box); // little space Box.VSplitLeft(ButtonWidth, &Button, &Box); static int s_GraphicsButton=0; if(DoButton_MenuTabTop(&s_GraphicsButton, Localize("Graphics"), g_Config.m_UiSettingsPage==SETTINGS_GRAPHICS, &Button)) { g_Config.m_UiSettingsPage = SETTINGS_GRAPHICS; } Box.VSplitLeft(Spacing, 0, &Box); // little space Box.VSplitLeft(ButtonWidth, &Button, &Box); static int s_SoundButton=0; if(DoButton_MenuTabTop(&s_SoundButton, Localize("Sound"), g_Config.m_UiSettingsPage==SETTINGS_SOUND, &Button)) { g_Config.m_UiSettingsPage = SETTINGS_SOUND; } } else if(Client()->State() == IClient::STATE_OFFLINE) { // render menu tabs if(m_MenuPage >= PAGE_INTERNET && m_MenuPage <= PAGE_FRIENDS) { float Spacing = 3.0f; float ButtonWidth = (Box.w/6.0f)-(Spacing*5.0)/6.0f; CUIRect Left, Right; Box.VSplitLeft(ButtonWidth*2.0f+Spacing, &Left, 0); Box.VSplitRight(ButtonWidth, 0, &Right); // render header backgrounds RenderTools()->DrawUIRect4(&Left, vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_B, 5.0f); RenderTools()->DrawUIRect4(&Right, vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_B, 5.0f); Left.HSplitBottom(25.0f, 0, &Left); Right.HSplitBottom(25.0f, 0, &Right); Left.VSplitLeft(ButtonWidth, &Button, &Left); static int s_InternetButton=0; if(DoButton_MenuTabTop(&s_InternetButton, Localize("Global"), m_ActivePage==PAGE_INTERNET, &Button)) { m_pClient->m_pCamera->ChangePosition(CCamera::POS_INTERNET); ServerBrowser()->Refresh(IServerBrowser::TYPE_INTERNET); NewPage = PAGE_INTERNET; g_Config.m_UiBrowserPage = PAGE_INTERNET; } Left.VSplitLeft(Spacing, 0, &Left); // little space Left.VSplitLeft(ButtonWidth, &Button, &Left); static int s_LanButton=0; if(DoButton_MenuTabTop(&s_LanButton, Localize("Local"), m_ActivePage==PAGE_LAN, &Button)) { m_pClient->m_pCamera->ChangePosition(CCamera::POS_LAN); ServerBrowser()->Refresh(IServerBrowser::TYPE_LAN); NewPage = PAGE_LAN; g_Config.m_UiBrowserPage = PAGE_LAN; } char aBuf[32]; if(m_BorwserPage == PAGE_BROWSER_BROWSER) str_copy(aBuf, Localize("Friends"), sizeof(aBuf)); else if(m_BorwserPage == PAGE_BROWSER_FRIENDS) str_copy(aBuf, Localize("Browser"), sizeof(aBuf)); static int s_FilterButton=0; if(DoButton_Menu(&s_FilterButton, aBuf, 0, &Right)) { m_BorwserPage++; if(m_BorwserPage >= NUM_PAGE_BROWSER) m_BorwserPage = 0; } } else if(m_MenuPage == PAGE_DEMOS) { // render header background RenderTools()->DrawUIRect4(&Box, vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_B, 5.0f); Box.HSplitBottom(25.0f, 0, &Box); // make the header look like an active tab RenderTools()->DrawUIRect(&Box, vec4(1.0f, 1.0f, 1.0f, 0.75f), CUI::CORNER_ALL, 5.0f); Box.HMargin(2.0f, &Box); TextRender()->TextColor(0.0f, 0.0f, 0.0f, 1.0f); TextRender()->TextOutlineColor(1.0f, 1.0f, 1.0f, 0.25f); UI()->DoLabel(&Box, Localize("Demo"), Box.h*ms_FontmodHeight, 0); TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); TextRender()->TextOutlineColor(0.0f, 0.0f, 0.0f, 0.3f); } } else { float Spacing = 3.0f; float ButtonWidth = (Box.w/6.0f)-(Spacing*5.0)/6.0f; // render header backgrounds CUIRect Left, Right; Box.VSplitLeft(ButtonWidth*4.0f+Spacing*3.0f, &Left, 0); Box.VSplitRight(ButtonWidth, 0, &Right); RenderTools()->DrawUIRect4(&Left, vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_B, 5.0f); RenderTools()->DrawUIRect4(&Right, vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_B, 5.0f); Left.HSplitBottom(25.0f, 0, &Left); Right.HSplitBottom(25.0f, 0, &Right); // online menus if(m_GamePage != PAGE_SETTINGS) // Game stuff { Left.VSplitLeft(ButtonWidth, &Button, &Left); static int s_GameButton=0; if(DoButton_MenuTabTop(&s_GameButton, Localize("Game"), m_ActivePage==PAGE_GAME, &Button)) NewPage = PAGE_GAME; Left.VSplitLeft(Spacing, 0, &Left); // little space Left.VSplitLeft(ButtonWidth, &Button, &Left); static int s_PlayersButton=0; if(DoButton_MenuTabTop(&s_PlayersButton, Localize("Players"), m_ActivePage==PAGE_PLAYERS, &Button)) NewPage = PAGE_PLAYERS; Left.VSplitLeft(Spacing, 0, &Left); // little space Left.VSplitLeft(ButtonWidth, &Button, &Left); static int s_ServerInfoButton=0; if(DoButton_MenuTabTop(&s_ServerInfoButton, Localize("Server info"), m_ActivePage==PAGE_SERVER_INFO, &Button)) NewPage = PAGE_SERVER_INFO; Left.VSplitLeft(Spacing, 0, &Left); // little space Left.VSplitLeft(ButtonWidth, &Button, &Left); static int s_CallVoteButton=0; if(DoButton_MenuTabTop(&s_CallVoteButton, Localize("Call vote"), m_ActivePage==PAGE_CALLVOTE, &Button)) NewPage = PAGE_CALLVOTE; static int s_SettingsButton=0; if(DoButton_MenuTabTop(&s_SettingsButton, Localize("Settings"), 0, &Right)) NewPage = PAGE_SETTINGS; } } if(NewPage != -1) { if(Client()->State() == IClient::STATE_OFFLINE) m_MenuPage = NewPage; else m_GamePage = NewPage; } } void CMenus::RenderLoading() { // TODO: not supported right now due to separate render thread static int64 LastLoadRender = 0; float Percent = m_LoadCurrent++/(float)m_LoadTotal; // make sure that we don't render for each little thing we load // because that will slow down loading if we have vsync if(time_get()-LastLoadRender < time_freq()/60) return; LastLoadRender = time_get(); CUIRect Screen = *UI()->Screen(); Graphics()->MapScreen(Screen.x, Screen.y, Screen.w, Screen.h); RenderBackground(); float w = 700; float h = 200; float x = Screen.w/2-w/2; float y = Screen.h/2-h/2; Graphics()->BlendNormal(); Graphics()->TextureClear(); Graphics()->QuadsBegin(); Graphics()->SetColor(0,0,0,0.50f); RenderTools()->DrawRoundRect(x, y, w, h, 40.0f); Graphics()->QuadsEnd(); const char *pCaption = Localize("Loading"); CUIRect r; r.x = x; r.y = y+20; r.w = w; r.h = h; UI()->DoLabel(&r, pCaption, 48.0f, 0, -1); Graphics()->TextureClear(); Graphics()->QuadsBegin(); Graphics()->SetColor(1,1,1,0.75f); RenderTools()->DrawRoundRect(x+40, y+h-75, (w-80)*Percent, 25, 5.0f); Graphics()->QuadsEnd(); Graphics()->Swap(); } void CMenus::RenderNews(CUIRect MainView) { RenderTools()->DrawUIRect(&MainView, vec4(1.0f, 1.0f, 1.0f, 0.25f), CUI::CORNER_ALL, 10.0f); } void CMenus::RenderBackButton(CUIRect MainView) { // same size like tabs in top but variables not really needed float Spacing = 3.0f; float ButtonWidth = (MainView.w/6.0f)-(Spacing*5.0)/6.0f; // render background MainView.HSplitBottom(60.0f, 0, &MainView); MainView.VSplitLeft(ButtonWidth, &MainView, 0); RenderTools()->DrawUIRect4(&MainView, vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.0f), CUI::CORNER_T, 5.0f); // back to main menu CUIRect Button; MainView.HSplitTop(25.0f, &MainView, 0); Button = MainView; static int s_MenuButton=0; if(DoButton_Menu(&s_MenuButton, Localize("Back"), 0, &Button) || m_EscapePressed) { if(Client()->State() != IClient::STATE_OFFLINE) m_GamePage = PAGE_GAME; else m_MenuPage = PAGE_START; } } int CMenus::MenuImageScan(const char *pName, int IsDir, int DirType, void *pUser) { CMenus *pSelf = (CMenus *)pUser; int l = str_length(pName); if(l < 4 || IsDir || str_comp(pName+l-4, ".png") != 0) return 0; char aBuf[512]; str_format(aBuf, sizeof(aBuf), "menuimages/%s", pName); CImageInfo Info; if(!pSelf->Graphics()->LoadPNG(&Info, aBuf, DirType)) { str_format(aBuf, sizeof(aBuf), "failed to load menu image from %s", pName); pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "game", aBuf); return 0; } CMenuImage MenuImage; MenuImage.m_OrgTexture = pSelf->Graphics()->LoadTextureRaw(Info.m_Width, Info.m_Height, Info.m_Format, Info.m_pData, Info.m_Format, 0); unsigned char *d = (unsigned char *)Info.m_pData; //int Pitch = Info.m_Width*4; // create colorless version int Step = Info.m_Format == CImageInfo::FORMAT_RGBA ? 4 : 3; // make the texture gray scale for(int i = 0; i < Info.m_Width*Info.m_Height; i++) { int v = (d[i*Step]+d[i*Step+1]+d[i*Step+2])/3; d[i*Step] = v; d[i*Step+1] = v; d[i*Step+2] = v; } /* same grey like sinks int Freq[256] = {0}; int OrgWeight = 0; int NewWeight = 192; // find most common frequence for(int y = 0; y < Info.m_Height; y++) for(int x = 0; x < Info.m_Width; x++) { if(d[y*Pitch+x*4+3] > 128) Freq[d[y*Pitch+x*4]]++; } for(int i = 1; i < 256; i++) { if(Freq[OrgWeight] < Freq[i]) OrgWeight = i; } // reorder int InvOrgWeight = 255-OrgWeight; int InvNewWeight = 255-NewWeight; for(int y = 0; y < Info.m_Height; y++) for(int x = 0; x < Info.m_Width; x++) { int v = d[y*Pitch+x*4]; if(v <= OrgWeight) v = (int)(((v/(float)OrgWeight) * NewWeight)); else v = (int)(((v-OrgWeight)/(float)InvOrgWeight)*InvNewWeight + NewWeight); d[y*Pitch+x*4] = v; d[y*Pitch+x*4+1] = v; d[y*Pitch+x*4+2] = v; } */ MenuImage.m_GreyTexture = pSelf->Graphics()->LoadTextureRaw(Info.m_Width, Info.m_Height, Info.m_Format, Info.m_pData, Info.m_Format, 0); mem_free(Info.m_pData); // set menu image data str_copy(MenuImage.m_aName, pName, min((int)sizeof(MenuImage.m_aName),l-3)); str_format(aBuf, sizeof(aBuf), "load menu image %s", MenuImage.m_aName); pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "game", aBuf); pSelf->m_lMenuImages.add(MenuImage); return 0; } const CMenus::CMenuImage *CMenus::FindMenuImage(const char *pName) { for(int i = 0; i < m_lMenuImages.size(); i++) { if(str_comp(m_lMenuImages[i].m_aName, pName) == 0) return &m_lMenuImages[i]; } return 0; } void CMenus::UpdateVideoFormats() { m_NumVideoFormats = 0; for(int i = 0; i < m_NumModes; i++) { int G = gcd(m_aModes[i].m_Width, m_aModes[i].m_Height); int Width = m_aModes[i].m_Width/G; int Height = m_aModes[i].m_Height/G; // check if we already have the format bool Found = false; for(int j = 0; j < m_NumVideoFormats; j++) { if(Width == m_aVideoFormats[j].m_WidthValue && Height == m_aVideoFormats[j].m_HeightValue) { Found = true; break; } } if(!Found) { m_aVideoFormats[m_NumVideoFormats].m_WidthValue = Width; m_aVideoFormats[m_NumVideoFormats].m_HeightValue = Height; m_NumVideoFormats++; // sort the array for(int k = 0; k < m_NumVideoFormats-1; k++) // ffs, bubblesort { for(int j = 0; j < m_NumVideoFormats-k-1; j++) { if((float)m_aVideoFormats[j].m_WidthValue/(float)m_aVideoFormats[j].m_HeightValue > (float)m_aVideoFormats[j+1].m_WidthValue/(float)m_aVideoFormats[j+1].m_HeightValue) { CVideoFormat Tmp = m_aVideoFormats[j]; m_aVideoFormats[j] = m_aVideoFormats[j+1]; m_aVideoFormats[j+1] = Tmp; } } } } } } void CMenus::UpdatedFilteredVideoModes() { m_lFilteredVideoModes.clear(); for(int i = 0; i < m_NumModes; i++) { int G = gcd(m_aModes[i].m_Width, m_aModes[i].m_Height); if(m_aVideoFormats[m_CurrentVideoFormat].m_WidthValue == m_aModes[i].m_Width/G && m_aVideoFormats[m_CurrentVideoFormat].m_HeightValue == m_aModes[i].m_Height/G) m_lFilteredVideoModes.add(m_aModes[i]); } } void CMenus::OnInit() { m_NumModes = Graphics()->GetVideoModes(m_aModes, MAX_RESOLUTIONS); UpdateVideoFormats(); bool Found = false; for(int i = 0; i < m_NumVideoFormats; i++) { int G = gcd(g_Config.m_GfxScreenWidth, g_Config.m_GfxScreenHeight); if(m_aVideoFormats[i].m_WidthValue == g_Config.m_GfxScreenWidth/G && m_aVideoFormats[i].m_HeightValue == g_Config.m_GfxScreenHeight/G) { m_CurrentVideoFormat = i; Found = true; break; } } if(!Found) m_CurrentVideoFormat = 0; UpdatedFilteredVideoModes(); // load menu images m_lMenuImages.clear(); Storage()->ListDirectory(IStorage::TYPE_ALL, "menuimages", MenuImageScan, this); /* array<string> my_strings; array<string>::range r2; my_strings.add("4"); my_strings.add("6"); my_strings.add("1"); my_strings.add("3"); my_strings.add("7"); my_strings.add("5"); my_strings.add("2"); for(array<string>::range r = my_strings.all(); !r.empty(); r.pop_front()) dbg_msg("", "%s", r.front().cstr()); sort(my_strings.all()); dbg_msg("", "after:"); for(array<string>::range r = my_strings.all(); !r.empty(); r.pop_front()) dbg_msg("", "%s", r.front().cstr()); array<int> myarray; myarray.add(4); myarray.add(6); myarray.add(1); myarray.add(3); myarray.add(7); myarray.add(5); myarray.add(2); for(array<int>::range r = myarray.all(); !r.empty(); r.pop_front()) dbg_msg("", "%d", r.front()); sort(myarray.all()); sort_verify(myarray.all()); dbg_msg("", "after:"); for(array<int>::range r = myarray.all(); !r.empty(); r.pop_front()) dbg_msg("", "%d", r.front()); exit(-1); // */ // clear filter lists //m_lFilters.clear(); if(g_Config.m_ClShowWelcome) m_Popup = POPUP_LANGUAGE; g_Config.m_ClShowWelcome = 0; Console()->Chain("add_favorite", ConchainServerbrowserUpdate, this); Console()->Chain("remove_favorite", ConchainServerbrowserUpdate, this); Console()->Chain("add_friend", ConchainFriendlistUpdate, this); Console()->Chain("remove_friend", ConchainFriendlistUpdate, this); m_TextureBlob = Graphics()->LoadTexture("blob.png", IStorage::TYPE_ALL, CImageInfo::FORMAT_AUTO, 0); // setup load amount m_LoadCurrent = 0; m_LoadTotal = g_pData->m_NumImages; if(!g_Config.m_ClThreadsoundloading) m_LoadTotal += g_pData->m_NumSounds; } void CMenus::PopupMessage(const char *pTopic, const char *pBody, const char *pButton, int Next) { // reset active item UI()->SetActiveItem(0); str_copy(m_aMessageTopic, pTopic, sizeof(m_aMessageTopic)); str_copy(m_aMessageBody, pBody, sizeof(m_aMessageBody)); str_copy(m_aMessageButton, pButton, sizeof(m_aMessageButton)); m_Popup = POPUP_MESSAGE; m_NextPopup = Next; } int CMenus::Render() { CUIRect Screen = *UI()->Screen(); Graphics()->MapScreen(Screen.x, Screen.y, Screen.w, Screen.h); static bool s_First = true; if(s_First) { // refresh server browser before we are in browser menu to save time m_pClient->m_pCamera->ChangePosition(CCamera::POS_START); if(g_Config.m_UiBrowserPage == PAGE_LAN) ServerBrowser()->Refresh(IServerBrowser::TYPE_LAN); else ServerBrowser()->Refresh(IServerBrowser::TYPE_INTERNET); m_pClient->m_pSounds->Enqueue(CSounds::CHN_MUSIC, SOUND_MENU); s_First = false; } // render background only if needed if(Client()->State() != IClient::STATE_ONLINE && !m_pClient->m_pMapLayersBackGround->MenuMapLoaded()) RenderBackground(); CUIRect TabBar, MainView; // some margin around the screen //Screen.Margin(10.0f, &Screen); static bool s_SoundCheck = false; if(!s_SoundCheck && m_Popup == POPUP_NONE) { if(Client()->SoundInitFailed()) m_Popup = POPUP_SOUNDERROR; s_SoundCheck = true; } if(m_Popup == POPUP_NONE) { if(m_MenuPage == PAGE_START && Client()->State() == IClient::STATE_OFFLINE) { RenderStartMenu(Screen); RenderLogo(Screen); } else { // do tab bar Screen.VMargin(Screen.w/2-365.0f, &MainView); MainView.HSplitTop(60.0f, &TabBar, &MainView); RenderMenubar(TabBar); // news is not implemented yet /*if(m_MenuPage <= PAGE_NEWS || m_MenuPage > PAGE_SETTINGS || (Client()->State() == IClient::STATE_OFFLINE && m_MenuPage >= PAGE_GAME && m_MenuPage <= PAGE_CALLVOTE)) { ServerBrowser()->Refresh(IServerBrowser::TYPE_INTERNET); m_MenuPage = PAGE_INTERNET; }*/ // render current page if(Client()->State() != IClient::STATE_OFFLINE) { if(m_GamePage == PAGE_GAME) RenderGame(MainView); else if(m_GamePage == PAGE_PLAYERS) RenderPlayers(MainView); else if(m_GamePage == PAGE_SERVER_INFO) RenderServerInfo(MainView); else if(m_GamePage == PAGE_CALLVOTE) RenderServerControl(MainView); else if(m_GamePage == PAGE_SETTINGS) RenderSettings(MainView); } else { if(m_MenuPage == PAGE_NEWS) RenderNews(MainView); else if(m_MenuPage == PAGE_INTERNET) RenderServerbrowser(MainView); else if(m_MenuPage == PAGE_LAN) RenderServerbrowser(MainView); else if(m_MenuPage == PAGE_DEMOS) RenderDemoList(MainView); else if(m_MenuPage == PAGE_FRIENDS) RenderServerbrowser(MainView); else if(m_MenuPage == PAGE_SETTINGS) RenderSettings(MainView); } } // do overlay popups DoPopupMenu(); } else { // make sure that other windows doesn't do anything funnay! //UI()->SetHotItem(0); //UI()->SetActiveItem(0); const char *pTitle = ""; const char *pExtraText = ""; const char *pButtonText = ""; int ExtraAlign = 0; int NumOptions = 4; if(m_Popup == POPUP_MESSAGE) { pTitle = m_aMessageTopic; pExtraText = m_aMessageBody; pButtonText = m_aMessageButton; } else if(m_Popup == POPUP_CONNECTING) { pTitle = Localize("Connecting to"); pButtonText = Localize("Abort"); if(Client()->MapDownloadTotalsize() > 0) { pTitle = Localize("Downloading map"); pExtraText = ""; NumOptions = 5; } } else if(m_Popup == POPUP_LANGUAGE) { pTitle = Localize("Language"); pButtonText = Localize("Ok"); NumOptions = 7; } else if(m_Popup == POPUP_COUNTRY) { pTitle = Localize("Country"); pButtonText = Localize("Ok"); NumOptions = 8; } else if(m_Popup == POPUP_DISCONNECTED) { pTitle = Localize("Disconnected"); pExtraText = Client()->ErrorString(); pButtonText = Localize("Ok"); } else if(m_Popup == POPUP_PURE) { pTitle = Localize("Disconnected"); pExtraText = Localize("The server is running a non-standard tuning on a pure game type."); pButtonText = Localize("Ok"); ExtraAlign = -1; } else if(m_Popup == POPUP_DELETE_DEMO) { pTitle = Localize("Delete demo"); pExtraText = Localize("Are you sure that you want to delete the demo?"); } else if(m_Popup == POPUP_RENAME_DEMO) { pTitle = Localize("Rename demo"); pExtraText = Localize("Are you sure you want to rename the demo?"); NumOptions = 6; } else if(m_Popup == POPUP_REMOVE_FRIEND) { pTitle = Localize("Remove friend"); pExtraText = Localize("Are you sure that you want to remove the player from your friends list?"); } else if(m_Popup == POPUP_SAVE_SKIN) { pTitle = Localize("Save skin"); pExtraText = Localize("Are you sure you want to save your skin? If a skin with this name already exists, it will be replaced."); NumOptions = 6; ExtraAlign = -1; } else if(m_Popup == POPUP_DELETE_SKIN) { pTitle = Localize("Delete skin"); pExtraText = Localize("Are you sure that you want to delete the skin?"); } else if(m_Popup == POPUP_SOUNDERROR) { pTitle = Localize("Sound error"); pExtraText = Localize("The audio device couldn't be initialised."); pButtonText = Localize("Ok"); ExtraAlign = -1; } else if(m_Popup == POPUP_PASSWORD) { pTitle = Localize("Password incorrect"); pExtraText = "Please enter the password."; } else if(m_Popup == POPUP_QUIT) { pTitle = Localize("Quit"); pExtraText = Localize("Are you sure that you want to quit?"); } else if(m_Popup == POPUP_FIRST_LAUNCH) { pTitle = Localize("Welcome to Teeworlds"); pExtraText = Localize("As this is the first time you launch the game, please enter your nick name below. It's recommended that you check the settings to adjust them to your liking before joining a server."); pButtonText = Localize("Enter"); NumOptions = 6; ExtraAlign = -1; } CUIRect Box, Part, BottomBar; float ButtonHeight = 20.0f; float ButtonHeightBig = ButtonHeight+5.0f; float SpacingH = 2.0f; float SpacingW = 3.0f; Box = Screen; Box.VMargin(Box.w/2.0f-(365.0f), &Box); float ButtonWidth = (Box.w/6.0f)-(SpacingW*5.0)/6.0f; Box.VMargin(ButtonWidth+SpacingW, &Box); Box.HMargin(Box.h/2.0f-((int)(NumOptions+1)*ButtonHeight+(int)(NumOptions)*SpacingH)/2.0f-10.0f, &Box); // render the box RenderTools()->DrawUIRect(&Box, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f); // headline Box.HSplitTop(ButtonHeightBig, &Part, &Box); Part.y += 3.0f; UI()->DoLabel(&Part, pTitle, Part.h*ms_FontmodHeight*0.8f, 0); // inner box Box.HSplitTop(SpacingH, 0, &Box); Box.HSplitBottom(ButtonHeight+5.0f+SpacingH, &Box, &BottomBar); BottomBar.HSplitTop(SpacingH, 0, &BottomBar); RenderTools()->DrawUIRect(&Box, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f); if(m_Popup == POPUP_QUIT) { CUIRect Yes, No; // additional info if(m_pClient->Editor()->HasUnsavedData()) { Box.HSplitTop(12.0f, 0, &Part); UI()->DoLabel(&Part, pExtraText, ButtonHeight*ms_FontmodHeight*0.8f, ExtraAlign); Part.HSplitTop(12.0f, 0, &Part); UI()->DoLabel(&Part, Localize("There's an unsaved map in the editor, you might want to save it before you quit the game."), ButtonHeight*ms_FontmodHeight*0.8f, ExtraAlign); } else { Box.HSplitTop(27.0f, 0, &Box); UI()->DoLabel(&Box, pExtraText, ButtonHeight*ms_FontmodHeight*0.8f, ExtraAlign); } // buttons BottomBar.VSplitMid(&No, &Yes); No.VSplitRight(SpacingW/2.0f, &No, 0); Yes.VSplitLeft(SpacingW/2.0f, 0, &Yes); static int s_ButtonAbort = 0; if(DoButton_Menu(&s_ButtonAbort, Localize("No"), 0, &No) || m_EscapePressed) m_Popup = POPUP_NONE; static int s_ButtonTryAgain = 0; if(DoButton_Menu(&s_ButtonTryAgain, Localize("Yes"), 0, &Yes) || m_EnterPressed) Client()->Quit(); } else if(m_Popup == POPUP_PASSWORD) { CUIRect EditBox, TryAgain, Abort; Box.HSplitTop(12.0f, 0, &Box); UI()->DoLabel(&Box, pExtraText, ButtonHeight*ms_FontmodHeight*0.8f, ExtraAlign); Box.HSplitBottom(ButtonHeight*1.7f, 0, &Box); Box.HSplitTop(20.0f, &EditBox, &Box); static float s_OffsetPassword = 0.0f; DoEditBoxOption(g_Config.m_Password, g_Config.m_Password, sizeof(g_Config.m_Password), &EditBox, Localize("Password"), ButtonWidth, &s_OffsetPassword, true); // buttons BottomBar.VSplitMid(&Abort, &TryAgain); Abort.VSplitRight(SpacingW/2.0f, &Abort, 0); TryAgain.VSplitLeft(SpacingW/2.0f, 0, &TryAgain); static int s_ButtonAbort = 0; if(DoButton_Menu(&s_ButtonAbort, Localize("Abort"), 0, &Abort) || m_EscapePressed) m_Popup = POPUP_NONE; static int s_ButtonTryAgain = 0; if(DoButton_Menu(&s_ButtonTryAgain, Localize("Try again"), 0, &TryAgain) || m_EnterPressed) { Client()->Connect(g_Config.m_UiServerAddress); } } else if(m_Popup == POPUP_CONNECTING) { static int s_Button = 0; if(DoButton_Menu(&s_Button, pButtonText, 0, &BottomBar) || m_EscapePressed || m_EnterPressed) { Client()->Disconnect(); m_Popup = POPUP_NONE; } if(Client()->MapDownloadTotalsize() > 0) { char aBuf[128]; int64 Now = time_get(); if(Now-m_DownloadLastCheckTime >= time_freq()) { if(m_DownloadLastCheckSize > Client()->MapDownloadAmount()) { // map downloaded restarted m_DownloadLastCheckSize = 0; } // update download speed float Diff = (Client()->MapDownloadAmount()-m_DownloadLastCheckSize)/((int)((Now-m_DownloadLastCheckTime)/time_freq())); float StartDiff = m_DownloadLastCheckSize-0.0f; if(StartDiff+Diff > 0.0f) m_DownloadSpeed = (Diff/(StartDiff+Diff))*(Diff/1.0f) + (StartDiff/(Diff+StartDiff))*m_DownloadSpeed; else m_DownloadSpeed = 0.0f; m_DownloadLastCheckTime = Now; m_DownloadLastCheckSize = Client()->MapDownloadAmount(); } Box.HSplitTop(15.f, 0, &Box); Box.HSplitTop(ButtonHeight, &Part, &Box); str_format(aBuf, sizeof(aBuf), "%d/%d KiB (%.1f KiB/s)", Client()->MapDownloadAmount()/1024, Client()->MapDownloadTotalsize()/1024, m_DownloadSpeed/1024.0f); UI()->DoLabel(&Part, aBuf, ButtonHeight*ms_FontmodHeight*0.8f, 0, -1); // time left const char *pTimeLeftString; int TimeLeft = max(1, m_DownloadSpeed > 0.0f ? static_cast<int>((Client()->MapDownloadTotalsize()-Client()->MapDownloadAmount())/m_DownloadSpeed) : 1); if(TimeLeft >= 60) { TimeLeft /= 60; pTimeLeftString = TimeLeft == 1 ? Localize("%i minute left") : Localize("%i minutes left"); } else pTimeLeftString = TimeLeft == 1 ? Localize("%i second left") : Localize("%i seconds left"); Box.HSplitTop(SpacingH, 0, &Box); Box.HSplitTop(ButtonHeight, &Part, &Box); str_format(aBuf, sizeof(aBuf), pTimeLeftString, TimeLeft); UI()->DoLabel(&Part, aBuf, ButtonHeight*ms_FontmodHeight*0.8f, 0, -1); // progress bar Box.HSplitTop(SpacingH, 0, &Box); Box.HSplitTop(ButtonHeight, &Part, &Box); Part.VMargin(40.0f, &Part); RenderTools()->DrawUIRect(&Part, vec4(1.0f, 1.0f, 1.0f, 0.25f), CUI::CORNER_ALL, 5.0f); Part.w = max(10.0f, (Part.w*Client()->MapDownloadAmount())/Client()->MapDownloadTotalsize()); RenderTools()->DrawUIRect(&Part, vec4(1.0f, 1.0f, 1.0f, 0.5f), CUI::CORNER_ALL, 5.0f); } else { Box.HSplitTop(27.0f, 0, &Box); UI()->DoLabel(&Box, g_Config.m_UiServerAddress, ButtonHeight*ms_FontmodHeight*0.8f, ExtraAlign); } } else if(m_Popup == POPUP_LANGUAGE) { RenderLanguageSelection(Box, false); static int s_Button = 0; if(DoButton_Menu(&s_Button, pButtonText, 0, &BottomBar) || m_EscapePressed || m_EnterPressed) m_Popup = POPUP_FIRST_LAUNCH; } else if(m_Popup == POPUP_COUNTRY) { // selected filter CBrowserFilter *pFilter = &m_lFilters[m_SelectedFilter]; int SortHash = 0; int Ping = 0; int Country = 0; char aGametype[32]; char aServerAddress[16]; pFilter->GetFilter(&SortHash, &Ping, &Country, aGametype, aServerAddress); static int ActSelection = -2; if(ActSelection == -2) ActSelection = Country; static float s_ScrollValue = 0.0f; int OldSelected = -1; UiDoListboxStart(&s_ScrollValue, 40.0f, 0, m_pClient->m_pCountryFlags->Num(), 12, OldSelected, s_ScrollValue, &Box, false); for(int i = 0; i < m_pClient->m_pCountryFlags->Num(); ++i) { const CCountryFlags::CCountryFlag *pEntry = m_pClient->m_pCountryFlags->GetByIndex(i); if(pEntry->m_CountryCode == ActSelection) OldSelected = i; CListboxItem Item = UiDoListboxNextItem(&pEntry->m_CountryCode, OldSelected == i); if(Item.m_Visible) { CUIRect Label; Item.m_Rect.Margin(5.0f, &Item.m_Rect); Item.m_Rect.HSplitBottom(10.0f, &Item.m_Rect, &Label); float OldWidth = Item.m_Rect.w; Item.m_Rect.w = Item.m_Rect.h*2; Item.m_Rect.x += (OldWidth-Item.m_Rect.w)/ 2.0f; Graphics()->TextureSet(pEntry->m_Texture); Graphics()->QuadsBegin(); Graphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f); IGraphics::CQuadItem QuadItem(Item.m_Rect.x, Item.m_Rect.y, Item.m_Rect.w, Item.m_Rect.h); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); if(i == OldSelected) { TextRender()->TextColor(0.0f, 0.0f, 0.0f, 1.0f); TextRender()->TextOutlineColor(1.0f, 1.0f, 1.0f, 0.25f); UI()->DoLabel(&Label, pEntry->m_aCountryCodeString, 10.0f, 0); TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); TextRender()->TextOutlineColor(0.0f, 0.0f, 0.0f, 0.3f); } else UI()->DoLabel(&Label, pEntry->m_aCountryCodeString, 10.0f, 0); } } const int NewSelected = UiDoListboxEnd(&s_ScrollValue, 0); if(OldSelected != NewSelected) ActSelection = m_pClient->m_pCountryFlags->GetByIndex(NewSelected)->m_CountryCode; Part.VMargin(120.0f, &Part); static int s_Button = 0; if(DoButton_Menu(&s_Button, pButtonText, 0, &BottomBar) || m_EnterPressed) { pFilter->SetFilter(SortHash, Ping, ActSelection, aGametype, aServerAddress); g_Config.m_BrFilterCountryIndex = ActSelection; m_Popup = POPUP_NONE; } if(m_EscapePressed) { ActSelection = Country; m_Popup = POPUP_NONE; } } else if(m_Popup == POPUP_DELETE_DEMO) { CUIRect Yes, No; Box.HSplitTop(27.0f, 0, &Box); UI()->DoLabel(&Box, pExtraText, ButtonHeight*ms_FontmodHeight*0.8f, ExtraAlign); // buttons BottomBar.VSplitMid(&No, &Yes); No.VSplitRight(SpacingW/2.0f, &No, 0); Yes.VSplitLeft(SpacingW/2.0f, 0, &Yes); static int s_ButtonNo = 0; if(DoButton_Menu(&s_ButtonNo, Localize("No"), 0, &No) || m_EscapePressed) m_Popup = POPUP_NONE; static int s_ButtonYes = 0; if(DoButton_Menu(&s_ButtonYes, Localize("Yes"), 0, &Yes) || m_EnterPressed) { m_Popup = POPUP_NONE; // delete demo if(m_DemolistSelectedIndex >= 0 && !m_DemolistSelectedIsDir) { char aBuf[512]; str_format(aBuf, sizeof(aBuf), "%s/%s", m_aCurrentDemoFolder, m_lDemos[m_DemolistSelectedIndex].m_aFilename); if(Storage()->RemoveFile(aBuf, m_lDemos[m_DemolistSelectedIndex].m_StorageType)) { DemolistPopulate(); DemolistOnUpdate(false); } else PopupMessage(Localize("Error"), Localize("Unable to delete the demo"), Localize("Ok")); } } } else if(m_Popup == POPUP_RENAME_DEMO) { CUIRect Yes, No, EditBox; Box.HSplitTop(27.0f, 0, &Box); UI()->DoLabel(&Box, pExtraText, ButtonHeight*ms_FontmodHeight*0.8f, ExtraAlign); Box.HSplitBottom(Box.h/2.0f, 0, &Box); Box.HSplitTop(20.0f, &EditBox, &Box); static float s_OffsetRenameDemo = 0.0f; DoEditBoxOption(m_aCurrentDemoFile, m_aCurrentDemoFile, sizeof(m_aCurrentDemoFile), &EditBox, Localize("Name"), ButtonWidth, &s_OffsetRenameDemo); // buttons BottomBar.VSplitMid(&No, &Yes); No.VSplitRight(SpacingW/2.0f, &No, 0); Yes.VSplitLeft(SpacingW/2.0f, 0, &Yes); static int s_ButtonNo = 0; if(DoButton_Menu(&s_ButtonNo, Localize("No"), 0, &No) || m_EscapePressed) m_Popup = POPUP_NONE; static int s_ButtonYes = 0; if(DoButton_Menu(&s_ButtonYes, Localize("Yes"), !m_aCurrentDemoFile[0], &Yes) || m_EnterPressed) { if(m_aCurrentDemoFile[0]) { m_Popup = POPUP_NONE; // rename demo if(m_DemolistSelectedIndex >= 0 && !m_DemolistSelectedIsDir) { char aBufOld[512]; str_format(aBufOld, sizeof(aBufOld), "%s/%s", m_aCurrentDemoFolder, m_lDemos[m_DemolistSelectedIndex].m_aFilename); int Length = str_length(m_aCurrentDemoFile); char aBufNew[512]; if(Length <= 4 || m_aCurrentDemoFile[Length-5] != '.' || str_comp_nocase(m_aCurrentDemoFile+Length-4, "demo")) str_format(aBufNew, sizeof(aBufNew), "%s/%s.demo", m_aCurrentDemoFolder, m_aCurrentDemoFile); else str_format(aBufNew, sizeof(aBufNew), "%s/%s", m_aCurrentDemoFolder, m_aCurrentDemoFile); if(Storage()->RenameFile(aBufOld, aBufNew, m_lDemos[m_DemolistSelectedIndex].m_StorageType)) { DemolistPopulate(); DemolistOnUpdate(false); } else PopupMessage(Localize("Error"), Localize("Unable to rename the demo"), Localize("Ok"), POPUP_RENAME_DEMO); } } } } else if(m_Popup == POPUP_REMOVE_FRIEND) { CUIRect Yes, No; Box.HSplitTop(27.0f, 0, &Box); UI()->DoLabel(&Box, pExtraText, ButtonHeight*ms_FontmodHeight*0.8f, ExtraAlign); // buttons BottomBar.VSplitMid(&No, &Yes); No.VSplitRight(SpacingW/2.0f, &No, 0); Yes.VSplitLeft(SpacingW/2.0f, 0, &Yes); static int s_ButtonNo = 0; if(DoButton_Menu(&s_ButtonNo, Localize("No"), 0, &No) || m_EscapePressed) m_Popup = POPUP_NONE; static int s_ButtonYes = 0; if(DoButton_Menu(&s_ButtonYes, Localize("Yes"), 0, &Yes) || m_EnterPressed) { m_Popup = POPUP_NONE; // remove friend if(m_FriendlistSelectedIndex >= 0) { m_pClient->Friends()->RemoveFriend(m_lFriends[m_FriendlistSelectedIndex].m_pFriendInfo->m_aName, m_lFriends[m_FriendlistSelectedIndex].m_pFriendInfo->m_aClan); FriendlistOnUpdate(); Client()->ServerBrowserUpdate(); } } } else if(m_Popup == POPUP_SAVE_SKIN) { CUIRect Yes, No, EditBox; Box.HSplitTop(24.0f, 0, &Box); Box.VMargin(10.0f, &Part); UI()->DoLabel(&Part, pExtraText, ButtonHeight*ms_FontmodHeight*0.8f, ExtraAlign, Box.w-20.0f); Box.HSplitBottom(Box.h/2.0f, 0, &Box); Box.HSplitTop(20.0f, &EditBox, &Box); static float s_OffsetSaveSkin = 0.0f; DoEditBoxOption(m_aSaveSkinName, m_aSaveSkinName, sizeof(m_aSaveSkinName), &EditBox, Localize("Name"), ButtonWidth, &s_OffsetSaveSkin); // buttons BottomBar.VSplitMid(&No, &Yes); No.VSplitRight(SpacingW/2.0f, &No, 0); Yes.VSplitLeft(SpacingW/2.0f, 0, &Yes); static int s_ButtonAbort = 0; if(DoButton_Menu(&s_ButtonAbort, Localize("No"), 0, &No) || m_EscapePressed) m_Popup = POPUP_NONE; static int s_ButtonTryAgain = 0; if(DoButton_Menu(&s_ButtonTryAgain, Localize("Yes"), !m_aSaveSkinName[0], &Yes) || m_EnterPressed) { if(m_aSaveSkinName[0]) { m_Popup = POPUP_NONE; SaveSkinfile(); m_aSaveSkinName[0] = 0; m_RefreshSkinSelector = true; } } } else if(m_Popup == POPUP_DELETE_SKIN) { CUIRect Yes, No; Box.HSplitTop(27.0f, 0, &Box); UI()->DoLabel(&Box, pExtraText, ButtonHeight*ms_FontmodHeight*0.8f, ExtraAlign); // buttons BottomBar.VSplitMid(&No, &Yes); No.VSplitRight(SpacingW/2.0f, &No, 0); Yes.VSplitLeft(SpacingW/2.0f, 0, &Yes); static int s_ButtonNo = 0; if(DoButton_Menu(&s_ButtonNo, Localize("No"), 0, &No) || m_EscapePressed) m_Popup = POPUP_NONE; static int s_ButtonYes = 0; if(DoButton_Menu(&s_ButtonYes, Localize("Yes"), 0, &Yes) || m_EnterPressed) { m_Popup = POPUP_NONE; // delete demo if(m_pSelectedSkin) { char aBuf[512]; str_format(aBuf, sizeof(aBuf), "skins/%s.json", m_pSelectedSkin->m_aName); if(Storage()->RemoveFile(aBuf, IStorage::TYPE_SAVE)) { m_pClient->m_pSkins->RemoveSkin(m_pSelectedSkin); m_RefreshSkinSelector = true; m_pSelectedSkin = 0; } else PopupMessage(Localize("Error"), Localize("Unable to delete the skin"), Localize("Ok")); } } } else if(m_Popup == POPUP_FIRST_LAUNCH) { CUIRect EditBox; Box.HSplitTop(20.0f, 0, &Box); Box.VMargin(10.0f, &Part); UI()->DoLabel(&Part, pExtraText, ButtonHeight*ms_FontmodHeight*0.8f, ExtraAlign, Box.w-20.0f); Box.HSplitBottom(ButtonHeight*2.0f, 0, &Box); Box.HSplitTop(ButtonHeight, &EditBox, &Box); static float s_OffsetName = 0.0f; DoEditBoxOption(g_Config.m_PlayerName, g_Config.m_PlayerName, sizeof(g_Config.m_PlayerName), &EditBox, Localize("Nickname"), ButtonWidth, &s_OffsetName); // button static int s_EnterButton = 0; if(DoButton_Menu(&s_EnterButton, pButtonText, 0, &BottomBar) || m_EnterPressed) { if(g_Config.m_PlayerName[0]) m_Popup = POPUP_NONE; else PopupMessage(Localize("Error"), Localize("Nickname is empty."), Localize("Ok"), POPUP_FIRST_LAUNCH); } } else { Box.HSplitTop(27.0f, 0, &Box); Box.VMargin(10.0f, &Part); UI()->DoLabel(&Part, pExtraText, ButtonHeight*ms_FontmodHeight*0.8f, ExtraAlign, -1); // button static int s_Button = 0; if(DoButton_Menu(&s_Button, pButtonText, 0, &BottomBar) || m_EscapePressed || m_EnterPressed) m_Popup = m_NextPopup; } if(m_Popup == POPUP_NONE) UI()->SetActiveItem(0); } return 0; } void CMenus::SetActive(bool Active) { m_MenuActive = Active; if(!m_MenuActive) { if(Client()->State() == IClient::STATE_ONLINE) { m_pClient->OnRelease(); } } else if(Client()->State() == IClient::STATE_DEMOPLAYBACK) { m_pClient->OnRelease(); } } void CMenus::OnReset() { } bool CMenus::OnMouseMove(float x, float y) { m_LastInput = time_get(); if(!m_MenuActive) return false; // prev mouse position m_PrevMousePos = m_MousePos; UI()->ConvertMouseMove(&x, &y); m_MousePos.x += x; m_MousePos.y += y; if(m_MousePos.x < 0) m_MousePos.x = 0; if(m_MousePos.y < 0) m_MousePos.y = 0; if(m_MousePos.x > Graphics()->ScreenWidth()) m_MousePos.x = Graphics()->ScreenWidth(); if(m_MousePos.y > Graphics()->ScreenHeight()) m_MousePos.y = Graphics()->ScreenHeight(); return true; } bool CMenus::OnInput(IInput::CEvent e) { m_LastInput = time_get(); // special handle esc and enter for popup purposes if(e.m_Flags&IInput::FLAG_PRESS) { if(e.m_Key == KEY_ESCAPE) { m_EscapePressed = true; SetActive(!IsActive()); return true; } } if(IsActive()) { if(e.m_Flags&IInput::FLAG_PRESS) { // special for popups if(e.m_Key == KEY_RETURN || e.m_Key == KEY_KP_ENTER) m_EnterPressed = true; else if(e.m_Key == KEY_DELETE) m_DeletePressed = true; } if(m_NumInputEvents < MAX_INPUTEVENTS) m_aInputEvents[m_NumInputEvents++] = e; return true; } return false; } void CMenus::OnConsoleInit() { // add filters m_lFilters.add(CBrowserFilter(CBrowserFilter::FILTER_ALL, Localize("All"), ServerBrowser(), IServerBrowser::FILTER_PING, 999, -1, "", "")); m_lFilters.add(CBrowserFilter(CBrowserFilter::FILTER_STANDARD, Localize("Standard Gametype"), ServerBrowser(), IServerBrowser::FILTER_COMPAT_VERSION|IServerBrowser::FILTER_PURE|IServerBrowser::FILTER_PURE_MAP|IServerBrowser::FILTER_PING, 999, -1, "", "")); m_lFilters.add(CBrowserFilter(CBrowserFilter::FILTER_FAVORITES, Localize("Favorites"), ServerBrowser(), IServerBrowser::FILTER_FAVORITE|IServerBrowser::FILTER_PING, 999, -1, "", "")); } void CMenus::OnStateChange(int NewState, int OldState) { // reset active item UI()->SetActiveItem(0); if(NewState == IClient::STATE_OFFLINE) { if(OldState >= IClient::STATE_ONLINE && NewState < IClient::STATE_QUITING) m_pClient->m_pSounds->Play(CSounds::CHN_MUSIC, SOUND_MENU, 1.0f); m_Popup = POPUP_NONE; if(Client()->ErrorString() && Client()->ErrorString()[0] != 0) { if(str_find(Client()->ErrorString(), "password")) { m_Popup = POPUP_PASSWORD; UI()->SetHotItem(&g_Config.m_Password); UI()->SetActiveItem(&g_Config.m_Password); } else m_Popup = POPUP_DISCONNECTED; } } else if(NewState == IClient::STATE_LOADING) { m_Popup = POPUP_CONNECTING; m_DownloadLastCheckTime = time_get(); m_DownloadLastCheckSize = 0; m_DownloadSpeed = 0.0f; //client_serverinfo_request(); } else if(NewState == IClient::STATE_CONNECTING) m_Popup = POPUP_CONNECTING; else if (NewState == IClient::STATE_ONLINE || NewState == IClient::STATE_DEMOPLAYBACK) { m_Popup = POPUP_NONE; SetActive(false); } } extern "C" void font_debug_render(); void CMenus::OnRender() { /* // text rendering test stuff render_background(); CTextCursor cursor; TextRender()->SetCursor(&cursor, 10, 10, 20, TEXTFLAG_RENDER); TextRender()->TextEx(&cursor, "ようこそ - ガイド", -1); TextRender()->SetCursor(&cursor, 10, 30, 15, TEXTFLAG_RENDER); TextRender()->TextEx(&cursor, "ようこそ - ガイド", -1); //Graphics()->TextureSet(-1); Graphics()->QuadsBegin(); Graphics()->QuadsDrawTL(60, 60, 5000, 5000); Graphics()->QuadsEnd(); return;*/ if(Client()->State() != IClient::STATE_ONLINE && Client()->State() != IClient::STATE_DEMOPLAYBACK) SetActive(true); if(Client()->State() == IClient::STATE_DEMOPLAYBACK) { CUIRect Screen = *UI()->Screen(); Graphics()->MapScreen(Screen.x, Screen.y, Screen.w, Screen.h); RenderDemoPlayer(Screen); } if(Client()->State() == IClient::STATE_ONLINE && m_pClient->m_ServerMode == m_pClient->SERVERMODE_PUREMOD) { Client()->Disconnect(); SetActive(true); m_Popup = POPUP_PURE; } if(!IsActive()) { m_EscapePressed = false; m_EnterPressed = false; m_DeletePressed = false; m_NumInputEvents = 0; return; } // update the ui CUIRect *pScreen = UI()->Screen(); float mx = (m_MousePos.x/(float)Graphics()->ScreenWidth())*pScreen->w; float my = (m_MousePos.y/(float)Graphics()->ScreenHeight())*pScreen->h; int Buttons = 0; if(m_UseMouseButtons) { if(Input()->KeyPressed(KEY_MOUSE_1)) Buttons |= 1; if(Input()->KeyPressed(KEY_MOUSE_2)) Buttons |= 2; if(Input()->KeyPressed(KEY_MOUSE_3)) Buttons |= 4; } UI()->Update(mx,my,mx*3.0f,my*3.0f,Buttons); // render if(Client()->State() != IClient::STATE_DEMOPLAYBACK) Render(); // render cursor Graphics()->TextureSet(g_pData->m_aImages[IMAGE_CURSOR].m_Id); Graphics()->QuadsBegin(); Graphics()->SetColor(1,1,1,1); IGraphics::CQuadItem QuadItem(mx, my, 24, 24); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); // render debug information if(g_Config.m_Debug) { CUIRect Screen = *UI()->Screen(); Graphics()->MapScreen(Screen.x, Screen.y, Screen.w, Screen.h); char aBuf[512]; str_format(aBuf, sizeof(aBuf), "%p %p %p", UI()->HotItem(), UI()->ActiveItem(), UI()->LastActiveItem()); CTextCursor Cursor; TextRender()->SetCursor(&Cursor, 10, 10, 10, TEXTFLAG_RENDER); TextRender()->TextEx(&Cursor, aBuf, -1); } m_EscapePressed = false; m_EnterPressed = false; m_DeletePressed = false; m_NumInputEvents = 0; } void CMenus::RenderBackground() { //Graphics()->Clear(1,1,1); //render_sunrays(0,0); float sw = 300*Graphics()->ScreenAspect(); float sh = 300; Graphics()->MapScreen(0, 0, sw, sh); // render background color Graphics()->TextureClear(); Graphics()->QuadsBegin(); //vec4 bottom(gui_color.r*0.3f, gui_color.g*0.3f, gui_color.b*0.3f, 1.0f); //vec4 bottom(0, 0, 0, 1.0f); vec4 Bottom(0.45f, 0.45f, 0.45f, 1.0f); vec4 Top(0.45f, 0.45f, 0.45f, 1.0f); IGraphics::CColorVertex Array[4] = { IGraphics::CColorVertex(0, Top.r, Top.g, Top.b, Top.a), IGraphics::CColorVertex(1, Top.r, Top.g, Top.b, Top.a), IGraphics::CColorVertex(2, Bottom.r, Bottom.g, Bottom.b, Bottom.a), IGraphics::CColorVertex(3, Bottom.r, Bottom.g, Bottom.b, Bottom.a)}; Graphics()->SetColorVertex(Array, 4); IGraphics::CQuadItem QuadItem(0, 0, sw, sh); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); // render the tiles Graphics()->TextureClear(); Graphics()->QuadsBegin(); float Size = 15.0f; float OffsetTime = fmod(Client()->LocalTime()*0.15f, 2.0f); for(int y = -2; y < (int)(sw/Size); y++) for(int x = -2; x < (int)(sh/Size); x++) { Graphics()->SetColor(0,0,0,0.045f); IGraphics::CQuadItem QuadItem((x-OffsetTime)*Size*2+(y&1)*Size, (y+OffsetTime)*Size, Size, Size); Graphics()->QuadsDrawTL(&QuadItem, 1); } Graphics()->QuadsEnd(); // render border fade Graphics()->TextureSet(m_TextureBlob); Graphics()->QuadsBegin(); Graphics()->SetColor(0,0,0,0.5f); QuadItem = IGraphics::CQuadItem(-100, -100, sw+200, sh+200); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); // restore screen {CUIRect Screen = *UI()->Screen(); Graphics()->MapScreen(Screen.x, Screen.y, Screen.w, Screen.h);} } ================================================ FILE: src/game/client/components/menus.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_CLIENT_COMPONENTS_MENUS_H #define GAME_CLIENT_COMPONENTS_MENUS_H #include <base/vmath.h> #include <base/tl/sorted_array.h> #include <engine/graphics.h> #include <engine/demo.h> #include <engine/friends.h> #include <game/voting.h> #include <game/client/component.h> #include <game/client/localization.h> #include <game/client/ui.h> #include "skins.h" // compnent to fetch keypresses, override all other input class CMenusKeyBinder : public CComponent { public: bool m_TakeKey; bool m_GotKey; IInput::CEvent m_Key; CMenusKeyBinder(); virtual bool OnInput(IInput::CEvent Event); }; class CMenus : public CComponent { typedef float (*FDropdownCallback)(CUIRect View, void *pUser); float *ButtonFade(const void *pID, float Seconds, int Checked=0); int DoButton_DemoPlayer(const void *pID, const char *pText, const CUIRect *pRect); int DoButton_SpriteID(const void *pID, int ImageID, int SpriteID, const CUIRect *pRect, int Corners=CUI::CORNER_ALL, float r=5.0f, bool Fade=true); int DoButton_SpriteClean(int ImageID, int SpriteID, const CUIRect *pRect); int DoButton_SpriteCleanID(const void *pID, int ImageID, int SpriteID, const CUIRect *pRect, bool Blend=true); int DoButton_Toggle(const void *pID, int Checked, const CUIRect *pRect, bool Active); int DoButton_Menu(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Corners=CUI::CORNER_ALL, float r=5.0f, float FontFactor=0.0f, vec4 ColorHot=vec4(1.0f, 1.0f, 1.0f, 0.75f), bool TextFade=true); int DoButton_MenuImage(const void *pID, const char *pText, int Checked, const CUIRect *pRect, const char *pImageName, float r=5.0f, float FontFactor=0.0f); int DoButton_MenuTab(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Corners); int DoButton_MenuTabTop(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Corners=CUI::CORNER_ALL, float r=5.0f, float FontFactor=0.0f); int DoButton_Customize(const void *pID, IGraphics::CTextureHandle Texture, int SpriteID, const CUIRect *pRect, float ImageRatio); int DoButton_CheckBox_Common(const void *pID, const char *pText, const char *pBoxText, const CUIRect *pRect, bool Checked=false); int DoButton_CheckBox(const void *pID, const char *pText, int Checked, const CUIRect *pRect); int DoButton_CheckBox_Number(const void *pID, const char *pText, int Checked, const CUIRect *pRect); int DoButton_MouseOver(int ImageID, int SpriteID, const CUIRect *pRect); /*static void ui_draw_menu_button(const void *id, const char *text, int checked, const CUIRect *r, const void *extra); static void ui_draw_keyselect_button(const void *id, const char *text, int checked, const CUIRect *r, const void *extra); static void ui_draw_menu_tab_button(const void *id, const char *text, int checked, const CUIRect *r, const void *extra); static void ui_draw_settings_tab_button(const void *id, const char *text, int checked, const CUIRect *r, const void *extra); */ int DoIcon(int ImageId, int SpriteId, const CUIRect *pRect); int DoButton_GridHeader(const void *pID, const char *pText, int Checked, const CUIRect *pRect); int DoButton_GridHeaderIcon(const void *pID, int ImageID, int SpriteID, const CUIRect *pRect, int Corners); //static void ui_draw_browse_icon(int what, const CUIRect *r); //static void ui_draw_grid_header(const void *id, const char *text, int checked, const CUIRect *r, const void *extra); /*static void ui_draw_checkbox_common(const void *id, const char *text, const char *boxtext, const CUIRect *r, const void *extra); static void ui_draw_checkbox(const void *id, const char *text, int checked, const CUIRect *r, const void *extra); static void ui_draw_checkbox_number(const void *id, const char *text, int checked, const CUIRect *r, const void *extra); */ int DoEditBox(void *pID, const CUIRect *pRect, char *pStr, unsigned StrSize, float FontSize, float *pOffset, bool Hidden=false, int Corners=CUI::CORNER_ALL); void DoEditBoxOption(void *pID, char *pOption, int OptionLength, const CUIRect *pRect, const char *pStr, float VSplitVal, float *pOffset, bool Hidden=false); void DoScrollbarOption(void *pID, int *pOption, const CUIRect *pRect, const char *pStr, float VSplitVal, int Min, int Max, bool infinite=false); float DoDropdownMenu(void *pID, const CUIRect *pRect, const char *pStr, float HeaderHeight, FDropdownCallback pfnCallback); void DoInfoBox(const CUIRect *pRect, const char *pLable, const char *pValue); //static int ui_do_edit_box(void *id, const CUIRect *rect, char *str, unsigned str_size, float font_size, bool hidden=false); float DoScrollbarV(const void *pID, const CUIRect *pRect, float Current); float DoScrollbarH(const void *pID, const CUIRect *pRect, float Current); void DoButton_KeySelect(const void *pID, const char *pText, int Checked, const CUIRect *pRect); int DoKeyReader(void *pID, const CUIRect *pRect, int Key); //static int ui_do_key_reader(void *id, const CUIRect *rect, int key); void UiDoGetButtons(int Start, int Stop, CUIRect View, float ButtonHeight, float Spacing); struct CListboxItem { int m_Visible; int m_Selected; CUIRect m_Rect; CUIRect m_HitRect; }; void UiDoListboxHeader(const CUIRect *pRect, const char *pTitle, float HeaderHeight, float Spacing); void UiDoListboxStart(const void *pID, float RowHeight, const char *pBottomText, int NumItems, int ItemsPerRow, int SelectedIndex, float ScrollValue, const CUIRect *pRect=0, bool Background=true); CListboxItem UiDoListboxNextItem(const void *pID, bool Selected = false); CListboxItem UiDoListboxNextRow(); int UiDoListboxEnd(float *pScrollValue, bool *pItemActivated); //static void demolist_listdir_callback(const char *name, int is_dir, void *user); //static void demolist_list_callback(const CUIRect *rect, int index, void *user); enum { POPUP_NONE=0, POPUP_FIRST_LAUNCH, POPUP_CONNECTING, POPUP_MESSAGE, POPUP_DISCONNECTED, POPUP_PURE, POPUP_LANGUAGE, POPUP_COUNTRY, POPUP_DELETE_DEMO, POPUP_RENAME_DEMO, POPUP_REMOVE_FRIEND, POPUP_SAVE_SKIN, POPUP_DELETE_SKIN, POPUP_SOUNDERROR, POPUP_PASSWORD, POPUP_QUIT, }; enum { PAGE_NEWS=0, PAGE_GAME, PAGE_PLAYERS, PAGE_SERVER_INFO, PAGE_CALLVOTE, PAGE_INTERNET, PAGE_LAN, PAGE_FRIENDS, PAGE_DEMOS, PAGE_SETTINGS, PAGE_SYSTEM, PAGE_START, PAGE_BROWSER_BROWSER=0, PAGE_BROWSER_FRIENDS, NUM_PAGE_BROWSER, SETTINGS_GENERAL=0, SETTINGS_PLAYER, SETTINGS_TEE, SETTINGS_CONTROLS, SETTINGS_GRAPHICS, SETTINGS_SOUND, }; int m_GamePage; int m_Popup; int m_ActivePage; int m_MenuPage; int m_BorwserPage; bool m_MenuActive; bool m_UseMouseButtons; vec2 m_MousePos; vec2 m_PrevMousePos; bool m_InfoMode; // images struct CMenuImage { char m_aName[64]; IGraphics::CTextureHandle m_OrgTexture; IGraphics::CTextureHandle m_GreyTexture; }; array<CMenuImage> m_lMenuImages; static int MenuImageScan(const char *pName, int IsDir, int DirType, void *pUser); const CMenuImage *FindMenuImage(const char* pName); int64 m_LastInput; // loading int m_LoadCurrent; int m_LoadTotal; // char m_aMessageTopic[512]; char m_aMessageBody[512]; char m_aMessageButton[512]; int m_NextPopup; void PopupMessage(const char *pTopic, const char *pBody, const char *pButton, int Next=POPUP_NONE); // TODO: this is a bit ugly but.. well.. yeah enum { MAX_INPUTEVENTS = 32 }; static IInput::CEvent m_aInputEvents[MAX_INPUTEVENTS]; static int m_NumInputEvents; // some settings static float ms_ButtonHeight; static float ms_ListheaderHeight; static float ms_FontmodHeight; // for settings bool m_NeedRestartGraphics; bool m_NeedRestartSound; int m_TeePartSelected; char m_aSaveSkinName[24]; void SaveSkinfile(); bool m_RefreshSkinSelector; const CSkins::CSkin *m_pSelectedSkin; // bool m_EscapePressed; bool m_EnterPressed; bool m_DeletePressed; // for map download popup int64 m_DownloadLastCheckTime; int m_DownloadLastCheckSize; float m_DownloadSpeed; // for call vote int m_CallvoteSelectedOption; int m_CallvoteSelectedPlayer; char m_aCallvoteReason[VOTE_REASON_LENGTH]; // for callbacks int *m_pActiveDropdown; // demo struct CDemoItem { char m_aFilename[128]; char m_aName[128]; bool m_IsDir; int m_StorageType; bool m_InfosLoaded; bool m_Valid; CDemoHeader m_Info; bool operator<(const CDemoItem &Other) { return !str_comp(m_aFilename, "..") ? true : !str_comp(Other.m_aFilename, "..") ? false : m_IsDir && !Other.m_IsDir ? true : !m_IsDir && Other.m_IsDir ? false : str_comp_filenames(m_aFilename, Other.m_aFilename) < 0; } }; sorted_array<CDemoItem> m_lDemos; char m_aCurrentDemoFolder[256]; char m_aCurrentDemoFile[64]; int m_DemolistSelectedIndex; bool m_DemolistSelectedIsDir; int m_DemolistStorageType; void DemolistOnUpdate(bool Reset); void DemolistPopulate(); static int DemolistFetchCallback(const char *pName, int IsDir, int StorageType, void *pUser); // friends struct CFriendItem { const CFriendInfo *m_pFriendInfo; int m_NumFound; bool operator<(const CFriendItem &Other) { if(m_NumFound && !Other.m_NumFound) return true; else if(!m_NumFound && Other.m_NumFound) return false; else { int Result = str_comp_nocase(m_pFriendInfo->m_aName, Other.m_pFriendInfo->m_aName); if(Result) return Result < 0; else return str_comp_nocase(m_pFriendInfo->m_aClan, Other.m_pFriendInfo->m_aClan) < 0; } } }; sorted_array<CFriendItem> m_lFriends; int m_FriendlistSelectedIndex; void FriendlistOnUpdate(); class CBrowserFilter { bool m_Extended; int m_Custom; char m_aName[64]; int m_Filter; class IServerBrowser *m_pServerBrowser; public: enum { FILTER_CUSTOM=0, FILTER_ALL, FILTER_STANDARD, FILTER_FAVORITES, }; // buttons var int m_SwitchButton; CBrowserFilter() {} CBrowserFilter(int Custom, const char* pName, IServerBrowser *pServerBrowser, int Filter, int Ping, int Country, const char* pGametype, const char* pServerAddress); void Switch(); bool Extended() const; int Custom() const; int Filter() const; const char* Name() const; void SetFilterNum(int Num); int NumSortedServers() const; int NumPlayers() const; const CServerInfo *SortedGet(int Index) const; const void *ID(int Index) const; void GetFilter(int *pSortHash, int *pPing, int *pCountry, char* pGametype, char* pServerAddress); void SetFilter(int SortHash, int Ping, int Country, const char* pGametype, const char* pServerAddress); }; array<CBrowserFilter> m_lFilters; int m_SelectedFilter; void RemoveFilter(int FilterIndex); void Move(bool Up, int Filter); class CInfoOverlay { public: enum { OVERLAY_SERVERINFO=0, OVERLAY_HEADERINFO, OVERLAY_PLAYERSINFO, }; int m_Type; const void *m_pData; float m_X; float m_Y; bool m_Reset; }; CInfoOverlay m_InfoOverlay; bool m_InfoOverlayActive; class CServerEntry { public: int m_Filter; int m_Index; }; CServerEntry m_SelectedServer; enum { FIXED=1, SPACER=2, COL_FLAG=0, COL_NAME, COL_GAMETYPE, COL_MAP, COL_PLAYERS, COL_PING, //COL_FAVORITE, //COL_INFO, NUM_COLS, }; struct CColumn { int m_ID; int m_Sort; CLocConstString m_Caption; int m_Direction; float m_Width; int m_Flags; CUIRect m_Rect; CUIRect m_Spacer; }; static CColumn ms_aCols[NUM_COLS]; enum { MAX_RESOLUTIONS=256, }; CVideoMode m_aModes[MAX_RESOLUTIONS]; int m_NumModes; struct CVideoFormat { int m_WidthValue; int m_HeightValue; }; CVideoFormat m_aVideoFormats[MAX_RESOLUTIONS]; sorted_array<CVideoMode> m_lFilteredVideoModes; int m_NumVideoFormats; int m_CurrentVideoFormat; void UpdateVideoFormats(); void UpdatedFilteredVideoModes(); // found in menus.cpp int Render(); //void render_background(); //void render_loading(float percent); void RenderMenubar(CUIRect r); void RenderNews(CUIRect MainView); void RenderBackButton(CUIRect MainView); // found in menus_demo.cpp void RenderDemoPlayer(CUIRect MainView); void RenderDemoList(CUIRect MainView); // found in menus_start.cpp void RenderStartMenu(CUIRect MainView); void RenderLogo(CUIRect MainView); // found in menus_ingame.cpp void RenderGame(CUIRect MainView); void RenderPlayers(CUIRect MainView); void RenderServerInfo(CUIRect MainView); void HandleCallvote(int Page, bool Force); void RenderServerControl(CUIRect MainView); void RenderServerControlKick(CUIRect MainView, bool FilterSpectators); void RenderServerControlServer(CUIRect MainView); // found in menus_browser.cpp int m_ScrollOffset; void RenderServerbrowserServerList(CUIRect View); void RenderServerbrowserFriendList(CUIRect View); void RenderServerbrowserServerDetail(CUIRect View, const CServerInfo *pInfo); void RenderServerbrowserFilters(CUIRect View); void RenderServerbrowserFriends(CUIRect View); void RenderServerbrowserBottomBox(CUIRect View); void RenderServerbrowserOverlay(); bool RenderFilterHeader(CUIRect View, int FilterIndex); int DoBrowserEntry(const void *pID, CUIRect *pRect, const CServerInfo *pEntry, bool Selected); void RenderServerbrowser(CUIRect MainView); static void ConchainFriendlistUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData); static void ConchainServerbrowserUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData); void SetOverlay(int Type, float x, float y, const void *pData); // found in menus_settings.cpp void RenderLanguageSelection(CUIRect MainView, bool Header=true); void RenderHSLPicker(CUIRect Picker); void RenderSkinSelection(CUIRect MainView); void RenderSkinPartSelection(CUIRect MainView); void RenderSettingsGeneral(CUIRect MainView); void RenderSettingsPlayer(CUIRect MainView); void RenderSettingsTee(CUIRect MainView); void RenderSettingsTeeBasic(CUIRect MainView); void RenderSettingsTeeCustom(CUIRect MainView); void RenderSettingsControls(CUIRect MainView); void RenderSettingsGraphics(CUIRect MainView); void RenderSettingsSound(CUIRect MainView); void RenderSettings(CUIRect MainView); // found in menu_callback.cpp static float RenderSettingsControlsMovement(CUIRect View, void *pUser); static float RenderSettingsControlsWeapon(CUIRect View, void *pUser); static float RenderSettingsControlsVoting(CUIRect View, void *pUser); static float RenderSettingsControlsChat(CUIRect View, void *pUser); static float RenderSettingsControlsMisc(CUIRect View, void *pUser); void SetActive(bool Active); void InvokePopupMenu(void *pID, int Flags, float X, float Y, float W, float H, int (*pfnFunc)(CMenus *pMenu, CUIRect Rect), void *pExtra=0); void DoPopupMenu(); static int PopupFilter(CMenus *pMenus, CUIRect View); IGraphics::CTextureHandle m_TextureBlob; public: void RenderBackground(); void UseMouseButtons(bool Use) { m_UseMouseButtons = Use; } static CMenusKeyBinder m_Binder; CMenus(); void RenderLoading(); bool IsActive() const { return m_MenuActive; } virtual void OnInit(); virtual void OnConsoleInit(); virtual void OnStateChange(int NewState, int OldState); virtual void OnReset(); virtual void OnRender(); virtual bool OnInput(IInput::CEvent Event); virtual bool OnMouseMove(float x, float y); }; #endif ================================================ FILE: src/game/client/components/menus_browser.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <engine/config.h> #include <engine/friends.h> #include <engine/graphics.h> #include <engine/keys.h> #include <engine/serverbrowser.h> #include <engine/textrender.h> #include <engine/shared/config.h> #include <game/generated/client_data.h> #include <game/generated/protocol.h> #include <game/version.h> #include <game/client/render.h> #include <game/client/ui.h> #include <game/client/components/countryflags.h> #include "menus.h" CMenus::CColumn CMenus::ms_aCols[] = { {COL_FLAG, -1, " ", -1, 87.0f, 0, {0}, {0}}, // Localize - these strings are localized within CLocConstString {COL_NAME, IServerBrowser::SORT_NAME, "Server", 0, 300.0f, 0, {0}, {0}}, {COL_GAMETYPE, IServerBrowser::SORT_GAMETYPE, "Type", 1, 70.0f, 0, {0}, {0}}, {COL_MAP, IServerBrowser::SORT_MAP, "Map", 1, 100.0f, 0, {0}, {0}}, {COL_PLAYERS, IServerBrowser::SORT_NUMPLAYERS, "Players", 1, 60.0f, 0, {0}, {0}}, {COL_PING, IServerBrowser::SORT_PING, "Ping", 1, 40.0f, 0, {0}, {0}}, //{COL_FAVORITE, -1, " ", 1, 14.0f, 0, {0}, {0}}, //{COL_INFO, -1, " ", 1, 14.0f, 0, {0}, {0}}, }; // filters CMenus::CBrowserFilter::CBrowserFilter(int Custom, const char* pName, IServerBrowser *pServerBrowser, int Filter, int Ping, int Country, const char* pGametype, const char* pServerAddress) : m_pServerBrowser(pServerBrowser) { m_Extended = true; m_Custom = Custom; str_copy(m_aName, pName, sizeof(m_aName)); m_Filter = pServerBrowser->AddFilter(Filter, Ping, Country, pGametype, pServerAddress); // init buttons m_SwitchButton = 0; } void CMenus::CBrowserFilter::Switch() { m_Extended ^= 1; } bool CMenus::CBrowserFilter::Extended() const { return m_Extended; } int CMenus::CBrowserFilter::Custom() const { return m_Custom; } int CMenus::CBrowserFilter::Filter() const { return m_Filter; } const char* CMenus::CBrowserFilter::Name() const { return m_aName; } const void *CMenus::CBrowserFilter::ID(int Index) const { return m_pServerBrowser->GetID(m_Filter, Index); } int CMenus::CBrowserFilter::NumSortedServers() const { return m_pServerBrowser->NumSortedServers(m_Filter); } int CMenus::CBrowserFilter::NumPlayers() const { return m_pServerBrowser->NumSortedPlayers(m_Filter); } const CServerInfo *CMenus::CBrowserFilter::SortedGet(int Index) const { return m_pServerBrowser->SortedGet(m_Filter, Index); } void CMenus::CBrowserFilter::SetFilterNum(int Num) { m_Filter = Num; } void CMenus::CBrowserFilter::GetFilter(int *pSortHash, int *pPing, int *pCountry, char* pGametype, char* pServerAddress) { m_pServerBrowser->GetFilter(m_Filter, pSortHash, pPing, pCountry, pGametype, pServerAddress); } void CMenus::CBrowserFilter::SetFilter(int SortHash, int Ping, int Country, const char* pGametype, const char* pServerAddress) { m_pServerBrowser->SetFilter(m_Filter, SortHash, Ping, Country, pGametype, pServerAddress); } void CMenus::RemoveFilter(int FilterIndex) { int Filter = m_lFilters[FilterIndex].Filter(); ServerBrowser()->RemoveFilter(Filter); m_lFilters.remove_index(FilterIndex); // update filter indexes for(int i = 0; i < m_lFilters.size(); i++) { CBrowserFilter *pFilter = &m_lFilters[i]; if(pFilter->Filter() > Filter) pFilter->SetFilterNum(pFilter->Filter()-1); } } void CMenus::Move(bool Up, int Filter) { // move up CBrowserFilter Temp = m_lFilters[Filter]; if(Up) { if(Filter > 0) { m_lFilters[Filter] = m_lFilters[Filter-1]; m_lFilters[Filter-1] = Temp; } } else // move down { if(Filter < m_lFilters.size()-1) { m_lFilters[Filter] = m_lFilters[Filter+1]; m_lFilters[Filter+1] = Temp; } } } void CMenus::SetOverlay(int Type, float x, float y, const void *pData) { if(m_InfoOverlay.m_Reset) { m_InfoOverlayActive = true; m_InfoOverlay.m_Type = Type; m_InfoOverlay.m_X = x; m_InfoOverlay.m_Y = y; m_InfoOverlay.m_pData = pData; m_InfoOverlay.m_Reset = false; } } int CMenus::DoBrowserEntry(const void *pID, CUIRect *pRect, const CServerInfo *pEntry, bool Selected) { // logic int ReturnValue = 0; int Inside = UI()->MouseInside(pRect); if(UI()->ActiveItem() == pID) { if(!UI()->MouseButton(0)) { if(Inside >= 0) ReturnValue = 1; UI()->SetActiveItem(0); } } if(UI()->HotItem() == pID) { if(UI()->MouseButton(0)) UI()->SetActiveItem(pID); CUIRect r = *pRect; RenderTools()->DrawUIRect(&r, vec4(1.0f, 1.0f, 1.0f, 0.5f), CUI::CORNER_ALL, 4.0f); } if(Inside) UI()->SetHotItem(pID); // update friend counter if(pEntry->m_FriendState != IFriends::FRIEND_NO) { for(int j = 0; j < pEntry->m_NumClients; ++j) { if(pEntry->m_aClients[j].m_FriendState != IFriends::FRIEND_NO) { unsigned NameHash = str_quickhash(pEntry->m_aClients[j].m_aName); unsigned ClanHash = str_quickhash(pEntry->m_aClients[j].m_aClan); for(int f = 0; f < m_lFriends.size(); ++f) { if(ClanHash == m_lFriends[f].m_pFriendInfo->m_ClanHash && (!m_lFriends[f].m_pFriendInfo->m_aName[0] || NameHash == m_lFriends[f].m_pFriendInfo->m_NameHash)) { m_lFriends[f].m_NumFound++; if(m_lFriends[f].m_pFriendInfo->m_aName[0]) break; } } } } } vec3 TextBaseColor = vec3(1.0f, 1.0f, 1.0f); if(Selected || Inside) { TextBaseColor = vec3(0.0f, 0.0f, 0.0f); TextRender()->TextOutlineColor(1.0f, 1.0f, 1.0f, 0.25f); } float TextAplpha = (pEntry->m_NumPlayers == pEntry->m_MaxPlayers || pEntry->m_NumClients == pEntry->m_MaxClients) ? 0.5f : 1.0f; for(int c = 0; c < NUM_COLS; c++) { CUIRect Button; char aTemp[64]; Button.x = ms_aCols[c].m_Rect.x; Button.y = pRect->y; Button.h = pRect->h; Button.w = ms_aCols[c].m_Rect.w; int ID = ms_aCols[c].m_ID; if(ID == COL_FLAG) { CUIRect Rect = Button; CUIRect Icon; Rect.VSplitLeft(2.0f, 0, &Rect); Rect.VSplitLeft(Rect.h, &Icon, &Rect); if(pEntry->m_Flags&IServerBrowser::FLAG_PASSWORD) { Icon.Margin(2.0f, &Icon); DoIcon(IMAGE_BROWSEICONS, Selected ? SPRITE_BROWSE_LOCK_B : SPRITE_BROWSE_LOCK_A, &Icon); } Rect.VSplitLeft(2.0f, 0, &Rect); Rect.VSplitLeft(Rect.h, &Icon, &Rect); if(!(pEntry->m_Flags&IServerBrowser::FLAG_PURE)) { Icon.Margin(2.0f, &Icon); DoIcon(IMAGE_BROWSEICONS, Selected ? SPRITE_BROWSE_UNPURE_B : SPRITE_BROWSE_UNPURE_A, &Icon); } Rect.VSplitLeft(2.0f, 0, &Rect); Rect.VSplitLeft(Rect.h, &Icon, &Rect); if(pEntry->m_Favorite) { Icon.Margin(2.0f, &Icon); DoIcon(IMAGE_BROWSEICONS, Selected ? SPRITE_BROWSE_STAR_B : SPRITE_BROWSE_STAR_A, &Icon); } Rect.VSplitLeft(2.0f, 0, &Rect); Rect.VSplitLeft(Rect.h, &Icon, &Rect); if(pEntry->m_FriendState != IFriends::FRIEND_NO) { Icon.Margin(2.0f, &Icon); DoIcon(IMAGE_BROWSEICONS, Selected ? SPRITE_BROWSE_HEART_B : SPRITE_BROWSE_HEART_A, &Icon); } } else if(ID == COL_NAME) { CTextCursor Cursor; float tw = TextRender()->TextWidth(0, 12.0f, pEntry->m_aName, -1); if(tw < Button.w) TextRender()->SetCursor(&Cursor, Button.x+Button.w/2.0f-tw/2.0f, Button.y, 12.0f, TEXTFLAG_RENDER); else { TextRender()->SetCursor(&Cursor, Button.x, Button.y, 12.0f, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); Cursor.m_LineWidth = Button.w; } TextRender()->TextColor(TextBaseColor.r, TextBaseColor.g, TextBaseColor.b, TextAplpha); if(g_Config.m_BrFilterString[0] && (pEntry->m_QuickSearchHit&IServerBrowser::QUICK_SERVERNAME)) { // highlight the parts that matches const char *pStr = str_find_nocase(pEntry->m_aName, g_Config.m_BrFilterString); if(pStr) { TextRender()->TextEx(&Cursor, pEntry->m_aName, (int)(pStr-pEntry->m_aName)); TextRender()->TextColor(0.4f, 0.4f, 1.0f, TextAplpha); TextRender()->TextEx(&Cursor, pStr, str_length(g_Config.m_BrFilterString)); TextRender()->TextColor(TextBaseColor.r, TextBaseColor.g, TextBaseColor.b, TextAplpha); TextRender()->TextEx(&Cursor, pStr+str_length(g_Config.m_BrFilterString), -1); } else TextRender()->TextEx(&Cursor, pEntry->m_aName, -1); } else TextRender()->TextEx(&Cursor, pEntry->m_aName, -1); } else if(ID == COL_MAP) { CTextCursor Cursor; float tw = TextRender()->TextWidth(0, 12.0f, pEntry->m_aMap, -1); if(tw < Button.w) TextRender()->SetCursor(&Cursor, Button.x+Button.w/2.0f-tw/2.0f, Button.y, 12.0f, TEXTFLAG_RENDER); else { TextRender()->SetCursor(&Cursor, Button.x, Button.y, 12.0f, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); Cursor.m_LineWidth = Button.w; } TextRender()->TextColor(TextBaseColor.r, TextBaseColor.g, TextBaseColor.b, TextAplpha); if(g_Config.m_BrFilterString[0] && (pEntry->m_QuickSearchHit&IServerBrowser::QUICK_MAPNAME)) { // highlight the parts that matches const char *pStr = str_find_nocase(pEntry->m_aMap, g_Config.m_BrFilterString); if(pStr) { TextRender()->TextEx(&Cursor, pEntry->m_aMap, (int)(pStr-pEntry->m_aMap)); TextRender()->TextColor(0.4f, 0.4f, 1.0f, TextAplpha); TextRender()->TextEx(&Cursor, pStr, str_length(g_Config.m_BrFilterString)); TextRender()->TextColor(TextBaseColor.r, TextBaseColor.g, TextBaseColor.b, TextAplpha); TextRender()->TextEx(&Cursor, pStr+str_length(g_Config.m_BrFilterString), -1); } else TextRender()->TextEx(&Cursor, pEntry->m_aMap, -1); } else TextRender()->TextEx(&Cursor, pEntry->m_aMap, -1); } else if(ID == COL_PLAYERS) { // handle mouse over if(m_InfoMode && UI()->MouseInside(&Button)) { // overlay SetOverlay(CInfoOverlay::OVERLAY_PLAYERSINFO, UI()->MouseX(), UI()->MouseY(), pEntry); // rect RenderTools()->DrawUIRect(&Button, vec4(0.973f, 0.863f, 0.207, 0.75f), CUI::CORNER_ALL, 5.0f); } TextRender()->TextColor(TextBaseColor.r, TextBaseColor.g, TextBaseColor.b, TextAplpha); if(g_Config.m_BrFilterSpectators) str_format(aTemp, sizeof(aTemp), "%d/%d", pEntry->m_NumPlayers, pEntry->m_MaxPlayers); else str_format(aTemp, sizeof(aTemp), "%d/%d", pEntry->m_NumClients, pEntry->m_MaxClients); if(g_Config.m_BrFilterString[0] && (pEntry->m_QuickSearchHit&IServerBrowser::QUICK_PLAYER)) TextRender()->TextColor(0.4f, 0.4f, 1.0f, TextAplpha); Button.y += 2.0f; UI()->DoLabel(&Button, aTemp, 12.0f, 0); } else if(ID == COL_PING) { int Ping = pEntry->m_Latency; vec4 Color; if(Selected || Inside) { Color = vec4(TextBaseColor.r, TextBaseColor.g, TextBaseColor.b, TextAplpha); } else { vec4 StartColor; vec4 EndColor; float MixVal; if(Ping <= 125) { StartColor = vec4(0.0f, 1.0f, 0.0f, TextAplpha); EndColor = vec4(1.0f, 1.0f, 0.0f, TextAplpha); MixVal = (Ping-50.0f)/75.0f; } else { StartColor = vec4(1.0f, 1.0f, 0.0f, TextAplpha); EndColor = vec4(1.0f, 0.0f, 0.0f, TextAplpha); MixVal = (Ping-125.0f)/75.0f; } Color = mix(StartColor, EndColor, MixVal); } str_format(aTemp, sizeof(aTemp), "%d", pEntry->m_Latency); TextRender()->TextColor(Color.r, Color.g, Color.b, Color.a); Button.y += 2.0f; UI()->DoLabel(&Button, aTemp, 12.0f, 0); } else if(ID == COL_GAMETYPE) { CTextCursor Cursor; float tw = TextRender()->TextWidth(0, 12.0f, pEntry->m_aGameType, -1); if(tw < Button.w) TextRender()->SetCursor(&Cursor, Button.x+Button.w/2.0f-tw/2.0f, Button.y, 12.0f, TEXTFLAG_RENDER); else { TextRender()->SetCursor(&Cursor, Button.x, Button.y, 12.0f, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); Cursor.m_LineWidth = Button.w; } TextRender()->TextColor(TextBaseColor.r, TextBaseColor.g, TextBaseColor.b, TextAplpha); TextRender()->TextEx(&Cursor, pEntry->m_aGameType, -1); } /*else if(ID == COL_FAVORITE) { Button.HMargin(1.5f, &Button); if(DoButton_SpriteClean(IMAGE_BROWSEICONS, pEntry->m_Favorite ? SPRITE_BROWSE_STAR_A : SPRITE_BROWSE_STAR_B, &Button)) { if(!pEntry->m_Favorite) ServerBrowser()->AddFavorite(pEntry); else ServerBrowser()->RemoveFavorite(pEntry); } } else if(ID == COL_INFO) { Button.HMargin(1.5f, &Button); if(DoButton_MouseOver(IMAGE_BROWSEICONS, SPRITE_BROWSE_HEART_A, &Button)) SetOverlay(CInfoOverlay::OVERLAY_SERVERINFO, Button.x, Button.y, pEntry); }*/ } TextRender()->TextOutlineColor(0.0f, 0.0f, 0.0f, 0.3f); TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); return ReturnValue; } bool CMenus::RenderFilterHeader(CUIRect View, int FilterIndex) { CBrowserFilter *pFilter = &m_lFilters[FilterIndex]; float ButtonHeight = 20.0f; float Spacing = 3.0f; RenderTools()->DrawUIRect(&View, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f); CUIRect Button, EditButtons; View.VSplitLeft(20.0f, &Button, &View); Button.Margin(2.0f, &Button); if(DoButton_SpriteClean(IMAGE_MENUICONS, pFilter->Extended() ? SPRITE_MENU_EXPANDED : SPRITE_MENU_COLLAPSED, &Button)) pFilter->Switch(); // split buttons from label View.VSplitLeft(Spacing, 0, &View); View.VSplitRight((ButtonHeight+Spacing)*4.0f, &View, &EditButtons); View.VSplitLeft(20.0f, 0, &View); // little space View.y += 2.0f; UI()->DoLabel(&View, pFilter->Name(), ButtonHeight*ms_FontmodHeight*0.8f, -1); /*if(pFilter->Custom() <= CBrowserFilter::FILTER_ALL) UI()->DoLabel(&View, pFilter->Name(), 12.0f, -1); else { Graphics()->TextureSet(g_pData->m_aImages[IMAGE_BROWSEICONS].m_Id); Graphics()->QuadsBegin(); if(pFilter->Custom() == CBrowserFilter::FILTER_STANDARD) RenderTools()->SelectSprite(SPRITE_BROWSE_STAR_B); else if(pFilter->Custom() == CBrowserFilter::FILTER_FAVORITES) RenderTools()->SelectSprite(SPRITE_BROWSE_STAR_A); IGraphics::CQuadItem QuadItem(Label.x, View.y, 18.0f, 18.0f); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); Label.VSplitLeft(25.0f, 0, &Label); UI()->DoLabel(&Label, pFilter->Name(), 12.0f, -1); }*/ EditButtons.VSplitRight(ButtonHeight, &EditButtons, &Button); Button.Margin(2.0f, &Button); if(pFilter->Custom() == CBrowserFilter::FILTER_CUSTOM) { if(DoButton_SpriteClean(IMAGE_TOOLICONS, SPRITE_TOOL_X_A, &Button)) { RemoveFilter(FilterIndex); return true; } } else DoIcon(IMAGE_TOOLICONS, SPRITE_TOOL_X_B, &Button); EditButtons.VSplitRight(Spacing, &EditButtons, 0); EditButtons.VSplitRight(ButtonHeight, &EditButtons, &Button); Button.Margin(2.0f, &Button); if(pFilter->Custom() == CBrowserFilter::FILTER_CUSTOM) { if(DoButton_SpriteClean(IMAGE_TOOLICONS, SPRITE_TOOL_EDIT_A, &Button)) { RemoveFilter(FilterIndex); return true; } } else DoIcon(IMAGE_TOOLICONS, SPRITE_TOOL_EDIT_B, &Button); /*EditButtons.VSplitRight(Spacing, &EditButtons, 0): EditButtons.VSplitRight(ButtonHeight, &EditButtons, &Button); Button.VSplitRight(18.0f, &View, &Button); if(DoButton_SpriteCleanID(pFilter, IMAGE_BROWSEICONS, SPRITE_BROWSE_STAR_A, &Button)) // TODO: using the address of filter as ID is prolly a bad idea { static int s_EditPopupID = 0; m_SelectedFilter = FilterIndex; InvokePopupMenu(&s_EditPopupID, 0, UI()->MouseX(), UI()->MouseY(), 200.0f, 310.0f, PopupFilter); }*/ EditButtons.VSplitRight(Spacing, &EditButtons, 0); EditButtons.VSplitRight(ButtonHeight, &EditButtons, &Button); Button.Margin(2.0f, &Button); if(FilterIndex < m_lFilters.size()-1) { if(DoButton_SpriteClean(IMAGE_TOOLICONS, SPRITE_TOOL_UP_A, &Button)) Move(false, FilterIndex); } else DoIcon(IMAGE_TOOLICONS, SPRITE_TOOL_UP_B, &Button); EditButtons.VSplitRight(Spacing, &EditButtons, 0); EditButtons.VSplitRight(ButtonHeight, &EditButtons, &Button); Button.Margin(2.0f, &Button); if(FilterIndex > 0) { if(DoButton_SpriteClean(IMAGE_TOOLICONS, SPRITE_TOOL_DOWN_A, &Button)) Move(true, FilterIndex); } else DoIcon(IMAGE_TOOLICONS, SPRITE_TOOL_DOWN_B, &Button); return false; } void CMenus::RenderServerbrowserOverlay() { if(!m_InfoOverlayActive) { m_InfoOverlay.m_Reset = true; return; } int Type = m_InfoOverlay.m_Type; CUIRect View; if(Type == CInfoOverlay::OVERLAY_HEADERINFO) { CBrowserFilter *pFilter = (CBrowserFilter*)m_InfoOverlay.m_pData; // get position View.x = m_InfoOverlay.m_X-100.0f; View.y = m_InfoOverlay.m_Y; View.w = 100.0f; View.h = 30.0f; // render background RenderTools()->DrawUIRect(&View, vec4(0.25f, 0.25f, 0.25f, 1.0f), CUI::CORNER_ALL, 6.0f); View.Margin(2.0f, &View); char aBuf[128]; str_format(aBuf, sizeof(aBuf), "%s: %d", Localize("Servers"), pFilter->NumSortedServers()); UI()->DoLabel(&View, aBuf, 12.0f, 0); View.HSplitMid(0, &View); str_format(aBuf, sizeof(aBuf), "%s: %d", Localize("Players"), pFilter->NumPlayers()); UI()->DoLabel(&View, aBuf, 12.0f, 0); } else if(Type == CInfoOverlay::OVERLAY_SERVERINFO) { const CServerInfo *pInfo = (CServerInfo*)m_InfoOverlay.m_pData; // get position View.x = m_InfoOverlay.m_X-210.0f; View.y = m_InfoOverlay.m_Y; View.w = 210.0f; View.h = pInfo->m_NumClients ? 98.0f + pInfo->m_NumClients*25.0f : 72.0f; if(View.y+View.h >= 590.0f) View.y -= View.y+View.h - 590.0f; // render background RenderTools()->DrawUIRect(&View, vec4(0.25f, 0.25f, 0.25f, 1.0f), CUI::CORNER_ALL, 6.0f); RenderServerbrowserServerDetail(View, pInfo); } else if(Type == CInfoOverlay::OVERLAY_PLAYERSINFO) { const CServerInfo *pInfo = (CServerInfo*)m_InfoOverlay.m_pData; CUIRect Screen = *UI()->Screen(); float ButtonHeight = 20.0f; TextRender()->TextOutlineColor(1.0f, 1.0f, 1.0f, 0.25f); TextRender()->TextColor(0.0f, 0.0f, 0.0f, 1.0f); if(pInfo && pInfo->m_NumClients) { // get position View.x = m_InfoOverlay.m_X+25.0f; View.y = m_InfoOverlay.m_Y; View.w = 250.0f; View.h = pInfo->m_NumClients*ButtonHeight; if(View.x+View.w > Screen.w-5.0f) { View.y += 25.0f; View.x -= View.x+View.w-Screen.w+5.0f; } if(View.y+View.h >= 590.0f) View.y -= View.y+View.h - 590.0f; // render background RenderTools()->DrawUIRect(&View, vec4(1.0f, 1.0f, 1.0f, 0.75f), CUI::CORNER_ALL, 6.0f); CUIRect ServerScoreBoard = View; CTextCursor Cursor; const float FontSize = 12.0f; for (int i = 0; i < pInfo->m_NumClients; i++) { CUIRect Name, Clan, Score, Flag; ServerScoreBoard.HSplitTop(ButtonHeight, &Name, &ServerScoreBoard); if(UI()->DoButtonLogic(&pInfo->m_aClients[i], "", 0, &Name)) { if(pInfo->m_aClients[i].m_FriendState == IFriends::FRIEND_PLAYER) m_pClient->Friends()->RemoveFriend(pInfo->m_aClients[i].m_aName, pInfo->m_aClients[i].m_aClan); else m_pClient->Friends()->AddFriend(pInfo->m_aClients[i].m_aName, pInfo->m_aClients[i].m_aClan); FriendlistOnUpdate(); Client()->ServerBrowserUpdate(); } vec4 Colour = pInfo->m_aClients[i].m_FriendState == IFriends::FRIEND_NO ? vec4(1.0f, 1.0f, 1.0f, (i%2+1)*0.05f) : vec4(0.5f, 1.0f, 0.5f, 0.15f+(i%2+1)*0.05f); RenderTools()->DrawUIRect(&Name, Colour, CUI::CORNER_ALL, 4.0f); Name.VSplitLeft(5.0f, 0, &Name); Name.VSplitLeft(30.0f, &Score, &Name); Name.VSplitRight(34.0f, &Name, &Flag); Flag.HMargin(4.0f, &Flag); Name.VSplitRight(40.0f, &Name, &Clan); // score if(pInfo->m_aClients[i].m_Player) { char aTemp[16]; str_format(aTemp, sizeof(aTemp), "%d", pInfo->m_aClients[i].m_Score); TextRender()->SetCursor(&Cursor, Score.x, Score.y+(Score.h-FontSize)/4.0f, FontSize, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); Cursor.m_LineWidth = Score.w; TextRender()->TextEx(&Cursor, aTemp, -1); } // name TextRender()->SetCursor(&Cursor, Name.x, Name.y+(Name.h-FontSize)/4.0f, FontSize, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); Cursor.m_LineWidth = Name.w; const char *pName = pInfo->m_aClients[i].m_aName; if(g_Config.m_BrFilterString[0]) { // highlight the parts that matches const char *s = str_find_nocase(pName, g_Config.m_BrFilterString); if(s) { TextRender()->TextEx(&Cursor, pName, (int)(s-pName)); TextRender()->TextColor(0.4f, 0.4f, 1.0f, 1.0f); TextRender()->TextEx(&Cursor, s, str_length(g_Config.m_BrFilterString)); TextRender()->TextColor(0.0f, 0.0f, 0.0f, 1.0f); TextRender()->TextEx(&Cursor, s+str_length(g_Config.m_BrFilterString), -1); } else TextRender()->TextEx(&Cursor, pName, -1); } else TextRender()->TextEx(&Cursor, pName, -1); // clan TextRender()->SetCursor(&Cursor, Clan.x, Clan.y+(Clan.h-FontSize)/4.0f, FontSize, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); Cursor.m_LineWidth = Clan.w; const char *pClan = pInfo->m_aClients[i].m_aClan; if(g_Config.m_BrFilterString[0]) { // highlight the parts that matches const char *s = str_find_nocase(pClan, g_Config.m_BrFilterString); if(s) { TextRender()->TextEx(&Cursor, pClan, (int)(s-pClan)); TextRender()->TextColor(0.4f, 0.4f, 1.0f, 1.0f); TextRender()->TextEx(&Cursor, s, str_length(g_Config.m_BrFilterString)); TextRender()->TextColor(0.0f, 0.0f, 0.0f, 1.0f); TextRender()->TextEx(&Cursor, s+str_length(g_Config.m_BrFilterString), -1); } else TextRender()->TextEx(&Cursor, pClan, -1); } else TextRender()->TextEx(&Cursor, pClan, -1); // flag vec4 Color(1.0f, 1.0f, 1.0f, 0.75f); m_pClient->m_pCountryFlags->Render(pInfo->m_aClients[i].m_Country, &Color, Flag.x, Flag.y, Flag.w, Flag.h); } } else { View.x = m_InfoOverlay.m_X+25.0f; View.y = m_InfoOverlay.m_Y; View.w = 150.0f; View.h = ButtonHeight; if(View.x+View.w > Screen.w-5.0f) { View.y += 25.0f; View.x -= View.x+View.w-Screen.w+5.0f; } if(View.y+View.h >= 590.0f) View.y -= View.y+View.h - 590.0f; // render background RenderTools()->DrawUIRect(&View, vec4(1.0f, 1.0f, 1.0f, 0.75f), CUI::CORNER_ALL, 6.0f); View.y += 2.0f; UI()->DoLabel(&View, Localize("no players"), View.h*ms_FontmodHeight*0.8f, 0); } TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); TextRender()->TextOutlineColor(0.0f, 0.0f, 0.0f, 0.3f); } // deactivate it vec2 OverlayCenter = vec2(View.x+View.w/2.0f, View.y+View.h/2.0f); float MouseDistance = distance(m_MousePos, OverlayCenter); float PrefMouseDistance = distance(m_PrevMousePos, OverlayCenter); if(PrefMouseDistance > MouseDistance && !UI()->MouseInside(&View)) { m_InfoOverlayActive = false; m_InfoOverlay.m_Reset = true; } } void CMenus::RenderServerbrowserServerList(CUIRect View) { CUIRect Headers, Status, InfoButton; float SpacingH = 2.0f; float ButtonHeight = 20.0f; // background RenderTools()->DrawUIRect(&View, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f); View.HSplitTop(ms_ListheaderHeight, &Headers, &View); View.HSplitBottom(ButtonHeight*3.0f+SpacingH*2.0f, &View, &Status); Headers.VSplitRight(ms_ListheaderHeight, &Headers, &InfoButton); // split for info button // do layout for(int i = 0; i < NUM_COLS; i++) { if(ms_aCols[i].m_Direction == -1) { Headers.VSplitLeft(ms_aCols[i].m_Width, &ms_aCols[i].m_Rect, &Headers); if(i+1 < NUM_COLS) { //Cols[i].flags |= SPACER; Headers.VSplitLeft(2, &ms_aCols[i].m_Spacer, &Headers); } } } for(int i = NUM_COLS-1; i >= 0; i--) { if(ms_aCols[i].m_Direction == 1) { Headers.VSplitRight(ms_aCols[i].m_Width, &Headers, &ms_aCols[i].m_Rect); Headers.VSplitRight(2, &Headers, &ms_aCols[i].m_Spacer); } } for(int i = 0; i < NUM_COLS; i++) { if(ms_aCols[i].m_Direction == 0) ms_aCols[i].m_Rect = Headers; } // do headers for(int i = 0; i < NUM_COLS; i++) { if(i == COL_FLAG) { CUIRect Rect = ms_aCols[i].m_Rect; CUIRect Icon; Rect.VSplitLeft(2.0f, 0, &Rect); Rect.VSplitLeft(Rect.h, &Icon, &Rect); Icon.Margin(2.0f, &Icon); DoIcon(IMAGE_BROWSEICONS, SPRITE_BROWSE_LOCK_A, &Icon); Rect.VSplitLeft(2.0f, 0, &Rect); Rect.VSplitLeft(Rect.h, &Icon, &Rect); Icon.Margin(2.0f, &Icon); DoIcon(IMAGE_BROWSEICONS, SPRITE_BROWSE_UNPURE_A, &Icon); Rect.VSplitLeft(2.0f, 0, &Rect); Rect.VSplitLeft(Rect.h, &Icon, &Rect); Icon.Margin(2.0f, &Icon); DoIcon(IMAGE_BROWSEICONS, SPRITE_BROWSE_STAR_A, &Icon); Rect.VSplitLeft(2.0f, 0, &Rect); Rect.VSplitLeft(Rect.h, &Icon, &Rect); Icon.Margin(2.0f, &Icon); DoIcon(IMAGE_BROWSEICONS, SPRITE_BROWSE_HEART_A, &Icon); } else if(DoButton_GridHeader(ms_aCols[i].m_Caption, ms_aCols[i].m_Caption, g_Config.m_BrSort == ms_aCols[i].m_Sort, &ms_aCols[i].m_Rect)) { if(ms_aCols[i].m_Sort != -1) { if(g_Config.m_BrSort == ms_aCols[i].m_Sort) g_Config.m_BrSortOrder ^= 1; else g_Config.m_BrSortOrder = 0; g_Config.m_BrSort = ms_aCols[i].m_Sort; } } } // do info icon at the end of the list header { InfoButton.Margin(2.0f, &InfoButton); static int s_InfoButton = 0; if(DoButton_SpriteCleanID(&s_InfoButton, IMAGE_INFOICONS, ((m_InfoMode && !UI()->MouseInside(&InfoButton)) || (!m_InfoMode && UI()->MouseInside(&InfoButton))) ? SPRITE_INFO_B : SPRITE_INFO_A, &InfoButton, false)) { m_InfoMode ^= 1; } } // split scrollbar from view CUIRect Scroll; View.VSplitRight(20.0f, &View, &Scroll); // scrollbar background RenderTools()->DrawUIRect(&Scroll, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f); // list background RenderTools()->DrawUIRect(&View, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f); { int Column = COL_PING; switch(g_Config.m_BrSort) { case IServerBrowser::SORT_NAME: Column = COL_NAME; break; case IServerBrowser::SORT_GAMETYPE: Column = COL_GAMETYPE; break; case IServerBrowser::SORT_MAP: Column = COL_MAP; break; case IServerBrowser::SORT_NUMPLAYERS: Column = COL_PLAYERS; break; } CUIRect Rect = View; Rect.x = CMenus::ms_aCols[Column].m_Rect.x; Rect.w = CMenus::ms_aCols[Column].m_Rect.w; RenderTools()->DrawUIRect(&Rect, vec4(0.0f, 0.0f, 0.0f, 0.05f), CUI::CORNER_ALL, 5.0f); } // display important messages in the middle of the screen so no // users misses it { CUIRect MsgBox = View; MsgBox.y += View.h/3; if(m_ActivePage == PAGE_INTERNET && ServerBrowser()->IsRefreshingMasters()) UI()->DoLabelScaled(&MsgBox, Localize("Refreshing master servers"), 16.0f, 0); else if(!ServerBrowser()->NumServers()) UI()->DoLabelScaled(&MsgBox, Localize("No servers found"), 16.0f, 0); /*else if(ServerBrowser()->NumServers() && !NumServers) UI()->DoLabelScaled(&MsgBox, Localize("No servers match your filter criteria"), 16.0f, 0);*/ } // count all the servers int NumServers = 0; for(int i = 0; i < m_lFilters.size(); i++) if(m_lFilters[i].Extended()) NumServers += m_lFilters[i].NumSortedServers(); int NumFilters = m_lFilters.size(); float ListHeight = (NumServers+(NumFilters-1)) * ms_aCols[0].m_Rect.h + NumFilters * 20.0f; //int Num = (int)((ListHeight-View.h)/ms_aCols[0].m_Rect.h))+1; //int Num = (int)(View.h/ms_aCols[0].m_Rect.h) + 1; static int s_ScrollBar = 0; static float s_ScrollValue = 0; Scroll.HMargin(5.0f, &Scroll); s_ScrollValue = DoScrollbarV(&s_ScrollBar, &Scroll, s_ScrollValue); int ScrollNum = (int)((ListHeight-View.h)/ms_aCols[0].m_Rect.h)+1; if(ScrollNum > 0) { if(m_ScrollOffset) { s_ScrollValue = (float)(m_ScrollOffset)/ScrollNum; m_ScrollOffset = 0; } if(Input()->KeyPresses(KEY_MOUSE_WHEEL_UP) && UI()->MouseInside(&View)) s_ScrollValue -= 3.0f/ScrollNum; if(Input()->KeyPresses(KEY_MOUSE_WHEEL_DOWN) && UI()->MouseInside(&View)) s_ScrollValue += 3.0f/ScrollNum; } else ScrollNum = 0; int SelectedFilter = m_SelectedServer.m_Filter; int SelectedIndex = m_SelectedServer.m_Index; if(SelectedFilter > -1) { for(int i = 0; i < m_NumInputEvents; i++) { int NewIndex = -1; int NewFilter = SelectedFilter; if(m_aInputEvents[i].m_Flags&IInput::FLAG_PRESS) { if(m_aInputEvents[i].m_Key == KEY_DOWN) { NewIndex = SelectedIndex + 1; if(NewIndex >= m_lFilters[SelectedFilter].NumSortedServers()) { // try to move to next filter for(int j = SelectedFilter+1; j < m_lFilters.size(); j++) { CBrowserFilter *pFilter = &m_lFilters[j]; if(pFilter->Extended() && pFilter->NumSortedServers()) { NewFilter = j; NewIndex = 0; break; } } } } else if(m_aInputEvents[i].m_Key == KEY_UP) { NewIndex = SelectedIndex - 1; if(NewIndex < 0) { // try to move to prev filter for(int j = SelectedFilter-1; j >= 0; j--) { CBrowserFilter *pFilter = &m_lFilters[j]; if(pFilter->Extended() && pFilter->NumSortedServers()) { NewFilter = j; NewIndex = pFilter->NumSortedServers()-1; break; } } } } } if(NewIndex > -1 && NewIndex < m_lFilters[NewFilter].NumSortedServers()) { // get index depending on all filters int TotalIndex = 0; int Filter = 0; while(Filter != NewFilter) { CBrowserFilter *pFilter = &m_lFilters[Filter]; if(pFilter->Extended()) TotalIndex += m_lFilters[Filter].NumSortedServers(); Filter++; } TotalIndex += NewIndex+1; //scroll float IndexY = View.y - s_ScrollValue*ScrollNum*ms_aCols[0].m_Rect.h + TotalIndex*ms_aCols[0].m_Rect.h + Filter*ms_aCols[0].m_Rect.h + Filter*20.0f; int Scroll = View.y > IndexY ? -1 : View.y+View.h < IndexY+ms_aCols[0].m_Rect.h ? 1 : 0; if(Scroll) { if(Scroll < 0) { int NumScrolls = (View.y-IndexY+ms_aCols[0].m_Rect.h-1.0f)/ms_aCols[0].m_Rect.h; s_ScrollValue -= (1.0f/ScrollNum)*NumScrolls; } else { int NumScrolls = (IndexY+ms_aCols[0].m_Rect.h-(View.y+View.h)+ms_aCols[0].m_Rect.h-1.0f)/ms_aCols[0].m_Rect.h; s_ScrollValue += (1.0f/ScrollNum)*NumScrolls; } } m_SelectedServer.m_Filter = NewFilter; m_SelectedServer.m_Index = NewIndex; const CServerInfo *pItem = ServerBrowser()->SortedGet(NewFilter, NewIndex); str_copy(g_Config.m_UiServerAddress, pItem->m_aAddress, sizeof(g_Config.m_UiServerAddress)); } } } if(s_ScrollValue < 0) s_ScrollValue = 0; if(s_ScrollValue > 1) s_ScrollValue = 1; // set clipping UI()->ClipEnable(&View); CUIRect OriginalView = View; View.y -= s_ScrollValue*ScrollNum*ms_aCols[0].m_Rect.h; int NumPlayers = ServerBrowser()->NumPlayers(); // reset friend counter for(int i = 0; i < m_lFriends.size(); m_lFriends[i++].m_NumFound = 0); for(int s = 0; s < m_lFilters.size(); s++) { CBrowserFilter *pFilter = &m_lFilters[s]; // dont do anything if the filter is empty if(!pFilter->NumSortedServers()) continue; // filter header CUIRect Row; View.HSplitTop(20.0f, &Row, &View); // render header bool Deleted = RenderFilterHeader(Row, s); if(Deleted && s >= m_lFilters.size()) break; if(pFilter->Extended()) { for (int i = 0; i < pFilter->NumSortedServers(); i++) { int ItemIndex = i; const CServerInfo *pItem = pFilter->SortedGet(ItemIndex); CUIRect SelectHitBox; View.HSplitTop(ms_ListheaderHeight, &Row, &View); SelectHitBox = Row; // select server if(m_SelectedServer.m_Filter == -1 || m_SelectedServer.m_Filter == s) { if(!str_comp(pItem->m_aAddress, g_Config.m_UiServerAddress)) { m_SelectedServer.m_Filter = s; m_SelectedServer.m_Index = ItemIndex; } } // make sure that only those in view can be selected if(Row.y+Row.h > OriginalView.y && Row.y < OriginalView.y+OriginalView.h) { if(m_SelectedServer.m_Filter == s && m_SelectedServer.m_Index == i) { CUIRect r = Row; RenderTools()->DrawUIRect(&r, vec4(1.0f, 1.0f, 1.0f, 0.5f), CUI::CORNER_ALL, 4.0f); } } else { // reset active item, if not visible if(UI()->ActiveItem() == pItem) UI()->SetActiveItem(0); // don't render invisible items continue; } if(DoBrowserEntry(pFilter->ID(ItemIndex), &Row, pItem, m_SelectedServer.m_Filter == s && m_SelectedServer.m_Index == i)) { m_SelectedServer.m_Filter = s; m_SelectedServer.m_Index = i; str_copy(g_Config.m_UiServerAddress, pItem->m_aAddress, sizeof(g_Config.m_UiServerAddress)); if(Input()->MouseDoubleClick()) Client()->Connect(g_Config.m_UiServerAddress); } } } if(s < m_lFilters.size()-1) View.HSplitTop(ms_ListheaderHeight, &Row, &View); } UI()->ClipDisable(); // bottom float SpacingW = 3.0f; float ButtonWidth = (Status.w/6.0f)-(SpacingW*5.0)/6.0f; // cut view CUIRect Left, Label, EditBox, Button; Status.VSplitLeft(ButtonWidth*3.0f+SpacingH*2.0f, &Left, &Status); // render quick search and host address Left.HSplitTop(((ButtonHeight*3.0f+SpacingH*2.0f)-(ButtonHeight*2.0f+SpacingH))/2.0f, 0, &Left); Left.HSplitTop(ButtonHeight, &Label, &Left); Label.VSplitRight(ButtonWidth*2.0f+SpacingH, &Label, &EditBox); Label.y += 2.0f; UI()->DoLabel(&Label, Localize("Search:"), ButtonHeight*ms_FontmodHeight*0.8f, 0); EditBox.VSplitRight(EditBox.h, &EditBox, &Button); static float s_ClearOffset = 0.0f; if(DoEditBox(&g_Config.m_BrFilterString, &EditBox, g_Config.m_BrFilterString, sizeof(g_Config.m_BrFilterString), ButtonHeight*ms_FontmodHeight*0.8f, &s_ClearOffset, false, CUI::CORNER_ALL)) Client()->ServerBrowserUpdate(); // clear button { static int s_ClearButton = 0; if(DoButton_SpriteID(&s_ClearButton, IMAGE_TOOLICONS, SPRITE_TOOL_X_A, &Button, CUI::CORNER_ALL, 5.0f, false)) { g_Config.m_BrFilterString[0] = 0; UI()->SetActiveItem(&g_Config.m_BrFilterString); Client()->ServerBrowserUpdate(); } } Left.HSplitTop(SpacingH, 0, &Left); Left.HSplitTop(ButtonHeight, &Label, 0); Label.VSplitRight(ButtonWidth*2.0f+SpacingH, &Label, &EditBox); Label.y += 2.0f; UI()->DoLabel(&Label, Localize("Host address:"), ButtonHeight*ms_FontmodHeight*0.8f, 0); static float s_AddressOffset = 0.0f; DoEditBox(&g_Config.m_UiServerAddress, &EditBox, g_Config.m_UiServerAddress, sizeof(g_Config.m_UiServerAddress), ButtonHeight*ms_FontmodHeight*0.8f, &s_AddressOffset, false, CUI::CORNER_ALL); // render status Status.HSplitTop(ButtonHeight+SpacingH, 0, &Status); Status.HSplitTop(ButtonHeight, &Status, 0); char aBuf[128]; if(ServerBrowser()->IsRefreshing()) str_format(aBuf, sizeof(aBuf), Localize("%d%% loaded"), ServerBrowser()->LoadingProgression()); else str_format(aBuf, sizeof(aBuf), Localize("%d servers, %d players"), ServerBrowser()->NumServers(), NumPlayers); Status.y += 2.0f; UI()->DoLabel(&Status, aBuf, 14.0f, 0); } void CMenus::RenderServerbrowserFilters(CUIRect View) { CUIRect ServerFilter = View, FilterHeader; const float FontSize = 12.0f; ServerFilter.HSplitBottom(42.5f, &ServerFilter, 0); // server filter ServerFilter.HSplitTop(ms_ListheaderHeight, &FilterHeader, &ServerFilter); RenderTools()->DrawUIRect(&FilterHeader, vec4(1,1,1,0.25f), CUI::CORNER_T, 4.0f); RenderTools()->DrawUIRect(&ServerFilter, vec4(0,0,0,0.15f), CUI::CORNER_B, 4.0f); UI()->DoLabelScaled(&FilterHeader, Localize("Server filter"), FontSize+2.0f, 0); CUIRect Button; ServerFilter.VSplitLeft(5.0f, 0, &ServerFilter); ServerFilter.Margin(3.0f, &ServerFilter); ServerFilter.VMargin(5.0f, &ServerFilter); ServerFilter.HSplitTop(20.0f, &Button, &ServerFilter); static int s_BrFilterEmpty = 0; if(DoButton_CheckBox(&s_BrFilterEmpty, Localize("Has people playing"), g_Config.m_BrFilterEmpty, &Button)) g_Config.m_BrFilterEmpty ^= 1; ServerFilter.HSplitTop(20.0f, &Button, &ServerFilter); static int s_BrFilterSpectators = 0; if(DoButton_CheckBox(&s_BrFilterSpectators, Localize("Count players only"), g_Config.m_BrFilterSpectators, &Button)) g_Config.m_BrFilterSpectators ^= 1; ServerFilter.HSplitTop(20.0f, &Button, &ServerFilter); static int s_BrFilterFull = 0; if(DoButton_CheckBox(&s_BrFilterFull, Localize("Server not full"), g_Config.m_BrFilterFull, &Button)) g_Config.m_BrFilterFull ^= 1; ServerFilter.HSplitTop(20.0f, &Button, &ServerFilter); static int s_BrFilterFriends = 0; if(DoButton_CheckBox(&s_BrFilterFriends, Localize("Show friends only"), g_Config.m_BrFilterFriends, &Button)) g_Config.m_BrFilterFriends ^= 1; ServerFilter.HSplitTop(20.0f, &Button, &ServerFilter); static int s_BrFilterPw = 0; if(DoButton_CheckBox(&s_BrFilterPw, Localize("No password"), g_Config.m_BrFilterPw, &Button)) g_Config.m_BrFilterPw ^= 1; ServerFilter.HSplitTop(20.0f, &Button, &ServerFilter); static int s_BrFilterCompatversion = 0; if(DoButton_CheckBox(&s_BrFilterCompatversion, Localize("Compatible version"), g_Config.m_BrFilterCompatversion, &Button)) g_Config.m_BrFilterCompatversion ^= 1; ServerFilter.HSplitTop(20.0f, &Button, &ServerFilter); static int s_BrFilterPure = 0; if(DoButton_CheckBox(&s_BrFilterPure, Localize("Standard gametype"), g_Config.m_BrFilterPure, &Button)) g_Config.m_BrFilterPure ^= 1; ServerFilter.HSplitTop(20.0f, &Button, &ServerFilter); static int s_BrFilterPureMap = 0; if(DoButton_CheckBox(&s_BrFilterPureMap, Localize("Standard map"), g_Config.m_BrFilterPureMap, &Button)) g_Config.m_BrFilterPureMap ^= 1; ServerFilter.HSplitTop(20.0f, &Button, &ServerFilter); static int s_BrFilterGametypeStrict = 0; if(DoButton_CheckBox(&s_BrFilterGametypeStrict, Localize("Strict gametype filter"), g_Config.m_BrFilterGametypeStrict, &Button)) g_Config.m_BrFilterGametypeStrict ^= 1; ServerFilter.HSplitTop(5.0f, 0, &ServerFilter); ServerFilter.HSplitTop(19.0f, &Button, &ServerFilter); UI()->DoLabelScaled(&Button, Localize("Game types:"), FontSize, -1); Button.VSplitRight(60.0f, 0, &Button); ServerFilter.HSplitTop(3.0f, 0, &ServerFilter); static float Offset = 0.0f; if(DoEditBox(&g_Config.m_BrFilterGametype, &Button, g_Config.m_BrFilterGametype, sizeof(g_Config.m_BrFilterGametype), FontSize, &Offset)) Client()->ServerBrowserUpdate(); { ServerFilter.HSplitTop(19.0f, &Button, &ServerFilter); CUIRect EditBox; Button.VSplitRight(60.0f, &Button, &EditBox); UI()->DoLabelScaled(&Button, Localize("Maximum ping:"), FontSize, -1); char aBuf[5]; str_format(aBuf, sizeof(aBuf), "%d", g_Config.m_BrFilterPing); static float Offset = 0.0f; DoEditBox(&g_Config.m_BrFilterPing, &EditBox, aBuf, sizeof(aBuf), FontSize, &Offset); g_Config.m_BrFilterPing = clamp(str_toint(aBuf), 0, 999); } // server address ServerFilter.HSplitTop(3.0f, 0, &ServerFilter); ServerFilter.HSplitTop(19.0f, &Button, &ServerFilter); UI()->DoLabelScaled(&Button, Localize("Server address:"), FontSize, -1); Button.VSplitRight(60.0f, 0, &Button); static float OffsetAddr = 0.0f; if(DoEditBox(&g_Config.m_BrFilterServerAddress, &Button, g_Config.m_BrFilterServerAddress, sizeof(g_Config.m_BrFilterServerAddress), FontSize, &OffsetAddr)) Client()->ServerBrowserUpdate(); // player country { CUIRect Rect; ServerFilter.HSplitTop(3.0f, 0, &ServerFilter); ServerFilter.HSplitTop(26.0f, &Button, &ServerFilter); Button.VSplitRight(60.0f, &Button, &Rect); Button.HMargin(3.0f, &Button); static int s_BrFilterCountry = 0; if(DoButton_CheckBox(&s_BrFilterCountry, Localize("Player country:"), g_Config.m_BrFilterCountry, &Button)) g_Config.m_BrFilterCountry ^= 1; float OldWidth = Rect.w; Rect.w = Rect.h*2; Rect.x += (OldWidth-Rect.w)/2.0f; vec4 Color(1.0f, 1.0f, 1.0f, g_Config.m_BrFilterCountry?1.0f: 0.5f); m_pClient->m_pCountryFlags->Render(g_Config.m_BrFilterCountryIndex, &Color, Rect.x, Rect.y, Rect.w, Rect.h); if(g_Config.m_BrFilterCountry && UI()->DoButtonLogic(&g_Config.m_BrFilterCountryIndex, "", 0, &Rect)) m_Popup = POPUP_COUNTRY; } ServerFilter.HSplitBottom(5.0f, &ServerFilter, 0); ServerFilter.HSplitBottom(ms_ButtonHeight-2.0f, &ServerFilter, &Button); static int s_ClearButton = 0; if(DoButton_Menu(&s_ClearButton, Localize("Reset filter"), 0, &Button)) { g_Config.m_BrFilterString[0] = 0; g_Config.m_BrFilterFull = 0; g_Config.m_BrFilterEmpty = 0; g_Config.m_BrFilterSpectators = 0; g_Config.m_BrFilterFriends = 0; g_Config.m_BrFilterCountry = 0; g_Config.m_BrFilterCountryIndex = -1; g_Config.m_BrFilterPw = 0; g_Config.m_BrFilterPing = 999; g_Config.m_BrFilterGametype[0] = 0; g_Config.m_BrFilterGametypeStrict = 0; g_Config.m_BrFilterServerAddress[0] = 0; g_Config.m_BrFilterPure = 1; g_Config.m_BrFilterPureMap = 1; g_Config.m_BrFilterCompatversion = 1; Client()->ServerBrowserUpdate(); } } void CMenus::RenderServerbrowserServerDetail(CUIRect View, const CServerInfo *pInfo) { View.Margin(2.0f, &View); CUIRect ServerDetails = View; CUIRect ServerScoreBoard, ServerHeader; // split off a piece to use for scoreboard ServerDetails.HSplitTop(70.0f, &ServerDetails, &ServerScoreBoard); ServerDetails.HSplitBottom(2.5f, &ServerDetails, 0x0); // server details CTextCursor Cursor; const float FontSize = 12.0f; ServerDetails.HSplitTop(ms_ListheaderHeight, &ServerHeader, &ServerDetails); RenderTools()->DrawUIRect(&ServerHeader, vec4(1,1,1,0.25f), CUI::CORNER_T, 4.0f); RenderTools()->DrawUIRect(&ServerDetails, vec4(0,0,0,0.15f), CUI::CORNER_B, 4.0f); UI()->DoLabelScaled(&ServerHeader, Localize("Server details"), FontSize+2.0f, 0); if(pInfo) { ServerDetails.VSplitLeft(5.0f, 0, &ServerDetails); ServerDetails.Margin(3.0f, &ServerDetails); CUIRect Row; static CLocConstString s_aLabels[] = { "Version", // Localize - these strings are localized within CLocConstString "Game type", "Ping"}; CUIRect LeftColumn; CUIRect RightColumn; ServerDetails.VSplitLeft(5.0f, 0x0, &ServerDetails); ServerDetails.VSplitLeft(80.0f, &LeftColumn, &RightColumn); for (unsigned int i = 0; i < sizeof(s_aLabels) / sizeof(s_aLabels[0]); i++) { LeftColumn.HSplitTop(15.0f, &Row, &LeftColumn); UI()->DoLabelScaled(&Row, s_aLabels[i], FontSize, -1); } RightColumn.HSplitTop(15.0f, &Row, &RightColumn); TextRender()->SetCursor(&Cursor, Row.x, Row.y, FontSize, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); Cursor.m_LineWidth = Row.w; TextRender()->TextEx(&Cursor, pInfo->m_aVersion, -1); RightColumn.HSplitTop(15.0f, &Row, &RightColumn); TextRender()->SetCursor(&Cursor, Row.x, Row.y, FontSize, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); Cursor.m_LineWidth = Row.w; TextRender()->TextEx(&Cursor, pInfo->m_aGameType, -1); char aTemp[16]; str_format(aTemp, sizeof(aTemp), "%d", pInfo->m_Latency); RightColumn.HSplitTop(15.0f, &Row, &RightColumn); TextRender()->SetCursor(&Cursor, Row.x, Row.y, FontSize, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); Cursor.m_LineWidth = Row.w; TextRender()->TextEx(&Cursor, aTemp, -1); } if(pInfo && pInfo->m_NumClients) { // server scoreboard ServerScoreBoard.HSplitTop(ms_ListheaderHeight, &ServerHeader, &ServerScoreBoard); RenderTools()->DrawUIRect(&ServerHeader, vec4(1,1,1,0.25f), CUI::CORNER_T, 4.0f); RenderTools()->DrawUIRect(&ServerScoreBoard, vec4(0,0,0,0.15f), CUI::CORNER_B, 4.0f); UI()->DoLabelScaled(&ServerHeader, Localize("Scoreboard"), FontSize+2.0f, 0); ServerScoreBoard.Margin(3.0f, &ServerScoreBoard); for (int i = 0; i < pInfo->m_NumClients; i++) { CUIRect Name, Clan, Score, Flag; ServerScoreBoard.HSplitTop(25.0f, &Name, &ServerScoreBoard); if(UI()->DoButtonLogic(&pInfo->m_aClients[i], "", 0, &Name)) { if(pInfo->m_aClients[i].m_FriendState == IFriends::FRIEND_PLAYER) m_pClient->Friends()->RemoveFriend(pInfo->m_aClients[i].m_aName, pInfo->m_aClients[i].m_aClan); else m_pClient->Friends()->AddFriend(pInfo->m_aClients[i].m_aName, pInfo->m_aClients[i].m_aClan); FriendlistOnUpdate(); Client()->ServerBrowserUpdate(); } vec4 Colour = pInfo->m_aClients[i].m_FriendState == IFriends::FRIEND_NO ? vec4(1.0f, 1.0f, 1.0f, (i%2+1)*0.05f) : vec4(0.5f, 1.0f, 0.5f, 0.15f+(i%2+1)*0.05f); RenderTools()->DrawUIRect(&Name, Colour, CUI::CORNER_ALL, 4.0f); Name.VSplitLeft(5.0f, 0, &Name); Name.VSplitLeft(30.0f, &Score, &Name); Name.VSplitRight(34.0f, &Name, &Flag); Flag.HMargin(4.0f, &Flag); Name.HSplitTop(11.0f, &Name, &Clan); // score if(pInfo->m_aClients[i].m_Player) { char aTemp[16]; str_format(aTemp, sizeof(aTemp), "%d", pInfo->m_aClients[i].m_Score); TextRender()->SetCursor(&Cursor, Score.x, Score.y+(Score.h-FontSize)/4.0f, FontSize, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); Cursor.m_LineWidth = Score.w; TextRender()->TextEx(&Cursor, aTemp, -1); } // name TextRender()->SetCursor(&Cursor, Name.x, Name.y, FontSize-2, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); Cursor.m_LineWidth = Name.w; const char *pName = pInfo->m_aClients[i].m_aName; if(g_Config.m_BrFilterString[0]) { // highlight the parts that matches const char *s = str_find_nocase(pName, g_Config.m_BrFilterString); if(s) { TextRender()->TextEx(&Cursor, pName, (int)(s-pName)); TextRender()->TextColor(0.4f, 0.4f, 1.0f, 1.0f); TextRender()->TextEx(&Cursor, s, str_length(g_Config.m_BrFilterString)); TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); TextRender()->TextEx(&Cursor, s+str_length(g_Config.m_BrFilterString), -1); } else TextRender()->TextEx(&Cursor, pName, -1); } else TextRender()->TextEx(&Cursor, pName, -1); // clan TextRender()->SetCursor(&Cursor, Clan.x, Clan.y, FontSize-2, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); Cursor.m_LineWidth = Clan.w; const char *pClan = pInfo->m_aClients[i].m_aClan; if(g_Config.m_BrFilterString[0]) { // highlight the parts that matches const char *s = str_find_nocase(pClan, g_Config.m_BrFilterString); if(s) { TextRender()->TextEx(&Cursor, pClan, (int)(s-pClan)); TextRender()->TextColor(0.4f, 0.4f, 1.0f, 1.0f); TextRender()->TextEx(&Cursor, s, str_length(g_Config.m_BrFilterString)); TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); TextRender()->TextEx(&Cursor, s+str_length(g_Config.m_BrFilterString), -1); } else TextRender()->TextEx(&Cursor, pClan, -1); } else TextRender()->TextEx(&Cursor, pClan, -1); // flag vec4 Color(1.0f, 1.0f, 1.0f, 0.5f); m_pClient->m_pCountryFlags->Render(pInfo->m_aClients[i].m_Country, &Color, Flag.x, Flag.y, Flag.w, Flag.h); } } } void CMenus::FriendlistOnUpdate() { m_lFriends.clear(); for(int i = 0; i < m_pClient->Friends()->NumFriends(); ++i) { CFriendItem Item; Item.m_pFriendInfo = m_pClient->Friends()->GetFriend(i); Item.m_NumFound = 0; m_lFriends.add_unsorted(Item); } m_lFriends.sort_range(); } void CMenus::RenderServerbrowserFriends(CUIRect View) { static int s_Inited = 0; if(!s_Inited) { FriendlistOnUpdate(); s_Inited = 1; } CUIRect ServerFriends = View, FilterHeader; const float FontSize = 10.0f; // header ServerFriends.HSplitTop(ms_ListheaderHeight, &FilterHeader, &ServerFriends); RenderTools()->DrawUIRect(&FilterHeader, vec4(1,1,1,0.25f), CUI::CORNER_T, 4.0f); RenderTools()->DrawUIRect(&ServerFriends, vec4(0,0,0,0.15f), 0, 4.0f); UI()->DoLabelScaled(&FilterHeader, Localize("Friends"), FontSize+4.0f, 0); CUIRect Button, List; ServerFriends.Margin(3.0f, &ServerFriends); ServerFriends.VMargin(3.0f, &ServerFriends); ServerFriends.HSplitBottom(100.0f, &List, &ServerFriends); // friends list(remove friend) static float s_ScrollValue = 0; static int s_FriendsList = 0; if(m_FriendlistSelectedIndex >= m_lFriends.size()) m_FriendlistSelectedIndex = m_lFriends.size()-1; UiDoListboxHeader(&List, "", 20.0f, 2.0f); UiDoListboxStart(&s_FriendsList, 30.0f, "", m_lFriends.size(), 1, m_FriendlistSelectedIndex, s_ScrollValue); m_lFriends.sort_range(); for(int i = 0; i < m_lFriends.size(); ++i) { CListboxItem Item = UiDoListboxNextItem(&m_lFriends[i]); if(Item.m_Visible) { Item.m_Rect.Margin(1.5f, &Item.m_Rect); CUIRect OnState; Item.m_Rect.VSplitRight(30.0f, &Item.m_Rect, &OnState); RenderTools()->DrawUIRect(&Item.m_Rect, vec4(1.0f, 1.0f, 1.0f, 0.1f), CUI::CORNER_L, 4.0f); Item.m_Rect.VMargin(2.5f, &Item.m_Rect); Item.m_Rect.HSplitTop(12.0f, &Item.m_Rect, &Button); UI()->DoLabelScaled(&Item.m_Rect, m_lFriends[i].m_pFriendInfo->m_aName, FontSize, -1); UI()->DoLabelScaled(&Button, m_lFriends[i].m_pFriendInfo->m_aClan, FontSize, -1); RenderTools()->DrawUIRect(&OnState, m_lFriends[i].m_NumFound ? vec4(0.0f, 1.0f, 0.0f, 0.25f) : vec4(1.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_R, 4.0f); OnState.HMargin((OnState.h-FontSize)/3, &OnState); OnState.VMargin(5.0f, &OnState); char aBuf[64]; str_format(aBuf, sizeof(aBuf), "%i", m_lFriends[i].m_NumFound); UI()->DoLabelScaled(&OnState, aBuf, FontSize+2, 1); } } bool Activated = false; m_FriendlistSelectedIndex = UiDoListboxEnd(&s_ScrollValue, &Activated); // activate found server with friend if(Activated && !m_EnterPressed && m_lFriends[m_FriendlistSelectedIndex].m_NumFound) { bool Found = false; for(int s = 0; s < m_lFilters.size(); s++) { CBrowserFilter *pFilter = &m_lFilters[s]; int NumServers = pFilter->NumSortedServers(); for (int i = 0; i < NumServers && !Found; i++) { int ItemIndex = m_SelectedServer.m_Filter != -1 ? (m_SelectedServer.m_Index+i+1)%NumServers : i; const CServerInfo *pItem = pFilter->SortedGet(ItemIndex); if(pItem->m_FriendState != IFriends::FRIEND_NO) { for(int j = 0; j < pItem->m_NumClients && !Found; ++j) { if(pItem->m_aClients[j].m_FriendState != IFriends::FRIEND_NO && str_quickhash(pItem->m_aClients[j].m_aClan) == m_lFriends[m_FriendlistSelectedIndex].m_pFriendInfo->m_ClanHash && (!m_lFriends[m_FriendlistSelectedIndex].m_pFriendInfo->m_aName[0] || str_quickhash(pItem->m_aClients[j].m_aName) == m_lFriends[m_FriendlistSelectedIndex].m_pFriendInfo->m_NameHash)) { str_copy(g_Config.m_UiServerAddress, pItem->m_aAddress, sizeof(g_Config.m_UiServerAddress)); m_ScrollOffset = ItemIndex; m_SelectedServer.m_Filter = s; m_SelectedServer.m_Index = ItemIndex; Found = true; } } } } } } ServerFriends.HSplitTop(2.5f, 0, &ServerFriends); ServerFriends.HSplitTop(20.0f, &Button, &ServerFriends); if(m_FriendlistSelectedIndex != -1) { static int s_RemoveButton = 0; if(DoButton_Menu(&s_RemoveButton, Localize("Remove"), 0, &Button)) m_Popup = POPUP_REMOVE_FRIEND; } // add friend if(m_pClient->Friends()->NumFriends() < IFriends::MAX_FRIENDS) { ServerFriends.HSplitTop(10.0f, 0, &ServerFriends); ServerFriends.HSplitTop(19.0f, &Button, &ServerFriends); char aBuf[64]; str_format(aBuf, sizeof(aBuf), "%s:", Localize("Name")); UI()->DoLabelScaled(&Button, aBuf, FontSize, -1); Button.VSplitLeft(80.0f, 0, &Button); static char s_aName[MAX_NAME_LENGTH] = {0}; static float s_OffsetName = 0.0f; DoEditBox(&s_aName, &Button, s_aName, sizeof(s_aName), FontSize, &s_OffsetName); ServerFriends.HSplitTop(3.0f, 0, &ServerFriends); ServerFriends.HSplitTop(19.0f, &Button, &ServerFriends); str_format(aBuf, sizeof(aBuf), "%s:", Localize("Clan")); UI()->DoLabelScaled(&Button, aBuf, FontSize, -1); Button.VSplitLeft(80.0f, 0, &Button); static char s_aClan[MAX_CLAN_LENGTH] = {0}; static float s_OffsetClan = 0.0f; DoEditBox(&s_aClan, &Button, s_aClan, sizeof(s_aClan), FontSize, &s_OffsetClan); ServerFriends.HSplitTop(3.0f, 0, &ServerFriends); ServerFriends.HSplitTop(20.0f, &Button, &ServerFriends); static int s_AddButton = 0; if(DoButton_Menu(&s_AddButton, Localize("Add Friend"), 0, &Button)) { m_pClient->Friends()->AddFriend(s_aName, s_aClan); FriendlistOnUpdate(); Client()->ServerBrowserUpdate(); } } } void CMenus::RenderServerbrowserBottomBox(CUIRect MainView) { // same size like tabs in top but variables not really needed float Spacing = 3.0f; float ButtonWidth = MainView.w/2.0f-Spacing/2.0f; // render background RenderTools()->DrawUIRect4(&MainView, vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.0f), CUI::CORNER_T, 5.0f); // back to main menu CUIRect Button; MainView.HSplitTop(25.0f, &MainView, 0); MainView.VSplitLeft(ButtonWidth, &Button, &MainView); static int s_RefreshButton=0; if(DoButton_Menu(&s_RefreshButton, Localize("Refresh"), 0, &Button)) { if(m_MenuPage == PAGE_INTERNET) ServerBrowser()->Refresh(IServerBrowser::TYPE_INTERNET); else if(m_MenuPage == PAGE_LAN) ServerBrowser()->Refresh(IServerBrowser::TYPE_LAN); } MainView.VSplitLeft(Spacing, 0, &MainView); // little space MainView.VSplitLeft(ButtonWidth, &Button, &MainView); static int s_JoinButton = 0; if(DoButton_Menu(&s_JoinButton, Localize("Connect"), 0, &Button) || m_EnterPressed) { Client()->Connect(g_Config.m_UiServerAddress); m_EnterPressed = false; } } void CMenus::RenderServerbrowser(CUIRect MainView) { /* +---------------------------+ | | | | | server list | | | |---------------------------+ | back | | bottom box | +------+ +------------+ */ CUIRect ServerList, BottomBox; MainView.HSplitTop(20.0f, 0, &MainView); MainView.HSplitBottom(80.0f, &ServerList, &MainView); // server list if(m_BorwserPage == PAGE_BROWSER_BROWSER) RenderServerbrowserServerList(ServerList); else if(m_BorwserPage == PAGE_BROWSER_FRIENDS) RenderServerbrowserFriendList(ServerList); /*// background RenderTools()->DrawUIRect(&MainView, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 12.0f); MainView.Margin(10.0f, &MainView); // create server list, status box, tab bar and tool box area MainView.VSplitRight(205.0f, &ServerList, &ToolBox); ServerList.VSplitRight(5.0f, &ServerList, 0); ToolBox.HSplitBottom(80.0f, &ToolBox, &ConnectBox); // tool box { RenderTools()->DrawUIRect(&ToolBox, vec4(0.0f, 0.0f, 0.0f, 0.15f), CUI::CORNER_T, 4.0f); RenderServerbrowserFilters(ToolBox); }*/ float Spacing = 3.0f; float ButtonWidth = (MainView.w/6.0f)-(Spacing*5.0)/6.0f; MainView.HSplitBottom(60.0f, 0, &BottomBox); BottomBox.VSplitRight(ButtonWidth*2.0f+Spacing, 0, &BottomBox); // connect box { RenderServerbrowserBottomBox(BottomBox); } // back button RenderBackButton(MainView); // render overlay if there is any RenderServerbrowserOverlay(); } // firend list void CMenus::RenderServerbrowserFriendList(CUIRect View) { //CUIRect Headers, Status, InfoButton; //float SpacingH = 2.0f; //float ButtonHeight = 20.0f; // background RenderTools()->DrawUIRect(&View, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f); } void CMenus::ConchainFriendlistUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData) { pfnCallback(pResult, pCallbackUserData); if(pResult->NumArguments() == 2 && ((CMenus *)pUserData)->Client()->State() == IClient::STATE_OFFLINE) { ((CMenus *)pUserData)->FriendlistOnUpdate(); ((CMenus *)pUserData)->Client()->ServerBrowserUpdate(); } } void CMenus::ConchainServerbrowserUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData) { pfnCallback(pResult, pCallbackUserData); /*if(pResult->NumArguments() && ((CMenus *)pUserData)->m_MenuPage == PAGE_FAVORITES && ((CMenus *)pUserData)->Client()->State() == IClient::STATE_OFFLINE) ((CMenus *)pUserData)->ServerBrowser()->Refresh(IServerBrowser::TYPE_FAVORITES);*/ } ================================================ FILE: src/game/client/components/menus_callback.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <engine/shared/config.h> #include "binds.h" #include "menus.h" typedef struct { CLocConstString m_Name; const char *m_pCommand; int m_KeyId; } CKeyInfo; static CKeyInfo gs_aKeys[] = { { "Move left", "+left", 0}, // Localize - these strings are localized within CLocConstString { "Move right", "+right", 0 }, { "Jump", "+jump", 0 }, { "Fire", "+fire", 0 }, { "Hook", "+hook", 0 }, { "Hammer", "+weapon1", 0 }, { "Pistol", "+weapon2", 0 }, { "Shotgun", "+weapon3", 0 }, { "Grenade", "+weapon4", 0 }, { "Laser", "+weapon5", 0 }, { "Next weapon", "+nextweapon", 0 }, { "Prev. weapon", "+prevweapon", 0 }, { "Vote yes", "vote yes", 0 }, { "Vote no", "vote no", 0 }, { "Chat", "chat all", 0 }, { "Team chat", "chat team", 0 }, { "Show chat", "+show_chat", 0 }, { "Emoticon", "+emote", 0 }, { "Spectator mode", "+spectate", 0 }, { "Spectate next", "spectate_next", 0 }, { "Spectate previous", "spectate_previous", 0 }, { "Console", "toggle_local_console", 0 }, { "Remote console", "toggle_remote_console", 0 }, { "Screenshot", "screenshot", 0 }, { "Scoreboard", "+scoreboard", 0 }, { "Respawn", "kill", 0 }, { "Ready", "ready_change", 0 }, }; /* This is for scripts/update_localization.py to work, don't remove! Localize("Move left");Localize("Move right");Localize("Jump");Localize("Fire");Localize("Hook");Localize("Hammer"); Localize("Pistol");Localize("Shotgun");Localize("Grenade");Localize("Laser");Localize("Next weapon");Localize("Prev. weapon"); Localize("Vote yes");Localize("Vote no");Localize("Chat");Localize("Team chat");Localize("Show chat");Localize("Emoticon"); Localize("Spectator mode");Localize("Spectate next");Localize("Spectate previous");Localize("Console");Localize("Remote console"); Localize("Screenshot");Localize("Scoreboard");Localize("Respawn");Localize("Ready"); */ const int g_KeyCount = sizeof(gs_aKeys) / sizeof(CKeyInfo); void CMenus::UiDoGetButtons(int Start, int Stop, CUIRect View, float ButtonHeight, float Spaceing) { for (int i = Start; i < Stop; i++) { View.HSplitTop(Spaceing, 0, &View); CKeyInfo &Key = gs_aKeys[i]; CUIRect Button, Label; View.HSplitTop(ButtonHeight, &Button, &View); RenderTools()->DrawUIRect(&Button, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f); Button.VSplitMid(&Label, &Button); char aBuf[64]; str_format(aBuf, sizeof(aBuf), "%s:", (const char *)Key.m_Name); Label.y += 2.0f; UI()->DoLabelScaled(&Label, aBuf, 13.0f, 0); int OldId = Key.m_KeyId; int NewId = DoKeyReader((void *)&gs_aKeys[i].m_Name, &Button, OldId); if(NewId != OldId) { if(OldId != 0 || NewId == 0) m_pClient->m_pBinds->Bind(OldId, ""); if(NewId != 0) m_pClient->m_pBinds->Bind(NewId, gs_aKeys[i].m_pCommand); } } } float CMenus::RenderSettingsControlsMovement(CUIRect View, void *pUser) { CMenus *pSelf = (CMenus*)pUser; // this is kinda slow, but whatever for(int i = 0; i < g_KeyCount; i++) gs_aKeys[i].m_KeyId = 0; for(int KeyId = 0; KeyId < KEY_LAST; KeyId++) { const char *pBind = pSelf->m_pClient->m_pBinds->Get(KeyId); if(!pBind[0]) continue; for(int i = 0; i < g_KeyCount; i++) if(str_comp(pBind, gs_aKeys[i].m_pCommand) == 0) { gs_aKeys[i].m_KeyId = KeyId; break; } } int NumOptions = 6; float ButtonHeight = 20.0f; float Spaceing = 2.0f; float BackgroundHeight = (float)NumOptions*ButtonHeight+(float)NumOptions*Spaceing; View.HSplitTop(BackgroundHeight, &View, 0); pSelf->RenderTools()->DrawUIRect(&View, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_B, 5.0f); CUIRect Button; View.HSplitTop(Spaceing, 0, &View); View.HSplitTop(ButtonHeight, &Button, &View); pSelf->DoScrollbarOption(&g_Config.m_InpMousesens, &g_Config.m_InpMousesens, &Button, Localize("Mouse sens."), 150.0f, 5, 500); pSelf->UiDoGetButtons(0, 5, View, ButtonHeight, Spaceing); return BackgroundHeight; } float CMenus::RenderSettingsControlsWeapon(CUIRect View, void *pUser) { CMenus *pSelf = (CMenus*)pUser; // this is kinda slow, but whatever for(int i = 0; i < g_KeyCount; i++) gs_aKeys[i].m_KeyId = 0; for(int KeyId = 0; KeyId < KEY_LAST; KeyId++) { const char *pBind = pSelf->m_pClient->m_pBinds->Get(KeyId); if(!pBind[0]) continue; for(int i = 0; i < g_KeyCount; i++) if(str_comp(pBind, gs_aKeys[i].m_pCommand) == 0) { gs_aKeys[i].m_KeyId = KeyId; break; } } int NumOptions = 7; float ButtonHeight = 20.0f; float Spaceing = 2.0f; float BackgroundHeight = (float)NumOptions*ButtonHeight+(float)NumOptions*Spaceing; View.HSplitTop(BackgroundHeight, &View, 0); pSelf->RenderTools()->DrawUIRect(&View, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_B, 5.0f); pSelf->UiDoGetButtons(5, 12, View, ButtonHeight, Spaceing); return BackgroundHeight; } float CMenus::RenderSettingsControlsVoting(CUIRect View, void *pUser) { CMenus *pSelf = (CMenus*)pUser; // this is kinda slow, but whatever for(int i = 0; i < g_KeyCount; i++) gs_aKeys[i].m_KeyId = 0; for(int KeyId = 0; KeyId < KEY_LAST; KeyId++) { const char *pBind = pSelf->m_pClient->m_pBinds->Get(KeyId); if(!pBind[0]) continue; for(int i = 0; i < g_KeyCount; i++) if(str_comp(pBind, gs_aKeys[i].m_pCommand) == 0) { gs_aKeys[i].m_KeyId = KeyId; break; } } int NumOptions = 2; float ButtonHeight = 20.0f; float Spaceing = 2.0f; float BackgroundHeight = (float)NumOptions*ButtonHeight+(float)NumOptions*Spaceing; View.HSplitTop(BackgroundHeight, &View, 0); pSelf->RenderTools()->DrawUIRect(&View, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_B, 5.0f); pSelf->UiDoGetButtons(12, 14, View, ButtonHeight, Spaceing); return BackgroundHeight; } float CMenus::RenderSettingsControlsChat(CUIRect View, void *pUser) { CMenus *pSelf = (CMenus*)pUser; // this is kinda slow, but whatever for(int i = 0; i < g_KeyCount; i++) gs_aKeys[i].m_KeyId = 0; for(int KeyId = 0; KeyId < KEY_LAST; KeyId++) { const char *pBind = pSelf->m_pClient->m_pBinds->Get(KeyId); if(!pBind[0]) continue; for(int i = 0; i < g_KeyCount; i++) if(str_comp(pBind, gs_aKeys[i].m_pCommand) == 0) { gs_aKeys[i].m_KeyId = KeyId; break; } } int NumOptions = 3; float ButtonHeight = 20.0f; float Spaceing = 2.0f; float BackgroundHeight = (float)NumOptions*ButtonHeight+(float)NumOptions*Spaceing; View.HSplitTop(BackgroundHeight, &View, 0); pSelf->RenderTools()->DrawUIRect(&View, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_B, 5.0f); pSelf->UiDoGetButtons(14, 17, View, ButtonHeight, Spaceing); return BackgroundHeight; } float CMenus::RenderSettingsControlsMisc(CUIRect View, void *pUser) { CMenus *pSelf = (CMenus*)pUser; // this is kinda slow, but whatever for(int i = 0; i < g_KeyCount; i++) gs_aKeys[i].m_KeyId = 0; for(int KeyId = 0; KeyId < KEY_LAST; KeyId++) { const char *pBind = pSelf->m_pClient->m_pBinds->Get(KeyId); if(!pBind[0]) continue; for(int i = 0; i < g_KeyCount; i++) if(str_comp(pBind, gs_aKeys[i].m_pCommand) == 0) { gs_aKeys[i].m_KeyId = KeyId; break; } } int NumOptions = 9; float ButtonHeight = 20.0f; float Spaceing = 2.0f; float BackgroundHeight = (float)NumOptions*ButtonHeight+(float)NumOptions*Spaceing; View.HSplitTop(BackgroundHeight, &View, 0); pSelf->RenderTools()->DrawUIRect(&View, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_B, 5.0f); pSelf->UiDoGetButtons(17, 26, View, ButtonHeight, Spaceing); return BackgroundHeight; } ================================================ FILE: src/game/client/components/menus_demo.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <base/math.h> #include <engine/demo.h> #include <engine/keys.h> #include <engine/graphics.h> #include <engine/textrender.h> #include <engine/storage.h> #include <game/client/render.h> #include <game/client/gameclient.h> #include <game/client/ui.h> #include <game/generated/client_data.h> #include "maplayers.h" #include "menus.h" int CMenus::DoButton_DemoPlayer(const void *pID, const char *pText, const CUIRect *pRect) { float Seconds = 0.6f; // 0.6 seconds for fade float *pFade = ButtonFade(pID, Seconds); RenderTools()->DrawUIRect(pRect, vec4(1,1,1, 0.5f+(*pFade/Seconds)*0.25f), CUI::CORNER_ALL, 5.0f); UI()->DoLabel(pRect, pText, 14.0f, 0); return UI()->DoButtonLogic(pID, pText, false, pRect); } void CMenus::RenderDemoPlayer(CUIRect MainView) { const IDemoPlayer::CInfo *pInfo = DemoPlayer()->BaseInfo(); const float SeekBarHeight = 15.0f; const float ButtonbarHeight = 20.0f; const float NameBarHeight = 20.0f; const float Margins = 5.0f; float TotalHeight; if(m_MenuActive) TotalHeight = SeekBarHeight+ButtonbarHeight+NameBarHeight+Margins*3; else TotalHeight = SeekBarHeight+Margins*2; MainView.HSplitBottom(TotalHeight, 0, &MainView); MainView.VSplitLeft(50.0f, 0, &MainView); MainView.VSplitRight(450.0f, &MainView, 0); RenderTools()->DrawUIRect(&MainView, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_T, 10.0f); MainView.Margin(5.0f, &MainView); CUIRect SeekBar, ButtonBar, NameBar; int CurrentTick = pInfo->m_CurrentTick - pInfo->m_FirstTick; int TotalTicks = pInfo->m_LastTick - pInfo->m_FirstTick; if(m_MenuActive) { MainView.HSplitTop(SeekBarHeight, &SeekBar, &ButtonBar); ButtonBar.HSplitTop(Margins, 0, &ButtonBar); ButtonBar.HSplitBottom(NameBarHeight, &ButtonBar, &NameBar); NameBar.HSplitTop(4.0f, 0, &NameBar); } else SeekBar = MainView; // do seekbar { static int s_SeekBarID = 0; void *id = &s_SeekBarID; char aBuffer[128]; // draw seek bar RenderTools()->DrawUIRect(&SeekBar, vec4(0,0,0,0.5f), CUI::CORNER_ALL, 5.0f); // draw filled bar float Amount = CurrentTick/(float)TotalTicks; CUIRect FilledBar = SeekBar; FilledBar.w = 10.0f + (FilledBar.w-10.0f)*Amount; RenderTools()->DrawUIRect(&FilledBar, vec4(1,1,1,0.5f), CUI::CORNER_ALL, 5.0f); // draw markers for(int i = 0; i < pInfo->m_NumTimelineMarkers; i++) { float Ratio = (pInfo->m_aTimelineMarkers[i]-pInfo->m_FirstTick) / (float)TotalTicks; Graphics()->TextureClear(); Graphics()->QuadsBegin(); Graphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f); IGraphics::CQuadItem QuadItem(SeekBar.x + (SeekBar.w-10.0f)*Ratio, SeekBar.y, UI()->PixelSize(), SeekBar.h); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); } // draw time str_format(aBuffer, sizeof(aBuffer), "%d:%02d / %d:%02d", CurrentTick/SERVER_TICK_SPEED/60, (CurrentTick/SERVER_TICK_SPEED)%60, TotalTicks/SERVER_TICK_SPEED/60, (TotalTicks/SERVER_TICK_SPEED)%60); UI()->DoLabel(&SeekBar, aBuffer, SeekBar.h*0.70f, 0); // do the logic int Inside = UI()->MouseInside(&SeekBar); if(UI()->ActiveItem() == id) { if(!UI()->MouseButton(0)) UI()->SetActiveItem(0); else { static float PrevAmount = 0.0f; float Amount = (UI()->MouseX()-SeekBar.x)/(float)SeekBar.w; if(Amount > 0.0f && Amount < 1.0f && absolute(PrevAmount-Amount) >= 0.01f) { PrevAmount = Amount; m_pClient->OnReset(); m_pClient->m_SuppressEvents = true; DemoPlayer()->SetPos(Amount); m_pClient->m_SuppressEvents = false; m_pClient->m_pMapLayersBackGround->EnvelopeUpdate(); m_pClient->m_pMapLayersForeGround->EnvelopeUpdate(); } } } else if(UI()->HotItem() == id) { if(UI()->MouseButton(0)) UI()->SetActiveItem(id); } if(Inside) UI()->SetHotItem(id); } if(CurrentTick == TotalTicks) { m_pClient->OnReset(); DemoPlayer()->Pause(); DemoPlayer()->SetPos(0); } bool IncreaseDemoSpeed = false, DecreaseDemoSpeed = false; if(m_MenuActive) { // do buttons CUIRect Button; // combined play and pause button ButtonBar.VSplitLeft(ButtonbarHeight, &Button, &ButtonBar); static int s_PlayPauseButton = 0; if(!pInfo->m_Paused) { if(DoButton_SpriteID(&s_PlayPauseButton, IMAGE_DEMOBUTTONS, SPRITE_DEMOBUTTON_PAUSE, &Button, CUI::CORNER_ALL)) DemoPlayer()->Pause(); } else { if(DoButton_SpriteID(&s_PlayPauseButton, IMAGE_DEMOBUTTONS, SPRITE_DEMOBUTTON_PLAY, &Button, CUI::CORNER_ALL)) DemoPlayer()->Unpause(); } // stop button ButtonBar.VSplitLeft(Margins, 0, &ButtonBar); ButtonBar.VSplitLeft(ButtonbarHeight, &Button, &ButtonBar); static int s_ResetButton = 0; if(DoButton_SpriteID(&s_ResetButton, IMAGE_DEMOBUTTONS, SPRITE_DEMOBUTTON_STOP, &Button, CUI::CORNER_ALL)) { m_pClient->OnReset(); DemoPlayer()->Pause(); DemoPlayer()->SetPos(0); } // slowdown ButtonBar.VSplitLeft(Margins, 0, &ButtonBar); ButtonBar.VSplitLeft(ButtonbarHeight, &Button, &ButtonBar); static int s_SlowDownButton = 0; if(DoButton_SpriteID(&s_SlowDownButton, IMAGE_DEMOBUTTONS, SPRITE_DEMOBUTTON_SLOWER, &Button, CUI::CORNER_ALL) || Input()->KeyPresses(KEY_MOUSE_WHEEL_DOWN)) DecreaseDemoSpeed = true; // fastforward ButtonBar.VSplitLeft(Margins, 0, &ButtonBar); ButtonBar.VSplitLeft(ButtonbarHeight, &Button, &ButtonBar); static int s_FastForwardButton = 0; if(DoButton_SpriteID(&s_FastForwardButton, IMAGE_DEMOBUTTONS, SPRITE_DEMOBUTTON_FASTER, &Button, CUI::CORNER_ALL)) IncreaseDemoSpeed = true; // speed meter ButtonBar.VSplitLeft(Margins*3, 0, &ButtonBar); char aBuffer[64]; if(pInfo->m_Speed >= 1.0f) str_format(aBuffer, sizeof(aBuffer), "x%.0f", pInfo->m_Speed); else str_format(aBuffer, sizeof(aBuffer), "x%.2f", pInfo->m_Speed); UI()->DoLabel(&ButtonBar, aBuffer, Button.h*0.7f, -1); // close button ButtonBar.VSplitRight(ButtonbarHeight*3, &ButtonBar, &Button); static int s_ExitButton = 0; if(DoButton_DemoPlayer(&s_ExitButton, Localize("Close"), &Button)) Client()->Disconnect(); // demo name char aDemoName[64] = {0}; DemoPlayer()->GetDemoName(aDemoName, sizeof(aDemoName)); char aBuf[128]; str_format(aBuf, sizeof(aBuf), Localize("Demofile: %s"), aDemoName); CTextCursor Cursor; TextRender()->SetCursor(&Cursor, NameBar.x, NameBar.y, Button.h*0.5f, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); Cursor.m_LineWidth = MainView.w; TextRender()->TextEx(&Cursor, aBuf, -1); } if(IncreaseDemoSpeed || Input()->KeyPresses(KEY_MOUSE_WHEEL_UP)) { if(pInfo->m_Speed < 0.1f) DemoPlayer()->SetSpeed(0.1f); else if(pInfo->m_Speed < 0.25f) DemoPlayer()->SetSpeed(0.25f); else if(pInfo->m_Speed < 0.5f) DemoPlayer()->SetSpeed(0.5f); else if(pInfo->m_Speed < 0.75f) DemoPlayer()->SetSpeed(0.75f); else if(pInfo->m_Speed < 1.0f) DemoPlayer()->SetSpeed(1.0f); else if(pInfo->m_Speed < 2.0f) DemoPlayer()->SetSpeed(2.0f); else if(pInfo->m_Speed < 4.0f) DemoPlayer()->SetSpeed(4.0f); else DemoPlayer()->SetSpeed(8.0f); } else if(DecreaseDemoSpeed || Input()->KeyPresses(KEY_MOUSE_WHEEL_DOWN)) { if(pInfo->m_Speed > 4.0f) DemoPlayer()->SetSpeed(4.0f); else if(pInfo->m_Speed > 2.0f) DemoPlayer()->SetSpeed(2.0f); else if(pInfo->m_Speed > 1.0f) DemoPlayer()->SetSpeed(1.0f); else if(pInfo->m_Speed > 0.75f) DemoPlayer()->SetSpeed(0.75f); else if(pInfo->m_Speed > 0.5f) DemoPlayer()->SetSpeed(0.5f); else if(pInfo->m_Speed > 0.25f) DemoPlayer()->SetSpeed(0.25f); else if(pInfo->m_Speed > 0.1f) DemoPlayer()->SetSpeed(0.1f); else DemoPlayer()->SetSpeed(0.05f); } } int CMenus::DemolistFetchCallback(const char *pName, int IsDir, int StorageType, void *pUser) { CMenus *pSelf = (CMenus *)pUser; int Length = str_length(pName); if((pName[0] == '.' && (pName[1] == 0 || (pName[1] == '.' && pName[2] == 0 && !str_comp(pSelf->m_aCurrentDemoFolder, "demos")))) || (!IsDir && (Length < 5 || str_comp(pName+Length-5, ".demo")))) return 0; CDemoItem Item; str_copy(Item.m_aFilename, pName, sizeof(Item.m_aFilename)); if(IsDir) { str_format(Item.m_aName, sizeof(Item.m_aName), "%s/", pName); Item.m_Valid = false; } else { str_copy(Item.m_aName, pName, min(static_cast<int>(sizeof(Item.m_aName)), Length-4)); Item.m_InfosLoaded = false; } Item.m_IsDir = IsDir != 0; Item.m_StorageType = StorageType; pSelf->m_lDemos.add_unsorted(Item); return 0; } void CMenus::DemolistPopulate() { m_lDemos.clear(); if(!str_comp(m_aCurrentDemoFolder, "demos")) m_DemolistStorageType = IStorage::TYPE_ALL; Storage()->ListDirectory(m_DemolistStorageType, m_aCurrentDemoFolder, DemolistFetchCallback, this); m_lDemos.sort_range(); } void CMenus::DemolistOnUpdate(bool Reset) { m_DemolistSelectedIndex = Reset ? m_lDemos.size() > 0 ? 0 : -1 : m_DemolistSelectedIndex >= m_lDemos.size() ? m_lDemos.size()-1 : m_DemolistSelectedIndex; m_DemolistSelectedIsDir = m_DemolistSelectedIndex < 0 ? false : m_lDemos[m_DemolistSelectedIndex].m_IsDir; } void CMenus::RenderDemoList(CUIRect MainView) { CUIRect BottomView; MainView.HSplitTop(20.0f, 0, &MainView); // back button RenderBackButton(MainView); // cut view MainView.HSplitBottom(80.0f, &MainView, &BottomView); BottomView.HSplitTop(20.f, 0, &BottomView); static int s_Inited = 0; if(!s_Inited) { DemolistPopulate(); DemolistOnUpdate(true); s_Inited = 1; } char aFooterLabel[128] = {0}; if(m_DemolistSelectedIndex >= 0) { CDemoItem *Item = &m_lDemos[m_DemolistSelectedIndex]; if(str_comp(Item->m_aFilename, "..") == 0) str_copy(aFooterLabel, Localize("Parent Folder"), sizeof(aFooterLabel)); else if(m_DemolistSelectedIsDir) str_copy(aFooterLabel, Localize("Folder"), sizeof(aFooterLabel)); else { if(!Item->m_InfosLoaded) { char aBuffer[512]; str_format(aBuffer, sizeof(aBuffer), "%s/%s", m_aCurrentDemoFolder, Item->m_aFilename); Item->m_Valid = DemoPlayer()->GetDemoInfo(Storage(), aBuffer, Item->m_StorageType, &Item->m_Info); Item->m_InfosLoaded = true; } if(!Item->m_Valid) str_copy(aFooterLabel, Localize("Invalid Demo"), sizeof(aFooterLabel)); else str_copy(aFooterLabel, Localize("Demo details"), sizeof(aFooterLabel)); } } CUIRect ListBox, Button, Label, FileIcon; MainView.HSplitTop(230.0f, &ListBox, &MainView); static int s_DemoListId = 0; static float s_ScrollValue = 0; UiDoListboxHeader(&ListBox, Localize("Recorded"), 20.0f, 2.0f); UiDoListboxStart(&s_DemoListId, 20.0f, 0, m_lDemos.size(), 1, m_DemolistSelectedIndex, s_ScrollValue); for(sorted_array<CDemoItem>::range r = m_lDemos.all(); !r.empty(); r.pop_front()) { CListboxItem Item = UiDoListboxNextItem((void*)(&r.front())); if(Item.m_Visible) { Item.m_Rect.VSplitLeft(Item.m_Rect.h, &FileIcon, &Item.m_Rect); Item.m_Rect.VSplitLeft(5.0f, 0, &Item.m_Rect); FileIcon.Margin(3.0f, &FileIcon); FileIcon.x += 3.0f; DoIcon(IMAGE_FILEICONS, r.front().m_IsDir?SPRITE_FILE_FOLDER:SPRITE_FILE_DEMO1, &FileIcon); if(!str_comp(m_lDemos[m_DemolistSelectedIndex].m_aName, r.front().m_aName)) { TextRender()->TextColor(0.0f, 0.0f, 0.0f, 1.0f); TextRender()->TextOutlineColor(1.0f, 1.0f, 1.0f, 0.25f); Item.m_Rect.y += 2.0f; UI()->DoLabel(&Item.m_Rect, r.front().m_aName, Item.m_Rect.h*ms_FontmodHeight*0.8f, 0); TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); TextRender()->TextOutlineColor(0.0f, 0.0f, 0.0f, 0.3f); } else { Item.m_Rect.y += 2.0f; UI()->DoLabel(&Item.m_Rect, r.front().m_aName, Item.m_Rect.h*ms_FontmodHeight*0.8f, 0); } } } bool Activated = false; m_DemolistSelectedIndex = UiDoListboxEnd(&s_ScrollValue, &Activated); DemolistOnUpdate(false); // render demo info int NumOptions = (!m_DemolistSelectedIsDir && m_DemolistSelectedIndex >= 0 && m_lDemos[m_DemolistSelectedIndex].m_Valid) ? 8 : 0; float ButtonHeight = 20.0f; float Spacing = 2.0f; float BackgroundHeight = (float)(NumOptions+1)*ButtonHeight+(float)NumOptions*Spacing; MainView.HSplitTop(10.0f, 0, &MainView); MainView.HSplitTop(BackgroundHeight, &MainView, 0); RenderTools()->DrawUIRect(&MainView, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f); MainView.HSplitTop(ButtonHeight, &Label, &MainView); Label.y += 2.0f; UI()->DoLabel(&Label, aFooterLabel, ButtonHeight*ms_FontmodHeight*0.8f, 0); if(!m_DemolistSelectedIsDir && m_DemolistSelectedIndex >= 0 && m_lDemos[m_DemolistSelectedIndex].m_Valid) { MainView.HSplitTop(Spacing, 0, &MainView); MainView.HSplitTop(ButtonHeight, &Button, &MainView); DoInfoBox(&Button, Localize("Created"), m_lDemos[m_DemolistSelectedIndex].m_Info.m_aTimestamp); MainView.HSplitTop(Spacing, 0, &MainView); MainView.HSplitTop(ButtonHeight, &Button, &MainView); DoInfoBox(&Button, Localize("Type"), m_lDemos[m_DemolistSelectedIndex].m_Info.m_aType); MainView.HSplitTop(Spacing, 0, &MainView); MainView.HSplitTop(ButtonHeight, &Button, &MainView); int Length = ((m_lDemos[m_DemolistSelectedIndex].m_Info.m_aLength[0]<<24)&0xFF000000) | ((m_lDemos[m_DemolistSelectedIndex].m_Info.m_aLength[1]<<16)&0xFF0000) | ((m_lDemos[m_DemolistSelectedIndex].m_Info.m_aLength[2]<<8)&0xFF00) | (m_lDemos[m_DemolistSelectedIndex].m_Info.m_aLength[3]&0xFF); char aBuf[64]; str_format(aBuf, sizeof(aBuf), "%d:%02d", Length/60, Length%60); DoInfoBox(&Button, Localize("Length"), aBuf); MainView.HSplitTop(Spacing, 0, &MainView); MainView.HSplitTop(ButtonHeight, &Button, &MainView); str_format(aBuf, sizeof(aBuf), "%d", m_lDemos[m_DemolistSelectedIndex].m_Info.m_Version); DoInfoBox(&Button, Localize("Version"), aBuf); MainView.HSplitTop(Spacing, 0, &MainView); MainView.HSplitTop(ButtonHeight, &Button, &MainView); DoInfoBox(&Button, Localize("Netversion"), m_lDemos[m_DemolistSelectedIndex].m_Info.m_aNetversion); MainView.HSplitTop(Spacing, 0, &MainView); MainView.HSplitTop(ButtonHeight, &Button, &MainView); DoInfoBox(&Button, Localize("Map"), m_lDemos[m_DemolistSelectedIndex].m_Info.m_aMapName); MainView.HSplitTop(Spacing, 0, &MainView); MainView.HSplitTop(ButtonHeight, &Button, &MainView); Button.VSplitLeft(ButtonHeight, 0, &Button); float Size = float((m_lDemos[m_DemolistSelectedIndex].m_Info.m_aMapSize[0]<<24) | (m_lDemos[m_DemolistSelectedIndex].m_Info.m_aMapSize[1]<<16) | (m_lDemos[m_DemolistSelectedIndex].m_Info.m_aMapSize[2]<<8) | (m_lDemos[m_DemolistSelectedIndex].m_Info.m_aMapSize[3]))/1024.0f; str_format(aBuf, sizeof(aBuf), Localize("%.3f KiB"), Size); DoInfoBox(&Button, Localize("Size"), aBuf); MainView.HSplitTop(Spacing, 0, &MainView); MainView.HSplitTop(ButtonHeight, &Button, &MainView); Button.VSplitLeft(ButtonHeight, 0, &Button); unsigned Crc = (m_lDemos[m_DemolistSelectedIndex].m_Info.m_aMapCrc[0]<<24) | (m_lDemos[m_DemolistSelectedIndex].m_Info.m_aMapCrc[1]<<16) | (m_lDemos[m_DemolistSelectedIndex].m_Info.m_aMapCrc[2]<<8) | (m_lDemos[m_DemolistSelectedIndex].m_Info.m_aMapCrc[3]); str_format(aBuf, sizeof(aBuf), "%08x", Crc); DoInfoBox(&Button, Localize("Crc"), aBuf); } // demo buttons int NumButtons = m_DemolistSelectedIsDir ? 2 : 4; Spacing = 3.0f; float ButtonWidth = (BottomView.w/6.0f)-(Spacing*5.0)/6.0f; float BackgroundWidth = ButtonWidth*(float)NumButtons+(float)(NumButtons-1)*Spacing; BottomView.VSplitRight(BackgroundWidth, 0, &BottomView); RenderTools()->DrawUIRect4(&BottomView, vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.0f), CUI::CORNER_T, 5.0f); BottomView.HSplitTop(25.0f, &BottomView, 0); BottomView.VSplitLeft(ButtonWidth, &Button, &BottomView); static int s_RefreshButton = 0; if(DoButton_Menu(&s_RefreshButton, Localize("Refresh"), 0, &Button)) { DemolistPopulate(); DemolistOnUpdate(false); } if(!m_DemolistSelectedIsDir) { BottomView.VSplitLeft(Spacing, 0, &BottomView); BottomView.VSplitLeft(ButtonWidth, &Button, &BottomView); static int s_DeleteButton = 0; if(DoButton_Menu(&s_DeleteButton, Localize("Delete"), 0, &Button) || m_DeletePressed) { if(m_DemolistSelectedIndex >= 0) { UI()->SetActiveItem(0); m_Popup = POPUP_DELETE_DEMO; return; } } BottomView.VSplitLeft(Spacing, 0, &BottomView); BottomView.VSplitLeft(ButtonWidth, &Button, &BottomView); static int s_RenameButton = 0; if(DoButton_Menu(&s_RenameButton, Localize("Rename"), 0, &Button)) { if(m_DemolistSelectedIndex >= 0) { UI()->SetActiveItem(0); m_Popup = POPUP_RENAME_DEMO; str_copy(m_aCurrentDemoFile, m_lDemos[m_DemolistSelectedIndex].m_aFilename, sizeof(m_aCurrentDemoFile)); return; } } } BottomView.VSplitLeft(Spacing, 0, &BottomView); BottomView.VSplitLeft(ButtonWidth, &Button, &BottomView); static int s_PlayButton = 0; if(DoButton_Menu(&s_PlayButton, m_DemolistSelectedIsDir?Localize("Open"):Localize("Play", "DemoBrowser"), 0, &Button) || Activated) { if(m_DemolistSelectedIndex >= 0) { if(m_DemolistSelectedIsDir) // folder { if(str_comp(m_lDemos[m_DemolistSelectedIndex].m_aFilename, "..") == 0) // parent folder fs_parent_dir(m_aCurrentDemoFolder); else // sub folder { char aTemp[256]; str_copy(aTemp, m_aCurrentDemoFolder, sizeof(aTemp)); str_format(m_aCurrentDemoFolder, sizeof(m_aCurrentDemoFolder), "%s/%s", aTemp, m_lDemos[m_DemolistSelectedIndex].m_aFilename); m_DemolistStorageType = m_lDemos[m_DemolistSelectedIndex].m_StorageType; } DemolistPopulate(); DemolistOnUpdate(true); } else // file { char aBuf[512]; str_format(aBuf, sizeof(aBuf), "%s/%s", m_aCurrentDemoFolder, m_lDemos[m_DemolistSelectedIndex].m_aFilename); const char *pError = Client()->DemoPlayer_Play(aBuf, m_lDemos[m_DemolistSelectedIndex].m_StorageType); if(pError) PopupMessage(Localize("Error loading demo"), pError, Localize("Ok")); else { UI()->SetActiveItem(0); return; } } } } } ================================================ FILE: src/game/client/components/menus_ingame.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <base/math.h> #include <engine/config.h> #include <engine/demo.h> #include <engine/friends.h> #include <engine/graphics.h> #include <engine/serverbrowser.h> #include <engine/textrender.h> #include <engine/shared/config.h> #include <game/generated/protocol.h> #include <game/generated/client_data.h> #include <game/client/animstate.h> #include <game/client/gameclient.h> #include <game/client/render.h> #include <game/client/ui.h> #include "menus.h" #include "motd.h" #include "voting.h" void CMenus::RenderGame(CUIRect MainView) { if(m_pClient->m_LocalClientID == -1) return; char aBuf[128]; const char *pNotification = 0; int TeamMod = m_pClient->m_aClients[m_pClient->m_LocalClientID].m_Team != TEAM_SPECTATORS ? -1 : 0; bool AllowSpec = true; int TimeLeft = 0; if(TeamMod+m_pClient->m_GameInfo.m_aTeamSize[TEAM_RED]+m_pClient->m_GameInfo.m_aTeamSize[TEAM_BLUE] >= m_pClient->m_ServerSettings.m_PlayerSlots) { str_format(aBuf, sizeof(aBuf), Localize("Only %d active players are allowed"), m_pClient->m_ServerSettings.m_PlayerSlots); pNotification = aBuf; } else if(m_pClient->m_ServerSettings.m_TeamLock) pNotification = Localize("Teams are locked"); else if(m_pClient->m_TeamCooldownTick+1 >= Client()->GameTick()) { TimeLeft = (m_pClient->m_TeamCooldownTick-Client()->GameTick())/Client()->GameTickSpeed()+1; str_format(aBuf, sizeof(aBuf), Localize("Teams are locked. Time to wait before changing team: %02d:%02d"), TimeLeft/60, TimeLeft%60); pNotification = aBuf; AllowSpec = false; } CUIRect Button, BottomView, Left, Middle, Right; // cut view MainView.HSplitBottom(80.0f, &MainView, &BottomView); // MainView not used for now BottomView.HSplitTop(20.f, 0, &BottomView); float Spacing = 3.0f; float ButtonWidth = (BottomView.w/6.0f)-(Spacing*5.0)/6.0f; BottomView.VSplitLeft(ButtonWidth*3.0f+Spacing*2.0f, &Left, &Middle); Middle.VSplitLeft(Spacing, 0, &Middle); Middle.VSplitLeft(ButtonWidth, &Middle, &Right); Right.VSplitRight(ButtonWidth, 0, &Right); if(!(m_pClient->m_GameInfo.m_GameFlags&GAMEFLAG_TEAMS)) Left.VSplitLeft(ButtonWidth, &Left, 0); // do backgrounds RenderTools()->DrawUIRect4(&Left, vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.0f), CUI::CORNER_T, 5.0f); RenderTools()->DrawUIRect4(&Middle, vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.0f), CUI::CORNER_T, 5.0f); RenderTools()->DrawUIRect4(&Right, vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.0f), CUI::CORNER_T, 5.0f); // do buttons Left.HSplitTop(25.0f, &Left, 0); Middle.HSplitTop(25.0f, &Middle, 0); Right.HSplitTop(25.0f, &Right, 0); if(pNotification != 0) { // print notice CUIRect Bar; MainView.HSplitTop(45.0f, &Bar, &MainView); RenderTools()->DrawUIRect(&Bar, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_B, 10.0f); Bar.HMargin(15.0f, &Bar); UI()->DoLabelScaled(&Bar, pNotification, 14.0f, 0); } // join buttons { // specator button int Team = m_pClient->m_aClients[m_pClient->m_LocalClientID].m_Team; if(pNotification && Team != TEAM_SPECTATORS) { if(TimeLeft) str_format(aBuf, sizeof(aBuf), "(%d)", TimeLeft); else str_copy(aBuf, Localize("locked"), sizeof(aBuf)); } else str_copy(aBuf, Localize(Team != TEAM_SPECTATORS ? "Spectate" : "Spactating"), sizeof(aBuf)); // Localize("Spectating"); Left.VSplitLeft(ButtonWidth, &Button, &Left); Left.VSplitLeft(Spacing, 0, &Left); static int s_SpectateButton = 0; if(DoButton_Menu(&s_SpectateButton, aBuf, Team == TEAM_SPECTATORS, &Button) && Team != TEAM_SPECTATORS && AllowSpec && !pNotification) { m_pClient->SendSwitchTeam(TEAM_SPECTATORS); SetActive(false); } // team button if(m_pClient->m_GameInfo.m_GameFlags&GAMEFLAG_TEAMS) { if(pNotification && Team != TEAM_RED) { if(TimeLeft) str_format(aBuf, sizeof(aBuf), "(%d)", TimeLeft); else str_copy(aBuf, Localize("locked"), sizeof(aBuf)); } else str_copy(aBuf, Localize(Team != TEAM_RED ? "Join red" : "Joined red"), sizeof(aBuf)); // Localize("Join red");Localize("Joined red"); Left.VSplitLeft(ButtonWidth, &Button, &Left); Left.VSplitLeft(Spacing, 0, &Left); static int s_RedButton = 0; if(DoButton_Menu(&s_RedButton, aBuf, Team == TEAM_RED, &Button, CUI::CORNER_ALL, 5.0f, 0.0f, vec4(0.975f, 0.17f, 0.17f, 0.75f), false) && Team != TEAM_RED && !pNotification) { m_pClient->SendSwitchTeam(TEAM_RED); SetActive(false); } if(pNotification && Team != TEAM_BLUE) { if(TimeLeft) str_format(aBuf, sizeof(aBuf), "(%d)", TimeLeft); else str_copy(aBuf, Localize("locked"), sizeof(aBuf)); } else str_copy(aBuf, Localize(Team != TEAM_BLUE ? "Join blue" : "Joined blue"), sizeof(aBuf)); // Localize("Join blue");Localize("Joined blue"); Left.VSplitLeft(ButtonWidth, &Button, &Left); static int s_BlueButton = 0; if(DoButton_Menu(&s_BlueButton, aBuf, Team == TEAM_BLUE, &Button, CUI::CORNER_ALL, 5.0f, 0.0f, vec4(0.17f, 0.46f, 0.975f, 0.75f), false) && Team != TEAM_BLUE && !pNotification) { m_pClient->SendSwitchTeam(TEAM_BLUE); SetActive(false); } } else { if(pNotification && Team != TEAM_RED) { if(TimeLeft) str_format(aBuf, sizeof(aBuf), "(%d)", TimeLeft); else str_copy(aBuf, Localize("locked"), sizeof(aBuf)); } else str_copy(aBuf, Localize(Team != TEAM_RED ? "Join" : "Joined"), sizeof(aBuf)); //Localize("Join");Localize("Joined"); Left.VSplitLeft(ButtonWidth, &Button, &Left); static int s_JoinButton = 0; if(DoButton_Menu(&s_JoinButton, aBuf, Team == TEAM_RED, &Button) && Team != TEAM_RED && !pNotification) { m_pClient->SendSwitchTeam(0); SetActive(false); } } } // Record button static int s_DemoButton = 0; bool Recording = DemoRecorder()->IsRecording(); if(DoButton_Menu(&s_DemoButton, Localize(Recording ? "Stop record" : "Record"), Recording, &Middle)) // Localize("Stop record");Localize("Record"); { if(!Recording) Client()->DemoRecorder_Start("demo", true); else Client()->DemoRecorder_Stop(); } // disconnect button static int s_DisconnectButton = 0; if(DoButton_Menu(&s_DisconnectButton, Localize("Disconnect"), 0, &Right)) Client()->Disconnect(); } void CMenus::RenderPlayers(CUIRect MainView) { CUIRect Button, ButtonBar, Options, Player; RenderTools()->DrawUIRect(&MainView, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 10.0f); // player options MainView.Margin(10.0f, &Options); RenderTools()->DrawUIRect(&Options, vec4(1.0f, 1.0f, 1.0f, 0.25f), CUI::CORNER_ALL, 10.0f); Options.Margin(10.0f, &Options); Options.HSplitTop(50.0f, &Button, &Options); UI()->DoLabelScaled(&Button, Localize("Player options"), 34.0f, -1); // headline Options.HSplitTop(34.0f, &ButtonBar, &Options); ButtonBar.VSplitRight(220.0f, &Player, &ButtonBar); UI()->DoLabelScaled(&Player, Localize("Player"), 24.0f, -1); ButtonBar.HMargin(1.0f, &ButtonBar); float Width = ButtonBar.h*2.0f; ButtonBar.VSplitLeft(Width, &Button, &ButtonBar); Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GUIICONS].m_Id); Graphics()->QuadsBegin(); RenderTools()->SelectSprite(SPRITE_GUIICON_MUTE); IGraphics::CQuadItem QuadItem(Button.x, Button.y, Button.w, Button.h); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); ButtonBar.VSplitLeft(20.0f, 0, &ButtonBar); ButtonBar.VSplitLeft(Width, &Button, &ButtonBar); Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GUIICONS].m_Id); Graphics()->QuadsBegin(); RenderTools()->SelectSprite(SPRITE_GUIICON_FRIEND); QuadItem = IGraphics::CQuadItem(Button.x, Button.y, Button.w, Button.h); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); // options static int s_aPlayerIDs[MAX_CLIENTS][2] = {{0}}; int Teams[3] = { TEAM_RED, TEAM_BLUE, TEAM_SPECTATORS }; for(int Team = 0; Team < 3; ++Team) { for(int i = 0, Count = 0; i < MAX_CLIENTS; ++i) { if(i == m_pClient->m_LocalClientID || !m_pClient->m_aClients[i].m_Active || m_pClient->m_aClients[i].m_Team != Teams[Team]) continue; Options.HSplitTop(28.0f, &ButtonBar, &Options); if(Count++%2 == 0) RenderTools()->DrawUIRect(&ButtonBar, vec4(1.0f, 1.0f, 1.0f, 0.25f), CUI::CORNER_ALL, 10.0f); ButtonBar.VSplitRight(220.0f, &Player, &ButtonBar); // player info Player.VSplitLeft(28.0f, &Button, &Player); CTeeRenderInfo Info = m_pClient->m_aClients[i].m_RenderInfo; Info.m_Size = Button.h; RenderTools()->RenderTee(CAnimState::GetIdle(), &Info, EMOTE_NORMAL, vec2(1.0f, 0.0f), vec2(Button.x+Button.h/2, Button.y+Button.h/2)); Player.HSplitTop(1.5f, 0, &Player); Player.VSplitMid(&Player, &Button); CTextCursor Cursor; TextRender()->SetCursor(&Cursor, Player.x, Player.y, 14.0f, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); Cursor.m_LineWidth = Player.w; TextRender()->TextEx(&Cursor, m_pClient->m_aClients[i].m_aName, -1); TextRender()->SetCursor(&Cursor, Button.x,Button.y, 14.0f, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); Cursor.m_LineWidth = Button.w; TextRender()->TextEx(&Cursor, m_pClient->m_aClients[i].m_aClan, -1); // ignore button ButtonBar.HMargin(2.0f, &ButtonBar); ButtonBar.VSplitLeft(Width, &Button, &ButtonBar); Button.VSplitLeft((Width-Button.h)/4.0f, 0, &Button); Button.VSplitLeft(Button.h, &Button, 0); if(g_Config.m_ClShowChatFriends && !m_pClient->m_aClients[i].m_Friend) DoButton_Toggle(&s_aPlayerIDs[i][0], 1, &Button, false); else if(DoButton_Toggle(&s_aPlayerIDs[i][0], m_pClient->m_aClients[i].m_ChatIgnore, &Button, true)) m_pClient->m_aClients[i].m_ChatIgnore ^= 1; // friend button ButtonBar.VSplitLeft(20.0f, &Button, &ButtonBar); ButtonBar.VSplitLeft(Width, &Button, &ButtonBar); Button.VSplitLeft((Width-Button.h)/4.0f, 0, &Button); Button.VSplitLeft(Button.h, &Button, 0); if(DoButton_Toggle(&s_aPlayerIDs[i][1], m_pClient->m_aClients[i].m_Friend, &Button, true)) { if(m_pClient->m_aClients[i].m_Friend) m_pClient->Friends()->RemoveFriend(m_pClient->m_aClients[i].m_aName, m_pClient->m_aClients[i].m_aClan); else m_pClient->Friends()->AddFriend(m_pClient->m_aClients[i].m_aName, m_pClient->m_aClients[i].m_aClan); m_pClient->m_aClients[i].m_Friend ^= 1; } } } } void CMenus::RenderServerInfo(CUIRect MainView) { if(!m_pClient->m_Snap.m_pLocalInfo) return; // fetch server info CServerInfo CurrentServerInfo; Client()->GetServerInfo(&CurrentServerInfo); // render background RenderTools()->DrawUIRect(&MainView, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 10.0f); CUIRect View, ServerInfo, GameInfo, Motd; float x = 0.0f; float y = 0.0f; char aBuf[1024]; // set view to use for all sub-modules MainView.Margin(10.0f, &View); // serverinfo View.HSplitTop(View.h/2/UI()->Scale()-5.0f, &ServerInfo, &Motd); ServerInfo.VSplitLeft(View.w/2/UI()->Scale()-5.0f, &ServerInfo, &GameInfo); RenderTools()->DrawUIRect(&ServerInfo, vec4(1,1,1,0.25f), CUI::CORNER_ALL, 10.0f); ServerInfo.Margin(5.0f, &ServerInfo); x = 5.0f; y = 0.0f; TextRender()->Text(0, ServerInfo.x+x, ServerInfo.y+y, 32, Localize("Server info"), 250); y += 32.0f+5.0f; mem_zero(aBuf, sizeof(aBuf)); str_format( aBuf, sizeof(aBuf), "%s\n\n" "%s: %s\n" "%s: %d\n" "%s: %s\n" "%s: %s\n", CurrentServerInfo.m_aName, Localize("Address"), g_Config.m_UiServerAddress, Localize("Ping"), m_pClient->m_Snap.m_pLocalInfo->m_Latency, Localize("Version"), CurrentServerInfo.m_aVersion, Localize("Password"), CurrentServerInfo.m_Flags&IServerBrowser::FLAG_PASSWORD ? Localize("Yes") : Localize("No") ); TextRender()->Text(0, ServerInfo.x+x, ServerInfo.y+y, 20, aBuf, 250); { CUIRect Button; bool IsFavorite = ServerBrowser()->IsFavorite(CurrentServerInfo.m_NetAddr); ServerInfo.HSplitBottom(20.0f, &ServerInfo, &Button); static int s_AddFavButton = 0; if(DoButton_CheckBox(&s_AddFavButton, Localize("Favorite"), IsFavorite, &Button)) { if(IsFavorite) ServerBrowser()->RemoveFavorite(&CurrentServerInfo); else ServerBrowser()->AddFavorite(&CurrentServerInfo); } } // gameinfo GameInfo.VSplitLeft(10.0f, 0x0, &GameInfo); RenderTools()->DrawUIRect(&GameInfo, vec4(1,1,1,0.25f), CUI::CORNER_ALL, 10.0f); GameInfo.Margin(5.0f, &GameInfo); x = 5.0f; y = 0.0f; TextRender()->Text(0, GameInfo.x+x, GameInfo.y+y, 32, Localize("Game info"), 250); y += 32.0f+5.0f; mem_zero(aBuf, sizeof(aBuf)); str_format( aBuf, sizeof(aBuf), "\n\n" "%s: %s\n" "%s: %s\n" "%s: %d\n" "%s: %d\n" "\n" "%s: %d/%d\n", Localize("Game type"), CurrentServerInfo.m_aGameType, Localize("Map"), CurrentServerInfo.m_aMap, Localize("Score limit"), m_pClient->m_GameInfo.m_ScoreLimit, Localize("Time limit"), m_pClient->m_GameInfo.m_TimeLimit, Localize("Players"), m_pClient->m_GameInfo.m_NumPlayers, CurrentServerInfo.m_MaxClients ); TextRender()->Text(0, GameInfo.x+x, GameInfo.y+y, 20, aBuf, 250); // motd Motd.HSplitTop(10.0f, 0, &Motd); RenderTools()->DrawUIRect(&Motd, vec4(1,1,1,0.25f), CUI::CORNER_ALL, 10.0f); Motd.Margin(5.0f, &Motd); y = 0.0f; x = 5.0f; TextRender()->Text(0, Motd.x+x, Motd.y+y, 32, Localize("MOTD"), -1); y += 32.0f+5.0f; TextRender()->Text(0, Motd.x+x, Motd.y+y, 16, m_pClient->m_pMotd->m_aServerMotd, (int)Motd.w); } void CMenus::RenderServerControlServer(CUIRect MainView) { static int s_VoteList = 0; static float s_ScrollValue = 0; CUIRect List = MainView; UiDoListboxHeader(&List, "", 20.0f, 2.0f); UiDoListboxStart(&s_VoteList, 24.0f, "", m_pClient->m_pVoting->m_NumVoteOptions, 1, m_CallvoteSelectedOption, s_ScrollValue); for(CVoteOptionClient *pOption = m_pClient->m_pVoting->m_pFirst; pOption; pOption = pOption->m_pNext) { CListboxItem Item = UiDoListboxNextItem(pOption); if(Item.m_Visible) UI()->DoLabelScaled(&Item.m_Rect, pOption->m_aDescription, 16.0f, -1); } m_CallvoteSelectedOption = UiDoListboxEnd(&s_ScrollValue, 0); } void CMenus::RenderServerControlKick(CUIRect MainView, bool FilterSpectators) { int NumOptions = 0; int Selected = -1; static int aPlayerIDs[MAX_CLIENTS]; int Teams[3] = { TEAM_RED, TEAM_BLUE, TEAM_SPECTATORS }; for(int Team = 0; Team < 3; ++Team) { for(int i = 0; i < MAX_CLIENTS; i++) { if(i == m_pClient->m_LocalClientID || !m_pClient->m_aClients[i].m_Active || m_pClient->m_aClients[i].m_Team != Teams[Team] || (FilterSpectators && m_pClient->m_aClients[i].m_Team == TEAM_SPECTATORS) || (!FilterSpectators && m_pClient->m_Snap.m_paPlayerInfos[i] && m_pClient->m_Snap.m_paPlayerInfos[i]->m_PlayerFlags&PLAYERFLAG_ADMIN)) continue; if(m_CallvoteSelectedPlayer == i) Selected = NumOptions; aPlayerIDs[NumOptions++] = i; } } static int s_VoteList = 0; static float s_ScrollValue = 0; CUIRect List = MainView; UiDoListboxHeader(&List, "", 20.0f, 2.0f); UiDoListboxStart(&s_VoteList, 24.0f, "", NumOptions, 1, Selected, s_ScrollValue); for(int i = 0; i < NumOptions; i++) { CListboxItem Item = UiDoListboxNextItem(&aPlayerIDs[i]); if(Item.m_Visible) { CTeeRenderInfo Info = m_pClient->m_aClients[aPlayerIDs[i]].m_RenderInfo; Info.m_Size = Item.m_Rect.h; Item.m_Rect.HSplitTop(5.0f, 0, &Item.m_Rect); // some margin from the top RenderTools()->RenderTee(CAnimState::GetIdle(), &Info, EMOTE_NORMAL, vec2(1,0), vec2(Item.m_Rect.x+Item.m_Rect.h/2, Item.m_Rect.y+Item.m_Rect.h/2)); Item.m_Rect.x +=Info.m_Size; UI()->DoLabelScaled(&Item.m_Rect, m_pClient->m_aClients[aPlayerIDs[i]].m_aName, 16.0f, -1); } } Selected = UiDoListboxEnd(&s_ScrollValue, 0); m_CallvoteSelectedPlayer = Selected != -1 ? aPlayerIDs[Selected] : -1; } void CMenus::HandleCallvote(int Page, bool Force) { if(Page == 0) m_pClient->m_pVoting->CallvoteOption(m_CallvoteSelectedOption, m_aCallvoteReason, Force); else if(Page == 1) { if(m_CallvoteSelectedPlayer >= 0 && m_CallvoteSelectedPlayer < MAX_CLIENTS && m_pClient->m_aClients[m_CallvoteSelectedPlayer].m_Active) { m_pClient->m_pVoting->CallvoteKick(m_CallvoteSelectedPlayer, m_aCallvoteReason, Force); SetActive(false); } } else if(Page == 2) { if(m_CallvoteSelectedPlayer >= 0 && m_CallvoteSelectedPlayer < MAX_CLIENTS && m_pClient->m_aClients[m_CallvoteSelectedPlayer].m_Active) { m_pClient->m_pVoting->CallvoteSpectate(m_CallvoteSelectedPlayer, m_aCallvoteReason, Force); SetActive(false); } } } void CMenus::RenderServerControl(CUIRect MainView) { if(m_pClient->m_LocalClientID == -1) return; static int s_ControlPage = 0; const char *pNotification = 0; char aBuf[64]; if(m_pClient->m_aClients[m_pClient->m_LocalClientID].m_Team == TEAM_SPECTATORS) pNotification = Localize("Spectators aren't allowed to start a vote."); else if(m_pClient->m_pVoting->IsVoting()) pNotification = Localize("Wait for current vote to end before calling a new one."); else if(m_pClient->m_pVoting->CallvoteBlockTime() != 0) { str_format(aBuf, sizeof(aBuf), Localize("You must wait %d seconds before making another vote"), m_pClient->m_pVoting->CallvoteBlockTime()); pNotification = aBuf; } bool Authed = Client()->RconAuthed(); if(pNotification && !Authed) { // only print notice CUIRect Bar; MainView.HSplitTop(45.0f, &Bar, &MainView); RenderTools()->DrawUIRect(&Bar, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 10.0f); Bar.HMargin(15.0f, &Bar); UI()->DoLabelScaled(&Bar, pNotification, 14.0f, 0); return; } // tab bar CUIRect Bottom, Extended, TabBar, Button; MainView.HSplitTop(20.0f, &Bottom, &MainView); RenderTools()->DrawUIRect(&Bottom, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_T, 10.0f); MainView.HSplitTop(20.0f, &TabBar, &MainView); { TabBar.VSplitLeft(TabBar.w/3, &Button, &TabBar); static int s_Button0 = 0; if(DoButton_MenuTab(&s_Button0, Localize("Change settings"), s_ControlPage == 0, &Button, 0)) s_ControlPage = 0; TabBar.VSplitMid(&Button, &TabBar); static int s_Button1 = 0; if(DoButton_MenuTab(&s_Button1, Localize("Kick player"), s_ControlPage == 1, &Button, 0)) s_ControlPage = 1; static int s_Button2 = 0; if(DoButton_MenuTab(&s_Button2, Localize("Move player to spectators"), s_ControlPage == 2, &TabBar, 0)) s_ControlPage = 2; } if(s_ControlPage == 1) { if(!m_pClient->m_ServerSettings.m_KickVote) pNotification = Localize("Server does not allow voting to kick players"); else if(m_pClient->m_GameInfo.m_aTeamSize[TEAM_RED]+m_pClient->m_GameInfo.m_aTeamSize[TEAM_BLUE] < m_pClient->m_ServerSettings.m_KickMin) { str_format(aBuf, sizeof(aBuf), Localize("Kick voting requires %d players on the server"), m_pClient->m_ServerSettings.m_KickMin); pNotification = aBuf; } } else if(s_ControlPage == 2 && !m_pClient->m_ServerSettings.m_SpecVote) pNotification = Localize("Server does not allow voting to move players to spectators"); if(pNotification && !Authed) { // only print notice CUIRect Bar; MainView.HSplitTop(45.0f, &Bar, &MainView); RenderTools()->DrawUIRect(&Bar, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_B, 10.0f); Bar.HMargin(15.0f, &Bar); UI()->DoLabelScaled(&Bar, pNotification, 14.0f, 0); return; } // render background RenderTools()->DrawUIRect(&MainView, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_B, 10.0f); MainView.Margin(10.0f, &MainView); MainView.HSplitBottom(90.0f, &MainView, &Extended); // render page MainView.HSplitBottom(ms_ButtonHeight + 5*2, &MainView, &Bottom); Bottom.HMargin(5.0f, &Bottom); if(s_ControlPage == 0) RenderServerControlServer(MainView); else if(s_ControlPage == 1) RenderServerControlKick(MainView, false); else if(s_ControlPage == 2) RenderServerControlKick(MainView, true); // vote menu { Bottom.VSplitRight(120.0f, &Bottom, &Button); // render kick reason CUIRect Reason, ClearButton; Bottom.VSplitRight(40.0f, &Bottom, 0); Bottom.VSplitRight(160.0f, &Bottom, &Reason); Reason.HSplitTop(5.0f, 0, &Reason); Reason.VSplitRight(Reason.h, &Reason, &ClearButton); const char *pLabel = Localize("Reason:"); UI()->DoLabelScaled(&Reason, pLabel, 14.0f, -1); float w = TextRender()->TextWidth(0, 14.0f, pLabel, -1); Reason.VSplitLeft(w+10.0f, 0, &Reason); static float s_Offset = 0.0f; DoEditBox(&m_aCallvoteReason, &Reason, m_aCallvoteReason, sizeof(m_aCallvoteReason), 14.0f, &s_Offset, false, CUI::CORNER_L); // clear button { static int s_ClearButton = 0; float *pClearButtonFade = ButtonFade(&s_ClearButton, 0.6f); RenderTools()->DrawUIRect(&ClearButton, vec4(1.0f, 1.0f, 1.0f, 0.33f+(*pClearButtonFade/0.6f)*0.165f), CUI::CORNER_R, 3.0f); UI()->DoLabel(&ClearButton, "x", ClearButton.h*ms_FontmodHeight, 0); if(UI()->DoButtonLogic(&s_ClearButton, "x", 0, &ClearButton)) m_aCallvoteReason[0] = 0; } if(pNotification == 0) { // call vote static int s_CallVoteButton = 0; if(DoButton_Menu(&s_CallVoteButton, Localize("Call vote"), 0, &Button)) HandleCallvote(s_ControlPage, false); } else { // print notice UI()->DoLabelScaled(&Bottom, pNotification, 14.0f, -1, Bottom.w); } // extended features (only available when authed in rcon) if(Authed) { // background Extended.Margin(10.0f, &Extended); Extended.HSplitTop(20.0f, &Bottom, &Extended); Extended.HSplitTop(5.0f, 0, &Extended); // force vote Bottom.VSplitLeft(5.0f, 0, &Bottom); Bottom.VSplitLeft(120.0f, &Button, &Bottom); static int s_ForceVoteButton = 0; if(DoButton_Menu(&s_ForceVoteButton, Localize("Force vote"), 0, &Button)) HandleCallvote(s_ControlPage, true); if(s_ControlPage == 0) { // remove vote Bottom.VSplitRight(10.0f, &Bottom, 0); Bottom.VSplitRight(120.0f, 0, &Button); static int s_RemoveVoteButton = 0; if(DoButton_Menu(&s_RemoveVoteButton, Localize("Remove"), 0, &Button)) m_pClient->m_pVoting->RemovevoteOption(m_CallvoteSelectedOption); // add vote Extended.HSplitTop(20.0f, &Bottom, &Extended); Bottom.VSplitLeft(5.0f, 0, &Bottom); Bottom.VSplitLeft(250.0f, &Button, &Bottom); UI()->DoLabelScaled(&Button, Localize("Vote description:"), 14.0f, -1); Bottom.VSplitLeft(20.0f, 0, &Button); UI()->DoLabelScaled(&Button, Localize("Vote command:"), 14.0f, -1); static char s_aVoteDescription[64] = {0}; static char s_aVoteCommand[512] = {0}; Extended.HSplitTop(20.0f, &Bottom, &Extended); Bottom.VSplitRight(10.0f, &Bottom, 0); Bottom.VSplitRight(120.0f, &Bottom, &Button); static int s_AddVoteButton = 0; if(DoButton_Menu(&s_AddVoteButton, Localize("Add"), 0, &Button)) if(s_aVoteDescription[0] != 0 && s_aVoteCommand[0] != 0) m_pClient->m_pVoting->AddvoteOption(s_aVoteDescription, s_aVoteCommand); Bottom.VSplitLeft(5.0f, 0, &Bottom); Bottom.VSplitLeft(250.0f, &Button, &Bottom); static float s_OffsetDesc = 0.0f; DoEditBox(&s_aVoteDescription, &Button, s_aVoteDescription, sizeof(s_aVoteDescription), 14.0f, &s_OffsetDesc, false, CUI::CORNER_ALL); Bottom.VMargin(20.0f, &Button); static float s_OffsetCmd = 0.0f; DoEditBox(&s_aVoteCommand, &Button, s_aVoteCommand, sizeof(s_aVoteCommand), 14.0f, &s_OffsetCmd, false, CUI::CORNER_ALL); } } } } ================================================ FILE: src/game/client/components/menus_popups.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <base/tl/array.h> #include <engine/shared/config.h> #include <engine/console.h> #include <engine/graphics.h> #include <engine/input.h> #include <engine/keys.h> #include <engine/storage.h> #include <engine/serverbrowser.h> #include "countryflags.h" #include "menus.h" // popup menu handling static struct { CUIRect m_Rect; void *m_pId; int (*m_pfnFunc)(CMenus *pMenu, CUIRect Rect); int m_IsMenu; void *m_pExtra; } s_Popups[8]; static int g_NumPopups = 0; void CMenus::InvokePopupMenu(void *pID, int Flags, float x, float y, float Width, float Height, int (*pfnFunc)(CMenus *pMenu, CUIRect Rect), void *pExtra) { if(x + Width > UI()->Screen()->w) x -= Width; if(y + Height > UI()->Screen()->h) y -= Height; s_Popups[g_NumPopups].m_pId = pID; s_Popups[g_NumPopups].m_IsMenu = Flags; s_Popups[g_NumPopups].m_Rect.x = x; s_Popups[g_NumPopups].m_Rect.y = y; s_Popups[g_NumPopups].m_Rect.w = Width; s_Popups[g_NumPopups].m_Rect.h = Height; s_Popups[g_NumPopups].m_pfnFunc = pfnFunc; s_Popups[g_NumPopups].m_pExtra = pExtra; g_NumPopups++; } void CMenus::DoPopupMenu() { for(int i = 0; i < g_NumPopups; i++) { bool Inside = UI()->MouseInside(&s_Popups[i].m_Rect); UI()->SetHotItem(&s_Popups[i].m_pId); if(UI()->ActiveItem() == &s_Popups[i].m_pId) { if(!UI()->MouseButton(0)) { if(!Inside) g_NumPopups--; UI()->SetActiveItem(0); } } else if(UI()->HotItem() == &s_Popups[i].m_pId) { if(UI()->MouseButton(0)) UI()->SetActiveItem(&s_Popups[i].m_pId); } int Corners = CUI::CORNER_ALL; if(s_Popups[i].m_IsMenu) Corners = CUI::CORNER_R|CUI::CORNER_B; CUIRect r = s_Popups[i].m_Rect; RenderTools()->DrawUIRect(&r, vec4(0.5f,0.5f,0.5f,0.75f), Corners, 3.0f); r.Margin(1.0f, &r); RenderTools()->DrawUIRect(&r, vec4(0,0,0,0.75f), Corners, 3.0f); r.Margin(4.0f, &r); if(s_Popups[i].m_pfnFunc(this, r)) g_NumPopups--; if(Input()->KeyDown(KEY_ESCAPE)) g_NumPopups--; } } int CMenus::PopupFilter(CMenus *pMenus, CUIRect View) { CUIRect ServerFilter = View, FilterHeader; const float FontSize = 12.0f; // slected filter CBrowserFilter *pFilter = &pMenus->m_lFilters[pMenus->m_SelectedFilter]; int SortHash = 0; int Ping = 0; int Country = 0; char aGametype[32]; char aServerAddress[16]; pFilter->GetFilter(&SortHash, &Ping, &Country, aGametype, aServerAddress); // server filter ServerFilter.HSplitTop(ms_ListheaderHeight, &FilterHeader, &ServerFilter); pMenus->RenderTools()->DrawUIRect(&FilterHeader, vec4(1,1,1,0.25f), CUI::CORNER_T, 4.0f); pMenus->RenderTools()->DrawUIRect(&ServerFilter, vec4(0,0,0,0.15f), CUI::CORNER_B, 4.0f); pMenus->UI()->DoLabelScaled(&FilterHeader, Localize("Server filter"), FontSize+2.0f, 0); CUIRect Button; ServerFilter.VSplitLeft(5.0f, 0, &ServerFilter); ServerFilter.Margin(3.0f, &ServerFilter); ServerFilter.VMargin(5.0f, &ServerFilter); ServerFilter.HSplitTop(20.0f, &Button, &ServerFilter); static int s_BrFilterEmpty = 0; if(pMenus->DoButton_CheckBox(&s_BrFilterEmpty, Localize("Has people playing"), SortHash&IServerBrowser::FILTER_EMPTY, &Button)) pFilter->SetFilter(SortHash^IServerBrowser::FILTER_EMPTY, Ping, Country, aGametype, aServerAddress); ServerFilter.HSplitTop(20.0f, &Button, &ServerFilter); static int s_BrFilterSpectators = 0; if(pMenus->DoButton_CheckBox(&s_BrFilterSpectators, Localize("Count players only"), SortHash&IServerBrowser::FILTER_SPECTATORS, &Button)) pFilter->SetFilter(SortHash^IServerBrowser::FILTER_SPECTATORS, Ping, Country, aGametype, aServerAddress); ServerFilter.HSplitTop(20.0f, &Button, &ServerFilter); static int s_BrFilterFull = 0; if(pMenus->DoButton_CheckBox(&s_BrFilterFull, Localize("Server not full"), SortHash&IServerBrowser::FILTER_FULL, &Button)) pFilter->SetFilter(SortHash^IServerBrowser::FILTER_FULL, Ping, Country, aGametype, aServerAddress); ServerFilter.HSplitTop(20.0f, &Button, &ServerFilter); static int s_BrFilterFriends = 0; if(pMenus->DoButton_CheckBox(&s_BrFilterFriends, Localize("Show friends only"), SortHash&IServerBrowser::FILTER_FRIENDS, &Button)) pFilter->SetFilter(SortHash^IServerBrowser::FILTER_FRIENDS, Ping, Country, aGametype, aServerAddress); ServerFilter.HSplitTop(20.0f, &Button, &ServerFilter); static int s_BrFilterPw = 0; if(pMenus->DoButton_CheckBox(&s_BrFilterPw, Localize("No password"), SortHash&IServerBrowser::FILTER_PW, &Button)) pFilter->SetFilter(SortHash^IServerBrowser::FILTER_PW, Ping, Country, aGametype, aServerAddress); ServerFilter.HSplitTop(20.0f, &Button, &ServerFilter); static int s_BrFilterCompatversion = 0; if(pMenus->DoButton_CheckBox(&s_BrFilterCompatversion, Localize("Compatible version"), SortHash&IServerBrowser::FILTER_COMPAT_VERSION, &Button)) pFilter->SetFilter(SortHash^IServerBrowser::FILTER_COMPAT_VERSION, Ping, Country, aGametype, aServerAddress); ServerFilter.HSplitTop(20.0f, &Button, &ServerFilter); static int s_BrFilterPure = 0; if(pMenus->DoButton_CheckBox(&s_BrFilterPure, Localize("Standard gametype"), SortHash&IServerBrowser::FILTER_PURE, &Button)) pFilter->SetFilter(SortHash^IServerBrowser::FILTER_PURE, Ping, Country, aGametype, aServerAddress); ServerFilter.HSplitTop(20.0f, &Button, &ServerFilter); static int s_BrFilterPureMap = 0; if(pMenus->DoButton_CheckBox(&s_BrFilterPureMap, Localize("Standard map"), SortHash&IServerBrowser::FILTER_PURE_MAP, &Button)) pFilter->SetFilter(SortHash^IServerBrowser::FILTER_PURE_MAP, Ping, Country, aGametype, aServerAddress); ServerFilter.HSplitTop(20.0f, &Button, &ServerFilter); static int s_BrFilterGametypeStrict = 0; if(pMenus->DoButton_CheckBox(&s_BrFilterGametypeStrict, Localize("Strict gametype filter"), SortHash&IServerBrowser::FILTER_GAMETYPE_STRICT, &Button)) pFilter->SetFilter(SortHash^IServerBrowser::FILTER_GAMETYPE_STRICT, Ping, Country, aGametype, aServerAddress); ServerFilter.HSplitTop(5.0f, 0, &ServerFilter); ServerFilter.HSplitTop(19.0f, &Button, &ServerFilter); pMenus->UI()->DoLabelScaled(&Button, Localize("Game types:"), FontSize, -1); Button.VSplitRight(60.0f, 0, &Button); ServerFilter.HSplitTop(3.0f, 0, &ServerFilter); static float Offset = 0.0f; static int s_BrFilterGametype = 0; if(pMenus->DoEditBox(&s_BrFilterGametype, &Button, aGametype, sizeof(aGametype), FontSize, &Offset)) pFilter->SetFilter(SortHash, Ping, Country, aGametype, aServerAddress); { ServerFilter.HSplitTop(19.0f, &Button, &ServerFilter); CUIRect EditBox; Button.VSplitRight(60.0f, &Button, &EditBox); pMenus->UI()->DoLabelScaled(&Button, Localize("Maximum ping:"), FontSize, -1); char aBuf[5]; str_format(aBuf, sizeof(aBuf), "%d", Ping); static float Offset = 0.0f; static int s_BrFilterPing = 0; pMenus->DoEditBox(&s_BrFilterPing, &EditBox, aBuf, sizeof(aBuf), FontSize, &Offset); int NewPing = clamp(str_toint(aBuf), 0, 999); if(NewPing != Ping) pFilter->SetFilter(SortHash, NewPing, Country, aGametype, aServerAddress); } // server address ServerFilter.HSplitTop(3.0f, 0, &ServerFilter); ServerFilter.HSplitTop(19.0f, &Button, &ServerFilter); pMenus->UI()->DoLabelScaled(&Button, Localize("Server address:"), FontSize, -1); Button.VSplitRight(60.0f, 0, &Button); static float OffsetAddr = 0.0f; static int s_BrFilterServerAddress = 0; if(pMenus->DoEditBox(&s_BrFilterServerAddress, &Button, aServerAddress, sizeof(aServerAddress), FontSize, &OffsetAddr)) pFilter->SetFilter(SortHash, Ping, Country, aGametype, aServerAddress); // player country { CUIRect Rect; ServerFilter.HSplitTop(3.0f, 0, &ServerFilter); ServerFilter.HSplitTop(26.0f, &Button, &ServerFilter); Button.VSplitRight(60.0f, &Button, &Rect); Button.HMargin(3.0f, &Button); static int s_BrFilterCountry = 0; if(pMenus->DoButton_CheckBox(&s_BrFilterCountry, Localize("Player country:"), SortHash&IServerBrowser::FILTER_COUNTRY, &Button)) pFilter->SetFilter(SortHash^IServerBrowser::FILTER_COUNTRY, Ping, Country, aGametype, aServerAddress); float OldWidth = Rect.w; Rect.w = Rect.h*2; Rect.x += (OldWidth-Rect.w)/2.0f; vec4 Color(1.0f, 1.0f, 1.0f, SortHash^IServerBrowser::FILTER_COUNTRY?1.0f: 0.5f); pMenus->m_pClient->m_pCountryFlags->Render(Country, &Color, Rect.x, Rect.y, Rect.w, Rect.h); static int s_BrFilterCountryIndex = 0; if(SortHash^IServerBrowser::FILTER_COUNTRY && pMenus->UI()->DoButtonLogic(&s_BrFilterCountryIndex, "", 0, &Rect)) pMenus->m_Popup = POPUP_COUNTRY; } return 0; } ================================================ FILE: src/game/client/components/menus_settings.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <base/math.h> #include <engine/engine.h> #include <engine/graphics.h> #include <engine/storage.h> #include <engine/textrender.h> #include <engine/external/json-parser/json.h> #include <engine/shared/config.h> #include <game/generated/protocol.h> #include <game/generated/client_data.h> #include <game/client/components/sounds.h> #include <game/client/ui.h> #include <game/client/render.h> #include <game/client/gameclient.h> #include <game/client/animstate.h> #include "binds.h" #include "countryflags.h" #include "menus.h" CMenusKeyBinder CMenus::m_Binder; CMenusKeyBinder::CMenusKeyBinder() { m_TakeKey = false; m_GotKey = false; } bool CMenusKeyBinder::OnInput(IInput::CEvent Event) { if(m_TakeKey) { if(Event.m_Flags&IInput::FLAG_PRESS) { m_Key = Event; m_GotKey = true; m_TakeKey = false; } return true; } return false; } int CMenus::DoButton_Customize(const void *pID, IGraphics::CTextureHandle Texture, int SpriteID, const CUIRect *pRect, float ImageRatio) { float Seconds = 0.6f; // 0.6 seconds for fade float *pFade = ButtonFade(pID, Seconds); RenderTools()->DrawUIRect(pRect, vec4(1.0f, 1.0f, 1.0f, 0.5f+(*pFade/Seconds)*0.25f), CUI::CORNER_ALL, 10.0f); Graphics()->TextureSet(Texture); Graphics()->QuadsBegin(); RenderTools()->SelectSprite(SpriteID); float Height = pRect->w/ImageRatio; IGraphics::CQuadItem QuadItem(pRect->x, pRect->y+(pRect->h-Height)/2, pRect->w, Height); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); return UI()->DoButtonLogic(pID, "", 0, pRect); } void CMenus::SaveSkinfile() { char aBuf[512]; str_format(aBuf, sizeof(aBuf), "skins/%s.json", m_aSaveSkinName); IOHANDLE File = Storage()->OpenFile(aBuf, IOFLAG_WRITE, IStorage::TYPE_SAVE); if(!File) return; // file start const char *p = "{\"skin\": {"; io_write(File, p, str_length(p)); int Count = 0; for(int PartIndex = 0; PartIndex < CSkins::NUM_SKINPARTS; PartIndex++) { if(!CSkins::ms_apSkinVariables[PartIndex][0]) continue; // part start if(Count == 0) { p = "\n"; io_write(File, p, str_length(p)); } else { p = ",\n"; io_write(File, p, str_length(p)); } str_format(aBuf, sizeof(aBuf), "\t\"%s\": {\n", CSkins::ms_apSkinPartNames[PartIndex]); io_write(File, aBuf, str_length(aBuf)); // part content str_format(aBuf, sizeof(aBuf), "\t\t\"filename\": \"%s\",\n", CSkins::ms_apSkinVariables[PartIndex]); io_write(File, aBuf, str_length(aBuf)); str_format(aBuf, sizeof(aBuf), "\t\t\"custom_colors\": \"%s\"", *CSkins::ms_apUCCVariables[PartIndex]?"true":"false"); io_write(File, aBuf, str_length(aBuf)); if(*CSkins::ms_apUCCVariables[PartIndex]) { for(int c = 0; c < CSkins::NUM_COLOR_COMPONENTS-1; c++) { int Val = (*CSkins::ms_apColorVariables[PartIndex] >> (2-c)*8) & 0xff; str_format(aBuf, sizeof(aBuf), ",\n\t\t\"%s\": %d", CSkins::ms_apColorComponents[c], Val); io_write(File, aBuf, str_length(aBuf)); } if(PartIndex == CSkins::SKINPART_TATTOO) { int Val = (*CSkins::ms_apColorVariables[PartIndex] >> 24) & 0xff; str_format(aBuf, sizeof(aBuf), ",\n\t\t\"%s\": %d", CSkins::ms_apColorComponents[3], Val); io_write(File, aBuf, str_length(aBuf)); } } // part end p = "\n\t}"; io_write(File, p, str_length(p)); ++Count; } // file end p = "}\n}\n"; io_write(File, p, str_length(p)); io_close(File); // add new skin to the skin list m_pClient->m_pSkins->AddSkin(m_aSaveSkinName); } void CMenus::RenderHSLPicker(CUIRect MainView) { CUIRect Label, Button, Picker; // background float Spacing = 2.0f; RenderTools()->DrawUIRect(&MainView, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f); // color header float HeaderHeight = 20.0f; MainView.HSplitTop(HeaderHeight, &Label, &MainView); Label.y += 2.0f; UI()->DoLabel(&Label, Localize("Color"), HeaderHeight*ms_FontmodHeight*0.8f, 0); MainView.HSplitTop(Spacing, 0, &MainView); // use custom color checkbox float ButtonHeight = 20.0f; MainView.HSplitTop(ButtonHeight, &Button, &MainView); static int s_CustomColors = 0; if(DoButton_CheckBox(&s_CustomColors, Localize("Custom colors"), *CSkins::ms_apUCCVariables[m_TeePartSelected], &Button)) *CSkins::ms_apUCCVariables[m_TeePartSelected] ^= 1; if(!(*CSkins::ms_apUCCVariables[m_TeePartSelected])) return; MainView.HSplitTop(Spacing, 0, &MainView); bool Modified = false; bool UseAlpha = m_TeePartSelected == CSkins::SKINPART_TATTOO; int Color = *CSkins::ms_apColorVariables[m_TeePartSelected]; int Hue, Sat, Lgt, Alp; Hue = (Color>>16)&0xff; Sat = (Color>>8)&0xff; Lgt = Color&0xff; if(UseAlpha) Alp = (Color>>24)&0xff; MainView.HSplitTop(144.0f, &Picker, &MainView); RenderTools()->DrawUIRect(&Picker, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f); float Dark = CSkins::DARKEST_COLOR_LGT/255.0f; IGraphics::CColorVertex ColorArray[4]; // Hue/Lgt picker : { Picker.VMargin((Picker.w-128)/2.0f, &Picker); Picker.HMargin((Picker.h-128.0f)/2.0f, &Picker); // picker Graphics()->TextureClear(); Graphics()->QuadsBegin(); // base: grey - hue vec3 c = HslToRgb(vec3(Hue/255.0f, 0.0f, 0.5f)); ColorArray[0] = IGraphics::CColorVertex(0, c.r, c.g, c.b, 1.0f); c = HslToRgb(vec3(Hue/255.0f, 1.0f, 0.5f)); ColorArray[1] = IGraphics::CColorVertex(1, c.r, c.g, c.b, 1.0f); c = HslToRgb(vec3(Hue/255.0f, 1.0f, 0.5f)); ColorArray[2] = IGraphics::CColorVertex(2, c.r, c.g, c.b, 1.0f); c = HslToRgb(vec3(Hue/255.0f, 0.0f, 0.5f)); ColorArray[3] = IGraphics::CColorVertex(3, c.r, c.g, c.b, 1.0f); Graphics()->SetColorVertex(ColorArray, 4); IGraphics::CQuadItem QuadItem(Picker.x, Picker.y, Picker.w, Picker.h); Graphics()->QuadsDrawTL(&QuadItem, 1); // white blending ColorArray[0] = IGraphics::CColorVertex(0, 1.0f, 1.0f, 1.0f, 0.0f); ColorArray[1] = IGraphics::CColorVertex(1, 1.0f, 1.0f, 1.0f, 0.0f); ColorArray[2] = IGraphics::CColorVertex(2, 1.0f, 1.0f, 1.0f, 1.0f); ColorArray[3] = IGraphics::CColorVertex(3, 1.0f, 1.0f, 1.0f, 1.0f); Graphics()->SetColorVertex(ColorArray, 4); IGraphics::CQuadItem WhiteGradient(Picker.x, Picker.y + Picker.h*(1-2*Dark)/((1-Dark)*2), Picker.w, Picker.h/((1-Dark)*2)); Graphics()->QuadsDrawTL(&WhiteGradient, 1); // black blending ColorArray[0] = IGraphics::CColorVertex(0, 0.0f, 0.0f, 0.0f, 1.0f-2*Dark); ColorArray[1] = IGraphics::CColorVertex(1, 0.0f, 0.0f, 0.0f, 1.0f-2*Dark); ColorArray[2] = IGraphics::CColorVertex(2, 0.0f, 0.0f, 0.0f, 0.0f); ColorArray[3] = IGraphics::CColorVertex(3, 0.0f, 0.0f, 0.0f, 0.0f); Graphics()->SetColorVertex(ColorArray, 4); IGraphics::CQuadItem BlackGradient(Picker.x, Picker.y, Picker.w, Picker.h*(1-2*Dark)/((1-Dark)*2)); Graphics()->QuadsDrawTL(&BlackGradient, 1); Graphics()->QuadsEnd(); // marker vec2 Marker = vec2(Sat/2.0f*UI()->Scale(), Lgt/2.0f*UI()->Scale()); Graphics()->TextureClear(); Graphics()->QuadsBegin(); Graphics()->SetColor(0.0f, 0.0f, 0.0f, 1.0f); IGraphics::CQuadItem aMarker[2]; aMarker[0] = IGraphics::CQuadItem(Picker.x+Marker.x, Picker.y+Marker.y - 5.0f*UI()->PixelSize(), UI()->PixelSize(), 11.0f*UI()->PixelSize()); aMarker[1] = IGraphics::CQuadItem(Picker.x+Marker.x - 5.0f*UI()->PixelSize(), Picker.y+Marker.y, 11.0f*UI()->PixelSize(), UI()->PixelSize()); Graphics()->QuadsDrawTL(aMarker, 2); Graphics()->QuadsEnd(); // logic float X, Y; static int s_HLPicker; if(UI()->DoPickerLogic(&s_HLPicker, &Picker, &X, &Y)) { Sat = (int)(255.0f*X/Picker.w); Lgt = (int)(255.0f*Y/Picker.h); Modified = true; } } MainView.HSplitTop(Spacing, 0, &MainView); // H/S/L/A sliders : { int NumBars = UseAlpha ? 4 : 3; const char *const apNames[4] = {Localize("Hue:"), Localize("Sat:"), Localize("Lgt:"), Localize("Alp:")}; int *const apVars[4] = {&Hue, &Sat, &Lgt, &Alp}; static int s_aButtons[12]; float SliderHeight = 16.0f; static const float s_aColorIndices[7][3] = {{1.0f, 0.0f, 0.0f}, {1.0f, 1.0f, 0.0f}, {0.0f, 1.0f, 0.0f}, {0.0f, 1.0f, 1.0f}, {0.0f, 0.0f, 1.0f}, {1.0f, 0.0f, 1.0f}, {1.0f, 0.0f, 0.0f}}; for(int i = 0; i < NumBars; i++) { CUIRect Bar; MainView.HSplitTop(SliderHeight, &Label, &MainView); MainView.HSplitTop(Spacing, 0, &MainView); // label RenderTools()->DrawUIRect(&Label, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f); Label.VSplitLeft((Label.w-160.0f)/2.0f, &Label, &Button); Label.y += 2.0f; UI()->DoLabelScaled(&Label, apNames[i], SliderHeight*ms_FontmodHeight*0.8f, 0); // button < Button.VSplitLeft(Button.h, &Button, &Bar); if(DoButton_Menu(&s_aButtons[i*3], "<", 0, &Button, CUI::CORNER_TL|CUI::CORNER_BL)) { *apVars[i] = max(0, *apVars[i]-1); Modified = true; } // bar Bar.VSplitLeft(128.0f, &Bar, &Button); int NumQuads = 1; if( i == 0) NumQuads = 6; else if ( i == 2) NumQuads = 2; else NumQuads = 1; float Length = Bar.w/NumQuads; float Offset = Length; vec4 ColorL, ColorR; Graphics()->TextureClear(); Graphics()->QuadsBegin(); for(int j = 0; j < NumQuads; ++j) { switch(i) { case 0: // Hue { ColorL = vec4(s_aColorIndices[j][0], s_aColorIndices[j][1], s_aColorIndices[j][2], 1.0f); ColorR = vec4(s_aColorIndices[j+1][0], s_aColorIndices[j+1][1], s_aColorIndices[j+1][2], 1.0f); } break; case 1: // Sat { vec3 c = HslToRgb(vec3(Hue/255.0f, 0.0f, Dark+Lgt/255.0f*(1.0f-Dark))); ColorL = vec4(c.r, c.g, c.b, 1.0f); c = HslToRgb(vec3(Hue/255.0f, 1.0f, Dark+Lgt/255.0f*(1.0f-Dark))); ColorR = vec4(c.r, c.g, c.b, 1.0f); } break; case 2: // Lgt { if(j == 0) { // Dark - 0.5f vec3 c = HslToRgb(vec3(Hue/255.0f, Sat/255.0f, Dark)); ColorL = vec4(c.r, c.g, c.b, 1.0f); c = HslToRgb(vec3(Hue/255.0f, Sat/255.0f, 0.5f)); ColorR = vec4(c.r, c.g, c.b, 1.0f); Length = Offset = Bar.w - Bar.w/((1-Dark)*2); } else { // 0.5f - 0.0f vec3 c = HslToRgb(vec3(Hue/255.0f, Sat/255.0f, 0.5f)); ColorL = vec4(c.r, c.g, c.b, 1.0f); c = HslToRgb(vec3(Hue/255.0f, Sat/255.0f, 1.0f)); ColorR = vec4(c.r, c.g, c.b, 1.0f); Length = Bar.w/((1-Dark)*2); } } break; default: // Alpha { vec3 c = HslToRgb(vec3(Hue/255.0f, Sat/255.0f, Dark+Lgt/255.0f*(1.0f-Dark))); ColorL = vec4(c.r, c.g, c.b, 0.0f); ColorR = vec4(c.r, c.g, c.b, 1.0f); } } ColorArray[0] = IGraphics::CColorVertex(0, ColorL.r, ColorL.g, ColorL.b, ColorL.a); ColorArray[1] = IGraphics::CColorVertex(1, ColorR.r, ColorR.g, ColorR.b, ColorR.a); ColorArray[2] = IGraphics::CColorVertex(2, ColorR.r, ColorR.g, ColorR.b, ColorR.a); ColorArray[3] = IGraphics::CColorVertex(3, ColorL.r, ColorL.g, ColorL.b, ColorL.a); Graphics()->SetColorVertex(ColorArray, 4); IGraphics::CQuadItem QuadItem(Bar.x+Offset*j, Bar.y, Length, Bar.h); Graphics()->QuadsDrawTL(&QuadItem, 1); } // bar marker Graphics()->SetColor(0.0f, 0.0f, 0.0f, 1.0f); IGraphics::CQuadItem QuadItem(Bar.x + min(127.0f, *apVars[i]/2.0f)*UI()->Scale(), Bar.y, UI()->PixelSize(), Bar.h); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); // button > Button.VSplitLeft(Button.h, &Button, &Label); if(DoButton_Menu(&s_aButtons[i*3+1], ">", 0, &Button, CUI::CORNER_TR|CUI::CORNER_BR)) { *apVars[i] = min(255, *apVars[i]+1); Modified = true; } // value label char aBuf[16]; str_format(aBuf, sizeof(aBuf), "%d", *apVars[i]); Label.y += 2.0f; UI()->DoLabelScaled(&Label, aBuf, SliderHeight*ms_FontmodHeight*0.8f, 0); // logic float X; if(UI()->DoPickerLogic(&s_aButtons[i*3+2], &Bar, &X, 0)) { *apVars[i] = X*255.0f/Bar.w; Modified = true; } } } if(Modified) { int NewVal = (Hue << 16) + (Sat << 8) + Lgt; for(int p = 0; p < CSkins::NUM_SKINPARTS; p++) { if(m_TeePartSelected == p) *CSkins::ms_apColorVariables[p] = NewVal; } if(UseAlpha) g_Config.m_PlayerColorTattoo = (Alp << 24) + NewVal; } } void CMenus::RenderSkinSelection(CUIRect MainView) { static sorted_array<const CSkins::CSkin *> s_paSkinList; static float s_ScrollValue = 0.0f; if(m_RefreshSkinSelector) { s_paSkinList.clear(); for(int i = 0; i < m_pClient->m_pSkins->Num(); ++i) { const CSkins::CSkin *s = m_pClient->m_pSkins->Get(i); // no special skins if((s->m_Flags&CSkins::SKINFLAG_SPECIAL) == 0) s_paSkinList.add(s); } m_RefreshSkinSelector = false; } m_pSelectedSkin = 0; int OldSelected = -1; UiDoListboxHeader(&MainView, Localize("Skins"), 20.0f, 2.0f); UiDoListboxStart(&m_RefreshSkinSelector, 50.0f, 0, s_paSkinList.size(), 10, OldSelected, s_ScrollValue); for(int i = 0; i < s_paSkinList.size(); ++i) { const CSkins::CSkin *s = s_paSkinList[i]; if(s == 0) continue; if(!str_comp(s->m_aName, g_Config.m_PlayerSkin)) { m_pSelectedSkin = s; OldSelected = i; } CListboxItem Item = UiDoListboxNextItem(&s_paSkinList[i], OldSelected == i); if(Item.m_Visible) { CTeeRenderInfo Info; for(int p = 0; p < CSkins::NUM_SKINPARTS; p++) { if(s->m_aUseCustomColors[p]) { Info.m_aTextures[p] = s->m_apParts[p]->m_ColorTexture; Info.m_aColors[p] = m_pClient->m_pSkins->GetColorV4(s->m_aPartColors[p], p==CSkins::SKINPART_TATTOO); } else { Info.m_aTextures[p] = s->m_apParts[p]->m_OrgTexture; Info.m_aColors[p] = vec4(1.0f, 1.0f, 1.0f, 1.0f); } } Info.m_Size = 50.0f; Item.m_Rect.HSplitTop(5.0f, 0, &Item.m_Rect); // some margin from the top RenderTools()->RenderTee(CAnimState::GetIdle(), &Info, 0, vec2(1.0f, 0.0f), vec2(Item.m_Rect.x+Item.m_Rect.w/2, Item.m_Rect.y+Item.m_Rect.h/2)); } } const int NewSelected = UiDoListboxEnd(&s_ScrollValue, 0); if(NewSelected != -1) { if(NewSelected != OldSelected) { m_pSelectedSkin = s_paSkinList[NewSelected]; mem_copy(g_Config.m_PlayerSkin, m_pSelectedSkin->m_aName, sizeof(g_Config.m_PlayerSkin)); for(int p = 0; p < CSkins::NUM_SKINPARTS; p++) { mem_copy(CSkins::ms_apSkinVariables[p], m_pSelectedSkin->m_apParts[p]->m_aName, 24); *CSkins::ms_apUCCVariables[p] = m_pSelectedSkin->m_aUseCustomColors[p]; *CSkins::ms_apColorVariables[p] = m_pSelectedSkin->m_aPartColors[p]; } } } OldSelected = NewSelected; } void CMenus::RenderSkinPartSelection(CUIRect MainView) { static bool s_InitSkinPartList = true; static sorted_array<const CSkins::CSkinPart *> s_paList[6]; static float s_ScrollValue = 0.0f; if(s_InitSkinPartList) { for(int p = 0; p < CSkins::NUM_SKINPARTS; p++) { s_paList[p].clear(); for(int i = 0; i < m_pClient->m_pSkins->NumSkinPart(p); ++i) { const CSkins::CSkinPart *s = m_pClient->m_pSkins->GetSkinPart(p, i); // no special skins if((s->m_Flags&CSkins::SKINFLAG_SPECIAL) == 0) s_paList[p].add(s); } } s_InitSkinPartList = false; } static int OldSelected = -1; UiDoListboxHeader(&MainView, CSkins::ms_apSkinPartNames[m_TeePartSelected], 20.0f, 2.0f); UiDoListboxStart(&s_InitSkinPartList, 50.0f, 0, s_paList[m_TeePartSelected].size(), 5, OldSelected, s_ScrollValue); for(int i = 0; i < s_paList[m_TeePartSelected].size(); ++i) { const CSkins::CSkinPart *s = s_paList[m_TeePartSelected][i]; if(s == 0) continue; if(!str_comp(s->m_aName, CSkins::ms_apSkinVariables[m_TeePartSelected])) OldSelected = i; CListboxItem Item = UiDoListboxNextItem(&s_paList[m_TeePartSelected][i], OldSelected == i); if(Item.m_Visible) { CTeeRenderInfo Info; for(int j = 0; j < CSkins::NUM_SKINPARTS; j++) { int SkinPart = m_pClient->m_pSkins->FindSkinPart(j, CSkins::ms_apSkinVariables[j], false); const CSkins::CSkinPart *pSkinPart = m_pClient->m_pSkins->GetSkinPart(j, SkinPart); if(*CSkins::ms_apUCCVariables[j]) { if(m_TeePartSelected == j) Info.m_aTextures[j] = s->m_ColorTexture; else Info.m_aTextures[j] = pSkinPart->m_ColorTexture; Info.m_aColors[j] = m_pClient->m_pSkins->GetColorV4(*CSkins::ms_apColorVariables[j], j==CSkins::SKINPART_TATTOO); } else { if(m_TeePartSelected == j) Info.m_aTextures[j] = s->m_OrgTexture; else Info.m_aTextures[j] = pSkinPart->m_OrgTexture; Info.m_aColors[j] = vec4(1.0f, 1.0f, 1.0f, 1.0f); } } Info.m_Size = 50.0f; Item.m_Rect.HSplitTop(5.0f, 0, &Item.m_Rect); // some margin from the top RenderTools()->RenderTee(CAnimState::GetIdle(), &Info, 0, vec2(1.0f, 0.0f), vec2(Item.m_Rect.x+Item.m_Rect.w/2, Item.m_Rect.y+Item.m_Rect.h/2)); } } const int NewSelected = UiDoListboxEnd(&s_ScrollValue, 0); if(NewSelected != -1) { if(NewSelected != OldSelected) { const CSkins::CSkinPart *s = s_paList[m_TeePartSelected][NewSelected]; mem_copy(CSkins::ms_apSkinVariables[m_TeePartSelected], s->m_aName, 24); g_Config.m_PlayerSkin[0] = 0; } } OldSelected = NewSelected; } class CLanguage { public: CLanguage() {} CLanguage(const char *n, const char *f, int Code) : m_Name(n), m_FileName(f), m_CountryCode(Code) {} string m_Name; string m_FileName; int m_CountryCode; bool operator<(const CLanguage &Other) { return m_Name < Other.m_Name; } }; void LoadLanguageIndexfile(IStorage *pStorage, IConsole *pConsole, sorted_array<CLanguage> *pLanguages) { // read file data into buffer const char *pFilename = "languages/index.json"; IOHANDLE File = pStorage->OpenFile(pFilename, IOFLAG_READ, IStorage::TYPE_ALL); if(!File) { pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "localization", "couldn't open index file"); return; } int FileSize = (int)io_length(File); char *pFileData = (char *)mem_alloc(FileSize+1, 1); io_read(File, pFileData, FileSize); pFileData[FileSize] = 0; io_close(File); // parse json data json_settings JsonSettings; mem_zero(&JsonSettings, sizeof(JsonSettings)); char aError[256]; json_value *pJsonData = json_parse_ex(&JsonSettings, pFileData, aError); if(pJsonData == 0) { pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, pFilename, aError); mem_free(pFileData); return; } // extract data const json_value &rStart = (*pJsonData)["language indices"]; if(rStart.type == json_array) { for(unsigned i = 0; i < rStart.u.array.length; ++i) { char aFileName[128]; str_format(aFileName, sizeof(aFileName), "languages/%s.json", (const char *)rStart[i]["file"]); pLanguages->add(CLanguage((const char *)rStart[i]["name"], aFileName, (long)rStart[i]["code"])); } } // clean up json_value_free(pJsonData); mem_free(pFileData); } void CMenus::RenderLanguageSelection(CUIRect MainView, bool Header) { static int s_LanguageList = 0; static int s_SelectedLanguage = 0; static sorted_array<CLanguage> s_Languages; static float s_ScrollValue = 0; if(s_Languages.size() == 0) { s_Languages.add(CLanguage("English", "", 826)); LoadLanguageIndexfile(Storage(), Console(), &s_Languages); for(int i = 0; i < s_Languages.size(); i++) if(str_comp(s_Languages[i].m_FileName, g_Config.m_ClLanguagefile) == 0) { s_SelectedLanguage = i; break; } } int OldSelected = s_SelectedLanguage; if(Header) UiDoListboxHeader(&MainView, Localize("Language"), 20.0f, 2.0f); UiDoListboxStart(&s_LanguageList, 20.0f, 0, s_Languages.size(), 1, s_SelectedLanguage, s_ScrollValue, Header?0:&MainView, Header?true:false); for(sorted_array<CLanguage>::range r = s_Languages.all(); !r.empty(); r.pop_front()) { CListboxItem Item = UiDoListboxNextItem(&r.front()); if(Item.m_Visible) { CUIRect Rect; Item.m_Rect.VSplitLeft(Item.m_Rect.h*2.0f, &Rect, &Item.m_Rect); Rect.VMargin(6.0f, &Rect); Rect.HMargin(3.0f, &Rect); vec4 Color(1.0f, 1.0f, 1.0f, 1.0f); m_pClient->m_pCountryFlags->Render(r.front().m_CountryCode, &Color, Rect.x, Rect.y, Rect.w, Rect.h); Item.m_Rect.y += 2.0f; if(!str_comp(s_Languages[s_SelectedLanguage].m_Name, r.front().m_Name)) { TextRender()->TextColor(0.0f, 0.0f, 0.0f, 1.0f); TextRender()->TextOutlineColor(1.0f, 1.0f, 1.0f, 0.25f); UI()->DoLabelScaled(&Item.m_Rect, r.front().m_Name, Item.m_Rect.h*ms_FontmodHeight*0.8f, -1); TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); TextRender()->TextOutlineColor(0.0f, 0.0f, 0.0f, 0.3f); } else UI()->DoLabelScaled(&Item.m_Rect, r.front().m_Name, Item.m_Rect.h*ms_FontmodHeight*0.8f, -1); } } s_SelectedLanguage = UiDoListboxEnd(&s_ScrollValue, 0); if(OldSelected != s_SelectedLanguage) { str_copy(g_Config.m_ClLanguagefile, s_Languages[s_SelectedLanguage].m_FileName, sizeof(g_Config.m_ClLanguagefile)); g_Localization.Load(s_Languages[s_SelectedLanguage].m_FileName, Storage(), Console()); } } void CMenus::RenderSettingsGeneral(CUIRect MainView) { CUIRect Label, Button, Game, Client, BottomView; // cut view MainView.HSplitBottom(80.0f, &MainView, &BottomView); BottomView.HSplitTop(20.f, 0, &BottomView); // render game menu backgrounds int NumOptions = g_Config.m_ClNameplates ? 8 : 5; float ButtonHeight = 20.0f; float Spacing = 2.0f; float BackgroundHeight = (float)(NumOptions+1)*ButtonHeight+(float)NumOptions*Spacing; MainView.HSplitTop(20.0f, 0, &MainView); MainView.HSplitTop(BackgroundHeight, &Game, &MainView); RenderTools()->DrawUIRect(&Game, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f); // render client menu background NumOptions = 2; if(g_Config.m_ClAutoDemoRecord) NumOptions += 1; if(g_Config.m_ClAutoScreenshot) NumOptions += 1; BackgroundHeight = (float)(NumOptions+1)*ButtonHeight+(float)NumOptions*Spacing; MainView.HSplitTop(10.0f, 0, &MainView); MainView.HSplitTop(BackgroundHeight, &Client, &MainView); RenderTools()->DrawUIRect(&Client, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f); // render game menu Game.HSplitTop(ButtonHeight, &Label, &Game); Label.y += 2.0f; UI()->DoLabel(&Label, Localize("Game"), ButtonHeight*ms_FontmodHeight*0.8f, 0); Game.HSplitTop(Spacing, 0, &Game); Game.HSplitTop(ButtonHeight, &Button, &Game); static int s_DynamicCameraButton = 0; if(DoButton_CheckBox(&s_DynamicCameraButton, Localize("Dynamic Camera"), g_Config.m_ClMouseDeadzone != 0, &Button)) { if(g_Config.m_ClMouseDeadzone) { g_Config.m_ClMouseFollowfactor = 0; g_Config.m_ClMouseMaxDistance = 400; g_Config.m_ClMouseDeadzone = 0; } else { g_Config.m_ClMouseFollowfactor = 60; g_Config.m_ClMouseMaxDistance = 1000; g_Config.m_ClMouseDeadzone = 300; } } Game.HSplitTop(Spacing, 0, &Game); Game.HSplitTop(ButtonHeight, &Button, &Game); static int s_AutoswitchWeapons = 0; if(DoButton_CheckBox(&s_AutoswitchWeapons, Localize("Switch weapon on pickup"), g_Config.m_ClAutoswitchWeapons, &Button)) g_Config.m_ClAutoswitchWeapons ^= 1; Game.HSplitTop(Spacing, 0, &Game); Game.HSplitTop(ButtonHeight, &Button, &Game); static int s_Showhud = 0; if(DoButton_CheckBox(&s_Showhud, Localize("Show ingame HUD"), g_Config.m_ClShowhud, &Button)) g_Config.m_ClShowhud ^= 1; Game.HSplitTop(Spacing, 0, &Game); Game.HSplitTop(ButtonHeight, &Button, &Game); static int s_Friendchat = 0; if(DoButton_CheckBox(&s_Friendchat, Localize("Show only chat messages from friends"), g_Config.m_ClShowChatFriends, &Button)) g_Config.m_ClShowChatFriends ^= 1; Game.HSplitTop(Spacing, 0, &Game); Game.HSplitTop(ButtonHeight, &Button, &Game); static int s_Nameplates = 0; if(DoButton_CheckBox(&s_Nameplates, Localize("Show name plates"), g_Config.m_ClNameplates, &Button)) g_Config.m_ClNameplates ^= 1; if(g_Config.m_ClNameplates) { Game.HSplitTop(Spacing, 0, &Game); Game.HSplitTop(ButtonHeight, &Button, &Game); Button.VSplitLeft(ButtonHeight, 0, &Button); static int s_NameplatesAlways = 0; if(DoButton_CheckBox(&s_NameplatesAlways, Localize("Always show name plates"), g_Config.m_ClNameplatesAlways, &Button)) g_Config.m_ClNameplatesAlways ^= 1; Game.HSplitTop(Spacing, 0, &Game); Game.HSplitTop(ButtonHeight, &Button, &Game); Button.VSplitLeft(ButtonHeight, 0, &Button); DoScrollbarOption(&g_Config.m_ClNameplatesSize, &g_Config.m_ClNameplatesSize, &Button, Localize("Size"), 100.0f, 0, 100); Game.HSplitTop(Spacing, 0, &Game); Game.HSplitTop(ButtonHeight, &Button, &Game); Button.VSplitLeft(ButtonHeight, 0, &Button); static int s_NameplatesTeamcolors = 0; if(DoButton_CheckBox(&s_NameplatesTeamcolors, Localize("Use team colors for name plates"), g_Config.m_ClNameplatesTeamcolors, &Button)) g_Config.m_ClNameplatesTeamcolors ^= 1; } // render client menu Client.HSplitTop(ButtonHeight, &Label, &Client); Label.y += 2.0f; UI()->DoLabel(&Label, Localize("Client"), ButtonHeight*ms_FontmodHeight*0.8f, 0); Client.HSplitTop(Spacing, 0, &Client); Client.HSplitTop(ButtonHeight, &Button, &Client); static int s_AutoDemoRecord = 0; if(DoButton_CheckBox(&s_AutoDemoRecord, Localize("Automatically record demos"), g_Config.m_ClAutoDemoRecord, &Button)) g_Config.m_ClAutoDemoRecord ^= 1; if(g_Config.m_ClAutoDemoRecord) { Client.HSplitTop(Spacing, 0, &Client); Client.HSplitTop(ButtonHeight, &Button, &Client); Button.VSplitLeft(ButtonHeight, 0, &Button); DoScrollbarOption(&g_Config.m_ClAutoDemoMax, &g_Config.m_ClAutoDemoMax, &Button, Localize("Max"), 100.0f, 0, 1000, true); } Client.HSplitTop(Spacing, 0, &Client); Client.HSplitTop(ButtonHeight, &Button, &Client); static int s_AutoScreenshot = 0; if(DoButton_CheckBox(&s_AutoScreenshot, Localize("Automatically take game over screenshot"), g_Config.m_ClAutoScreenshot, &Button)) g_Config.m_ClAutoScreenshot ^= 1; if(g_Config.m_ClAutoScreenshot) { Client.HSplitTop(Spacing, 0, &Client); Client.HSplitTop(ButtonHeight, &Button, &Client); Button.VSplitLeft(ButtonHeight, 0, &Button); DoScrollbarOption(&g_Config.m_ClAutoScreenshotMax, &g_Config.m_ClAutoScreenshotMax, &Button, Localize("Max"), 100.0f, 0, 1000, true); } MainView.HSplitTop(10.0f, 0, &MainView); // render language selection RenderLanguageSelection(MainView); // reset button Spacing = 3.0f; float ButtonWidth = (BottomView.w/6.0f)-(Spacing*5.0)/6.0f; BottomView.VSplitRight(ButtonWidth, 0, &BottomView); RenderTools()->DrawUIRect4(&BottomView, vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.0f), CUI::CORNER_T, 5.0f); BottomView.HSplitTop(25.0f, &BottomView, 0); Button = BottomView; static int s_ResetButton=0; if(DoButton_Menu(&s_ResetButton, Localize("Reset"), 0, &Button)) { g_Config.m_ClMouseFollowfactor = 60; g_Config.m_ClMouseMaxDistance = 1000; g_Config.m_ClMouseDeadzone = 300; g_Config.m_ClAutoswitchWeapons = 1; g_Config.m_ClShowhud = 1; g_Config.m_ClShowChatFriends = 0; g_Config.m_ClNameplates = 1; g_Config.m_ClNameplatesAlways = 1; g_Config.m_ClNameplatesSize = 50; g_Config.m_ClNameplatesTeamcolors = 1; g_Config.m_ClAutoDemoRecord = 0; g_Config.m_ClAutoDemoMax = 10; g_Config.m_ClAutoScreenshot = 0; g_Config.m_ClAutoScreenshotMax = 10; } } void CMenus::RenderSettingsPlayer(CUIRect MainView) { CUIRect Button, Left, Right, TopView, Label; // render game menu backgrounds float ButtonHeight = 20.0f; float Spacing = 2.0f; float BackgroundHeight = 2.0f*ButtonHeight+Spacing; MainView.HSplitTop(20.0f, 0, &MainView); MainView.HSplitBottom(80.0f, &MainView, 0); // now we have the total rect for the settings MainView.HSplitTop(BackgroundHeight, &TopView, &MainView); RenderTools()->DrawUIRect(&TopView, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f); // render game menu TopView.HSplitTop(ButtonHeight, &Label, &TopView); Label.y += 2.0f; UI()->DoLabel(&Label, Localize("Personal"), ButtonHeight*ms_FontmodHeight*0.8f, 0); // split menu TopView.HSplitTop(Spacing, 0, &TopView); TopView.VSplitMid(&Left, &Right); Left.VSplitRight(1.5f, &Left, 0); Right.VSplitLeft(1.5f, 0, &Right); // left menu Left.HSplitTop(ButtonHeight, &Button, &Left); static float s_OffsetName = 0.0f; DoEditBoxOption(g_Config.m_PlayerName, g_Config.m_PlayerName, sizeof(g_Config.m_PlayerName), &Button, Localize("Name"), 100.0f, &s_OffsetName); // right menu Right.HSplitTop(ButtonHeight, &Button, &Right); static float s_OffsetClan = 0.0f; DoEditBoxOption(g_Config.m_PlayerClan, g_Config.m_PlayerClan, sizeof(g_Config.m_PlayerClan), &Button, Localize("Clan"), 100.0f, &s_OffsetClan); // country flag selector MainView.HSplitTop(10.0f, 0, &MainView); static float s_ScrollValue = 0.0f; int OldSelected = -1; UiDoListboxHeader(&MainView, Localize("Country"), 20.0f, 2.0f); UiDoListboxStart(&s_ScrollValue, 40.0f, 0, m_pClient->m_pCountryFlags->Num(), 18, OldSelected, s_ScrollValue); for(int i = 0; i < m_pClient->m_pCountryFlags->Num(); ++i) { const CCountryFlags::CCountryFlag *pEntry = m_pClient->m_pCountryFlags->GetByIndex(i); if(pEntry->m_CountryCode == g_Config.m_PlayerCountry) OldSelected = i; CListboxItem Item = UiDoListboxNextItem(&pEntry->m_CountryCode, OldSelected == i); if(Item.m_Visible) { CUIRect Label; Item.m_Rect.Margin(5.0f, &Item.m_Rect); Item.m_Rect.HSplitBottom(10.0f, &Item.m_Rect, &Label); float OldWidth = Item.m_Rect.w; Item.m_Rect.w = Item.m_Rect.h*2; Item.m_Rect.x += (OldWidth-Item.m_Rect.w)/ 2.0f; Graphics()->TextureSet(pEntry->m_Texture); Graphics()->QuadsBegin(); Graphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f); IGraphics::CQuadItem QuadItem(Item.m_Rect.x, Item.m_Rect.y, Item.m_Rect.w, Item.m_Rect.h); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); if(i == OldSelected) { TextRender()->TextColor(0.0f, 0.0f, 0.0f, 1.0f); TextRender()->TextOutlineColor(1.0f, 1.0f, 1.0f, 0.25f); UI()->DoLabel(&Label, pEntry->m_aCountryCodeString, 10.0f, 0); TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); TextRender()->TextOutlineColor(0.0f, 0.0f, 0.0f, 0.3f); } else UI()->DoLabel(&Label, pEntry->m_aCountryCodeString, 10.0f, 0); } } const int NewSelected = UiDoListboxEnd(&s_ScrollValue, 0); if(OldSelected != NewSelected) { g_Config.m_PlayerCountry = m_pClient->m_pCountryFlags->GetByIndex(NewSelected)->m_CountryCode; } } void CMenus::RenderSettingsTeeBasic(CUIRect MainView) { RenderSkinSelection(MainView); // yes thats all here ^^ } void CMenus::RenderSettingsTeeCustom(CUIRect MainView) { CUIRect Label, Patterns, Button, Left, Right; // render skin preview background float SpacingH = 2.0f; float SpacingW = 3.0f; float ButtonHeight = 20.0f; float BoxSize = 297.0f; float BackgroundHeight = (ButtonHeight+SpacingH)*3.0f+BoxSize; MainView.HSplitTop(BackgroundHeight, &MainView, 0); RenderTools()->DrawUIRect(&MainView, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f); MainView.HSplitTop(ButtonHeight, &Label, &MainView); Label.y += 2.0f; UI()->DoLabel(&Label, Localize("Customize"), ButtonHeight*ms_FontmodHeight*0.8f, 0); // skin part selection MainView.HSplitTop(SpacingH, 0, &MainView); MainView.HSplitTop(ButtonHeight, &Patterns, &MainView); RenderTools()->DrawUIRect(&Patterns, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f); float ButtonWidth = (Patterns.w/6.0f)-(SpacingW*5.0)/6.0f; static int s_aPatternButtons[6] = {0}; for(int i = 0; i < CSkins::NUM_SKINPARTS; i++) { Patterns.VSplitLeft(ButtonWidth, &Button, &Patterns); if(DoButton_MenuTabTop(&s_aPatternButtons[i], CSkins::ms_apSkinPartNames[i], m_TeePartSelected==i, &Button)) { m_TeePartSelected = i; } Patterns.VSplitLeft(SpacingW, 0, &Patterns); } MainView.HSplitTop(SpacingH, 0, &MainView); MainView.VSplitMid(&Left, &Right); Left.VSplitRight(SpacingW/2.0f, &Left, 0); Right.VSplitLeft(SpacingW/2.0f, 0, &Right); // part selection RenderSkinPartSelection(Left); // HSL picker RenderHSLPicker(Right); } void CMenus::RenderSettingsTee(CUIRect MainView) { static bool s_CustomSkinMenu = false; CUIRect Button, Label, BottomView, Preview; // cut view MainView.HSplitBottom(80.0f, &MainView, &BottomView); BottomView.HSplitTop(20.f, 0, &BottomView); // render skin preview background float SpacingH = 2.0f; float SpacingW = 3.0f; float ButtonHeight = 20.0f; float SkinHeight = 50.0f; float BackgroundHeight = ButtonHeight+SpacingH+SkinHeight; if(!s_CustomSkinMenu) BackgroundHeight = (ButtonHeight+SpacingH)*2.0f+SkinHeight; MainView.HSplitTop(20.0f, 0, &MainView); MainView.HSplitTop(BackgroundHeight, &Preview, &MainView); RenderTools()->DrawUIRect(&Preview, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f); Preview.HSplitTop(ButtonHeight, &Label, &Preview); Label.y += 2.0f; UI()->DoLabel(&Label, Localize("Skin"), ButtonHeight*ms_FontmodHeight*0.8f, 0); // Preview { CUIRect Left, Right; Preview.HSplitTop(SpacingH, 0, &Preview); Preview.HSplitTop(SkinHeight, &Left, &Preview); // split the menu in 2 parts Left.VSplitMid(&Left, &Right); Left.VSplitRight(SpacingW/2.0f, &Left, 0); Right.VSplitLeft(SpacingW/2.0f, 0, &Right); // handle left RenderTools()->DrawUIRect(&Left, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f); Left.VSplitMid(&Label, &Left); Label.y += 17.0f; UI()->DoLabelScaled(&Label, Localize("Normal:"), ButtonHeight*ms_FontmodHeight*0.8f, 0); RenderTools()->DrawUIRect(&Left, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f); CTeeRenderInfo OwnSkinInfo; OwnSkinInfo.m_Size = 50.0f; for(int p = 0; p < CSkins::NUM_SKINPARTS; p++) { int SkinPart = m_pClient->m_pSkins->FindSkinPart(p, CSkins::ms_apSkinVariables[p], false); const CSkins::CSkinPart *pSkinPart = m_pClient->m_pSkins->GetSkinPart(p, SkinPart); if(*CSkins::ms_apUCCVariables[p]) { OwnSkinInfo.m_aTextures[p] = pSkinPart->m_ColorTexture; OwnSkinInfo.m_aColors[p] = m_pClient->m_pSkins->GetColorV4(*CSkins::ms_apColorVariables[p], p==CSkins::SKINPART_TATTOO); } else { OwnSkinInfo.m_aTextures[p] = pSkinPart->m_OrgTexture; OwnSkinInfo.m_aColors[p] = vec4(1.0f, 1.0f, 1.0f, 1.0f); } } RenderTools()->RenderTee(CAnimState::GetIdle(), &OwnSkinInfo, 0, vec2(1, 0), vec2(Left.x+Left.w/2.0f, Left.y+Left.h/2.0f+2.0f)); // handle right (team skins) RenderTools()->DrawUIRect(&Right, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f); Right.VSplitLeft(Right.w/3.0f+SpacingW/2.0f, &Label, &Right); Label.y += 17.0f; UI()->DoLabelScaled(&Label, Localize("Team:"), ButtonHeight*ms_FontmodHeight*0.8f, 0); Right.VSplitMid(&Left, &Right); Left.VSplitRight(SpacingW/2.0f, &Left, 0); Right.VSplitLeft(SpacingW/2.0f, 0, &Right); RenderTools()->DrawUIRect(&Left, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f); for(int p = 0; p < CSkins::NUM_SKINPARTS; p++) { int TeamColor = m_pClient->m_pSkins->GetTeamColor(*CSkins::ms_apUCCVariables[p], *CSkins::ms_apColorVariables[p], TEAM_RED, p); OwnSkinInfo.m_aColors[p] = m_pClient->m_pSkins->GetColorV4(TeamColor, p==CSkins::SKINPART_TATTOO); } RenderTools()->RenderTee(CAnimState::GetIdle(), &OwnSkinInfo, 0, vec2(1, 0), vec2(Left.x+Left.w/2.0f, Left.y+Left.h/2.0f+2.0f)); RenderTools()->DrawUIRect(&Right, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f); for(int p = 0; p < CSkins::NUM_SKINPARTS; p++) { int TeamColor = m_pClient->m_pSkins->GetTeamColor(*CSkins::ms_apUCCVariables[p], *CSkins::ms_apColorVariables[p], TEAM_BLUE, p); OwnSkinInfo.m_aColors[p] = m_pClient->m_pSkins->GetColorV4(TeamColor, p==CSkins::SKINPART_TATTOO); } RenderTools()->RenderTee(CAnimState::GetIdle(), &OwnSkinInfo, 0, vec2(1, 0), vec2(Right.x+Right.w/2.0f, Right.y+Right.h/2.0f+2.0f)); } if(!s_CustomSkinMenu) { Preview.HSplitTop(SpacingH, 0, &Preview); RenderTools()->DrawUIRect(&Preview, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f); Preview.y += 2.0f; UI()->DoLabel(&Preview, g_Config.m_PlayerSkin, ButtonHeight*ms_FontmodHeight*0.8f, 0); } MainView.HSplitTop(10.0f, 0, &MainView); if(s_CustomSkinMenu) RenderSettingsTeeCustom(MainView); else RenderSettingsTeeBasic(MainView); // bottom button float ButtonWidth = (BottomView.w/6.0f)-(SpacingW*5.0)/6.0f; float BackgroundWidth = s_CustomSkinMenu||(m_pSelectedSkin && (m_pSelectedSkin->m_Flags&CSkins::SKINFLAG_STANDARD) == 0) ? ButtonWidth*2.0f+SpacingW : ButtonWidth; BottomView.VSplitRight(BackgroundWidth, 0, &BottomView); RenderTools()->DrawUIRect4(&BottomView, vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.0f), CUI::CORNER_T, 5.0f); BottomView.HSplitTop(25.0f, &BottomView, 0); if(s_CustomSkinMenu) { BottomView.VSplitLeft(ButtonWidth, &Button, &BottomView); static int s_CustomSkinSaveButton=0; if(DoButton_Menu(&s_CustomSkinSaveButton, Localize("Save"), 0, &Button)) m_Popup = POPUP_SAVE_SKIN; BottomView.VSplitLeft(SpacingW, 0, &BottomView); } else if(m_pSelectedSkin && (m_pSelectedSkin->m_Flags&CSkins::SKINFLAG_STANDARD) == 0) { BottomView.VSplitLeft(ButtonWidth, &Button, &BottomView); static int s_CustomSkinSaveButton=0; if(DoButton_Menu(&s_CustomSkinSaveButton, Localize("Delete"), 0, &Button)) m_Popup = POPUP_DELETE_SKIN; BottomView.VSplitLeft(SpacingW, 0, &BottomView); } BottomView.VSplitLeft(ButtonWidth, &Button, &BottomView); static int s_CustomSwitchButton=0; if(DoButton_Menu(&s_CustomSwitchButton, s_CustomSkinMenu ? Localize("Basic") : Localize("Custom"), 0, &Button)) { if(s_CustomSkinMenu) s_CustomSkinMenu = false; else s_CustomSkinMenu = true; } } //typedef void (*pfnAssignFuncCallback)(CConfiguration *pConfig, int Value); void CMenus::RenderSettingsControls(CUIRect MainView) { MainView.HSplitTop(20.0f, 0, &MainView); // cut view CUIRect BottomView, Button; MainView.HSplitBottom(80.0f, &MainView, &BottomView); BottomView.HSplitTop(20.f, 0, &BottomView); float HeaderHeight = 20.0f; static int s_MovementDropdown = 0; float Split = DoDropdownMenu(&s_MovementDropdown, &MainView, Localize("Movement"), HeaderHeight, RenderSettingsControlsMovement); MainView.HSplitTop(Split+10.0f, 0, &MainView); static int s_WeaponDropdown = 0; Split = DoDropdownMenu(&s_WeaponDropdown, &MainView, Localize("Weapon"), HeaderHeight, RenderSettingsControlsWeapon); MainView.HSplitTop(Split+10.0f, 0, &MainView); static int s_VotingDropdown = 0; Split = DoDropdownMenu(&s_VotingDropdown, &MainView, Localize("Voting"), HeaderHeight, RenderSettingsControlsVoting); MainView.HSplitTop(Split+10.0f, 0, &MainView); static int s_ChatDropdown = 0; Split = DoDropdownMenu(&s_ChatDropdown, &MainView, Localize("Chat"), HeaderHeight, RenderSettingsControlsChat); MainView.HSplitTop(Split+10.0f, 0, &MainView); static int s_MiscDropdown = 0; Split = DoDropdownMenu(&s_MiscDropdown, &MainView, Localize("Misc"), HeaderHeight, RenderSettingsControlsMisc); // reset button float Spacing = 3.0f; float ButtonWidth = (BottomView.w/6.0f)-(Spacing*5.0)/6.0f; BottomView.VSplitRight(ButtonWidth, 0, &BottomView); RenderTools()->DrawUIRect4(&BottomView, vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.0f), CUI::CORNER_T, 5.0f); BottomView.HSplitTop(25.0f, &BottomView, 0); Button = BottomView; static int s_ResetButton=0; if(DoButton_Menu(&s_ResetButton, Localize("Reset"), 0, &Button)) m_pClient->m_pBinds->SetDefaults(); } void CMenus::RenderSettingsGraphics(CUIRect MainView) { char aBuf[128]; bool CheckSettings = false; static int s_GfxScreenWidth = g_Config.m_GfxScreenWidth; static int s_GfxScreenHeight = g_Config.m_GfxScreenHeight; static int s_GfxBorderless = g_Config.m_GfxBorderless; static int s_GfxFullscreen = g_Config.m_GfxFullscreen; static int s_GfxVsync = g_Config.m_GfxVsync; static int s_GfxFsaaSamples = g_Config.m_GfxFsaaSamples; static int s_GfxTextureQuality = g_Config.m_GfxTextureQuality; static int s_GfxTextureCompression = g_Config.m_GfxTextureCompression; CUIRect Label, Button, Screen, Texture, BottomView; // cut view MainView.HSplitBottom(80.0f, &MainView, &BottomView); BottomView.HSplitTop(20.f, 0, &BottomView); // render screen menu background int NumOptions = g_Config.m_GfxFullscreen ? 3 : 4; float ButtonHeight = 20.0f; float Spacing = 2.0f; float BackgroundHeight = (float)(NumOptions+1)*ButtonHeight+(float)NumOptions*Spacing; MainView.HSplitTop(20.0f, 0, &MainView); MainView.HSplitTop(BackgroundHeight, &Screen, &MainView); RenderTools()->DrawUIRect(&Screen, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f); // render textures menu background NumOptions = 3; BackgroundHeight = (float)(NumOptions+1)*ButtonHeight+(float)NumOptions*Spacing; MainView.HSplitTop(10.0f, 0, &MainView); MainView.HSplitTop(BackgroundHeight, &Texture, &MainView); RenderTools()->DrawUIRect(&Texture, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f); // render screen menu Screen.HSplitTop(ButtonHeight, &Label, &Screen); Label.y += 2.0f; UI()->DoLabel(&Label, Localize("Screen"), ButtonHeight*ms_FontmodHeight*0.8f, 0); Screen.HSplitTop(Spacing, 0, &Screen); Screen.HSplitTop(ButtonHeight, &Button, &Screen); static int s_ButtonGfxFullscreen = 0; if(DoButton_CheckBox(&s_ButtonGfxFullscreen, Localize("Fullscreen"), g_Config.m_GfxFullscreen, &Button)) { g_Config.m_GfxFullscreen ^= 1; if(g_Config.m_GfxFullscreen && g_Config.m_GfxBorderless) g_Config.m_GfxBorderless = 0; CheckSettings = true; } if(!g_Config.m_GfxFullscreen) { Screen.HSplitTop(Spacing, 0, &Screen); Screen.HSplitTop(ButtonHeight, &Button, &Screen); Button.VSplitLeft(ButtonHeight, 0, &Button); static int s_ButtonGfxBorderless = 0; if(DoButton_CheckBox(&s_ButtonGfxBorderless, Localize("Borderless window"), g_Config.m_GfxBorderless, &Button)) { g_Config.m_GfxBorderless ^= 1; if(g_Config.m_GfxBorderless && g_Config.m_GfxFullscreen) g_Config.m_GfxFullscreen = 0; CheckSettings = true; } } Screen.HSplitTop(Spacing, 0, &Screen); Screen.HSplitTop(ButtonHeight, &Button, &Screen); static int s_ButtonGfxVsync = 0; if(DoButton_CheckBox(&s_ButtonGfxVsync, Localize("V-Sync"), g_Config.m_GfxVsync, &Button)) { g_Config.m_GfxVsync ^= 1; CheckSettings = true; } // FSAA button { Screen.HSplitTop(Spacing, 0, &Screen); Screen.HSplitTop(ButtonHeight, &Button, &Screen); RenderTools()->DrawUIRect(&Button, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f); CUIRect Text; Button.VSplitLeft(ButtonHeight+5.0f, 0, &Button); Button.VSplitLeft(100.0f, &Text, &Button); char aBuf[32]; str_format(aBuf, sizeof(aBuf), "%s:", Localize("Anti Aliasing")); Text.y += 2.0f; UI()->DoLabel(&Text, aBuf, Text.h*ms_FontmodHeight*0.8f, -1); Button.VSplitLeft(70.0f, &Button, 0); str_format(aBuf, sizeof(aBuf), "%dx", g_Config.m_GfxFsaaSamples); static int s_ButtonGfxFsaaSamples = 0; if(DoButton_Menu(&s_ButtonGfxFsaaSamples, aBuf, 0, &Button)) { if(!g_Config.m_GfxFsaaSamples) g_Config.m_GfxFsaaSamples = 2; else if(g_Config.m_GfxFsaaSamples == 16) g_Config.m_GfxFsaaSamples = 0; else g_Config.m_GfxFsaaSamples *= 2; CheckSettings = true; } } // render texture menu Texture.HSplitTop(ButtonHeight, &Label, &Texture); Label.y += 2.0f; UI()->DoLabel(&Label, Localize("Texture"), ButtonHeight*ms_FontmodHeight*0.8f, 0); Texture.HSplitTop(Spacing, 0, &Texture); Texture.HSplitTop(ButtonHeight, &Button, &Texture); static int s_ButtonGfxTextureQuality = 0; if(DoButton_CheckBox(&s_ButtonGfxTextureQuality, Localize("Quality Textures"), g_Config.m_GfxTextureQuality, &Button)) { g_Config.m_GfxTextureQuality ^= 1; CheckSettings = true; } Texture.HSplitTop(Spacing, 0, &Texture); Texture.HSplitTop(ButtonHeight, &Button, &Texture); static int s_ButtonGfxTextureCompression = 0; if(DoButton_CheckBox(&s_ButtonGfxTextureCompression, Localize("Texture Compression"), g_Config.m_GfxTextureCompression, &Button)) { g_Config.m_GfxTextureCompression ^= 1; CheckSettings = true; } Texture.HSplitTop(Spacing, 0, &Texture); Texture.HSplitTop(ButtonHeight, &Button, &Texture); static int s_ButtonGfxHighDetail = 0; if(DoButton_CheckBox(&s_ButtonGfxHighDetail, Localize("High Detail"), g_Config.m_GfxHighDetail, &Button)) g_Config.m_GfxHighDetail ^= 1; // render screen modes MainView.HSplitTop(10.0f, 0, &MainView); // display mode list { // custom list header NumOptions = 2; CUIRect Header, Button; MainView.HSplitTop(ButtonHeight*(float)(NumOptions+1)+Spacing*(float)(NumOptions+1), &Header, 0); RenderTools()->DrawUIRect(&Header, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_T, 5.0f); // draw header MainView.HSplitTop(ButtonHeight, &Header, &MainView); Header.y += 2.0f; UI()->DoLabel(&Header, Localize("Resolutions"), Header.h*ms_FontmodHeight*0.8f, 0); // supported modes button MainView.HSplitTop(Spacing, 0, &MainView); MainView.HSplitTop(ButtonHeight, &Button, &MainView); static int s_GfxDisplayAllModes = 0; if(DoButton_CheckBox(&s_GfxDisplayAllModes, Localize("Show only supported"), g_Config.m_GfxDisplayAllModes^1, &Button)) { g_Config.m_GfxDisplayAllModes ^= 1; m_NumModes = Graphics()->GetVideoModes(m_aModes, MAX_RESOLUTIONS); UpdateVideoFormats(); bool Found = false; for(int i = 0; i < m_NumVideoFormats; i++) { int G = gcd(g_Config.m_GfxScreenWidth, g_Config.m_GfxScreenHeight); if(m_aVideoFormats[i].m_WidthValue == g_Config.m_GfxScreenWidth/G && m_aVideoFormats[i].m_HeightValue == g_Config.m_GfxScreenHeight/G) { m_CurrentVideoFormat = i; Found = true; break; } } if(!Found) m_CurrentVideoFormat = 0; UpdatedFilteredVideoModes(); } // format changer { MainView.HSplitTop(Spacing, 0, &MainView); MainView.HSplitTop(ButtonHeight, &Button, &MainView); RenderTools()->DrawUIRect(&Button, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f); CUIRect Text, Value, Unit; Button.VSplitLeft(Button.w/3.0f, &Text, &Button); Button.VSplitMid(&Value, &Unit); char aBuf[32]; str_format(aBuf, sizeof(aBuf), "%s:", Localize("Format")); Text.y += 2.0f; UI()->DoLabel(&Text, aBuf, Text.h*ms_FontmodHeight*0.8f, 0); Unit.y += 2.0f; if((float)m_aVideoFormats[m_CurrentVideoFormat].m_WidthValue/(float)m_aVideoFormats[m_CurrentVideoFormat].m_HeightValue >= 1.55f) UI()->DoLabel(&Unit, Localize("Wide"), Unit.h*ms_FontmodHeight*0.8f, 0); else UI()->DoLabel(&Unit, Localize("Letterbox"), Unit.h*ms_FontmodHeight*0.8f, 0); str_format(aBuf, sizeof(aBuf), "%d:%d", m_aVideoFormats[m_CurrentVideoFormat].m_WidthValue, m_aVideoFormats[m_CurrentVideoFormat].m_HeightValue); static int s_VideoFormatButton = 0; if(DoButton_Menu(&s_VideoFormatButton, aBuf, 0, &Value)) { m_CurrentVideoFormat++; if(m_CurrentVideoFormat == m_NumVideoFormats) m_CurrentVideoFormat = 0; UpdatedFilteredVideoModes(); } } MainView.HSplitTop(Spacing, 0, &MainView); static float s_ScrollValue = 0; static int s_DisplayModeList = 0; int OldSelected = -1; int G = gcd(s_GfxScreenWidth, s_GfxScreenHeight); str_format(aBuf, sizeof(aBuf), "%s: %dx%d (%d:%d)", Localize("Current"), s_GfxScreenWidth, s_GfxScreenHeight, s_GfxScreenWidth/G, s_GfxScreenHeight/G); UiDoListboxStart(&s_DisplayModeList, 20.0f, aBuf, m_lFilteredVideoModes.size(), 1, OldSelected, s_ScrollValue, &MainView); for(int i = 0; i < m_lFilteredVideoModes.size(); ++i) { if(g_Config.m_GfxScreenWidth == m_lFilteredVideoModes[i].m_Width && g_Config.m_GfxScreenHeight == m_lFilteredVideoModes[i].m_Height) { OldSelected = i; } CListboxItem Item = UiDoListboxNextItem(&m_lFilteredVideoModes[i], OldSelected == i); if(Item.m_Visible) { str_format(aBuf, sizeof(aBuf), " %dx%d", m_lFilteredVideoModes[i].m_Width, m_lFilteredVideoModes[i].m_Height); if(i == OldSelected) { TextRender()->TextColor(0.0f, 0.0f, 0.0f, 1.0f); TextRender()->TextOutlineColor(1.0f, 1.0f, 1.0f, 0.25f); Item.m_Rect.y += 2.0f; UI()->DoLabelScaled(&Item.m_Rect, aBuf, Item.m_Rect.h*ms_FontmodHeight*0.8f, 0); TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); TextRender()->TextOutlineColor(0.0f, 0.0f, 0.0f, 0.3f); } else { Item.m_Rect.y += 2.0f; UI()->DoLabelScaled(&Item.m_Rect, aBuf, Item.m_Rect.h*ms_FontmodHeight*0.8f, 0); } } } const int NewSelected = UiDoListboxEnd(&s_ScrollValue, 0); if(OldSelected != NewSelected) { g_Config.m_GfxScreenWidth = m_lFilteredVideoModes[NewSelected].m_Width; g_Config.m_GfxScreenHeight = m_lFilteredVideoModes[NewSelected].m_Height; CheckSettings = true; } } // reset button Spacing = 3.0f; float ButtonWidth = (BottomView.w/6.0f)-(Spacing*5.0)/6.0f; BottomView.VSplitRight(ButtonWidth, 0, &BottomView); RenderTools()->DrawUIRect4(&BottomView, vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.0f), CUI::CORNER_T, 5.0f); BottomView.HSplitTop(25.0f, &BottomView, 0); Button = BottomView; static int s_ResetButton=0; if(DoButton_Menu(&s_ResetButton, Localize("Reset"), 0, &Button)) { g_Config.m_GfxScreenWidth = Graphics()->GetDesktopScreenWidth(); g_Config.m_GfxScreenHeight = Graphics()->GetDesktopScreenHeight(); g_Config.m_GfxBorderless = 0; g_Config.m_GfxFullscreen = 1; g_Config.m_GfxVsync = 1; g_Config.m_GfxFsaaSamples = 0; g_Config.m_GfxTextureQuality = 1; g_Config.m_GfxTextureCompression = 0; g_Config.m_GfxHighDetail = 1; if(g_Config.m_GfxDisplayAllModes) { g_Config.m_GfxDisplayAllModes = 0; m_NumModes = Graphics()->GetVideoModes(m_aModes, MAX_RESOLUTIONS); UpdateVideoFormats(); bool Found = false; for(int i = 0; i < m_NumVideoFormats; i++) { int G = gcd(g_Config.m_GfxScreenWidth, g_Config.m_GfxScreenHeight); if(m_aVideoFormats[i].m_WidthValue == g_Config.m_GfxScreenWidth/G && m_aVideoFormats[i].m_HeightValue == g_Config.m_GfxScreenHeight/G) { m_CurrentVideoFormat = i; Found = true; break; } } if(!Found) m_CurrentVideoFormat = 0; UpdatedFilteredVideoModes(); } CheckSettings = true; } // check if the new settings require a restart if(CheckSettings) { if(s_GfxScreenWidth == g_Config.m_GfxScreenWidth && s_GfxScreenHeight == g_Config.m_GfxScreenHeight && s_GfxBorderless == g_Config.m_GfxBorderless && s_GfxFullscreen == g_Config.m_GfxFullscreen && s_GfxVsync == g_Config.m_GfxVsync && s_GfxFsaaSamples == g_Config.m_GfxFsaaSamples && s_GfxTextureQuality == g_Config.m_GfxTextureQuality && s_GfxTextureCompression == g_Config.m_GfxTextureCompression) m_NeedRestartGraphics = false; else m_NeedRestartGraphics = true; } } void CMenus::RenderSettingsSound(CUIRect MainView) { CUIRect Label, Button, Sound, Detail, BottomView; // render sound menu background int NumOptions = g_Config.m_SndEnable ? 3 : 1; float ButtonHeight = 20.0f; float Spacing = 2.0f; float BackgroundHeight = (float)(NumOptions+1)*ButtonHeight+(float)NumOptions*Spacing; MainView.HSplitTop(20.0f, 0, &MainView); MainView.HSplitTop(BackgroundHeight, &Sound, &MainView); RenderTools()->DrawUIRect(&Sound, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f); // render detail menu background if(g_Config.m_SndEnable) { BackgroundHeight = 2.0f*ButtonHeight+Spacing; MainView.HSplitTop(10.0f, 0, &MainView); MainView.HSplitTop(BackgroundHeight, &Detail, &MainView); RenderTools()->DrawUIRect(&Detail, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f); } static int s_SndEnable = g_Config.m_SndEnable; static int s_SndRate = g_Config.m_SndRate; // render sound menu Sound.HSplitTop(ButtonHeight, &Label, &Sound); Label.y += 2.0f; UI()->DoLabel(&Label, Localize("Sound"), ButtonHeight*ms_FontmodHeight*0.8f, 0); Sound.HSplitTop(Spacing, 0, &Sound); Sound.HSplitTop(ButtonHeight, &Button, &Sound); static int s_ButtonSndEnable = 0; if(DoButton_CheckBox(&s_ButtonSndEnable, Localize("Use sounds"), g_Config.m_SndEnable, &Button)) { g_Config.m_SndEnable ^= 1; if(g_Config.m_SndEnable) { if(g_Config.m_SndMusic) m_pClient->m_pSounds->Play(CSounds::CHN_MUSIC, SOUND_MENU, 1.0f); } else m_pClient->m_pSounds->Stop(SOUND_MENU); m_NeedRestartSound = g_Config.m_SndEnable && (!s_SndEnable || s_SndRate != g_Config.m_SndRate); } if(g_Config.m_SndEnable) { Sound.HSplitTop(Spacing, 0, &Sound); Sound.HSplitTop(ButtonHeight, &Button, &Sound); Button.VSplitLeft(ButtonHeight, 0, &Button); static int s_ButtonSndMusic = 0; if(DoButton_CheckBox(&s_ButtonSndMusic, Localize("Play background music"), g_Config.m_SndMusic, &Button)) { g_Config.m_SndMusic ^= 1; if(Client()->State() == IClient::STATE_OFFLINE) { if(g_Config.m_SndMusic) m_pClient->m_pSounds->Play(CSounds::CHN_MUSIC, SOUND_MENU, 1.0f); else m_pClient->m_pSounds->Stop(SOUND_MENU); } } Sound.HSplitTop(Spacing, 0, &Sound); Sound.HSplitTop(ButtonHeight, &Button, &Sound); Button.VSplitLeft(ButtonHeight, 0, &Button); static int s_ButtonSndNonactiveMute = 0; if(DoButton_CheckBox(&s_ButtonSndNonactiveMute, Localize("Mute when not active"), g_Config.m_SndNonactiveMute, &Button)) g_Config.m_SndNonactiveMute ^= 1; // render detail menu Detail.HSplitTop(ButtonHeight, &Label, &Detail); Label.y += 2.0f; UI()->DoLabel(&Label, Localize("Detail"), ButtonHeight*ms_FontmodHeight*0.8f, 0); // split menu CUIRect Left, Right; Detail.HSplitTop(Spacing, 0, &Detail); Detail.VSplitMid(&Left, &Right); Left.VSplitRight(1.5f, &Left, 0); Right.VSplitLeft(1.5f, 0, &Right); // sample rate thingy { Left.HSplitTop(ButtonHeight, &Button, &Left); RenderTools()->DrawUIRect(&Button, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_ALL, 5.0f); CUIRect Text, Value, Unit; Button.VSplitLeft(Button.w/3.0f, &Text, &Button); Button.VSplitMid(&Value, &Unit); char aBuf[32]; str_format(aBuf, sizeof(aBuf), "%s:", Localize("Sample rate")); Text.y += 2.0f; UI()->DoLabel(&Text, aBuf, Text.h*ms_FontmodHeight*0.8f, 0); Unit.y += 2.0f; UI()->DoLabel(&Unit, "kHz", Unit.h*ms_FontmodHeight*0.8f, 0); if(g_Config.m_SndRate != 48000 && g_Config.m_SndRate != 44100) g_Config.m_SndRate = 48000; if(g_Config.m_SndRate == 48000) str_copy(aBuf, "48.0", sizeof(aBuf)); else str_copy(aBuf, "44.1", sizeof(aBuf)); static int s_SampleRateButton = 0; if(DoButton_Menu(&s_SampleRateButton, aBuf, 0, &Value)) { if(g_Config.m_SndRate == 48000) g_Config.m_SndRate = 44100; else g_Config.m_SndRate = 48000; } m_NeedRestartSound = !s_SndEnable || s_SndRate != g_Config.m_SndRate; } Right.HSplitTop(ButtonHeight, &Button, &Right); DoScrollbarOption(&g_Config.m_SndVolume, &g_Config.m_SndVolume, &Button, Localize("Volume"), 110.0f, 0, 100); } // reset button MainView.HSplitBottom(60.0f, 0, &BottomView); Spacing = 3.0f; float ButtonWidth = (BottomView.w/6.0f)-(Spacing*5.0)/6.0f; BottomView.VSplitRight(ButtonWidth, 0, &BottomView); RenderTools()->DrawUIRect4(&BottomView, vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.0f), CUI::CORNER_T, 5.0f); BottomView.HSplitTop(25.0f, &BottomView, 0); Button = BottomView; static int s_ResetButton=0; if(DoButton_Menu(&s_ResetButton, Localize("Reset"), 0, &Button)) { g_Config.m_SndEnable = 1; if(!g_Config.m_SndMusic) { g_Config.m_SndMusic = 1; m_pClient->m_pSounds->Play(CSounds::CHN_MUSIC, SOUND_MENU, 1.0f); } g_Config.m_SndNonactiveMute = 0; g_Config.m_SndRate = 48000; g_Config.m_SndVolume = 100; } } void CMenus::RenderSettings(CUIRect MainView) { // handle which page should be rendered if(g_Config.m_UiSettingsPage == SETTINGS_GENERAL) RenderSettingsGeneral(MainView); else if(g_Config.m_UiSettingsPage == SETTINGS_PLAYER) RenderSettingsPlayer(MainView); else if(g_Config.m_UiSettingsPage == SETTINGS_TEE) RenderSettingsTee(MainView); else if(g_Config.m_UiSettingsPage == SETTINGS_CONTROLS) RenderSettingsControls(MainView); else if(g_Config.m_UiSettingsPage == SETTINGS_GRAPHICS) RenderSettingsGraphics(MainView); else if(g_Config.m_UiSettingsPage == SETTINGS_SOUND) RenderSettingsSound(MainView); MainView.HSplitBottom(60.0f, 0, &MainView); // reset warning if(m_NeedRestartGraphics || m_NeedRestartSound) { // background CUIRect RestartWarning; MainView.HSplitTop(25.0f, &RestartWarning, 0); RestartWarning.VMargin(140.0f, &RestartWarning); RenderTools()->DrawUIRect(&RestartWarning, vec4(1.0f, 1.0f, 1.0f, 0.25f), CUI::CORNER_ALL, 5.0f); // text TextRender()->TextColor(0.973f, 0.863f, 0.207, 1.0f); RestartWarning.y += 2.0f; UI()->DoLabel(&RestartWarning, Localize("You must restart the game for all settings to take effect."), RestartWarning.h*ms_FontmodHeight*0.75f, 0); TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); } RenderBackButton(MainView); } ================================================ FILE: src/game/client/components/menus_start.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <engine/graphics.h> #include <engine/textrender.h> #include <engine/shared/config.h> #include <game/version.h> #include <game/client/render.h> #include <game/client/ui.h> #include <game/generated/client_data.h> #include "menus.h" void CMenus::RenderStartMenu(CUIRect MainView) { CUIRect TopMenu, BottomMenu; MainView.VMargin(MainView.w/2-190.0f, &TopMenu); TopMenu.HSplitTop(365.0f, &TopMenu, &BottomMenu); //TopMenu.HSplitBottom(145.0f, &TopMenu, 0); RenderTools()->DrawUIRect4(&TopMenu, vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_B, 10.0f); TopMenu.HSplitTop(145.0f, 0, &TopMenu); CUIRect Button; TopMenu.HSplitBottom(40.0f, &TopMenu, &Button); static int s_SettingsButton = 0; if(g_Config.m_ClShowStartMenuImages) { if(DoButton_MenuImage(&s_SettingsButton, Localize("Settings"), 0, &Button, "settings", 10.0f, 0.5f)) { m_MenuPage = PAGE_SETTINGS; } } else { if(DoButton_Menu(&s_SettingsButton, Localize("Settings"), 0, &Button, CUI::CORNER_ALL, 10.0f, 0.5f)) { m_MenuPage = PAGE_SETTINGS; } } /*TopMenu.HSplitBottom(5.0f, &TopMenu, 0); // little space TopMenu.HSplitBottom(40.0f, &TopMenu, &Bottom); static int s_LocalServerButton = 0; if(g_Config.m_ClShowStartMenuImages) { if(DoButton_MenuImage(&s_LocalServerButton, Localize("Local server"), 0, &Button, "local_server", 10.0f, 0.5f)) { } } else { if(DoButton_Menu(&s_LocalServerButton, Localize("Local server"), 0, &Button, CUI::CORNER_ALL, 10.0f, 0.5f)) { } }*/ TopMenu.HSplitBottom(5.0f, &TopMenu, 0); // little space TopMenu.HSplitBottom(40.0f, &TopMenu, &Button); static int s_DemoButton = 0; if(g_Config.m_ClShowStartMenuImages) { if(DoButton_MenuImage(&s_DemoButton, Localize("Demos"), 0, &Button, "demos", 10.0f, 0.5f)) { m_MenuPage = PAGE_DEMOS; DemolistPopulate(); DemolistOnUpdate(false); } } else { if(DoButton_Menu(&s_DemoButton, Localize("Demos"), 0, &Button, CUI::CORNER_ALL, 10.0f, 0.5f)) { m_MenuPage = PAGE_DEMOS; DemolistPopulate(); DemolistOnUpdate(false); } } TopMenu.HSplitBottom(5.0f, &TopMenu, 0); // little space TopMenu.HSplitBottom(40.0f, &TopMenu, &Button); static int s_MapEditorButton = 0; if(g_Config.m_ClShowStartMenuImages) { if(DoButton_MenuImage(&s_MapEditorButton, Localize("Editor"), 0, &Button, "editor", 10.0f, 0.5f)) { g_Config.m_ClEditor = 1; Input()->MouseModeRelative(); } } else { if(DoButton_Menu(&s_MapEditorButton, Localize("Editor"), 0, &Button, CUI::CORNER_ALL, 10.0f, 0.5f)) { g_Config.m_ClEditor = 1; Input()->MouseModeRelative(); } } TopMenu.HSplitBottom(5.0f, &TopMenu, 0); // little space TopMenu.HSplitBottom(40.0f, &TopMenu, &Button); static int s_PlayButton = 0; if(g_Config.m_ClShowStartMenuImages) { if(DoButton_MenuImage(&s_PlayButton, Localize("Play"), 0, &Button, "play_game", 10.0f, 0.5f)) m_MenuPage = g_Config.m_UiBrowserPage; } else { if(DoButton_Menu(&s_PlayButton, Localize("Play"), 0, &Button, CUI::CORNER_ALL, 10.0f, 0.5f)) m_MenuPage = g_Config.m_UiBrowserPage; } BottomMenu.HSplitTop(90.0f, 0, &BottomMenu); RenderTools()->DrawUIRect4(&BottomMenu, vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.0f), CUI::CORNER_T, 10.0f); BottomMenu.HSplitTop(40.0f, &Button, &TopMenu); static int s_QuitButton = 0; if(DoButton_Menu(&s_QuitButton, Localize("Quit"), 0, &Button, CUI::CORNER_ALL, 10.0f, 0.5f)) m_Popup = POPUP_QUIT; // render version CUIRect Version; MainView.HSplitBottom(50.0f, 0, &Version); Version.VMargin(50.0f, &Version); char aBuf[64]; if(str_comp(Client()->LatestVersion(), "0") != 0) { str_format(aBuf, sizeof(aBuf), Localize("Teeworlds %s is out! Download it at www.teeworlds.com!"), Client()->LatestVersion()); TextRender()->TextColor(1.0f, 0.4f, 0.4f, 1.0f); UI()->DoLabelScaled(&Version, aBuf, 14.0f, 0); TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); } UI()->DoLabelScaled(&Version, GAME_VERSION, 14.0f, 1); } void CMenus::RenderLogo(CUIRect MainView) { // render cursor Graphics()->TextureSet(g_pData->m_aImages[IMAGE_BANNER].m_Id); Graphics()->QuadsBegin(); Graphics()->SetColor(1,1,1,1); IGraphics::CQuadItem QuadItem(MainView.w/2-140, 60, 280, 70); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); } ================================================ FILE: src/game/client/components/motd.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <engine/shared/config.h> #include <engine/graphics.h> #include <engine/textrender.h> #include <engine/keys.h> #include <game/generated/protocol.h> #include <game/generated/client_data.h> #include <game/client/gameclient.h> #include "motd.h" void CMotd::Clear() { m_ServerMotdTime = 0; } bool CMotd::IsActive() { return time_get() < m_ServerMotdTime; } void CMotd::OnStateChange(int NewState, int OldState) { if(OldState == IClient::STATE_ONLINE || OldState == IClient::STATE_OFFLINE) Clear(); } void CMotd::OnRender() { if(!IsActive()) return; float Width = 400*3.0f*Graphics()->ScreenAspect(); float Height = 400*3.0f; Graphics()->MapScreen(0, 0, Width, Height); float h = 800.0f; float w = 650.0f; float x = Width/2 - w/2; float y = 150.0f; Graphics()->BlendNormal(); Graphics()->TextureClear(); Graphics()->QuadsBegin(); Graphics()->SetColor(0,0,0,0.5f); RenderTools()->DrawRoundRect(x, y, w, h, 40.0f); Graphics()->QuadsEnd(); TextRender()->Text(0, x+40.0f, y+40.0f, 32.0f, m_aServerMotd, (int)(w-80.0f)); } void CMotd::OnMessage(int MsgType, void *pRawMsg) { if(Client()->State() == IClient::STATE_DEMOPLAYBACK) return; if(MsgType == NETMSGTYPE_SV_MOTD) { CNetMsg_Sv_Motd *pMsg = (CNetMsg_Sv_Motd *)pRawMsg; // process escaping str_copy(m_aServerMotd, pMsg->m_pMessage, sizeof(m_aServerMotd)); for(int i = 0; m_aServerMotd[i]; i++) { if(m_aServerMotd[i] == '\\') { if(m_aServerMotd[i+1] == 'n') { m_aServerMotd[i] = ' '; m_aServerMotd[i+1] = '\n'; i++; } } } if(m_aServerMotd[0] && g_Config.m_ClMotdTime) m_ServerMotdTime = time_get()+time_freq()*g_Config.m_ClMotdTime; else m_ServerMotdTime = 0; } } bool CMotd::OnInput(IInput::CEvent Event) { if(IsActive() && Event.m_Flags&IInput::FLAG_PRESS && Event.m_Key == KEY_ESCAPE) { Clear(); return true; } return false; } ================================================ FILE: src/game/client/components/motd.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_CLIENT_COMPONENTS_MOTD_H #define GAME_CLIENT_COMPONENTS_MOTD_H #include <game/client/component.h> class CMotd : public CComponent { // motd int64 m_ServerMotdTime; public: char m_aServerMotd[900]; void Clear(); bool IsActive(); virtual void OnRender(); virtual void OnStateChange(int NewState, int OldState); virtual void OnMessage(int MsgType, void *pRawMsg); virtual bool OnInput(IInput::CEvent Event); }; #endif ================================================ FILE: src/game/client/components/nameplates.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <engine/textrender.h> #include <engine/shared/config.h> #include <game/generated/protocol.h> #include <game/generated/client_data.h> #include <game/client/gameclient.h> #include <game/client/animstate.h> #include "nameplates.h" #include "controls.h" void CNamePlates::RenderNameplate( const CNetObj_Character *pPrevChar, const CNetObj_Character *pPlayerChar, const CNetObj_PlayerInfo *pPlayerInfo, int ClientID ) { float IntraTick = Client()->IntraGameTick(); vec2 Position = mix(vec2(pPrevChar->m_X, pPrevChar->m_Y), vec2(pPlayerChar->m_X, pPlayerChar->m_Y), IntraTick); float FontSize = 18.0f + 20.0f * g_Config.m_ClNameplatesSize / 100.0f; // render name plate if(m_pClient->m_LocalClientID != ClientID) { float a = 1; if(g_Config.m_ClNameplatesAlways == 0) a = clamp(1-powf(distance(m_pClient->m_pControls->m_TargetPos, Position)/200.0f,16.0f), 0.0f, 1.0f); const char *pName = m_pClient->m_aClients[ClientID].m_aName; float tw = TextRender()->TextWidth(0, FontSize, pName, -1); TextRender()->TextOutlineColor(0.0f, 0.0f, 0.0f, 0.5f*a); TextRender()->TextColor(1.0f, 1.0f, 1.0f, a); if(g_Config.m_ClNameplatesTeamcolors && m_pClient->m_GameInfo.m_GameFlags&GAMEFLAG_TEAMS) { if(m_pClient->m_aClients[ClientID].m_Team == TEAM_RED) TextRender()->TextColor(1.0f, 0.5f, 0.5f, a); else if(m_pClient->m_aClients[ClientID].m_Team == TEAM_BLUE) TextRender()->TextColor(0.7f, 0.7f, 1.0f, a); } TextRender()->Text(0, Position.x-tw/2.0f, Position.y-FontSize-38.0f, FontSize, pName, -1); if(g_Config.m_Debug) // render client id when in debug aswell { char aBuf[128]; str_format(aBuf, sizeof(aBuf),"%d", ClientID); TextRender()->Text(0, Position.x, Position.y-90, 28.0f, aBuf, -1); } TextRender()->TextColor(1,1,1,1); TextRender()->TextOutlineColor(0.0f, 0.0f, 0.0f, 0.3f); } } void CNamePlates::OnRender() { if (!g_Config.m_ClNameplates) return; for(int i = 0; i < MAX_CLIENTS; i++) { // only render active characters if(!m_pClient->m_Snap.m_aCharacters[i].m_Active) continue; const void *pInfo = Client()->SnapFindItem(IClient::SNAP_CURRENT, NETOBJTYPE_PLAYERINFO, i); if(pInfo) { RenderNameplate( &m_pClient->m_Snap.m_aCharacters[i].m_Prev, &m_pClient->m_Snap.m_aCharacters[i].m_Cur, (const CNetObj_PlayerInfo *)pInfo, i); } } } ================================================ FILE: src/game/client/components/nameplates.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_CLIENT_COMPONENTS_NAMEPLATES_H #define GAME_CLIENT_COMPONENTS_NAMEPLATES_H #include <game/client/component.h> class CNamePlates : public CComponent { void RenderNameplate( const CNetObj_Character *pPrevChar, const CNetObj_Character *pPlayerChar, const CNetObj_PlayerInfo *pPlayerInfo, int ClientID ); public: virtual void OnRender(); }; #endif ================================================ FILE: src/game/client/components/particles.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <base/math.h> #include <engine/graphics.h> #include <engine/demo.h> #include <game/generated/client_data.h> #include <game/client/render.h> #include <game/gamecore.h> #include "particles.h" CParticles::CParticles() { OnReset(); m_RenderTrail.m_pParts = this; m_RenderExplosions.m_pParts = this; m_RenderGeneral.m_pParts = this; } void CParticles::OnReset() { // reset particles for(int i = 0; i < MAX_PARTICLES; i++) { m_aParticles[i].m_PrevPart = i-1; m_aParticles[i].m_NextPart = i+1; } m_aParticles[0].m_PrevPart = 0; m_aParticles[MAX_PARTICLES-1].m_NextPart = -1; m_FirstFree = 0; for(int i = 0; i < NUM_GROUPS; i++) m_aFirstPart[i] = -1; } void CParticles::Add(int Group, CParticle *pPart) { if(Client()->State() == IClient::STATE_DEMOPLAYBACK) { const IDemoPlayer::CInfo *pInfo = DemoPlayer()->BaseInfo(); if(pInfo->m_Paused) return; } else { if(m_pClient->m_Snap.m_pGameData && m_pClient->m_Snap.m_pGameData->m_GameStateFlags&GAMESTATEFLAG_PAUSED) return; } if (m_FirstFree == -1) return; // remove from the free list int Id = m_FirstFree; m_FirstFree = m_aParticles[Id].m_NextPart; if(m_FirstFree != -1) m_aParticles[m_FirstFree].m_PrevPart = -1; // copy data m_aParticles[Id] = *pPart; // insert to the group list m_aParticles[Id].m_PrevPart = -1; m_aParticles[Id].m_NextPart = m_aFirstPart[Group]; if(m_aFirstPart[Group] != -1) m_aParticles[m_aFirstPart[Group]].m_PrevPart = Id; m_aFirstPart[Group] = Id; // set some parameters m_aParticles[Id].m_Life = 0; } void CParticles::Update(float TimePassed) { static float FrictionFraction = 0; FrictionFraction += TimePassed; if(FrictionFraction > 2.0f) // safty messure FrictionFraction = 0; int FrictionCount = 0; while(FrictionFraction > 0.05f) { FrictionCount++; FrictionFraction -= 0.05f; } for(int g = 0; g < NUM_GROUPS; g++) { int i = m_aFirstPart[g]; while(i != -1) { int Next = m_aParticles[i].m_NextPart; //m_aParticles[i].vel += flow_get(m_aParticles[i].pos)*time_passed * m_aParticles[i].flow_affected; m_aParticles[i].m_Vel.y += m_aParticles[i].m_Gravity*TimePassed; for(int f = 0; f < FrictionCount; f++) // apply friction m_aParticles[i].m_Vel *= m_aParticles[i].m_Friction; // move the point vec2 Vel = m_aParticles[i].m_Vel*TimePassed; Collision()->MovePoint(&m_aParticles[i].m_Pos, &Vel, 0.1f+0.9f*frandom(), NULL); m_aParticles[i].m_Vel = Vel* (1.0f/TimePassed); m_aParticles[i].m_Life += TimePassed; m_aParticles[i].m_Rot += TimePassed * m_aParticles[i].m_Rotspeed; // check particle death if(m_aParticles[i].m_Life > m_aParticles[i].m_LifeSpan) { // remove it from the group list if(m_aParticles[i].m_PrevPart != -1) m_aParticles[m_aParticles[i].m_PrevPart].m_NextPart = m_aParticles[i].m_NextPart; else m_aFirstPart[g] = m_aParticles[i].m_NextPart; if(m_aParticles[i].m_NextPart != -1) m_aParticles[m_aParticles[i].m_NextPart].m_PrevPart = m_aParticles[i].m_PrevPart; // insert to the free list if(m_FirstFree != -1) m_aParticles[m_FirstFree].m_PrevPart = i; m_aParticles[i].m_PrevPart = -1; m_aParticles[i].m_NextPart = m_FirstFree; m_FirstFree = i; } i = Next; } } } void CParticles::OnRender() { if(Client()->State() < IClient::STATE_ONLINE) return; static int64 LastTime = 0; int64 t = time_get(); if(Client()->State() == IClient::STATE_DEMOPLAYBACK) { const IDemoPlayer::CInfo *pInfo = DemoPlayer()->BaseInfo(); if(!pInfo->m_Paused) Update((float)((t-LastTime)/(double)time_freq())*pInfo->m_Speed); } else { if(m_pClient->m_Snap.m_pGameData && !(m_pClient->m_Snap.m_pGameData->m_GameStateFlags&GAMESTATEFLAG_PAUSED)) Update((float)((t-LastTime)/(double)time_freq())); } LastTime = t; } void CParticles::RenderGroup(int Group) { Graphics()->BlendNormal(); //gfx_blend_additive(); Graphics()->TextureSet(g_pData->m_aImages[IMAGE_PARTICLES].m_Id); Graphics()->QuadsBegin(); int i = m_aFirstPart[Group]; while(i != -1) { RenderTools()->SelectSprite(m_aParticles[i].m_Spr); float a = m_aParticles[i].m_Life / m_aParticles[i].m_LifeSpan; vec2 p = m_aParticles[i].m_Pos; float Size = mix(m_aParticles[i].m_StartSize, m_aParticles[i].m_EndSize, a); Graphics()->QuadsSetRotation(m_aParticles[i].m_Rot); Graphics()->SetColor( m_aParticles[i].m_Color.r, m_aParticles[i].m_Color.g, m_aParticles[i].m_Color.b, m_aParticles[i].m_Color.a); // pow(a, 0.75f) * IGraphics::CQuadItem QuadItem(p.x, p.y, Size, Size); Graphics()->QuadsDraw(&QuadItem, 1); i = m_aParticles[i].m_NextPart; } Graphics()->QuadsEnd(); Graphics()->BlendNormal(); } ================================================ FILE: src/game/client/components/particles.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_CLIENT_COMPONENTS_PARTICLES_H #define GAME_CLIENT_COMPONENTS_PARTICLES_H #include <base/vmath.h> #include <game/client/component.h> // particles struct CParticle { void SetDefault() { m_Vel = vec2(0,0); m_LifeSpan = 0; m_StartSize = 32; m_EndSize = 32; m_Rot = 0; m_Rotspeed = 0; m_Gravity = 0; m_Friction = 0; m_FlowAffected = 1.0f; m_Color = vec4(1,1,1,1); } vec2 m_Pos; vec2 m_Vel; int m_Spr; float m_FlowAffected; float m_LifeSpan; float m_StartSize; float m_EndSize; float m_Rot; float m_Rotspeed; float m_Gravity; float m_Friction; vec4 m_Color; // set by the particle system float m_Life; int m_PrevPart; int m_NextPart; }; class CParticles : public CComponent { friend class CGameClient; public: enum { GROUP_PROJECTILE_TRAIL=0, GROUP_EXPLOSIONS, GROUP_GENERAL, NUM_GROUPS }; CParticles(); void Add(int Group, CParticle *pPart); virtual void OnReset(); virtual void OnRender(); private: enum { MAX_PARTICLES=1024*8, }; CParticle m_aParticles[MAX_PARTICLES]; int m_FirstFree; int m_aFirstPart[NUM_GROUPS]; void RenderGroup(int Group); void Update(float TimePassed); template<int TGROUP> class CRenderGroup : public CComponent { public: CParticles *m_pParts; virtual void OnRender() { m_pParts->RenderGroup(TGROUP); } }; CRenderGroup<GROUP_PROJECTILE_TRAIL> m_RenderTrail; CRenderGroup<GROUP_EXPLOSIONS> m_RenderExplosions; CRenderGroup<GROUP_GENERAL> m_RenderGeneral; }; #endif ================================================ FILE: src/game/client/components/players.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <engine/demo.h> #include <engine/engine.h> #include <engine/graphics.h> #include <engine/shared/config.h> #include <game/generated/protocol.h> #include <game/generated/client_data.h> #include <game/gamecore.h> // get_angle #include <game/client/animstate.h> #include <game/client/gameclient.h> #include <game/client/ui.h> #include <game/client/render.h> #include <game/client/components/flow.h> #include <game/client/components/skins.h> #include <game/client/components/effects.h> #include <game/client/components/sounds.h> #include <game/client/components/controls.h> #include "players.h" void CPlayers::RenderHand(CTeeRenderInfo *pInfo, vec2 CenterPos, vec2 Dir, float AngleOffset, vec2 PostRotOffset) { // for drawing hand //const skin *s = skin_get(skin_id); float BaseSize = 15.0f; //dir = normalize(hook_pos-pos); vec2 HandPos = CenterPos + Dir; float Angle = GetAngle(Dir); if (Dir.x < 0) Angle -= AngleOffset; else Angle += AngleOffset; vec2 DirX = Dir; vec2 DirY(-Dir.y,Dir.x); if (Dir.x < 0) DirY = -DirY; HandPos += DirX * PostRotOffset.x; HandPos += DirY * PostRotOffset.y; //Graphics()->TextureSet(data->m_aImages[IMAGE_CHAR_DEFAULT].id); Graphics()->TextureSet(pInfo->m_aTextures[CSkins::SKINPART_HANDS]); Graphics()->QuadsBegin(); vec4 Color = pInfo->m_aColors[CSkins::SKINPART_HANDS]; Graphics()->SetColor(Color.r, Color.g, Color.b, Color.a); // two passes for (int i = 0; i < 2; i++) { bool OutLine = i == 0; RenderTools()->SelectSprite(OutLine?SPRITE_TEE_HAND_OUTLINE:SPRITE_TEE_HAND, 0, 0, 0); Graphics()->QuadsSetRotation(Angle); IGraphics::CQuadItem QuadItem(HandPos.x, HandPos.y, 2*BaseSize, 2*BaseSize); Graphics()->QuadsDraw(&QuadItem, 1); } Graphics()->QuadsSetRotation(0); Graphics()->QuadsEnd(); } inline float NormalizeAngular(float f) { return fmod(f+pi*2, pi*2); } inline float AngularMixDirection (float Src, float Dst) { return sinf(Dst-Src) >0?1:-1; } inline float AngularDistance(float Src, float Dst) { return asinf(sinf(Dst-Src)); } inline float AngularApproach(float Src, float Dst, float Amount) { float d = AngularMixDirection (Src, Dst); float n = Src + Amount*d; if(AngularMixDirection (n, Dst) != d) return Dst; return n; } void CPlayers::RenderHook( const CNetObj_Character *pPrevChar, const CNetObj_Character *pPlayerChar, const CNetObj_PlayerInfo *pPrevInfo, const CNetObj_PlayerInfo *pPlayerInfo, int ClientID ) { CNetObj_Character Prev; CNetObj_Character Player; Prev = *pPrevChar; Player = *pPlayerChar; CTeeRenderInfo RenderInfo = m_aRenderInfo[ClientID]; float IntraTick = Client()->IntraGameTick(); // set size RenderInfo.m_Size = 64.0f; // use preditect players if needed if(m_pClient->m_LocalClientID == ClientID && g_Config.m_ClPredict && Client()->State() != IClient::STATE_DEMOPLAYBACK) { if(!m_pClient->m_Snap.m_pLocalCharacter || (m_pClient->m_Snap.m_pGameData && m_pClient->m_Snap.m_pGameData->m_GameStateFlags&(GAMESTATEFLAG_PAUSED|GAMESTATEFLAG_ROUNDOVER|GAMESTATEFLAG_GAMEOVER))) { } else { // apply predicted results m_pClient->m_PredictedChar.Write(&Player); m_pClient->m_PredictedPrevChar.Write(&Prev); IntraTick = Client()->PredIntraGameTick(); } } vec2 Position = mix(vec2(Prev.m_X, Prev.m_Y), vec2(Player.m_X, Player.m_Y), IntraTick); // draw hook if (Prev.m_HookState>0 && Player.m_HookState>0) { Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id); Graphics()->QuadsBegin(); //Graphics()->QuadsBegin(); vec2 Pos = Position; vec2 HookPos; if(pPlayerChar->m_HookedPlayer != -1) { if(m_pClient->m_LocalClientID != -1 && pPlayerChar->m_HookedPlayer == m_pClient->m_LocalClientID) { if(Client()->State() == IClient::STATE_DEMOPLAYBACK) // only use prediction if needed HookPos = vec2(m_pClient->m_LocalCharacterPos.x, m_pClient->m_LocalCharacterPos.y); else HookPos = mix(vec2(m_pClient->m_PredictedPrevChar.m_Pos.x, m_pClient->m_PredictedPrevChar.m_Pos.y), vec2(m_pClient->m_PredictedChar.m_Pos.x, m_pClient->m_PredictedChar.m_Pos.y), Client()->PredIntraGameTick()); } else if(m_pClient->m_LocalClientID == ClientID) { HookPos = mix(vec2(m_pClient->m_Snap.m_aCharacters[pPlayerChar->m_HookedPlayer].m_Prev.m_X, m_pClient->m_Snap.m_aCharacters[pPlayerChar->m_HookedPlayer].m_Prev.m_Y), vec2(m_pClient->m_Snap.m_aCharacters[pPlayerChar->m_HookedPlayer].m_Cur.m_X, m_pClient->m_Snap.m_aCharacters[pPlayerChar->m_HookedPlayer].m_Cur.m_Y), Client()->IntraGameTick()); } else HookPos = mix(vec2(pPrevChar->m_HookX, pPrevChar->m_HookY), vec2(pPlayerChar->m_HookX, pPlayerChar->m_HookY), Client()->IntraGameTick()); } else HookPos = mix(vec2(Prev.m_HookX, Prev.m_HookY), vec2(Player.m_HookX, Player.m_HookY), IntraTick); float d = distance(Pos, HookPos); vec2 Dir = normalize(Pos-HookPos); Graphics()->QuadsSetRotation(GetAngle(Dir)+pi); // render head RenderTools()->SelectSprite(SPRITE_HOOK_HEAD); IGraphics::CQuadItem QuadItem(HookPos.x, HookPos.y, 24,16); Graphics()->QuadsDraw(&QuadItem, 1); // render chain RenderTools()->SelectSprite(SPRITE_HOOK_CHAIN); IGraphics::CQuadItem Array[1024]; int i = 0; for(float f = 24; f < d && i < 1024; f += 24, i++) { vec2 p = HookPos + Dir*f; Array[i] = IGraphics::CQuadItem(p.x, p.y,24,16); } Graphics()->QuadsDraw(Array, i); Graphics()->QuadsSetRotation(0); Graphics()->QuadsEnd(); RenderHand(&RenderInfo, Position, normalize(HookPos-Pos), -pi/2, vec2(20, 0)); } } void CPlayers::RenderPlayer( const CNetObj_Character *pPrevChar, const CNetObj_Character *pPlayerChar, const CNetObj_PlayerInfo *pPrevInfo, const CNetObj_PlayerInfo *pPlayerInfo, int ClientID ) { CNetObj_Character Prev; CNetObj_Character Player; Prev = *pPrevChar; Player = *pPlayerChar; CNetObj_PlayerInfo pInfo = *pPlayerInfo; CTeeRenderInfo RenderInfo = m_aRenderInfo[ClientID]; // set size RenderInfo.m_Size = 64.0f; float IntraTick = Client()->IntraGameTick(); float Angle = mix((float)Prev.m_Angle, (float)Player.m_Angle, IntraTick)/256.0f; //float angle = 0; if(m_pClient->m_LocalClientID == ClientID && Client()->State() != IClient::STATE_DEMOPLAYBACK) { // just use the direct input if it's local player we are rendering Angle = GetAngle(m_pClient->m_pControls->m_MousePos); } else { /* float mixspeed = Client()->FrameTime()*2.5f; if(player.attacktick != prev.attacktick) // shooting boosts the mixing speed mixspeed *= 15.0f; // move the delta on a constant speed on a x^2 curve float current = g_GameClient.m_aClients[info.cid].angle; float target = player.angle/256.0f; float delta = angular_distance(current, target); float sign = delta < 0 ? -1 : 1; float new_delta = delta - 2*mixspeed*sqrt(delta*sign)*sign + mixspeed*mixspeed; // make sure that it doesn't vibrate when it's still if(fabs(delta) < 2/256.0f) angle = target; else angle = angular_approach(current, target, fabs(delta-new_delta)); g_GameClient.m_aClients[info.cid].angle = angle;*/ } // use preditect players if needed if(m_pClient->m_LocalClientID == ClientID && g_Config.m_ClPredict && Client()->State() != IClient::STATE_DEMOPLAYBACK) { if(!m_pClient->m_Snap.m_pLocalCharacter || (m_pClient->m_Snap.m_pGameData && m_pClient->m_Snap.m_pGameData->m_GameStateFlags&(GAMESTATEFLAG_PAUSED|GAMESTATEFLAG_ROUNDOVER|GAMESTATEFLAG_GAMEOVER))) { } else { // apply predicted results m_pClient->m_PredictedChar.Write(&Player); m_pClient->m_PredictedPrevChar.Write(&Prev); IntraTick = Client()->PredIntraGameTick(); } } vec2 Direction = GetDirection((int)(Angle*256.0f)); vec2 Position = mix(vec2(Prev.m_X, Prev.m_Y), vec2(Player.m_X, Player.m_Y), IntraTick); vec2 Vel = mix(vec2(Prev.m_VelX/256.0f, Prev.m_VelY/256.0f), vec2(Player.m_VelX/256.0f, Player.m_VelY/256.0f), IntraTick); m_pClient->m_pFlow->Add(Position, Vel*100.0f, 10.0f); RenderInfo.m_GotAirJump = Player.m_Jumped&2?0:1; bool Stationary = Player.m_VelX <= 1 && Player.m_VelX >= -1; bool InAir = !Collision()->CheckPoint(Player.m_X, Player.m_Y+16); bool WantOtherDir = (Player.m_Direction == -1 && Vel.x > 0) || (Player.m_Direction == 1 && Vel.x < 0); // evaluate animation float WalkTime = fmod(absolute(Position.x), 100.0f)/100.0f; CAnimState State; State.Set(&g_pData->m_aAnimations[ANIM_BASE], 0); if(InAir) State.Add(&g_pData->m_aAnimations[ANIM_INAIR], 0, 1.0f); // TODO: some sort of time here else if(Stationary) State.Add(&g_pData->m_aAnimations[ANIM_IDLE], 0, 1.0f); // TODO: some sort of time here else if(!WantOtherDir) State.Add(&g_pData->m_aAnimations[ANIM_WALK], WalkTime, 1.0f); static float s_LastGameTickTime = Client()->GameTickTime(); if(m_pClient->m_Snap.m_pGameData && !(m_pClient->m_Snap.m_pGameData->m_GameStateFlags&GAMESTATEFLAG_PAUSED)) s_LastGameTickTime = Client()->GameTickTime(); if (Player.m_Weapon == WEAPON_HAMMER) { float ct = (Client()->PrevGameTick()-Player.m_AttackTick)/(float)SERVER_TICK_SPEED + s_LastGameTickTime; State.Add(&g_pData->m_aAnimations[ANIM_HAMMER_SWING], clamp(ct*5.0f,0.0f,1.0f), 1.0f); } if (Player.m_Weapon == WEAPON_NINJA) { float ct = (Client()->PrevGameTick()-Player.m_AttackTick)/(float)SERVER_TICK_SPEED + s_LastGameTickTime; State.Add(&g_pData->m_aAnimations[ANIM_NINJA_SWING], clamp(ct*2.0f,0.0f,1.0f), 1.0f); } // do skidding if(!InAir && WantOtherDir && length(Vel*50) > 500.0f) { static int64 SkidSoundTime = 0; if(time_get()-SkidSoundTime > time_freq()/10) { m_pClient->m_pSounds->PlayAt(CSounds::CHN_WORLD, SOUND_PLAYER_SKID, 0.25f, Position); SkidSoundTime = time_get(); } m_pClient->m_pEffects->SkidTrail( Position+vec2(-Player.m_Direction*6,12), vec2(-Player.m_Direction*100*length(Vel),-50) ); } // draw gun { Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id); Graphics()->QuadsBegin(); Graphics()->QuadsSetRotation(State.GetAttach()->m_Angle*pi*2+Angle); // normal weapons int iw = clamp(Player.m_Weapon, 0, NUM_WEAPONS-1); RenderTools()->SelectSprite(g_pData->m_Weapons.m_aId[iw].m_pSpriteBody, Direction.x < 0 ? SPRITE_FLAG_FLIP_Y : 0); vec2 Dir = Direction; float Recoil = 0.0f; vec2 p; if (Player.m_Weapon == WEAPON_HAMMER) { // Static position for hammer p = Position + vec2(State.GetAttach()->m_X, State.GetAttach()->m_Y); p.y += g_pData->m_Weapons.m_aId[iw].m_Offsety; // if attack is under way, bash stuffs if(Direction.x < 0) { Graphics()->QuadsSetRotation(-pi/2-State.GetAttach()->m_Angle*pi*2); p.x -= g_pData->m_Weapons.m_aId[iw].m_Offsetx; } else { Graphics()->QuadsSetRotation(-pi/2+State.GetAttach()->m_Angle*pi*2); } RenderTools()->DrawSprite(p.x, p.y, g_pData->m_Weapons.m_aId[iw].m_VisualSize); } else if (Player.m_Weapon == WEAPON_NINJA) { p = Position; p.y += g_pData->m_Weapons.m_aId[iw].m_Offsety; if(Direction.x < 0) { Graphics()->QuadsSetRotation(-pi/2-State.GetAttach()->m_Angle*pi*2); p.x -= g_pData->m_Weapons.m_aId[iw].m_Offsetx; m_pClient->m_pEffects->PowerupShine(p+vec2(32,0), vec2(32,12)); } else { Graphics()->QuadsSetRotation(-pi/2+State.GetAttach()->m_Angle*pi*2); m_pClient->m_pEffects->PowerupShine(p-vec2(32,0), vec2(32,12)); } RenderTools()->DrawSprite(p.x, p.y, g_pData->m_Weapons.m_aId[iw].m_VisualSize); // HADOKEN if ((Client()->GameTick()-Player.m_AttackTick) <= (SERVER_TICK_SPEED / 6) && g_pData->m_Weapons.m_aId[iw].m_NumSpriteMuzzles) { int IteX = rand() % g_pData->m_Weapons.m_aId[iw].m_NumSpriteMuzzles; static int s_LastIteX = IteX; if(Client()->State() == IClient::STATE_DEMOPLAYBACK) { const IDemoPlayer::CInfo *pInfo = DemoPlayer()->BaseInfo(); if(pInfo->m_Paused) IteX = s_LastIteX; else s_LastIteX = IteX; } else { if(m_pClient->m_Snap.m_pGameData && m_pClient->m_Snap.m_pGameData->m_GameStateFlags&GAMESTATEFLAG_PAUSED) IteX = s_LastIteX; else s_LastIteX = IteX; } if(g_pData->m_Weapons.m_aId[iw].m_aSpriteMuzzles[IteX]) { vec2 Dir = vec2(pPlayerChar->m_X,pPlayerChar->m_Y) - vec2(pPrevChar->m_X, pPrevChar->m_Y); Dir = normalize(Dir); float HadOkenAngle = GetAngle(Dir); Graphics()->QuadsSetRotation(HadOkenAngle ); //float offsety = -data->weapons[iw].muzzleoffsety; RenderTools()->SelectSprite(g_pData->m_Weapons.m_aId[iw].m_aSpriteMuzzles[IteX], 0); vec2 DirY(-Dir.y,Dir.x); p = Position; float OffsetX = g_pData->m_Weapons.m_aId[iw].m_Muzzleoffsetx; p -= Dir * OffsetX; RenderTools()->DrawSprite(p.x, p.y, 160.0f); } } } else { // TODO: should be an animation Recoil = 0; static float s_LastIntraTick = IntraTick; if(m_pClient->m_Snap.m_pGameData && !(m_pClient->m_Snap.m_pGameData->m_GameStateFlags&GAMESTATEFLAG_PAUSED)) s_LastIntraTick = IntraTick; float a = (Client()->GameTick()-Player.m_AttackTick+s_LastIntraTick)/5.0f; if(a < 1) Recoil = sinf(a*pi); p = Position + Dir * g_pData->m_Weapons.m_aId[iw].m_Offsetx - Dir*Recoil*10.0f; p.y += g_pData->m_Weapons.m_aId[iw].m_Offsety; RenderTools()->DrawSprite(p.x, p.y, g_pData->m_Weapons.m_aId[iw].m_VisualSize); } if (Player.m_Weapon == WEAPON_GUN || Player.m_Weapon == WEAPON_SHOTGUN) { // check if we're firing stuff if(g_pData->m_Weapons.m_aId[iw].m_NumSpriteMuzzles)//prev.attackticks) { float Alpha = 0.0f; int Phase1Tick = (Client()->GameTick() - Player.m_AttackTick); if (Phase1Tick < (g_pData->m_Weapons.m_aId[iw].m_Muzzleduration + 3)) { float t = ((((float)Phase1Tick) + IntraTick)/(float)g_pData->m_Weapons.m_aId[iw].m_Muzzleduration); Alpha = mix(2.0f, 0.0f, min(1.0f,max(0.0f,t))); } int IteX = rand() % g_pData->m_Weapons.m_aId[iw].m_NumSpriteMuzzles; static int s_LastIteX = IteX; if(Client()->State() == IClient::STATE_DEMOPLAYBACK) { const IDemoPlayer::CInfo *pInfo = DemoPlayer()->BaseInfo(); if(pInfo->m_Paused) IteX = s_LastIteX; else s_LastIteX = IteX; } else { if(m_pClient->m_Snap.m_pGameData && m_pClient->m_Snap.m_pGameData->m_GameStateFlags&GAMESTATEFLAG_PAUSED) IteX = s_LastIteX; else s_LastIteX = IteX; } if (Alpha > 0.0f && g_pData->m_Weapons.m_aId[iw].m_aSpriteMuzzles[IteX]) { float OffsetY = -g_pData->m_Weapons.m_aId[iw].m_Muzzleoffsety; RenderTools()->SelectSprite(g_pData->m_Weapons.m_aId[iw].m_aSpriteMuzzles[IteX], Direction.x < 0 ? SPRITE_FLAG_FLIP_Y : 0); if(Direction.x < 0) OffsetY = -OffsetY; vec2 DirY(-Dir.y,Dir.x); vec2 MuzzlePos = p + Dir * g_pData->m_Weapons.m_aId[iw].m_Muzzleoffsetx + DirY * OffsetY; RenderTools()->DrawSprite(MuzzlePos.x, MuzzlePos.y, g_pData->m_Weapons.m_aId[iw].m_VisualSize); } } } Graphics()->QuadsEnd(); switch (Player.m_Weapon) { case WEAPON_GUN: RenderHand(&RenderInfo, p, Direction, -3*pi/4, vec2(-15, 4)); break; case WEAPON_SHOTGUN: RenderHand(&RenderInfo, p, Direction, -pi/2, vec2(-5, 4)); break; case WEAPON_GRENADE: RenderHand(&RenderInfo, p, Direction, -pi/2, vec2(-4, 7)); break; } } // render the "shadow" tee if(m_pClient->m_LocalClientID == ClientID && g_Config.m_Debug) { vec2 GhostPosition = mix(vec2(pPrevChar->m_X, pPrevChar->m_Y), vec2(pPlayerChar->m_X, pPlayerChar->m_Y), Client()->IntraGameTick()); CTeeRenderInfo Ghost = RenderInfo; for(int p = 0; p < CSkins::NUM_SKINPARTS; p++) Ghost.m_aColors[p].a *= 0.5f; RenderTools()->RenderTee(&State, &Ghost, Player.m_Emote, Direction, GhostPosition); // render ghost } RenderTools()->RenderTee(&State, &RenderInfo, Player.m_Emote, Direction, Position); if(pInfo.m_PlayerFlags&PLAYERFLAG_CHATTING) { Graphics()->TextureSet(g_pData->m_aImages[IMAGE_EMOTICONS].m_Id); Graphics()->QuadsBegin(); RenderTools()->SelectSprite(SPRITE_DOTDOT); IGraphics::CQuadItem QuadItem(Position.x + 24, Position.y - 40, 64,64); Graphics()->QuadsDraw(&QuadItem, 1); Graphics()->QuadsEnd(); } if (m_pClient->m_aClients[ClientID].m_EmoticonStart != -1 && m_pClient->m_aClients[ClientID].m_EmoticonStart + 2 * Client()->GameTickSpeed() > Client()->GameTick()) { Graphics()->TextureSet(g_pData->m_aImages[IMAGE_EMOTICONS].m_Id); Graphics()->QuadsBegin(); int SinceStart = Client()->GameTick() - m_pClient->m_aClients[ClientID].m_EmoticonStart; int FromEnd = m_pClient->m_aClients[ClientID].m_EmoticonStart + 2 * Client()->GameTickSpeed() - Client()->GameTick(); float a = 1; if (FromEnd < Client()->GameTickSpeed() / 5) a = FromEnd / (Client()->GameTickSpeed() / 5.0); float h = 1; if (SinceStart < Client()->GameTickSpeed() / 10) h = SinceStart / (Client()->GameTickSpeed() / 10.0); float Wiggle = 0; if (SinceStart < Client()->GameTickSpeed() / 5) Wiggle = SinceStart / (Client()->GameTickSpeed() / 5.0); float WiggleAngle = sinf(5*Wiggle); Graphics()->QuadsSetRotation(pi/6*WiggleAngle); Graphics()->SetColor(1.0f,1.0f,1.0f,a); // client_datas::emoticon is an offset from the first emoticon RenderTools()->SelectSprite(SPRITE_OOP + m_pClient->m_aClients[ClientID].m_Emoticon); IGraphics::CQuadItem QuadItem(Position.x, Position.y - 23 - 32*h, 64, 64*h); Graphics()->QuadsDraw(&QuadItem, 1); Graphics()->QuadsEnd(); } } void CPlayers::OnRender() { // update RenderInfo for ninja bool IsTeamplay = (m_pClient->m_GameInfo.m_GameFlags&GAMEFLAG_TEAMS) != 0; for(int i = 0; i < MAX_CLIENTS; ++i) { m_aRenderInfo[i] = m_pClient->m_aClients[i].m_RenderInfo; if(m_pClient->m_Snap.m_aCharacters[i].m_Cur.m_Weapon == WEAPON_NINJA) { // change the skin for the player to the ninja int Skin = m_pClient->m_pSkins->Find("x_ninja", true); if(Skin != -1) { const CSkins::CSkin *pNinja = m_pClient->m_pSkins->Get(Skin); for(int p = 0; p < CSkins::NUM_SKINPARTS; p++) { if(IsTeamplay) { m_aRenderInfo[i].m_aTextures[p] = pNinja->m_apParts[p]->m_ColorTexture; int ColorVal = m_pClient->m_pSkins->GetTeamColor(true, pNinja->m_aPartColors[p], m_pClient->m_aClients[i].m_Team, p); m_aRenderInfo[i].m_aColors[p] = m_pClient->m_pSkins->GetColorV4(ColorVal, p==CSkins::SKINPART_TATTOO); } else if(pNinja->m_aUseCustomColors[p]) { m_aRenderInfo[i].m_aTextures[p] = pNinja->m_apParts[p]->m_ColorTexture; m_aRenderInfo[i].m_aColors[p] = m_pClient->m_pSkins->GetColorV4(pNinja->m_aPartColors[p], p==CSkins::SKINPART_TATTOO); } else { m_aRenderInfo[i].m_aTextures[p] = pNinja->m_apParts[p]->m_OrgTexture; m_aRenderInfo[i].m_aColors[p] = vec4(1.0f, 1.0f, 1.0f, 1.0f); } } } } } // render other players in two passes, first pass we render the other, second pass we render our self for(int p = 0; p < 4; p++) { for(int i = 0; i < MAX_CLIENTS; i++) { // only render active characters if(!m_pClient->m_Snap.m_aCharacters[i].m_Active) continue; const void *pPrevInfo = Client()->SnapFindItem(IClient::SNAP_PREV, NETOBJTYPE_PLAYERINFO, i); const void *pInfo = Client()->SnapFindItem(IClient::SNAP_CURRENT, NETOBJTYPE_PLAYERINFO, i); if(pPrevInfo && pInfo) { // bool Local = m_pClient->m_LocalClientID == i; if((p % 2) == 0 && Local) continue; if((p % 2) == 1 && !Local) continue; CNetObj_Character PrevChar = m_pClient->m_Snap.m_aCharacters[i].m_Prev; CNetObj_Character CurChar = m_pClient->m_Snap.m_aCharacters[i].m_Cur; if(p<2) RenderHook( &PrevChar, &CurChar, (const CNetObj_PlayerInfo *)pPrevInfo, (const CNetObj_PlayerInfo *)pInfo, i ); else RenderPlayer( &PrevChar, &CurChar, (const CNetObj_PlayerInfo *)pPrevInfo, (const CNetObj_PlayerInfo *)pInfo, i ); } } } } ================================================ FILE: src/game/client/components/players.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_CLIENT_COMPONENTS_PLAYERS_H #define GAME_CLIENT_COMPONENTS_PLAYERS_H #include <game/client/component.h> class CPlayers : public CComponent { CTeeRenderInfo m_aRenderInfo[MAX_CLIENTS]; void RenderHand(class CTeeRenderInfo *pInfo, vec2 CenterPos, vec2 Dir, float AngleOffset, vec2 PostRotOffset); void RenderPlayer( const CNetObj_Character *pPrevChar, const CNetObj_Character *pPlayerChar, const CNetObj_PlayerInfo *pPrevInfo, const CNetObj_PlayerInfo *pPlayerInfo, int ClientID ); void RenderHook( const CNetObj_Character *pPrevChar, const CNetObj_Character *pPlayerChar, const CNetObj_PlayerInfo *pPrevInfo, const CNetObj_PlayerInfo *pPlayerInfo, int ClientID ); public: virtual void OnRender(); }; #endif ================================================ FILE: src/game/client/components/scoreboard.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <engine/demo.h> #include <engine/graphics.h> #include <engine/textrender.h> #include <engine/shared/config.h> #include <game/generated/client_data.h> #include <game/generated/protocol.h> #include <game/client/animstate.h> #include <game/client/gameclient.h> #include <game/client/localization.h> #include <game/client/render.h> #include <game/client/components/countryflags.h> #include <game/client/components/motd.h> #include "scoreboard.h" CScoreboard::CScoreboard() { OnReset(); } void CScoreboard::ConKeyScoreboard(IConsole::IResult *pResult, void *pUserData) { ((CScoreboard *)pUserData)->m_Active = pResult->GetInteger(0) != 0; } void CScoreboard::OnReset() { m_Active = false; } void CScoreboard::OnRelease() { m_Active = false; } void CScoreboard::OnConsoleInit() { Console()->Register("+scoreboard", "", CFGFLAG_CLIENT, ConKeyScoreboard, this, "Show scoreboard"); } void CScoreboard::RenderGoals(float x, float y, float w) { float h = 50.0f; Graphics()->BlendNormal(); Graphics()->TextureClear(); Graphics()->QuadsBegin(); Graphics()->SetColor(0,0,0,0.5f); RenderTools()->DrawRoundRect(x, y, w, h, 10.0f); Graphics()->QuadsEnd(); // render goals y += 10.0f; if(m_pClient->m_GameInfo.m_ScoreLimit) { char aBuf[64]; str_format(aBuf, sizeof(aBuf), "%s: %d", Localize("Score limit"), m_pClient->m_GameInfo.m_ScoreLimit); TextRender()->Text(0, x+10.0f, y, 20.0f, aBuf, -1); } if(m_pClient->m_GameInfo.m_TimeLimit) { char aBuf[64]; str_format(aBuf, sizeof(aBuf), Localize("Time limit: %d min"), m_pClient->m_GameInfo.m_TimeLimit); TextRender()->Text(0, x+230.0f, y, 20.0f, aBuf, -1); } if(m_pClient->m_GameInfo.m_MatchNum && m_pClient->m_GameInfo.m_MatchCurrent) { char aBuf[64]; str_format(aBuf, sizeof(aBuf), "%s %d/%d", Localize("Match"), m_pClient->m_GameInfo.m_MatchCurrent, m_pClient->m_GameInfo.m_MatchNum); float tw = TextRender()->TextWidth(0, 20.0f, aBuf, -1); TextRender()->Text(0, x+w-tw-10.0f, y, 20.0f, aBuf, -1); } } void CScoreboard::RenderSpectators(float x, float y, float w) { float h = 140.0f; // background Graphics()->BlendNormal(); Graphics()->TextureClear(); Graphics()->QuadsBegin(); Graphics()->SetColor(0,0,0,0.5f); RenderTools()->DrawRoundRect(x, y, w, h, 10.0f); Graphics()->QuadsEnd(); // Headline y += 10.0f; TextRender()->Text(0, x+10.0f, y, 28.0f, Localize("Spectators"), w-20.0f); // spectator names y += 30.0f; bool Multiple = false; CTextCursor Cursor; TextRender()->SetCursor(&Cursor, x+10.0f, y, 22.0f, TEXTFLAG_RENDER); Cursor.m_LineWidth = w-20.0f; Cursor.m_MaxLines = 4; for(int i = 0; i < MAX_CLIENTS; ++i) { const CNetObj_PlayerInfo *pInfo = m_pClient->m_Snap.m_paPlayerInfos[i]; if(!pInfo || m_pClient->m_aClients[i].m_Team != TEAM_SPECTATORS) continue; if(Multiple) TextRender()->TextEx(&Cursor, ", ", -1); if(pInfo->m_PlayerFlags&PLAYERFLAG_WATCHING) TextRender()->TextColor(1.0f, 1.0f, 0.0f, 1.0f); TextRender()->TextEx(&Cursor, m_pClient->m_aClients[i].m_aName, -1); TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); Multiple = true; } } void CScoreboard::RenderScoreboard(float x, float y, float w, int Team, const char *pTitle) { if(Team == TEAM_SPECTATORS) return; float h = 760.0f; // background Graphics()->BlendNormal(); Graphics()->TextureClear(); Graphics()->QuadsBegin(); Graphics()->SetColor(0.0f, 0.0f, 0.0f, 0.5f); RenderTools()->DrawRoundRect(x, y, w, h, 17.0f); Graphics()->QuadsEnd(); // render title float TitleFontsize = 40.0f; if(!pTitle) { if(m_pClient->m_Snap.m_pGameData->m_GameStateFlags&GAMESTATEFLAG_GAMEOVER) pTitle = Localize("Game over"); else if(m_pClient->m_Snap.m_pGameData->m_GameStateFlags&GAMESTATEFLAG_ROUNDOVER) pTitle = Localize("Round over"); else pTitle = Localize("Score board"); } TextRender()->Text(0, x+20.0f, y, TitleFontsize, pTitle, -1); char aBuf[128] = {0}; if(m_pClient->m_GameInfo.m_GameFlags&GAMEFLAG_TEAMS) { int Score = Team == TEAM_RED ? m_pClient->m_Snap.m_pGameDataTeam->m_TeamscoreRed : m_pClient->m_Snap.m_pGameDataTeam->m_TeamscoreBlue; str_format(aBuf, sizeof(aBuf), "%d", Score); } else { if(m_pClient->m_Snap.m_SpecInfo.m_Active && m_pClient->m_Snap.m_SpecInfo.m_SpectatorID != SPEC_FREEVIEW && m_pClient->m_Snap.m_paPlayerInfos[m_pClient->m_Snap.m_SpecInfo.m_SpectatorID]) { int Score = m_pClient->m_Snap.m_paPlayerInfos[m_pClient->m_Snap.m_SpecInfo.m_SpectatorID]->m_Score; str_format(aBuf, sizeof(aBuf), "%d", Score); } else if(m_pClient->m_Snap.m_pLocalInfo) { int Score = m_pClient->m_Snap.m_pLocalInfo->m_Score; str_format(aBuf, sizeof(aBuf), "%d", Score); } } float tw = TextRender()->TextWidth(0, TitleFontsize, aBuf, -1); TextRender()->Text(0, x+w-tw-20.0f, y, TitleFontsize, aBuf, -1); // calculate measurements x += 10.0f; float LineHeight = 60.0f; float TeeSizeMod = 1.0f; float Spacing = 16.0f; if(m_pClient->m_GameInfo.m_aTeamSize[Team] > 12) { LineHeight = 40.0f; TeeSizeMod = 0.8f; Spacing = 0.0f; } else if(m_pClient->m_GameInfo.m_aTeamSize[Team] > 8) { LineHeight = 50.0f; TeeSizeMod = 0.9f; Spacing = 8.0f; } float ScoreOffset = x+10.0f, ScoreLength = 60.0f; float TeeOffset = ScoreOffset+ScoreLength, TeeLength = 60*TeeSizeMod; float NameOffset = TeeOffset+TeeLength, NameLength = 300.0f-TeeLength; float PingOffset = x+610.0f, PingLength = 65.0f; float CountryOffset = PingOffset-(LineHeight-Spacing-TeeSizeMod*5.0f)*2.0f, CountryLength = (LineHeight-Spacing-TeeSizeMod*5.0f)*2.0f; float ClanOffset = x+370.0f, ClanLength = 230.0f-CountryLength; // render headlines y += 50.0f; float HeadlineFontsize = 22.0f; TextRender()->TextColor(1.0f, 1.0f, 1.0f, 0.7f); tw = TextRender()->TextWidth(0, HeadlineFontsize, Localize("Score"), -1); TextRender()->Text(0, ScoreOffset+ScoreLength-tw, y, HeadlineFontsize, Localize("Score"), -1); TextRender()->Text(0, NameOffset, y, HeadlineFontsize, Localize("Name"), -1); tw = TextRender()->TextWidth(0, HeadlineFontsize, Localize("Clan"), -1); TextRender()->Text(0, ClanOffset+ClanLength/2-tw/2, y, HeadlineFontsize, Localize("Clan"), -1); tw = TextRender()->TextWidth(0, HeadlineFontsize, Localize("Ping"), -1); TextRender()->Text(0, PingOffset+PingLength-tw, y, HeadlineFontsize, Localize("Ping"), -1); TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); // render player entries y += HeadlineFontsize*2.0f; float FontSize = 24.0f; CTextCursor Cursor; for(int RenderDead = 0; RenderDead < 2; ++RenderDead) { float ColorAlpha = RenderDead ? 0.5f : 1.0f; TextRender()->TextColor(1.0f, 1.0f, 1.0f, ColorAlpha); for(int i = 0; i < MAX_CLIENTS; i++) { // make sure that we render the correct team const CGameClient::CPlayerInfoItem *pInfo = &m_pClient->m_Snap.m_aInfoByScore[i]; if(!pInfo->m_pPlayerInfo || m_pClient->m_aClients[pInfo->m_ClientID].m_Team != Team || (!RenderDead && (pInfo->m_pPlayerInfo->m_PlayerFlags&PLAYERFLAG_DEAD)) || (RenderDead && !(pInfo->m_pPlayerInfo->m_PlayerFlags&PLAYERFLAG_DEAD))) continue; // background so it's easy to find the local player or the followed one in spectator mode if(m_pClient->m_LocalClientID == pInfo->m_ClientID || (m_pClient->m_Snap.m_SpecInfo.m_Active && pInfo->m_ClientID == m_pClient->m_Snap.m_SpecInfo.m_SpectatorID)) { Graphics()->TextureClear(); Graphics()->QuadsBegin(); Graphics()->SetColor(1.0f, 1.0f, 1.0f, 0.25f*ColorAlpha); RenderTools()->DrawRoundRect(x, y, w-20.0f, LineHeight, 15.0f); Graphics()->QuadsEnd(); } // score str_format(aBuf, sizeof(aBuf), "%d", clamp(pInfo->m_pPlayerInfo->m_Score, -999, 999)); tw = TextRender()->TextWidth(0, FontSize, aBuf, -1); TextRender()->SetCursor(&Cursor, ScoreOffset+ScoreLength-tw, y+Spacing, FontSize, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); Cursor.m_LineWidth = ScoreLength; TextRender()->TextEx(&Cursor, aBuf, -1); // flag if(m_pClient->m_GameInfo.m_GameFlags&GAMEFLAG_FLAGS && m_pClient->m_Snap.m_pGameDataFlag && (m_pClient->m_Snap.m_pGameDataFlag->m_FlagCarrierRed == pInfo->m_ClientID || m_pClient->m_Snap.m_pGameDataFlag->m_FlagCarrierBlue == pInfo->m_ClientID)) { Graphics()->BlendNormal(); Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id); Graphics()->QuadsBegin(); RenderTools()->SelectSprite(m_pClient->m_aClients[pInfo->m_ClientID].m_Team==TEAM_RED ? SPRITE_FLAG_BLUE : SPRITE_FLAG_RED, SPRITE_FLAG_FLIP_X); float Size = LineHeight; IGraphics::CQuadItem QuadItem(TeeOffset+0.0f, y-5.0f-Spacing/2.0f, Size/2.0f, Size); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); } // avatar if(RenderDead) { Graphics()->BlendNormal(); Graphics()->TextureSet(g_pData->m_aImages[IMAGE_DEADTEE].m_Id); Graphics()->QuadsBegin(); IGraphics::CQuadItem QuadItem(TeeOffset, y, 64*TeeSizeMod, 64*TeeSizeMod); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); } else { CTeeRenderInfo TeeInfo = m_pClient->m_aClients[pInfo->m_ClientID].m_RenderInfo; TeeInfo.m_Size *= TeeSizeMod; RenderTools()->RenderTee(CAnimState::GetIdle(), &TeeInfo, EMOTE_NORMAL, vec2(1.0f, 0.0f), vec2(TeeOffset+TeeLength/2, y+LineHeight/2)); } // name // todo: improve visual player ready state if(!(pInfo->m_pPlayerInfo->m_PlayerFlags&PLAYERFLAG_READY)) TextRender()->TextColor(1.0f, 0.5f, 0.5f, ColorAlpha); else if(RenderDead && pInfo->m_pPlayerInfo->m_PlayerFlags&PLAYERFLAG_WATCHING) TextRender()->TextColor(1.0f, 1.0f, 0.0f, ColorAlpha); TextRender()->SetCursor(&Cursor, NameOffset, y+Spacing, FontSize, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); Cursor.m_LineWidth = NameLength; TextRender()->TextEx(&Cursor, m_pClient->m_aClients[pInfo->m_ClientID].m_aName, -1); TextRender()->TextColor(1.0f, 1.0f, 1.0f, ColorAlpha); // clan tw = TextRender()->TextWidth(0, FontSize, m_pClient->m_aClients[pInfo->m_ClientID].m_aClan, -1); TextRender()->SetCursor(&Cursor, ClanOffset+ClanLength/2-tw/2, y+Spacing, FontSize, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); Cursor.m_LineWidth = ClanLength; TextRender()->TextEx(&Cursor, m_pClient->m_aClients[pInfo->m_ClientID].m_aClan, -1); // country flag vec4 Color(1.0f, 1.0f, 1.0f, 0.5f*ColorAlpha); m_pClient->m_pCountryFlags->Render(m_pClient->m_aClients[pInfo->m_ClientID].m_Country, &Color, CountryOffset, y+(Spacing+TeeSizeMod*5.0f)/2.0f, CountryLength, LineHeight-Spacing-TeeSizeMod*5.0f); // ping str_format(aBuf, sizeof(aBuf), "%d", clamp(pInfo->m_pPlayerInfo->m_Latency, 0, 1000)); TextRender()->TextColor(1.0f, 1.0f, 1.0f, 0.7f); tw = TextRender()->TextWidth(0, FontSize, aBuf, -1); TextRender()->SetCursor(&Cursor, PingOffset+PingLength-tw, y+Spacing, FontSize, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); Cursor.m_LineWidth = PingLength; TextRender()->TextEx(&Cursor, aBuf, -1); TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); y += LineHeight+Spacing; } } TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); } void CScoreboard::RenderRecordingNotification(float x) { if(!m_pClient->DemoRecorder()->IsRecording()) return; //draw the box Graphics()->BlendNormal(); Graphics()->TextureClear(); Graphics()->QuadsBegin(); Graphics()->SetColor(0.0f, 0.0f, 0.0f, 0.4f); RenderTools()->DrawRoundRectExt(x, 0.0f, 180.0f, 50.0f, 15.0f, CUI::CORNER_B); Graphics()->QuadsEnd(); //draw the red dot Graphics()->QuadsBegin(); Graphics()->SetColor(1.0f, 0.0f, 0.0f, 1.0f); RenderTools()->DrawRoundRect(x+20, 15.0f, 20.0f, 20.0f, 10.0f); Graphics()->QuadsEnd(); //draw the text char aBuf[64]; int Seconds = m_pClient->DemoRecorder()->Length(); str_format(aBuf, sizeof(aBuf), Localize("REC %3d:%02d"), Seconds/60, Seconds%60); TextRender()->Text(0, x+50.0f, 10.0f, 20.0f, aBuf, -1); } void CScoreboard::OnRender() { if(!Active()) return; // if the score board is active, then we should clear the motd message aswell if(m_pClient->m_pMotd->IsActive()) m_pClient->m_pMotd->Clear(); float Width = 400*3.0f*Graphics()->ScreenAspect(); float Height = 400*3.0f; Graphics()->MapScreen(0, 0, Width, Height); float w = 700.0f; if(m_pClient->m_Snap.m_pGameData) { if(!(m_pClient->m_GameInfo.m_GameFlags&GAMEFLAG_TEAMS)) RenderScoreboard(Width/2-w/2, 150.0f, w, 0, 0); else if(m_pClient->m_Snap.m_pGameDataTeam) { const char *pRedClanName = GetClanName(TEAM_RED); const char *pBlueClanName = GetClanName(TEAM_BLUE); if(m_pClient->m_Snap.m_pGameData->m_GameStateFlags&GAMESTATEFLAG_GAMEOVER) { char aText[256]; str_copy(aText, Localize("Draw!"), sizeof(aText)); if(m_pClient->m_Snap.m_pGameDataTeam->m_TeamscoreRed > m_pClient->m_Snap.m_pGameDataTeam->m_TeamscoreBlue) { if(pRedClanName) str_format(aText, sizeof(aText), Localize("%s wins!"), pRedClanName); else str_copy(aText, Localize("Red team wins!"), sizeof(aText)); } else if(m_pClient->m_Snap.m_pGameDataTeam->m_TeamscoreBlue > m_pClient->m_Snap.m_pGameDataTeam->m_TeamscoreRed) { if(pBlueClanName) str_format(aText, sizeof(aText), Localize("%s wins!"), pBlueClanName); else str_copy(aText, Localize("Blue team wins!"), sizeof(aText)); } float w = TextRender()->TextWidth(0, 86.0f, aText, -1); TextRender()->Text(0, Width/2-w/2, 39, 86.0f, aText, -1); } else if(m_pClient->m_Snap.m_pGameData->m_GameStateFlags&GAMESTATEFLAG_ROUNDOVER) { char aText[256]; str_copy(aText, Localize("Round over!"), sizeof(aText)); float w = TextRender()->TextWidth(0, 86.0f, aText, -1); TextRender()->Text(0, Width/2-w/2, 39, 86.0f, aText, -1); } RenderScoreboard(Width/2-w-5.0f, 150.0f, w, TEAM_RED, pRedClanName ? pRedClanName : Localize("Red team")); RenderScoreboard(Width/2+5.0f, 150.0f, w, TEAM_BLUE, pBlueClanName ? pBlueClanName : Localize("Blue team")); } RenderGoals(Width/2-w/2, 150+760+10, w); RenderSpectators(Width/2-w/2, 150+760+10+50+10, w); } RenderRecordingNotification((Width/7)*4); } bool CScoreboard::Active() { // if we activly wanna look on the scoreboard if(m_Active) return true; if(m_pClient->m_LocalClientID != -1 && m_pClient->m_aClients[m_pClient->m_LocalClientID].m_Team != TEAM_SPECTATORS) { // we are not a spectator, check if we are dead, don't follow a player and the game isn't paused if(!m_pClient->m_Snap.m_pLocalCharacter && !m_pClient->m_Snap.m_SpecInfo.m_Active && !(m_pClient->m_Snap.m_pGameData && m_pClient->m_Snap.m_pGameData->m_GameStateFlags&GAMESTATEFLAG_PAUSED)) return true; } // if the game is over if(m_pClient->m_Snap.m_pGameData && m_pClient->m_Snap.m_pGameData->m_GameStateFlags&(GAMESTATEFLAG_ROUNDOVER|GAMESTATEFLAG_GAMEOVER)) return true; return false; } const char *CScoreboard::GetClanName(int Team) { int ClanPlayers = 0; const char *pClanName = 0; for(int i = 0; i < MAX_CLIENTS; i++) { if(!m_pClient->m_aClients[i].m_Active || m_pClient->m_aClients[i].m_Team != Team) continue; if(!pClanName) { pClanName = m_pClient->m_aClients[i].m_aClan; ClanPlayers++; } else { if(str_comp(m_pClient->m_aClients[i].m_aClan, pClanName) == 0) ClanPlayers++; else return 0; } } if(ClanPlayers > 1 && pClanName[0]) return pClanName; else return 0; } ================================================ FILE: src/game/client/components/scoreboard.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_CLIENT_COMPONENTS_SCOREBOARD_H #define GAME_CLIENT_COMPONENTS_SCOREBOARD_H #include <game/client/component.h> class CScoreboard : public CComponent { void RenderGoals(float x, float y, float w); void RenderSpectators(float x, float y, float w); void RenderScoreboard(float x, float y, float w, int Team, const char *pTitle); void RenderRecordingNotification(float x); static void ConKeyScoreboard(IConsole::IResult *pResult, void *pUserData); const char *GetClanName(int Team); bool m_Active; public: CScoreboard(); virtual void OnReset(); virtual void OnConsoleInit(); virtual void OnRender(); virtual void OnRelease(); bool Active(); }; #endif ================================================ FILE: src/game/client/components/skins.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <math.h> #include <base/system.h> #include <base/math.h> #include <engine/graphics.h> #include <engine/storage.h> #include <engine/external/json-parser/json.h> #include <engine/shared/config.h> #include "skins.h" const char * const CSkins::ms_apSkinPartNames[NUM_SKINPARTS] = {"body", "tattoo", "decoration", "hands", "feet", "eyes"}; const char * const CSkins::ms_apColorComponents[NUM_COLOR_COMPONENTS] = {"hue", "sat", "lgt", "alp"}; char *const CSkins::ms_apSkinVariables[NUM_SKINPARTS] = {g_Config.m_PlayerSkinBody, g_Config.m_PlayerSkinTattoo, g_Config.m_PlayerSkinDecoration, g_Config.m_PlayerSkinHands, g_Config.m_PlayerSkinFeet, g_Config.m_PlayerSkinEyes}; int *const CSkins::ms_apUCCVariables[NUM_SKINPARTS] = {&g_Config.m_PlayerUseCustomColorBody, &g_Config.m_PlayerUseCustomColorTattoo, &g_Config.m_PlayerUseCustomColorDecoration, &g_Config.m_PlayerUseCustomColorHands, &g_Config.m_PlayerUseCustomColorFeet, &g_Config.m_PlayerUseCustomColorEyes}; int *const CSkins::ms_apColorVariables[NUM_SKINPARTS] = {&g_Config.m_PlayerColorBody, &g_Config.m_PlayerColorTattoo, &g_Config.m_PlayerColorDecoration, &g_Config.m_PlayerColorHands, &g_Config.m_PlayerColorFeet, &g_Config.m_PlayerColorEyes}; int CSkins::SkinPartScan(const char *pName, int IsDir, int DirType, void *pUser) { CSkins *pSelf = (CSkins *)pUser; int l = str_length(pName); if(l < 4 || IsDir || str_comp(pName+l-4, ".png") != 0) return 0; char aBuf[512]; str_format(aBuf, sizeof(aBuf), "skins/%s/%s", CSkins::ms_apSkinPartNames[pSelf->m_ScanningPart], pName); CImageInfo Info; if(!pSelf->Graphics()->LoadPNG(&Info, aBuf, DirType)) { str_format(aBuf, sizeof(aBuf), "failed to load skin part '%s'", pName); pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "skins", aBuf); return 0; } CSkinPart Part; Part.m_OrgTexture = pSelf->Graphics()->LoadTextureRaw(Info.m_Width, Info.m_Height, Info.m_Format, Info.m_pData, Info.m_Format, 0); Part.m_BloodColor = vec3(1.0f, 1.0f, 1.0f); unsigned char *d = (unsigned char *)Info.m_pData; int Pitch = Info.m_Width*4; // dig out blood color if(pSelf->m_ScanningPart == SKINPART_BODY) { int PartX = Info.m_Width/2; int PartY = 0; int PartWidth = Info.m_Width/2; int PartHeight = Info.m_Height/2; int aColors[3] = {0}; for(int y = PartY; y < PartY+PartHeight; y++) for(int x = PartX; x < PartX+PartWidth; x++) { if(d[y*Pitch+x*4+3] > 128) { aColors[0] += d[y*Pitch+x*4+0]; aColors[1] += d[y*Pitch+x*4+1]; aColors[2] += d[y*Pitch+x*4+2]; } } Part.m_BloodColor = normalize(vec3(aColors[0], aColors[1], aColors[2])); } // create colorless version int Step = Info.m_Format == CImageInfo::FORMAT_RGBA ? 4 : 3; // make the texture gray scale for(int i = 0; i < Info.m_Width*Info.m_Height; i++) { int v = (d[i*Step]+d[i*Step+1]+d[i*Step+2])/3; d[i*Step] = v; d[i*Step+1] = v; d[i*Step+2] = v; } Part.m_ColorTexture = pSelf->Graphics()->LoadTextureRaw(Info.m_Width, Info.m_Height, Info.m_Format, Info.m_pData, Info.m_Format, 0); mem_free(Info.m_pData); // set skin part data Part.m_Flags = 0; if(pName[0] == 'x' && pName[1] == '_') Part.m_Flags |= SKINFLAG_SPECIAL; if(DirType != IStorage::TYPE_SAVE) Part.m_Flags |= SKINFLAG_STANDARD; str_copy(Part.m_aName, pName, min((int)sizeof(Part.m_aName),l-3)); if(g_Config.m_Debug) { str_format(aBuf, sizeof(aBuf), "load skin part %s", Part.m_aName); pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "skins", aBuf); } pSelf->m_aaSkinParts[pSelf->m_ScanningPart].add(Part); return 0; } int CSkins::SkinScan(const char *pName, int IsDir, int DirType, void *pUser) { int l = str_length(pName); if(l < 5 || IsDir || str_comp(pName+l-5, ".json") != 0) return 0; CSkins *pSelf = (CSkins *)pUser; // read file data into buffer char aBuf[512]; str_format(aBuf, sizeof(aBuf), "skins/%s", pName); IOHANDLE File = pSelf->Storage()->OpenFile(aBuf, IOFLAG_READ, IStorage::TYPE_ALL); if(!File) return 0; int FileSize = (int)io_length(File); char *pFileData = (char *)mem_alloc(FileSize+1, 1); io_read(File, pFileData, FileSize); pFileData[FileSize] = 0; io_close(File); // init CSkin Skin = pSelf->m_DummySkin; bool SpecialSkin = pName[0] == 'x' && pName[1] == '_'; // parse json data json_settings JsonSettings; mem_zero(&JsonSettings, sizeof(JsonSettings)); char aError[256]; json_value *pJsonData = json_parse_ex(&JsonSettings, pFileData, aError); if(pJsonData == 0) { pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, aBuf, aError); mem_free(pFileData); return 0; } // extract data const json_value &rStart = (*pJsonData)["skin"]; if(rStart.type == json_object) { for(int PartIndex = 0; PartIndex < NUM_SKINPARTS; ++PartIndex) { const json_value &rPart = rStart[(const char *)ms_apSkinPartNames[PartIndex]]; if(rPart.type != json_object) continue; // filename const json_value &rFilename = rPart["filename"]; if(rFilename.type == json_string) { int SkinPart = pSelf->FindSkinPart(PartIndex, (const char *)rFilename, SpecialSkin); if(SkinPart > -1) Skin.m_apParts[PartIndex] = pSelf->GetSkinPart(PartIndex, SkinPart); } // use custom colors bool UseCustomColors = false; const json_value &rColour = rPart["custom_colors"]; if(rColour.type == json_string) { UseCustomColors = str_comp((const char *)rColour, "true") == 0; } Skin.m_aUseCustomColors[PartIndex] = UseCustomColors; // color components if(!UseCustomColors) continue; for(int i = 0; i < NUM_COLOR_COMPONENTS; i++) { if(PartIndex != SKINPART_TATTOO && i == 3) continue; const json_value &rComponent = rPart[(const char *)ms_apColorComponents[i]]; if(rComponent.type == json_integer) { switch(i) { case 0: Skin.m_aPartColors[PartIndex] = (Skin.m_aPartColors[PartIndex]&0xFF00FFFF) | (rComponent.u.integer << 16); break; case 1: Skin.m_aPartColors[PartIndex] = (Skin.m_aPartColors[PartIndex]&0xFFFF00FF) | (rComponent.u.integer << 8); break; case 2: Skin.m_aPartColors[PartIndex] = (Skin.m_aPartColors[PartIndex]&0xFFFFFF00) | rComponent.u.integer; break; case 3: Skin.m_aPartColors[PartIndex] = (Skin.m_aPartColors[PartIndex]&0x00FFFFFF) | (rComponent.u.integer << 24); break; } } } } } // clean up json_value_free(pJsonData); mem_free(pFileData); // set skin data Skin.m_Flags = SpecialSkin ? SKINFLAG_SPECIAL : 0; if(DirType != IStorage::TYPE_SAVE) Skin.m_Flags |= SKINFLAG_STANDARD; str_copy(Skin.m_aName, pName, min((int)sizeof(Skin.m_aName),l-4)); if(g_Config.m_Debug) { str_format(aBuf, sizeof(aBuf), "load skin %s", Skin.m_aName); pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "skins", aBuf); } pSelf->m_aSkins.add(Skin); return 0; } void CSkins::OnInit() { for(int p = 0; p < NUM_SKINPARTS; p++) { m_aaSkinParts[p].clear(); // add none part if(p == SKINPART_TATTOO || p == SKINPART_DECORATION) { CSkinPart NoneSkinPart; NoneSkinPart.m_Flags = SKINFLAG_STANDARD; str_copy(NoneSkinPart.m_aName, "", sizeof(NoneSkinPart.m_aName)); NoneSkinPart.m_BloodColor = vec3(1.0f, 1.0f, 1.0f); m_aaSkinParts[p].add(NoneSkinPart); } // load skin parts char aBuf[64]; str_format(aBuf, sizeof(aBuf), "skins/%s", ms_apSkinPartNames[p]); m_ScanningPart = p; Storage()->ListDirectory(IStorage::TYPE_ALL, aBuf, SkinPartScan, this); // add dummy skin part if(!m_aaSkinParts[p].size()) { CSkinPart DummySkinPart; DummySkinPart.m_Flags = SKINFLAG_STANDARD; str_copy(DummySkinPart.m_aName, "dummy", sizeof(DummySkinPart.m_aName)); DummySkinPart.m_BloodColor = vec3(1.0f, 1.0f, 1.0f); m_aaSkinParts[p].add(DummySkinPart); } } // create dummy skin m_DummySkin.m_Flags = SKINFLAG_STANDARD; str_copy(m_DummySkin.m_aName, "dummy", sizeof(m_DummySkin.m_aName)); for(int p = 0; p < NUM_SKINPARTS; p++) { int Default; if(p == SKINPART_TATTOO || p == SKINPART_DECORATION) Default = FindSkinPart(p, "", false); else Default = FindSkinPart(p, "standard", false); if(Default < 0) Default = 0; m_DummySkin.m_apParts[p] = GetSkinPart(p, Default); m_DummySkin.m_aPartColors[p] = p==SKINPART_TATTOO ? (255<<24)+65408 : 65408; m_DummySkin.m_aUseCustomColors[p] = 0; } // load skins m_aSkins.clear(); Storage()->ListDirectory(IStorage::TYPE_ALL, "skins", SkinScan, this); // add dummy skin if(!m_aSkins.size()) m_aSkins.add(m_DummySkin); } void CSkins::AddSkin(const char *pSkinName) { CSkin Skin = m_DummySkin; Skin.m_Flags = 0; str_copy(Skin.m_aName, pSkinName, sizeof(Skin.m_aName)); for(int PartIndex = 0; PartIndex < NUM_SKINPARTS; ++PartIndex) { int SkinPart = FindSkinPart(PartIndex, ms_apSkinVariables[PartIndex], false); if(SkinPart > -1) Skin.m_apParts[PartIndex] = GetSkinPart(PartIndex, SkinPart); Skin.m_aUseCustomColors[PartIndex] = *ms_apUCCVariables[PartIndex]; Skin.m_aPartColors[PartIndex] = *ms_apColorVariables[PartIndex]; } m_aSkins.add(Skin); } void CSkins::RemoveSkin(const CSkin *pSkin) { m_aSkins.remove(*pSkin); } int CSkins::Num() { return m_aSkins.size(); } int CSkins::NumSkinPart(int Part) { return m_aaSkinParts[Part].size(); } const CSkins::CSkin *CSkins::Get(int Index) { return &m_aSkins[max(0, Index%m_aSkins.size())]; } int CSkins::Find(const char *pName, bool AllowSpecialSkin) { for(int i = 0; i < m_aSkins.size(); i++) { if(str_comp(m_aSkins[i].m_aName, pName) == 0 && ((m_aSkins[i].m_Flags&SKINFLAG_SPECIAL) == 0 || AllowSpecialSkin)) return i; } return -1; } const CSkins::CSkinPart *CSkins::GetSkinPart(int Part, int Index) { int Size = m_aaSkinParts[Part].size(); return &m_aaSkinParts[Part][max(0, Index%Size)]; } int CSkins::FindSkinPart(int Part, const char *pName, bool AllowSpecialPart) { for(int i = 0; i < m_aaSkinParts[Part].size(); i++) { if(str_comp(m_aaSkinParts[Part][i].m_aName, pName) == 0 && ((m_aaSkinParts[Part][i].m_Flags&SKINFLAG_SPECIAL) == 0 || AllowSpecialPart)) return i; } return -1; } vec3 CSkins::GetColorV3(int v) const { float Dark = DARKEST_COLOR_LGT/255.0f; return HslToRgb(vec3(((v>>16)&0xff)/255.0f, ((v>>8)&0xff)/255.0f, Dark+(v&0xff)/255.0f*(1.0f-Dark))); } vec4 CSkins::GetColorV4(int v, bool UseAlpha) const { vec3 r = GetColorV3(v); float Alpha = UseAlpha ? ((v>>24)&0xff)/255.0f : 1.0f; return vec4(r.r, r.g, r.b, Alpha); } int CSkins::GetTeamColor(int UseCustomColors, int PartColor, int Team, int Part) const { static const int s_aTeamColors[3] = {12895054, 65387, 10223467}; if(!UseCustomColors) { int ColorVal = s_aTeamColors[Team+1]; if(Part == SKINPART_TATTOO) ColorVal |= 0xff000000; return ColorVal; } /*blue128: 128/PI*ARCSIN(COS((PI*(x+10)/128)))+182 // (decoration, tattoo, hands) blue64: 64/PI*ARCSIN(COS((PI*(x-76)/64)))+172 // (body, feet, eyes) red128: Mod((128/PI*ARCSIN(COS((PI*(x-105)/128)))+297),256) red64: Mod((64/PI*ARCSIN(COS((PI*(x-56)/64)))+280),256)*/ int MinSat = 160; int MaxSat = 255; float Dark = DARKEST_COLOR_LGT/255.0f; int MinLgt = Dark + 64*(1.0f-Dark); int MaxLgt = Dark + 191*(1.0f-Dark); int Hue = 0; int Sat = (PartColor>>8)&0xff; int Lgt = PartColor&0xff; int NewHue; if(Team == TEAM_RED) { if(Part == SKINPART_TATTOO || Part == SKINPART_DECORATION || Part == SKINPART_HANDS) NewHue = (int)(128.0f/pi*asinf(cosf(pi/128.0f*(Hue-105.0f))) + 297.0f) % 256; else NewHue = (int)(64.0f/pi*asinf(cosf(pi/64.0f*(Hue-56.0f))) + 280.0f) % 256; } else NewHue = 64.0f/pi*asinf(cosf(pi/64.0f*(Hue-76.0f))) + 172.0f; int NewSat = clamp(Sat, MinSat, MaxSat); int NewLgt = clamp(Lgt, MinLgt, MaxLgt); int ColorVal = (NewHue<<16) + (NewSat<<8) + NewLgt; if(Part == SKINPART_TATTOO) ColorVal += PartColor&0xff000000; return ColorVal; } ================================================ FILE: src/game/client/components/skins.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_CLIENT_COMPONENTS_SKINS_H #define GAME_CLIENT_COMPONENTS_SKINS_H #include <base/vmath.h> #include <base/tl/sorted_array.h> #include <game/client/component.h> // todo: fix duplicate skins (different paths) class CSkins : public CComponent { public: enum { SKINFLAG_SPECIAL=1<<0, SKINFLAG_STANDARD=1<<1, SKINPART_BODY=0, SKINPART_TATTOO, SKINPART_DECORATION, SKINPART_HANDS, SKINPART_FEET, SKINPART_EYES, NUM_SKINPARTS, DARKEST_COLOR_LGT=61, NUM_COLOR_COMPONENTS=4 }; struct CSkinPart { int m_Flags; char m_aName[24]; IGraphics::CTextureHandle m_OrgTexture; IGraphics::CTextureHandle m_ColorTexture; vec3 m_BloodColor; bool operator<(const CSkinPart &Other) { return str_comp_nocase(m_aName, Other.m_aName) < 0; } }; struct CSkin { int m_Flags; char m_aName[24]; const CSkinPart *m_apParts[NUM_SKINPARTS]; int m_aPartColors[NUM_SKINPARTS]; int m_aUseCustomColors[NUM_SKINPARTS]; bool operator<(const CSkin &Other) { return str_comp_nocase(m_aName, Other.m_aName) < 0; } bool operator==(const CSkin &Other) { return mem_comp(this, &Other, sizeof(CSkin)) == 0; } }; static const char * const ms_apSkinPartNames[NUM_SKINPARTS]; static const char * const ms_apColorComponents[NUM_COLOR_COMPONENTS]; static char * const ms_apSkinVariables[NUM_SKINPARTS]; static int * const ms_apUCCVariables[NUM_SKINPARTS]; // use custom color static int * const ms_apColorVariables[NUM_SKINPARTS]; // void OnInit(); void AddSkin(const char *pSkinName); void RemoveSkin(const CSkin *pSkin); int Num(); int NumSkinPart(int Part); const CSkin *Get(int Index); int Find(const char *pName, bool AllowSpecialSkin); const CSkinPart *GetSkinPart(int Part, int Index); int FindSkinPart(int Part, const char *pName, bool AllowSpecialPart); vec3 GetColorV3(int v) const; vec4 GetColorV4(int v, bool UseAlpha) const; int GetTeamColor(int UseCustomColors, int PartColor, int Team, int Part) const; private: int m_ScanningPart; sorted_array<CSkinPart> m_aaSkinParts[NUM_SKINPARTS]; sorted_array<CSkin> m_aSkins; CSkin m_DummySkin; static int SkinPartScan(const char *pName, int IsDir, int DirType, void *pUser); static int SkinScan(const char *pName, int IsDir, int DirType, void *pUser); }; #endif ================================================ FILE: src/game/client/components/sounds.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <engine/engine.h> #include <engine/sound.h> #include <engine/shared/config.h> #include <game/generated/client_data.h> #include <game/client/gameclient.h> #include <game/client/components/camera.h> #include <game/client/components/menus.h> #include "sounds.h" struct CUserData { CGameClient *m_pGameClient; bool m_Render; } g_UserData; static int LoadSoundsThread(void *pUser) { CUserData *pData = static_cast<CUserData *>(pUser); for(int s = 0; s < g_pData->m_NumSounds; s++) { for(int i = 0; i < g_pData->m_aSounds[s].m_NumSounds; i++) { ISound::CSampleHandle Id = pData->m_pGameClient->Sound()->LoadWV(g_pData->m_aSounds[s].m_aSounds[i].m_pFilename); g_pData->m_aSounds[s].m_aSounds[i].m_Id = Id; } if(pData->m_Render) pData->m_pGameClient->m_pMenus->RenderLoading(); } return 0; } ISound::CSampleHandle CSounds::GetSampleId(int SetId) { if(!g_Config.m_SndEnable || !Sound()->IsSoundEnabled() || m_WaitForSoundJob || SetId < 0 || SetId >= g_pData->m_NumSounds) return ISound::CSampleHandle(); CDataSoundset *pSet = &g_pData->m_aSounds[SetId]; if(!pSet->m_NumSounds) return ISound::CSampleHandle(); if(pSet->m_NumSounds == 1) return pSet->m_aSounds[0].m_Id; // return random one int Id; do { Id = rand() % pSet->m_NumSounds; } while(Id == pSet->m_Last); pSet->m_Last = Id; return pSet->m_aSounds[Id].m_Id; } void CSounds::OnInit() { // setup sound channels Sound()->SetChannel(CSounds::CHN_GUI, 1.0f, 0.0f); Sound()->SetChannel(CSounds::CHN_MUSIC, 1.0f, 0.0f); Sound()->SetChannel(CSounds::CHN_WORLD, 0.9f, 1.0f); Sound()->SetChannel(CSounds::CHN_GLOBAL, 1.0f, 0.0f); Sound()->SetListenerPos(0.0f, 0.0f); ClearQueue(); // load sounds if(g_Config.m_ClThreadsoundloading) { g_UserData.m_pGameClient = m_pClient; g_UserData.m_Render = false; m_pClient->Engine()->AddJob(&m_SoundJob, LoadSoundsThread, &g_UserData); m_WaitForSoundJob = true; } else { g_UserData.m_pGameClient = m_pClient; g_UserData.m_Render = true; LoadSoundsThread(&g_UserData); m_WaitForSoundJob = false; } } void CSounds::OnReset() { if(Client()->State() >= IClient::STATE_ONLINE) { Sound()->StopAll(); ClearQueue(); } } void CSounds::OnStateChange(int NewState, int OldState) { if(NewState == IClient::STATE_ONLINE || NewState == IClient::STATE_DEMOPLAYBACK) OnReset(); } void CSounds::OnRender() { // check for sound initialisation if(m_WaitForSoundJob) { if(m_SoundJob.Status() == CJob::STATE_DONE) m_WaitForSoundJob = false; else return; } // set listner pos Sound()->SetListenerPos(m_pClient->m_pCamera->m_Center.x, m_pClient->m_pCamera->m_Center.y); // play sound from queue if(m_QueuePos > 0) { int64 Now = time_get(); if(m_QueueWaitTime <= Now) { Play(m_aQueue[0].m_Channel, m_aQueue[0].m_SetId, 1.0f); m_QueueWaitTime = Now+time_freq()*3/10; // wait 300ms before playing the next one if(--m_QueuePos > 0) mem_move(m_aQueue, m_aQueue+1, m_QueuePos*sizeof(QueueEntry)); } } } void CSounds::ClearQueue() { mem_zero(m_aQueue, sizeof(m_aQueue)); m_QueuePos = 0; m_QueueWaitTime = time_get(); } void CSounds::Enqueue(int Channel, int SetId) { // add sound to the queue if(m_QueuePos < QUEUE_SIZE) { if(Channel == CHN_MUSIC || !g_Config.m_ClEditor) { m_aQueue[m_QueuePos].m_Channel = Channel; m_aQueue[m_QueuePos++].m_SetId = SetId; } } } void CSounds::Play(int Chn, int SetId, float Vol) { if(Chn == CHN_MUSIC && !g_Config.m_SndMusic) return; ISound::CSampleHandle SampleId = GetSampleId(SetId); if(!SampleId.IsValid()) return; int Flags = 0; if(Chn == CHN_MUSIC) Flags = ISound::FLAG_LOOP; Sound()->Play(Chn, SampleId, Flags); } void CSounds::PlayAt(int Chn, int SetId, float Vol, vec2 Pos) { if(Chn == CHN_MUSIC && !g_Config.m_SndMusic) return; ISound::CSampleHandle SampleId = GetSampleId(SetId); if(!SampleId.IsValid()) return; int Flags = 0; if(Chn == CHN_MUSIC) Flags = ISound::FLAG_LOOP; Sound()->PlayAt(Chn, SampleId, Flags, Pos.x, Pos.y); } void CSounds::Stop(int SetId) { if(m_WaitForSoundJob || SetId < 0 || SetId >= g_pData->m_NumSounds) return; CDataSoundset *pSet = &g_pData->m_aSounds[SetId]; for(int i = 0; i < pSet->m_NumSounds; i++) Sound()->Stop(pSet->m_aSounds[i].m_Id); } ================================================ FILE: src/game/client/components/sounds.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_CLIENT_COMPONENTS_SOUNDS_H #define GAME_CLIENT_COMPONENTS_SOUNDS_H #include <engine/sound.h> #include <game/client/component.h> class CSounds : public CComponent { enum { QUEUE_SIZE = 32, }; struct QueueEntry { int m_Channel; int m_SetId; } m_aQueue[QUEUE_SIZE]; int m_QueuePos; int64 m_QueueWaitTime; class CJob m_SoundJob; bool m_WaitForSoundJob; ISound::CSampleHandle GetSampleId(int SetId); public: // sound channels enum { CHN_GUI=0, CHN_MUSIC, CHN_WORLD, CHN_GLOBAL, }; virtual void OnInit(); virtual void OnReset(); virtual void OnStateChange(int NewState, int OldState); virtual void OnRender(); void ClearQueue(); void Enqueue(int Channel, int SetId); void Play(int Channel, int SetId, float Vol); void PlayAt(int Channel, int SetId, float Vol, vec2 Pos); void Stop(int SetId); }; #endif ================================================ FILE: src/game/client/components/spectator.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <engine/demo.h> #include <engine/graphics.h> #include <engine/textrender.h> #include <engine/shared/config.h> #include <game/generated/client_data.h> #include <game/generated/protocol.h> #include <game/client/animstate.h> #include <game/client/render.h> #include "spectator.h" void CSpectator::ConKeySpectator(IConsole::IResult *pResult, void *pUserData) { CSpectator *pSelf = (CSpectator *)pUserData; if(pSelf->m_pClient->m_Snap.m_SpecInfo.m_Active && (pSelf->Client()->State() != IClient::STATE_DEMOPLAYBACK || pSelf->DemoPlayer()->GetDemoType() == IDemoPlayer::DEMOTYPE_SERVER)) pSelf->m_Active = pResult->GetInteger(0) != 0; } void CSpectator::ConSpectate(IConsole::IResult *pResult, void *pUserData) { ((CSpectator *)pUserData)->Spectate(pResult->GetInteger(0)); } void CSpectator::ConSpectateNext(IConsole::IResult *pResult, void *pUserData) { CSpectator *pSelf = (CSpectator *)pUserData; int NewSpectatorID; bool GotNewSpectatorID = false; if(pSelf->m_pClient->m_Snap.m_SpecInfo.m_SpectatorID == SPEC_FREEVIEW) { for(int i = 0; i < MAX_CLIENTS; i++) { if(!pSelf->m_pClient->m_aClients[i].m_Active || pSelf->m_pClient->m_aClients[i].m_Team == TEAM_SPECTATORS) continue; NewSpectatorID = i; GotNewSpectatorID = true; break; } } else { for(int i = pSelf->m_pClient->m_Snap.m_SpecInfo.m_SpectatorID + 1; i < MAX_CLIENTS; i++) { if(!pSelf->m_pClient->m_aClients[i].m_Active || pSelf->m_pClient->m_aClients[i].m_Team == TEAM_SPECTATORS) continue; NewSpectatorID = i; GotNewSpectatorID = true; break; } if(!GotNewSpectatorID) { for(int i = 0; i < pSelf->m_pClient->m_Snap.m_SpecInfo.m_SpectatorID; i++) { if(!pSelf->m_pClient->m_aClients[i].m_Active || pSelf->m_pClient->m_aClients[i].m_Team == TEAM_SPECTATORS) continue; NewSpectatorID = i; GotNewSpectatorID = true; break; } } } if(GotNewSpectatorID) pSelf->Spectate(NewSpectatorID); } void CSpectator::ConSpectatePrevious(IConsole::IResult *pResult, void *pUserData) { CSpectator *pSelf = (CSpectator *)pUserData; int NewSpectatorID; bool GotNewSpectatorID = false; if(pSelf->m_pClient->m_Snap.m_SpecInfo.m_SpectatorID == SPEC_FREEVIEW) { for(int i = MAX_CLIENTS -1; i > -1; i--) { if(!pSelf->m_pClient->m_aClients[i].m_Active || pSelf->m_pClient->m_aClients[i].m_Team == TEAM_SPECTATORS) continue; NewSpectatorID = i; GotNewSpectatorID = true; break; } } else { for(int i = pSelf->m_pClient->m_Snap.m_SpecInfo.m_SpectatorID - 1; i > -1; i--) { if(!pSelf->m_pClient->m_aClients[i].m_Active || pSelf->m_pClient->m_aClients[i].m_Team == TEAM_SPECTATORS) continue; NewSpectatorID = i; GotNewSpectatorID = true; break; } if(!GotNewSpectatorID) { for(int i = MAX_CLIENTS - 1; i > pSelf->m_pClient->m_Snap.m_SpecInfo.m_SpectatorID; i--) { if(!pSelf->m_pClient->m_aClients[i].m_Active || pSelf->m_pClient->m_aClients[i].m_Team == TEAM_SPECTATORS) continue; NewSpectatorID = i; GotNewSpectatorID = true; break; } } } if(GotNewSpectatorID) pSelf->Spectate(NewSpectatorID); } CSpectator::CSpectator() { OnReset(); } void CSpectator::OnConsoleInit() { Console()->Register("+spectate", "", CFGFLAG_CLIENT, ConKeySpectator, this, "Open spectator mode selector"); Console()->Register("spectate", "i", CFGFLAG_CLIENT, ConSpectate, this, "Switch spectator mode"); Console()->Register("spectate_next", "", CFGFLAG_CLIENT, ConSpectateNext, this, "Spectate the next player"); Console()->Register("spectate_previous", "", CFGFLAG_CLIENT, ConSpectatePrevious, this, "Spectate the previous player"); } bool CSpectator::OnMouseMove(float x, float y) { if(!m_Active) return false; UI()->ConvertMouseMove(&x, &y); m_SelectorMouse += vec2(x,y); return true; } void CSpectator::OnRelease() { OnReset(); } void CSpectator::OnRender() { if(!m_Active) { if(m_WasActive) { if(m_SelectedSpectatorID != NO_SELECTION) Spectate(m_SelectedSpectatorID); m_WasActive = false; } return; } if(!m_pClient->m_Snap.m_SpecInfo.m_Active) { m_Active = false; m_WasActive = false; return; } m_WasActive = true; m_SelectedSpectatorID = NO_SELECTION; // draw background float Width = 400*3.0f*Graphics()->ScreenAspect(); float Height = 400*3.0f; Graphics()->MapScreen(0, 0, Width, Height); Graphics()->BlendNormal(); Graphics()->TextureClear(); Graphics()->QuadsBegin(); Graphics()->SetColor(0.0f, 0.0f, 0.0f, 0.3f); RenderTools()->DrawRoundRect(Width/2.0f-300.0f, Height/2.0f-300.0f, 600.0f, 600.0f, 20.0f); Graphics()->QuadsEnd(); // clamp mouse position to selector area m_SelectorMouse.x = clamp(m_SelectorMouse.x, -280.0f, 280.0f); m_SelectorMouse.y = clamp(m_SelectorMouse.y, -280.0f, 280.0f); // draw selections float FontSize = 20.0f; float StartY = -190.0f; float LineHeight = 60.0f; bool Selected = false; if(m_pClient->m_aClients[m_pClient->m_LocalClientID].m_Team == TEAM_SPECTATORS) { if(m_pClient->m_Snap.m_SpecInfo.m_SpectatorID == SPEC_FREEVIEW) { Graphics()->TextureClear(); Graphics()->QuadsBegin(); Graphics()->SetColor(1.0f, 1.0f, 1.0f, 0.25f); RenderTools()->DrawRoundRect(Width/2.0f-280.0f, Height/2.0f-280.0f, 270.0f, 60.0f, 20.0f); Graphics()->QuadsEnd(); } if(m_SelectorMouse.x >= -280.0f && m_SelectorMouse.x <= -10.0f && m_SelectorMouse.y >= -280.0f && m_SelectorMouse.y <= -220.0f) { m_SelectedSpectatorID = SPEC_FREEVIEW; Selected = true; } TextRender()->TextColor(1.0f, 1.0f, 1.0f, Selected?1.0f:0.5f); TextRender()->Text(0, Width/2.0f-240.0f, Height/2.0f-265.0f, FontSize, Localize("Free-View"), -1); } float x = -270.0f, y = StartY; for(int i = 0, Count = 0; i < MAX_CLIENTS; ++i) { if(!m_pClient->m_Snap.m_paPlayerInfos[i] || m_pClient->m_aClients[i].m_Team == TEAM_SPECTATORS || (m_pClient->m_aClients[m_pClient->m_LocalClientID].m_Team != TEAM_SPECTATORS && (m_pClient->m_Snap.m_paPlayerInfos[i]->m_PlayerFlags&PLAYERFLAG_DEAD || m_pClient->m_aClients[m_pClient->m_LocalClientID].m_Team != m_pClient->m_aClients[i].m_Team || i == m_pClient->m_LocalClientID))) continue; if(++Count%9 == 0) { x += 290.0f; y = StartY; } if(m_pClient->m_Snap.m_SpecInfo.m_SpectatorID == i) { Graphics()->TextureClear(); Graphics()->QuadsBegin(); Graphics()->SetColor(1.0f, 1.0f, 1.0f, 0.25f); RenderTools()->DrawRoundRect(Width/2.0f+x-10.0f, Height/2.0f+y-10.0f, 270.0f, 60.0f, 20.0f); Graphics()->QuadsEnd(); } Selected = false; if(m_SelectorMouse.x >= x-10.0f && m_SelectorMouse.x <= x+260.0f && m_SelectorMouse.y >= y-10.0f && m_SelectorMouse.y <= y+50.0f) { m_SelectedSpectatorID = i; Selected = true; } TextRender()->TextColor(1.0f, 1.0f, 1.0f, Selected?1.0f:0.5f); TextRender()->Text(0, Width/2.0f+x+50.0f, Height/2.0f+y+5.0f, FontSize, m_pClient->m_aClients[i].m_aName, 220.0f); // flag if(m_pClient->m_GameInfo.m_GameFlags&GAMEFLAG_FLAGS && m_pClient->m_Snap.m_pGameDataFlag && (m_pClient->m_Snap.m_pGameDataFlag->m_FlagCarrierRed == i || m_pClient->m_Snap.m_pGameDataFlag->m_FlagCarrierBlue == i)) { Graphics()->BlendNormal(); Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id); Graphics()->QuadsBegin(); RenderTools()->SelectSprite(m_pClient->m_aClients[i].m_Team==TEAM_RED ? SPRITE_FLAG_BLUE : SPRITE_FLAG_RED, SPRITE_FLAG_FLIP_X); float Size = LineHeight; IGraphics::CQuadItem QuadItem(Width/2.0f+x-LineHeight/5.0f, Height/2.0f+y-LineHeight/3.0f, Size/2.0f, Size); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); } CTeeRenderInfo TeeInfo = m_pClient->m_aClients[i].m_RenderInfo; RenderTools()->RenderTee(CAnimState::GetIdle(), &TeeInfo, EMOTE_NORMAL, vec2(1.0f, 0.0f), vec2(Width/2.0f+x+20.0f, Height/2.0f+y+20.0f)); y += LineHeight; } TextRender()->TextColor(1.0f, 1.0f, 1.0f, 1.0f); // draw cursor Graphics()->TextureSet(g_pData->m_aImages[IMAGE_CURSOR].m_Id); Graphics()->QuadsBegin(); Graphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f); IGraphics::CQuadItem QuadItem(m_SelectorMouse.x+Width/2.0f, m_SelectorMouse.y+Height/2.0f, 48.0f, 48.0f); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); } void CSpectator::OnReset() { m_WasActive = false; m_Active = false; m_SelectedSpectatorID = NO_SELECTION; } void CSpectator::Spectate(int SpectatorID) { if(Client()->State() == IClient::STATE_DEMOPLAYBACK) { m_pClient->m_DemoSpecID = clamp(SpectatorID, (int)SPEC_FREEVIEW, MAX_CLIENTS-1); return; } if(m_pClient->m_Snap.m_SpecInfo.m_SpectatorID == SpectatorID) return; CNetMsg_Cl_SetSpectatorMode Msg; Msg.m_SpectatorID = SpectatorID; Client()->SendPackMsg(&Msg, MSGFLAG_VITAL); } ================================================ FILE: src/game/client/components/spectator.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_CLIENT_COMPONENTS_SPECTATOR_H #define GAME_CLIENT_COMPONENTS_SPECTATOR_H #include <base/vmath.h> #include <game/client/component.h> class CSpectator : public CComponent { enum { NO_SELECTION=-2, }; bool m_Active; bool m_WasActive; int m_SelectedSpectatorID; vec2 m_SelectorMouse; static void ConKeySpectator(IConsole::IResult *pResult, void *pUserData); static void ConSpectate(IConsole::IResult *pResult, void *pUserData); static void ConSpectateNext(IConsole::IResult *pResult, void *pUserData); static void ConSpectatePrevious(IConsole::IResult *pResult, void *pUserData); public: CSpectator(); virtual void OnConsoleInit(); virtual bool OnMouseMove(float x, float y); virtual void OnRender(); virtual void OnRelease(); virtual void OnReset(); void Spectate(int SpectatorID); }; #endif ================================================ FILE: src/game/client/components/voting.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <base/vmath.h> #include <engine/shared/config.h> #include <game/client/render.h> #include <game/generated/protocol.h> #include "chat.h" #include "voting.h" void CVoting::ConVote(IConsole::IResult *pResult, void *pUserData) { CVoting *pSelf = (CVoting *)pUserData; if(str_comp_nocase(pResult->GetString(0), "yes") == 0) pSelf->Vote(1); else if(str_comp_nocase(pResult->GetString(0), "no") == 0) pSelf->Vote(-1); } void CVoting::Callvote(const char *pType, const char *pValue, const char *pReason, bool ForceVote) { CNetMsg_Cl_CallVote Msg = {0}; Msg.m_Type = pType; Msg.m_Value = pValue; Msg.m_Reason = pReason; Msg.m_Force = ForceVote; Client()->SendPackMsg(&Msg, MSGFLAG_VITAL); } void CVoting::CallvoteSpectate(int ClientID, const char *pReason, bool ForceVote) { char aBuf[32]; str_format(aBuf, sizeof(aBuf), "%d", ClientID); Callvote("spectate", aBuf, pReason, ForceVote); } void CVoting::CallvoteKick(int ClientID, const char *pReason, bool ForceVote) { char aBuf[32]; str_format(aBuf, sizeof(aBuf), "%d", ClientID); Callvote("kick", aBuf, pReason, ForceVote); } void CVoting::CallvoteOption(int OptionID, const char *pReason, bool ForceVote) { CVoteOptionClient *pOption = m_pFirst; while(pOption && OptionID >= 0) { if(OptionID == 0) { Callvote("option", pOption->m_aDescription, pReason, ForceVote); break; } OptionID--; pOption = pOption->m_pNext; } } void CVoting::RemovevoteOption(int OptionID) { CVoteOptionClient *pOption = m_pFirst; while(pOption && OptionID >= 0) { if(OptionID == 0) { char aBuf[128]; str_format(aBuf, sizeof(aBuf), "remove_vote \"%s\"", pOption->m_aDescription); Client()->Rcon(aBuf); break; } OptionID--; pOption = pOption->m_pNext; } } void CVoting::AddvoteOption(const char *pDescription, const char *pCommand) { char aBuf[128]; str_format(aBuf, sizeof(aBuf), "add_vote \"%s\" %s", pDescription, pCommand); Client()->Rcon(aBuf); } void CVoting::Vote(int v) { CNetMsg_Cl_Vote Msg = {v}; Client()->SendPackMsg(&Msg, MSGFLAG_VITAL); } CVoting::CVoting() { ClearOptions(); m_Closetime = 0; m_aDescription[0] = 0; m_aReason[0] = 0; m_Yes = m_No = m_Pass = m_Total = 0; m_Voted = 0; } void CVoting::AddOption(const char *pDescription) { CVoteOptionClient *pOption; if(m_pRecycleFirst) { pOption = m_pRecycleFirst; m_pRecycleFirst = m_pRecycleFirst->m_pNext; if(m_pRecycleFirst) m_pRecycleFirst->m_pPrev = 0; else m_pRecycleLast = 0; } else pOption = (CVoteOptionClient *)m_Heap.Allocate(sizeof(CVoteOptionClient)); pOption->m_pNext = 0; pOption->m_pPrev = m_pLast; if(pOption->m_pPrev) pOption->m_pPrev->m_pNext = pOption; m_pLast = pOption; if(!m_pFirst) m_pFirst = pOption; str_copy(pOption->m_aDescription, pDescription, sizeof(pOption->m_aDescription)); ++m_NumVoteOptions; } void CVoting::ClearOptions() { m_Heap.Reset(); m_NumVoteOptions = 0; m_pFirst = 0; m_pLast = 0; m_pRecycleFirst = 0; m_pRecycleLast = 0; } void CVoting::OnReset() { if(Client()->State() == IClient::STATE_LOADING) // do not reset active vote while connecting return; m_Closetime = 0; m_aDescription[0] = 0; m_aReason[0] = 0; m_Yes = m_No = m_Pass = m_Total = 0; m_Voted = 0; m_CallvoteBlockTick = 0; } void CVoting::OnConsoleInit() { Console()->Register("vote", "r", CFGFLAG_CLIENT, ConVote, this, "Vote yes/no"); } void CVoting::OnMessage(int MsgType, void *pRawMsg) { if(MsgType == NETMSGTYPE_SV_VOTESET) { CNetMsg_Sv_VoteSet *pMsg = (CNetMsg_Sv_VoteSet *)pRawMsg; int BlockTick = m_CallvoteBlockTick; char aBuf[128]; if(pMsg->m_Timeout) { OnReset(); str_copy(m_aDescription, pMsg->m_pDescription, sizeof(m_aDescription)); str_copy(m_aReason, pMsg->m_pReason, sizeof(m_aReason)); m_Closetime = time_get() + time_freq() * pMsg->m_Timeout; if(pMsg->m_ClientID != -1) { switch(pMsg->m_Type) { case VOTE_START_OP: str_format(aBuf, sizeof(aBuf), Localize("'%s' called vote to change server option '%s' (%s)"), m_pClient->m_aClients[pMsg->m_ClientID].m_aName, pMsg->m_pDescription, pMsg->m_pReason); m_pClient->m_pChat->AddLine(-1, 0, aBuf); break; case VOTE_START_KICK: str_format(aBuf, sizeof(aBuf), Localize("'%s' called for vote to kick '%s' (%s)"), m_pClient->m_aClients[pMsg->m_ClientID].m_aName, pMsg->m_pDescription, pMsg->m_pReason); m_pClient->m_pChat->AddLine(-1, 0, aBuf); break; case VOTE_START_SPEC: str_format(aBuf, sizeof(aBuf), Localize("'%s' called for vote to move '%s' to spectators (%s)"), m_pClient->m_aClients[pMsg->m_ClientID].m_aName, pMsg->m_pDescription, pMsg->m_pReason); m_pClient->m_pChat->AddLine(-1, 0, aBuf); } if(pMsg->m_ClientID == m_pClient->m_LocalClientID) m_CallvoteBlockTick = Client()->GameTick()+Client()->GameTickSpeed()*VOTE_COOLDOWN; } } else { switch(pMsg->m_Type) { case VOTE_START_OP: str_format(aBuf, sizeof(aBuf), Localize("Admin forced server option '%s' (%s)"), pMsg->m_pDescription, pMsg->m_pReason); m_pClient->m_pChat->AddLine(-1, 0, aBuf); break; case VOTE_START_SPEC: str_format(aBuf, sizeof(aBuf), Localize("Admin moved '%s' to spectator (%s)"), pMsg->m_pDescription, pMsg->m_pReason); m_pClient->m_pChat->AddLine(-1, 0, aBuf); break; case VOTE_END_ABORT: OnReset(); m_pClient->m_pChat->AddLine(-1, 0, Localize("Vote aborted")); break; case VOTE_END_PASS: OnReset(); if(pMsg->m_ClientID == -1) m_pClient->m_pChat->AddLine(-1, 0, Localize("Admin forced vote yes")); else m_pClient->m_pChat->AddLine(-1, 0, Localize("Vote passed")); break; case VOTE_END_FAIL: OnReset(); if(pMsg->m_ClientID == -1) m_pClient->m_pChat->AddLine(-1, 0, Localize("Admin forced vote no")); else m_pClient->m_pChat->AddLine(-1, 0, Localize("Vote failed")); m_CallvoteBlockTick = BlockTick; } } } else if(MsgType == NETMSGTYPE_SV_VOTESTATUS) { CNetMsg_Sv_VoteStatus *pMsg = (CNetMsg_Sv_VoteStatus *)pRawMsg; m_Yes = pMsg->m_Yes; m_No = pMsg->m_No; m_Pass = pMsg->m_Pass; m_Total = pMsg->m_Total; } else if(MsgType == NETMSGTYPE_SV_VOTECLEAROPTIONS) { ClearOptions(); } else if(MsgType == NETMSGTYPE_SV_VOTEOPTIONADD) { CNetMsg_Sv_VoteOptionAdd *pMsg = (CNetMsg_Sv_VoteOptionAdd *)pRawMsg; AddOption(pMsg->m_pDescription); } else if(MsgType == NETMSGTYPE_SV_VOTEOPTIONREMOVE) { CNetMsg_Sv_VoteOptionRemove *pMsg = (CNetMsg_Sv_VoteOptionRemove *)pRawMsg; for(CVoteOptionClient *pOption = m_pFirst; pOption; pOption = pOption->m_pNext) { if(str_comp(pOption->m_aDescription, pMsg->m_pDescription) == 0) { // remove it from the list if(m_pFirst == pOption) m_pFirst = m_pFirst->m_pNext; if(m_pLast == pOption) m_pLast = m_pLast->m_pPrev; if(pOption->m_pPrev) pOption->m_pPrev->m_pNext = pOption->m_pNext; if(pOption->m_pNext) pOption->m_pNext->m_pPrev = pOption->m_pPrev; --m_NumVoteOptions; // add it to recycle list pOption->m_pNext = 0; pOption->m_pPrev = m_pRecycleLast; if(pOption->m_pPrev) pOption->m_pPrev->m_pNext = pOption; m_pRecycleLast = pOption; if(!m_pRecycleFirst) m_pRecycleLast = pOption; break; } } } } void CVoting::OnRender() { } void CVoting::RenderBars(CUIRect Bars, bool Text) { RenderTools()->DrawUIRect(&Bars, vec4(0.8f,0.8f,0.8f,0.5f), CUI::CORNER_ALL, Bars.h/3); CUIRect Splitter = Bars; Splitter.x = Splitter.x+Splitter.w/2; Splitter.w = Splitter.h/2.0f; Splitter.x -= Splitter.w/2; RenderTools()->DrawUIRect(&Splitter, vec4(0.4f,0.4f,0.4f,0.5f), CUI::CORNER_ALL, Splitter.h/4); if(m_Total) { CUIRect PassArea = Bars; if(m_Yes) { CUIRect YesArea = Bars; YesArea.w *= m_Yes/(float)m_Total; RenderTools()->DrawUIRect(&YesArea, vec4(0.2f,0.9f,0.2f,0.85f), CUI::CORNER_ALL, Bars.h/3); if(Text) { char Buf[256]; str_format(Buf, sizeof(Buf), "%d", m_Yes); UI()->DoLabel(&YesArea, Buf, Bars.h*0.75f, 0); } PassArea.x += YesArea.w; PassArea.w -= YesArea.w; } if(m_No) { CUIRect NoArea = Bars; NoArea.w *= m_No/(float)m_Total; NoArea.x = (Bars.x + Bars.w)-NoArea.w; RenderTools()->DrawUIRect(&NoArea, vec4(0.9f,0.2f,0.2f,0.85f), CUI::CORNER_ALL, Bars.h/3); if(Text) { char Buf[256]; str_format(Buf, sizeof(Buf), "%d", m_No); UI()->DoLabel(&NoArea, Buf, Bars.h*0.75f, 0); } PassArea.w -= NoArea.w; } if(Text && m_Pass) { char Buf[256]; str_format(Buf, sizeof(Buf), "%d", m_Pass); UI()->DoLabel(&PassArea, Buf, Bars.h*0.75f, 0); } } } ================================================ FILE: src/game/client/components/voting.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_CLIENT_COMPONENTS_VOTING_H #define GAME_CLIENT_COMPONENTS_VOTING_H #include <engine/shared/memheap.h> #include <game/voting.h> #include <game/client/component.h> #include <game/client/ui.h> class CVoting : public CComponent { CHeap m_Heap; static void ConVote(IConsole::IResult *pResult, void *pUserData); int64 m_Closetime; char m_aDescription[VOTE_DESC_LENGTH]; char m_aReason[VOTE_REASON_LENGTH]; int m_Voted; int m_Yes, m_No, m_Pass, m_Total; int m_CallvoteBlockTick; void ClearOptions(); void Callvote(const char *pType, const char *pValue, const char *pReason, bool ForceVote); public: int m_NumVoteOptions; CVoteOptionClient *m_pFirst; CVoteOptionClient *m_pLast; CVoteOptionClient *m_pRecycleFirst; CVoteOptionClient *m_pRecycleLast; CVoting(); virtual void OnReset(); virtual void OnConsoleInit(); virtual void OnMessage(int Msgtype, void *pRawMsg); virtual void OnRender(); void RenderBars(CUIRect Bars, bool Text); void CallvoteSpectate(int ClientID, const char *pReason, bool ForceVote = false); void CallvoteKick(int ClientID, const char *pReason, bool ForceVote = false); void CallvoteOption(int OptionID, const char *pReason, bool ForceVote = false); void AddOption(const char *pDescription); void RemovevoteOption(int OptionID); void AddvoteOption(const char *pDescription, const char *pCommand); void Vote(int v); // -1 = no, 1 = yes int SecondsLeft() { return (m_Closetime - time_get())/time_freq(); } bool IsVoting() { return m_Closetime != 0; } int TakenChoice() const { return m_Voted; } const char *VoteDescription() const { return m_aDescription; } const char *VoteReason() const { return m_aReason; } int CallvoteBlockTime() const { return m_CallvoteBlockTick > Client()->GameTick() ? (m_CallvoteBlockTick-Client()->GameTick())/Client()->GameTickSpeed() : 0; } }; #endif ================================================ FILE: src/game/client/gameclient.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <engine/editor.h> #include <engine/engine.h> #include <engine/friends.h> #include <engine/graphics.h> #include <engine/textrender.h> #include <engine/demo.h> #include <engine/map.h> #include <engine/storage.h> #include <engine/sound.h> #include <engine/serverbrowser.h> #include <engine/shared/demo.h> #include <engine/shared/config.h> #include <game/generated/protocol.h> #include <game/generated/client_data.h> #include <game/version.h> #include "localization.h" #include "render.h" #include "gameclient.h" #include "components/binds.h" #include "components/broadcast.h" #include "components/camera.h" #include "components/chat.h" #include "components/console.h" #include "components/controls.h" #include "components/countryflags.h" #include "components/damageind.h" #include "components/debughud.h" #include "components/effects.h" #include "components/emoticon.h" #include "components/flow.h" #include "components/hud.h" #include "components/items.h" #include "components/killmessages.h" #include "components/mapimages.h" #include "components/maplayers.h" #include "components/menus.h" #include "components/motd.h" #include "components/particles.h" #include "components/players.h" #include "components/nameplates.h" #include "components/scoreboard.h" #include "components/skins.h" #include "components/sounds.h" #include "components/spectator.h" #include "components/voting.h" // instanciate all systems static CKillMessages gs_KillMessages; static CCamera gs_Camera; static CChat gs_Chat; static CMotd gs_Motd; static CBroadcast gs_Broadcast; static CGameConsole gs_GameConsole; static CBinds gs_Binds; static CParticles gs_Particles; static CMenus gs_Menus; static CSkins gs_Skins; static CCountryFlags gs_CountryFlags; static CFlow gs_Flow; static CHud gs_Hud; static CDebugHud gs_DebugHud; static CControls gs_Controls; static CEffects gs_Effects; static CScoreboard gs_Scoreboard; static CSounds gs_Sounds; static CEmoticon gs_Emoticon; static CDamageInd gsDamageInd; static CVoting gs_Voting; static CSpectator gs_Spectator; static CPlayers gs_Players; static CNamePlates gs_NamePlates; static CItems gs_Items; static CMapImages gs_MapImages; static CMapLayers gs_MapLayersBackGround(CMapLayers::TYPE_BACKGROUND); static CMapLayers gs_MapLayersForeGround(CMapLayers::TYPE_FOREGROUND); CGameClient::CStack::CStack() { m_Num = 0; } void CGameClient::CStack::Add(class CComponent *pComponent) { m_paComponents[m_Num++] = pComponent; } const char *CGameClient::Version() { return GAME_VERSION; } const char *CGameClient::NetVersion() { return GAME_NETVERSION; } const char *CGameClient::GetItemName(int Type) { return m_NetObjHandler.GetObjName(Type); } const char *CGameClient::GetTeamName(int Team, bool Teamplay) const { if(Teamplay) { if(Team == TEAM_RED) return Localize("red team"); else if(Team == TEAM_BLUE) return Localize("blue team"); } else if(Team == 0) return Localize("game"); return Localize("spectators"); } enum { DO_CHAT=0, DO_BROADCAST, DO_SPECIAL, PARA_NONE=0, PARA_I, PARA_II, PARA_III, }; struct CGameMsg { int m_Action; int m_ParaType; const char *m_pText; }; static CGameMsg gs_GameMsgList[NUM_GAMEMSGS] = { {/*GAMEMSG_TEAM_SWAP*/ DO_CHAT, PARA_NONE, "Teams were swapped"}, {/*GAMEMSG_SPEC_INVALIDID*/ DO_CHAT, PARA_NONE, "Invalid spectator id used"}, //! {/*GAMEMSG_TEAM_SHUFFLE*/ DO_CHAT, PARA_NONE, "Teams were shuffled"}, {/*GAMEMSG_TEAM_BALANCE*/ DO_CHAT, PARA_NONE, "Teams have been balanced"}, {/*GAMEMSG_CTF_DROP*/ DO_SPECIAL, PARA_NONE, ""}, // special - play ctf drop sound {/*GAMEMSG_CTF_RETURN*/ DO_SPECIAL, PARA_NONE, ""}, // special - play ctf return sound {/*GAMEMSG_TEAM_ALL*/ DO_SPECIAL, PARA_I, "All players were moved to the %s"}, // special - add team name {/*GAMEMSG_TEAM_BALANCE_VICTIM*/ DO_SPECIAL, PARA_I, "You were moved to %s due to team balancing"}, // special - add team name {/*GAMEMSG_CTF_GRAB*/ DO_SPECIAL, PARA_I, ""}, // special - play ctf grab sound based on team {/*GAMEMSG_CTF_CAPTURE*/ DO_SPECIAL, PARA_III, ""}, // special - play ctf capture sound + capture chat message }; void CGameClient::OnConsoleInit() { m_pEngine = Kernel()->RequestInterface<IEngine>(); m_pClient = Kernel()->RequestInterface<IClient>(); m_pTextRender = Kernel()->RequestInterface<ITextRender>(); m_pSound = Kernel()->RequestInterface<ISound>(); m_pInput = Kernel()->RequestInterface<IInput>(); m_pConsole = Kernel()->RequestInterface<IConsole>(); m_pStorage = Kernel()->RequestInterface<IStorage>(); m_pDemoPlayer = Kernel()->RequestInterface<IDemoPlayer>(); m_pDemoRecorder = Kernel()->RequestInterface<IDemoRecorder>(); m_pServerBrowser = Kernel()->RequestInterface<IServerBrowser>(); m_pEditor = Kernel()->RequestInterface<IEditor>(); m_pFriends = Kernel()->RequestInterface<IFriends>(); // setup pointers m_pBinds = &::gs_Binds; m_pBroadcast = &::gs_Broadcast; m_pGameConsole = &::gs_GameConsole; m_pParticles = &::gs_Particles; m_pMenus = &::gs_Menus; m_pSkins = &::gs_Skins; m_pCountryFlags = &::gs_CountryFlags; m_pChat = &::gs_Chat; m_pFlow = &::gs_Flow; m_pCamera = &::gs_Camera; m_pControls = &::gs_Controls; m_pEffects = &::gs_Effects; m_pSounds = &::gs_Sounds; m_pMotd = &::gs_Motd; m_pDamageind = &::gsDamageInd; m_pMapimages = &::gs_MapImages; m_pVoting = &::gs_Voting; m_pScoreboard = &::gs_Scoreboard; m_pItems = &::gs_Items; m_pMapLayersBackGround = &::gs_MapLayersBackGround; m_pMapLayersForeGround = &::gs_MapLayersForeGround; // make a list of all the systems, make sure to add them in the corrent render order m_All.Add(m_pSkins); m_All.Add(m_pCountryFlags); m_All.Add(m_pMapimages); m_All.Add(m_pEffects); // doesn't render anything, just updates effects m_All.Add(m_pParticles); // doesn't render anything, just updates all the particles m_All.Add(m_pBinds); m_All.Add(m_pControls); m_All.Add(m_pCamera); m_All.Add(m_pSounds); m_All.Add(m_pVoting); m_All.Add(&gs_MapLayersBackGround); // first to render m_All.Add(&m_pParticles->m_RenderTrail); m_All.Add(m_pItems); m_All.Add(&gs_Players); m_All.Add(&gs_MapLayersForeGround); m_All.Add(&m_pParticles->m_RenderExplosions); m_All.Add(&gs_NamePlates); m_All.Add(&m_pParticles->m_RenderGeneral); m_All.Add(m_pDamageind); m_All.Add(&gs_Hud); m_All.Add(&gs_Spectator); m_All.Add(&gs_Emoticon); m_All.Add(&gs_KillMessages); m_All.Add(m_pChat); m_All.Add(&gs_Broadcast); m_All.Add(&gs_DebugHud); m_All.Add(&gs_Scoreboard); m_All.Add(m_pMotd); m_All.Add(m_pMenus); m_All.Add(m_pGameConsole); // build the input stack m_Input.Add(&m_pMenus->m_Binder); // this will take over all input when we want to bind a key m_Input.Add(&m_pBinds->m_SpecialBinds); m_Input.Add(m_pGameConsole); m_Input.Add(m_pChat); // chat has higher prio due to tha you can quit it by pressing esc m_Input.Add(m_pMotd); // for pressing esc to remove it m_Input.Add(m_pMenus); m_Input.Add(&gs_Spectator); m_Input.Add(&gs_Emoticon); m_Input.Add(m_pControls); m_Input.Add(m_pBinds); // add the some console commands Console()->Register("kill", "", CFGFLAG_CLIENT, ConKill, this, "Kill yourself"); Console()->Register("ready_change", "", CFGFLAG_CLIENT, ConReadyChange, this, "Change ready state"); Console()->Chain("add_friend", ConchainFriendUpdate, this); Console()->Chain("remove_friend", ConchainFriendUpdate, this); for(int i = 0; i < m_All.m_Num; i++) m_All.m_paComponents[i]->m_pClient = this; // let all the other components register their console commands for(int i = 0; i < m_All.m_Num; i++) m_All.m_paComponents[i]->OnConsoleInit(); // m_SuppressEvents = false; } void CGameClient::OnInit() { m_pGraphics = Kernel()->RequestInterface<IGraphics>(); // propagate pointers m_UI.SetGraphics(Graphics(), TextRender()); m_RenderTools.m_pGraphics = Graphics(); m_RenderTools.m_pUI = UI(); int64 Start = time_get(); // set the language g_Localization.Load(g_Config.m_ClLanguagefile, Storage(), Console()); // TODO: this should be different // setup item sizes for(int i = 0; i < NUM_NETOBJTYPES; i++) Client()->SnapSetStaticsize(i, m_NetObjHandler.GetObjSize(i)); // load default font static CFont *pDefaultFont = 0; char aFontName[256]; str_format(aFontName, sizeof(aFontName), "fonts/%s", g_Config.m_ClFontfile); char aFilename[512]; IOHANDLE File = Storage()->OpenFile(aFontName, IOFLAG_READ, IStorage::TYPE_ALL, aFilename, sizeof(aFilename)); if(File) { io_close(File); pDefaultFont = TextRender()->LoadFont(aFilename); TextRender()->SetDefaultFont(pDefaultFont); } if(!pDefaultFont) { char aBuf[256]; str_format(aBuf, sizeof(aBuf), "failed to load font. filename='%s'", aFontName); Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "gameclient", aBuf); } // init all components for(int i = m_All.m_Num-1; i >= 0; --i) m_All.m_paComponents[i]->OnInit(); // setup load amount// load textures for(int i = 0; i < g_pData->m_NumImages; i++) { g_pData->m_aImages[i].m_Id = Graphics()->LoadTexture(g_pData->m_aImages[i].m_pFilename, IStorage::TYPE_ALL, CImageInfo::FORMAT_AUTO, 0); m_pMenus->RenderLoading(); } OnReset(); int64 End = time_get(); char aBuf[256]; str_format(aBuf, sizeof(aBuf), "initialisation finished after %.2fms", ((End-Start)*1000)/(float)time_freq()); Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "gameclient", aBuf); m_ServerMode = SERVERMODE_PURE; } void CGameClient::DispatchInput() { // handle mouse movement float x = 0.0f, y = 0.0f; Input()->MouseRelative(&x, &y); if(x != 0.0f || y != 0.0f) { for(int h = 0; h < m_Input.m_Num; h++) { if(m_Input.m_paComponents[h]->OnMouseMove(x, y)) break; } } // handle key presses for(int i = 0; i < Input()->NumEvents(); i++) { IInput::CEvent e = Input()->GetEvent(i); for(int h = 0; h < m_Input.m_Num; h++) { if(m_Input.m_paComponents[h]->OnInput(e)) { //dbg_msg("", "%d char=%d key=%d flags=%d", h, e.ch, e.key, e.flags); break; } } } // clear all events for this frame Input()->ClearEvents(); } int CGameClient::OnSnapInput(int *pData) { return m_pControls->SnapInput(pData); } void CGameClient::OnConnected() { m_Layers.Init(Kernel()); m_Collision.Init(Layers()); RenderTools()->RenderTilemapGenerateSkip(Layers()); for(int i = 0; i < m_All.m_Num; i++) { m_All.m_paComponents[i]->OnMapLoad(); m_All.m_paComponents[i]->OnReset(); } m_ServerMode = SERVERMODE_PURE; // send the inital info SendStartInfo(); } void CGameClient::OnReset() { // clear out the invalid pointers m_LastNewPredictedTick = -1; mem_zero(&m_Snap, sizeof(m_Snap)); for(int i = 0; i < MAX_CLIENTS; i++) m_aClients[i].Reset(this); for(int i = 0; i < m_All.m_Num; i++) m_All.m_paComponents[i]->OnReset(); m_LocalClientID = -1; m_TeamCooldownTick = 0; mem_zero(&m_GameInfo, sizeof(m_GameInfo)); m_DemoSpecID = SPEC_FREEVIEW; m_Tuning = CTuningParams(); } void CGameClient::UpdatePositions() { // local character position if(g_Config.m_ClPredict && Client()->State() != IClient::STATE_DEMOPLAYBACK) { if(!m_Snap.m_pLocalCharacter || (m_Snap.m_pGameData && m_Snap.m_pGameData->m_GameStateFlags&(GAMESTATEFLAG_PAUSED|GAMESTATEFLAG_ROUNDOVER|GAMESTATEFLAG_GAMEOVER))) { // don't use predicted } else m_LocalCharacterPos = mix(m_PredictedPrevChar.m_Pos, m_PredictedChar.m_Pos, Client()->PredIntraGameTick()); } else if(m_Snap.m_pLocalCharacter && m_Snap.m_pLocalPrevCharacter) { m_LocalCharacterPos = mix( vec2(m_Snap.m_pLocalPrevCharacter->m_X, m_Snap.m_pLocalPrevCharacter->m_Y), vec2(m_Snap.m_pLocalCharacter->m_X, m_Snap.m_pLocalCharacter->m_Y), Client()->IntraGameTick()); } // spectator position if(m_Snap.m_SpecInfo.m_Active) { if(Client()->State() == IClient::STATE_DEMOPLAYBACK && DemoPlayer()->GetDemoType() == IDemoPlayer::DEMOTYPE_SERVER && m_Snap.m_SpecInfo.m_SpectatorID != SPEC_FREEVIEW) { m_Snap.m_SpecInfo.m_Position = mix( vec2(m_Snap.m_aCharacters[m_Snap.m_SpecInfo.m_SpectatorID].m_Prev.m_X, m_Snap.m_aCharacters[m_Snap.m_SpecInfo.m_SpectatorID].m_Prev.m_Y), vec2(m_Snap.m_aCharacters[m_Snap.m_SpecInfo.m_SpectatorID].m_Cur.m_X, m_Snap.m_aCharacters[m_Snap.m_SpecInfo.m_SpectatorID].m_Cur.m_Y), Client()->IntraGameTick()); m_Snap.m_SpecInfo.m_UsePosition = true; } else if(m_Snap.m_pSpectatorInfo && (Client()->State() == IClient::STATE_DEMOPLAYBACK || m_Snap.m_SpecInfo.m_SpectatorID != SPEC_FREEVIEW)) { if(m_Snap.m_pPrevSpectatorInfo) m_Snap.m_SpecInfo.m_Position = mix(vec2(m_Snap.m_pPrevSpectatorInfo->m_X, m_Snap.m_pPrevSpectatorInfo->m_Y), vec2(m_Snap.m_pSpectatorInfo->m_X, m_Snap.m_pSpectatorInfo->m_Y), Client()->IntraGameTick()); else m_Snap.m_SpecInfo.m_Position = vec2(m_Snap.m_pSpectatorInfo->m_X, m_Snap.m_pSpectatorInfo->m_Y); m_Snap.m_SpecInfo.m_UsePosition = true; } } } void CGameClient::EvolveCharacter(CNetObj_Character *pCharacter, int Tick) { CWorldCore TempWorld; CCharacterCore TempCore; mem_zero(&TempCore, sizeof(TempCore)); TempCore.Init(&TempWorld, Collision()); TempCore.Read(pCharacter); while(pCharacter->m_Tick < Tick) { pCharacter->m_Tick++; TempCore.Tick(false); TempCore.Move(); TempCore.Quantize(); } TempCore.Write(pCharacter); } void CGameClient::OnRender() { /*Graphics()->Clear(1,0,0); menus->render_background(); return;*/ /* Graphics()->Clear(1,0,0); Graphics()->MapScreen(0,0,100,100); Graphics()->QuadsBegin(); Graphics()->SetColor(1,1,1,1); Graphics()->QuadsDraw(50, 50, 30, 30); Graphics()->QuadsEnd(); return;*/ // update the local character and spectate position UpdatePositions(); // dispatch all input to systems DispatchInput(); // render all systems for(int i = 0; i < m_All.m_Num; i++) m_All.m_paComponents[i]->OnRender(); } void CGameClient::OnRelease() { // release all systems for(int i = 0; i < m_All.m_Num; i++) m_All.m_paComponents[i]->OnRelease(); } void CGameClient::OnMessage(int MsgId, CUnpacker *pUnpacker) { Client()->RecordGameMessage(true); // special messages if(MsgId == NETMSGTYPE_SV_EXTRAPROJECTILE) { int Num = pUnpacker->GetInt(); for(int k = 0; k < Num; k++) { CNetObj_Projectile Proj; for(unsigned i = 0; i < sizeof(CNetObj_Projectile)/sizeof(int); i++) ((int *)&Proj)[i] = pUnpacker->GetInt(); if(pUnpacker->Error()) return; m_pItems->AddExtraProjectile(&Proj); } return; } else if(MsgId == NETMSGTYPE_SV_TUNEPARAMS && Client()->State() != IClient::STATE_DEMOPLAYBACK) { Client()->RecordGameMessage(false); // unpack the new tuning CTuningParams NewTuning; int *pParams = (int *)&NewTuning; for(unsigned i = 0; i < sizeof(CTuningParams)/sizeof(int); i++) pParams[i] = pUnpacker->GetInt(); // check for unpacking errors if(pUnpacker->Error()) return; m_ServerMode = SERVERMODE_PURE; // apply new tuning m_Tuning = NewTuning; return; } else if(MsgId == NETMSGTYPE_SV_VOTEOPTIONLISTADD) { int NumOptions = pUnpacker->GetInt(); for(int i = 0; i < NumOptions; i++) { const char *pDescription = pUnpacker->GetString(CUnpacker::SANITIZE_CC); if(pUnpacker->Error()) return; m_pVoting->AddOption(pDescription); } } else if(MsgId == NETMSGTYPE_SV_GAMEMSG) { int GameMsgID = pUnpacker->GetInt(); int aParaI[3]; int NumParaI = 0; // get paras switch(gs_GameMsgList[GameMsgID].m_ParaType) { case PARA_III: aParaI[NumParaI++] = pUnpacker->GetInt(); case PARA_II: aParaI[NumParaI++] = pUnpacker->GetInt(); case PARA_I: aParaI[NumParaI++] = pUnpacker->GetInt(); } // check for unpacking errors if(pUnpacker->Error()) return; // handle special messages static char aBuf[256]; if(gs_GameMsgList[GameMsgID].m_Action == DO_SPECIAL) { switch(GameMsgID) { case GAMEMSG_CTF_DROP: if(m_SuppressEvents) return; m_pSounds->Enqueue(CSounds::CHN_GLOBAL, SOUND_CTF_DROP); break; case GAMEMSG_CTF_RETURN: if(m_SuppressEvents) return; m_pSounds->Enqueue(CSounds::CHN_GLOBAL, SOUND_CTF_RETURN); break; case GAMEMSG_TEAM_BALANCE_VICTIM: str_format(aBuf, sizeof(aBuf), Localize(gs_GameMsgList[GameMsgID].m_pText), GetTeamName(aParaI[0], m_GameInfo.m_GameFlags&GAMEFLAG_TEAMS)); m_pBroadcast->DoBroadcast(aBuf); break; case GAMEMSG_CTF_GRAB: if(m_SuppressEvents) return; if(m_LocalClientID != -1 && (m_aClients[m_LocalClientID].m_Team != aParaI[0] || (m_Snap.m_SpecInfo.m_Active && m_Snap.m_SpecInfo.m_SpectatorID != -1 && m_aClients[m_Snap.m_SpecInfo.m_SpectatorID].m_Team != aParaI[0]))) m_pSounds->Enqueue(CSounds::CHN_GLOBAL, SOUND_CTF_GRAB_PL); else m_pSounds->Enqueue(CSounds::CHN_GLOBAL, SOUND_CTF_GRAB_EN); break; case GAMEMSG_CTF_CAPTURE: m_pSounds->Enqueue(CSounds::CHN_GLOBAL, SOUND_CTF_CAPTURE); if(aParaI[2] <= 60*Client()->GameTickSpeed()) str_format(aBuf, sizeof(aBuf), "The %s flag was captured by '%s' (%.2f seconds)", aParaI[0] ? Localize("blue") : Localize("red"), m_aClients[clamp(aParaI[1], 0, MAX_CLIENTS-1)].m_aName, aParaI[2]/(float)Client()->GameTickSpeed()); else str_format(aBuf, sizeof(aBuf), "The %s flag was captured by '%s'", aParaI[0] ? Localize("blue") : Localize("red"), m_aClients[clamp(aParaI[1], 0, MAX_CLIENTS-1)].m_aName); m_pChat->AddLine(-1, 0, aBuf); } return; } // build message const char *pText = ""; if(NumParaI == 0) pText = Localize(gs_GameMsgList[GameMsgID].m_pText); else { if(NumParaI == 1) str_format(aBuf, sizeof(aBuf), Localize(gs_GameMsgList[GameMsgID].m_pText), aParaI[0]); else if(NumParaI == 2) str_format(aBuf, sizeof(aBuf), Localize(gs_GameMsgList[GameMsgID].m_pText), aParaI[0], aParaI[1]); else if(NumParaI == 3) str_format(aBuf, sizeof(aBuf), Localize(gs_GameMsgList[GameMsgID].m_pText), aParaI[0], aParaI[1], aParaI[2]); pText = aBuf; } // handle message switch(gs_GameMsgList[GameMsgID].m_Action) { case DO_CHAT: m_pChat->AddLine(-1, 0, pText); break; case DO_BROADCAST: m_pBroadcast->DoBroadcast(pText); } } void *pRawMsg = m_NetObjHandler.SecureUnpackMsg(MsgId, pUnpacker); if(!pRawMsg) { char aBuf[256]; str_format(aBuf, sizeof(aBuf), "dropped weird message '%s' (%d), failed on '%s'", m_NetObjHandler.GetMsgName(MsgId), MsgId, m_NetObjHandler.FailedMsgOn()); Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "client", aBuf); return; } // TODO: this should be done smarter for(int i = 0; i < m_All.m_Num; i++) m_All.m_paComponents[i]->OnMessage(MsgId, pRawMsg); if(MsgId == NETMSGTYPE_SV_CLIENTINFO && Client()->State() != IClient::STATE_DEMOPLAYBACK) { Client()->RecordGameMessage(false); CNetMsg_Sv_ClientInfo *pMsg = (CNetMsg_Sv_ClientInfo *)pRawMsg; if(pMsg->m_Local) { if(m_LocalClientID != -1) { if(g_Config.m_Debug) Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "client", "invalid local clientinfo"); return; } m_LocalClientID = pMsg->m_ClientID; } else { if(m_aClients[pMsg->m_ClientID].m_Active) { if(g_Config.m_Debug) Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "client", "invalid clientinfo"); return; } if(m_LocalClientID != -1) { DoEnterMessage(pMsg->m_pName, pMsg->m_Team); if(m_pDemoRecorder->IsRecording()) { CNetMsg_De_ClientEnter Msg; Msg.m_pName = pMsg->m_pName; Msg.m_Team = pMsg->m_Team; Client()->SendPackMsg(&Msg, MSGFLAG_NOSEND|MSGFLAG_RECORD); } } } m_aClients[pMsg->m_ClientID].m_Active = true; m_aClients[pMsg->m_ClientID].m_Team = pMsg->m_Team; str_copy(m_aClients[pMsg->m_ClientID].m_aName, pMsg->m_pName, sizeof(m_aClients[pMsg->m_ClientID].m_aName)); str_copy(m_aClients[pMsg->m_ClientID].m_aClan, pMsg->m_pClan, sizeof(m_aClients[pMsg->m_ClientID].m_aClan)); m_aClients[pMsg->m_ClientID].m_Country = pMsg->m_Country; for(int i = 0; i < 6; i++) { str_copy(m_aClients[pMsg->m_ClientID].m_aaSkinPartNames[i], pMsg->m_apSkinPartNames[i], 24); m_aClients[pMsg->m_ClientID].m_aUseCustomColors[i] = pMsg->m_aUseCustomColors[i]; m_aClients[pMsg->m_ClientID].m_aSkinPartColors[i] = pMsg->m_aSkinPartColors[i]; } // update friend state m_aClients[pMsg->m_ClientID].m_Friend = Friends()->IsFriend(m_aClients[pMsg->m_ClientID].m_aName, m_aClients[pMsg->m_ClientID].m_aClan, true); m_aClients[pMsg->m_ClientID].UpdateRenderInfo(this, true); m_GameInfo.m_NumPlayers++; // calculate team-balance if(m_aClients[pMsg->m_ClientID].m_Team != TEAM_SPECTATORS) m_GameInfo.m_aTeamSize[m_aClients[pMsg->m_ClientID].m_Team]++; } else if(MsgId == NETMSGTYPE_SV_CLIENTDROP && Client()->State() != IClient::STATE_DEMOPLAYBACK) { Client()->RecordGameMessage(false); CNetMsg_Sv_ClientDrop *pMsg = (CNetMsg_Sv_ClientDrop *)pRawMsg; if(m_LocalClientID == pMsg->m_ClientID || !m_aClients[pMsg->m_ClientID].m_Active) { if(g_Config.m_Debug) Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "client", "invalid clientdrop"); return; } DoLeaveMessage(m_aClients[pMsg->m_ClientID].m_aName, pMsg->m_pReason); CNetMsg_De_ClientLeave Msg; Msg.m_pName = m_aClients[pMsg->m_ClientID].m_aName; Msg.m_pReason = pMsg->m_pReason; Client()->SendPackMsg(&Msg, MSGFLAG_NOSEND|MSGFLAG_RECORD); m_GameInfo.m_NumPlayers--; // calculate team-balance if(m_aClients[pMsg->m_ClientID].m_Team != TEAM_SPECTATORS) m_GameInfo.m_aTeamSize[m_aClients[pMsg->m_ClientID].m_Team]--; m_aClients[pMsg->m_ClientID].Reset(this); } else if(MsgId == NETMSGTYPE_SV_GAMEINFO && Client()->State() != IClient::STATE_DEMOPLAYBACK) { Client()->RecordGameMessage(false); CNetMsg_Sv_GameInfo *pMsg = (CNetMsg_Sv_GameInfo *)pRawMsg; m_GameInfo.m_GameFlags = pMsg->m_GameFlags; m_GameInfo.m_ScoreLimit = pMsg->m_ScoreLimit; m_GameInfo.m_TimeLimit = pMsg->m_TimeLimit; m_GameInfo.m_MatchNum = pMsg->m_MatchNum; m_GameInfo.m_MatchCurrent = pMsg->m_MatchCurrent; } else if(MsgId == NETMSGTYPE_SV_SERVERSETTINGS && Client()->State() != IClient::STATE_DEMOPLAYBACK) { Client()->RecordGameMessage(false); CNetMsg_Sv_ServerSettings *pMsg = (CNetMsg_Sv_ServerSettings *)pRawMsg; if(!m_ServerSettings.m_TeamLock && pMsg->m_TeamLock) m_pChat->AddLine(-1, 0, Localize("Teams were locked")); else if(m_ServerSettings.m_TeamLock && !pMsg->m_TeamLock) m_pChat->AddLine(-1, 0, Localize("Teams were unlocked")); m_ServerSettings.m_KickVote = pMsg->m_KickVote; m_ServerSettings.m_KickMin = pMsg->m_KickMin; m_ServerSettings.m_SpecVote = pMsg->m_SpecVote; m_ServerSettings.m_TeamLock = pMsg->m_TeamLock; m_ServerSettings.m_TeamBalance = pMsg->m_TeamBalance; m_ServerSettings.m_PlayerSlots = pMsg->m_PlayerSlots; } else if(MsgId == NETMSGTYPE_SV_TEAM) { CNetMsg_Sv_Team *pMsg = (CNetMsg_Sv_Team *)pRawMsg; if(Client()->State() != IClient::STATE_DEMOPLAYBACK) { // calculate team-balance if(m_aClients[pMsg->m_ClientID].m_Team != TEAM_SPECTATORS) m_GameInfo.m_aTeamSize[m_aClients[pMsg->m_ClientID].m_Team]--; m_aClients[pMsg->m_ClientID].m_Team = pMsg->m_Team; if(m_aClients[pMsg->m_ClientID].m_Team != TEAM_SPECTATORS) m_GameInfo.m_aTeamSize[m_aClients[pMsg->m_ClientID].m_Team]++; m_aClients[pMsg->m_ClientID].UpdateRenderInfo(this, false); if(pMsg->m_ClientID == m_LocalClientID) m_TeamCooldownTick = pMsg->m_CooldownTick; } if(pMsg->m_Silent == 0) { DoTeamChangeMessage(m_aClients[pMsg->m_ClientID].m_aName, pMsg->m_Team); } } else if(MsgId == NETMSGTYPE_SV_READYTOENTER) { Client()->EnterGame(); } else if (MsgId == NETMSGTYPE_SV_EMOTICON) { CNetMsg_Sv_Emoticon *pMsg = (CNetMsg_Sv_Emoticon *)pRawMsg; // apply m_aClients[pMsg->m_ClientID].m_Emoticon = pMsg->m_Emoticon; m_aClients[pMsg->m_ClientID].m_EmoticonStart = Client()->GameTick(); } else if(MsgId == NETMSGTYPE_DE_CLIENTENTER && Client()->State() == IClient::STATE_DEMOPLAYBACK) { CNetMsg_De_ClientEnter *pMsg = (CNetMsg_De_ClientEnter *)pRawMsg; DoEnterMessage(pMsg->m_pName, pMsg->m_Team); } else if(MsgId == NETMSGTYPE_DE_CLIENTLEAVE && Client()->State() == IClient::STATE_DEMOPLAYBACK) { CNetMsg_De_ClientLeave *pMsg = (CNetMsg_De_ClientLeave *)pRawMsg; DoLeaveMessage(pMsg->m_pName, pMsg->m_pReason); } } void CGameClient::OnStateChange(int NewState, int OldState) { // reset everything when not already connected (to keep gathered stuff) if(NewState < IClient::STATE_ONLINE) OnReset(); // then change the state for(int i = 0; i < m_All.m_Num; i++) m_All.m_paComponents[i]->OnStateChange(NewState, OldState); } void CGameClient::OnShutdown() {} void CGameClient::OnEnterGame() {} void CGameClient::OnGameOver() { if(Client()->State() != IClient::STATE_DEMOPLAYBACK && g_Config.m_ClEditor == 0) Client()->AutoScreenshot_Start(); } void CGameClient::OnStartGame() { if(Client()->State() != IClient::STATE_DEMOPLAYBACK) Client()->DemoRecorder_HandleAutoStart(); } void CGameClient::OnRconLine(const char *pLine) { m_pGameConsole->PrintLine(CGameConsole::CONSOLETYPE_REMOTE, pLine); } void CGameClient::ProcessEvents() { if(m_SuppressEvents) return; int SnapType = IClient::SNAP_CURRENT; int Num = Client()->SnapNumItems(SnapType); for(int Index = 0; Index < Num; Index++) { IClient::CSnapItem Item; const void *pData = Client()->SnapGetItem(SnapType, Index, &Item); if(Item.m_Type == NETEVENTTYPE_DAMAGEIND) { CNetEvent_DamageInd *ev = (CNetEvent_DamageInd *)pData; m_pEffects->DamageIndicator(vec2(ev->m_X, ev->m_Y), GetDirection(ev->m_Angle)); } else if(Item.m_Type == NETEVENTTYPE_EXPLOSION) { CNetEvent_Explosion *ev = (CNetEvent_Explosion *)pData; m_pEffects->Explosion(vec2(ev->m_X, ev->m_Y)); } else if(Item.m_Type == NETEVENTTYPE_HAMMERHIT) { CNetEvent_HammerHit *ev = (CNetEvent_HammerHit *)pData; m_pEffects->HammerHit(vec2(ev->m_X, ev->m_Y)); } else if(Item.m_Type == NETEVENTTYPE_SPAWN) { CNetEvent_Spawn *ev = (CNetEvent_Spawn *)pData; m_pEffects->PlayerSpawn(vec2(ev->m_X, ev->m_Y)); } else if(Item.m_Type == NETEVENTTYPE_DEATH) { CNetEvent_Death *ev = (CNetEvent_Death *)pData; m_pEffects->PlayerDeath(vec2(ev->m_X, ev->m_Y), ev->m_ClientID); } else if(Item.m_Type == NETEVENTTYPE_SOUNDWORLD) { CNetEvent_SoundWorld *ev = (CNetEvent_SoundWorld *)pData; m_pSounds->PlayAt(CSounds::CHN_WORLD, ev->m_SoundID, 1.0f, vec2(ev->m_X, ev->m_Y)); } } } void CGameClient::ProcessTriggeredEvents(int Events, vec2 Pos) { if(m_SuppressEvents) return; if(Events&COREEVENTFLAG_GROUND_JUMP) m_pSounds->PlayAt(CSounds::CHN_WORLD, SOUND_PLAYER_JUMP, 1.0f, Pos); if(Events&COREEVENTFLAG_AIR_JUMP) m_pEffects->AirJump(Pos); if(Events&COREEVENTFLAG_HOOK_ATTACH_PLAYER) m_pSounds->PlayAt(CSounds::CHN_WORLD, SOUND_HOOK_ATTACH_PLAYER, 1.0f, Pos); if(Events&COREEVENTFLAG_HOOK_ATTACH_GROUND) m_pSounds->PlayAt(CSounds::CHN_WORLD, SOUND_HOOK_ATTACH_GROUND, 1.0f, Pos); if(Events&COREEVENTFLAG_HOOK_HIT_NOHOOK) m_pSounds->PlayAt(CSounds::CHN_WORLD, SOUND_HOOK_NOATTACH, 1.0f, Pos); /*if(Events&COREEVENTFLAG_HOOK_LAUNCH) m_pSounds->PlayAt(CSounds::CHN_WORLD, SOUND_HOOK_LOOP, 1.0f, Pos); if(Events&COREEVENTFLAG_HOOK_RETRACT) m_pSounds->PlayAt(CSounds::CHN_WORLD, SOUND_PLAYER_JUMP, 1.0f, Pos);*/ } void CGameClient::OnNewSnapshot() { // clear out the invalid pointers mem_zero(&m_Snap, sizeof(m_Snap)); // secure snapshot { int Num = Client()->SnapNumItems(IClient::SNAP_CURRENT); for(int Index = 0; Index < Num; Index++) { IClient::CSnapItem Item; void *pData = Client()->SnapGetItem(IClient::SNAP_CURRENT, Index, &Item); if(m_NetObjHandler.ValidateObj(Item.m_Type, pData, Item.m_DataSize) != 0) { if(g_Config.m_Debug) { char aBuf[256]; str_format(aBuf, sizeof(aBuf), "invalidated index=%d type=%d (%s) size=%d id=%d", Index, Item.m_Type, m_NetObjHandler.GetObjName(Item.m_Type), Item.m_DataSize, Item.m_ID); Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", aBuf); } Client()->SnapInvalidateItem(IClient::SNAP_CURRENT, Index); } } } ProcessEvents(); if(g_Config.m_DbgStress) { if((Client()->GameTick()%100) == 0) { char aMessage[64]; int MsgLen = rand()%(sizeof(aMessage)-1); for(int i = 0; i < MsgLen; i++) aMessage[i] = 'a'+(rand()%('z'-'a')); aMessage[MsgLen] = 0; CNetMsg_Cl_Say Msg; Msg.m_Team = rand()&1; Msg.m_pMessage = aMessage; Client()->SendPackMsg(&Msg, MSGFLAG_VITAL); } } CTuningParams StandardTuning; if(Client()->State() == IClient::STATE_DEMOPLAYBACK) { m_Tuning = StandardTuning; mem_zero(&m_GameInfo, sizeof(m_GameInfo)); } // go trough all the items in the snapshot and gather the info we want { int Num = Client()->SnapNumItems(IClient::SNAP_CURRENT); for(int i = 0; i < Num; i++) { IClient::CSnapItem Item; const void *pData = Client()->SnapGetItem(IClient::SNAP_CURRENT, i, &Item); // demo items if(Client()->State() == IClient::STATE_DEMOPLAYBACK) { if(Item.m_Type == NETOBJTYPE_DE_CLIENTINFO) { const CNetObj_De_ClientInfo *pInfo = (const CNetObj_De_ClientInfo *)pData; int ClientID = Item.m_ID; CClientData *pClient = &m_aClients[ClientID]; if(pInfo->m_Local) m_LocalClientID = ClientID; pClient->m_Active = true; pClient->m_Team = pInfo->m_Team; IntsToStr(pInfo->m_aName, 4, pClient->m_aName); IntsToStr(pInfo->m_aClan, 3, pClient->m_aClan); pClient->m_Country = pInfo->m_Country; for(int p = 0; p < CSkins::NUM_SKINPARTS; p++) { IntsToStr(pInfo->m_aaSkinPartNames[p], 6, pClient->m_aaSkinPartNames[p]); pClient->m_aUseCustomColors[p] = pInfo->m_aUseCustomColors[p]; pClient->m_aSkinPartColors[p] = pInfo->m_aSkinPartColors[p]; } m_GameInfo.m_NumPlayers++; // calculate team-balance if(pClient->m_Team != TEAM_SPECTATORS) m_GameInfo.m_aTeamSize[pClient->m_Team]++; } else if(Item.m_Type == NETOBJTYPE_DE_GAMEINFO) { const CNetObj_De_GameInfo *pInfo = (const CNetObj_De_GameInfo *)pData; m_GameInfo.m_GameFlags = pInfo->m_GameFlags; m_GameInfo.m_ScoreLimit = pInfo->m_ScoreLimit; m_GameInfo.m_TimeLimit = pInfo->m_TimeLimit; m_GameInfo.m_MatchNum = pInfo->m_MatchNum; m_GameInfo.m_MatchCurrent = pInfo->m_MatchCurrent; } else if(Item.m_Type == NETOBJTYPE_DE_TUNEPARAMS) { const CNetObj_De_TuneParams *pInfo = (const CNetObj_De_TuneParams *)pData; mem_copy(&m_Tuning, pInfo->m_aTuneParams, sizeof(m_Tuning)); m_ServerMode = SERVERMODE_PURE; } } // network items if(Item.m_Type == NETOBJTYPE_PLAYERINFO) { const CNetObj_PlayerInfo *pInfo = (const CNetObj_PlayerInfo *)pData; int ClientID = Item.m_ID; if(m_aClients[ClientID].m_Active) { m_Snap.m_paPlayerInfos[ClientID] = pInfo; m_Snap.m_aInfoByScore[ClientID].m_pPlayerInfo = pInfo; m_Snap.m_aInfoByScore[ClientID].m_ClientID = ClientID; if(m_LocalClientID == ClientID) { m_Snap.m_pLocalInfo = pInfo; if(m_aClients[ClientID].m_Team == TEAM_SPECTATORS) { m_Snap.m_SpecInfo.m_Active = true; m_Snap.m_SpecInfo.m_SpectatorID = SPEC_FREEVIEW; } } } } else if(Item.m_Type == NETOBJTYPE_CHARACTER) { const void *pOld = Client()->SnapFindItem(IClient::SNAP_PREV, NETOBJTYPE_CHARACTER, Item.m_ID); m_Snap.m_aCharacters[Item.m_ID].m_Cur = *((const CNetObj_Character *)pData); // clamp ammo count for non ninja weapon if(m_Snap.m_aCharacters[Item.m_ID].m_Cur.m_Weapon != WEAPON_NINJA) m_Snap.m_aCharacters[Item.m_ID].m_Cur.m_AmmoCount = clamp(m_Snap.m_aCharacters[Item.m_ID].m_Cur.m_AmmoCount, 0, 10); if(pOld) { m_Snap.m_aCharacters[Item.m_ID].m_Active = true; m_Snap.m_aCharacters[Item.m_ID].m_Prev = *((const CNetObj_Character *)pOld); if(m_Snap.m_aCharacters[Item.m_ID].m_Prev.m_Tick) EvolveCharacter(&m_Snap.m_aCharacters[Item.m_ID].m_Prev, Client()->PrevGameTick()); if(m_Snap.m_aCharacters[Item.m_ID].m_Cur.m_Tick) EvolveCharacter(&m_Snap.m_aCharacters[Item.m_ID].m_Cur, Client()->GameTick()); } if(Item.m_ID != m_LocalClientID || Client()->State() == IClient::STATE_DEMOPLAYBACK) ProcessTriggeredEvents(m_Snap.m_aCharacters[Item.m_ID].m_Cur.m_TriggeredEvents, vec2(m_Snap.m_aCharacters[Item.m_ID].m_Cur.m_X, m_Snap.m_aCharacters[Item.m_ID].m_Cur.m_Y)); } else if(Item.m_Type == NETOBJTYPE_SPECTATORINFO) { m_Snap.m_pSpectatorInfo = (const CNetObj_SpectatorInfo *)pData; m_Snap.m_pPrevSpectatorInfo = (const CNetObj_SpectatorInfo *)Client()->SnapFindItem(IClient::SNAP_PREV, NETOBJTYPE_SPECTATORINFO, Item.m_ID); m_Snap.m_SpecInfo.m_Active = true; m_Snap.m_SpecInfo.m_SpectatorID = m_Snap.m_pSpectatorInfo->m_SpectatorID; } else if(Item.m_Type == NETOBJTYPE_GAMEDATA) { m_Snap.m_pGameData = (const CNetObj_GameData *)pData; static bool s_GameOver = 0; if(!s_GameOver && m_Snap.m_pGameData->m_GameStateFlags&GAMESTATEFLAG_GAMEOVER) OnGameOver(); else if(s_GameOver && !(m_Snap.m_pGameData->m_GameStateFlags&GAMESTATEFLAG_GAMEOVER)) OnStartGame(); s_GameOver = m_Snap.m_pGameData->m_GameStateFlags&GAMESTATEFLAG_GAMEOVER; } else if(Item.m_Type == NETOBJTYPE_GAMEDATATEAM) { m_Snap.m_pGameDataTeam = (const CNetObj_GameDataTeam *)pData; } else if(Item.m_Type == NETOBJTYPE_GAMEDATAFLAG) { m_Snap.m_pGameDataFlag = (const CNetObj_GameDataFlag *)pData; m_Snap.m_GameDataFlagSnapID = Item.m_ID; } else if(Item.m_Type == NETOBJTYPE_FLAG) m_Snap.m_paFlags[Item.m_ID%2] = (const CNetObj_Flag *)pData; } } // setup local pointers if(m_LocalClientID >= 0) { CSnapState::CCharacterInfo *c = &m_Snap.m_aCharacters[m_LocalClientID]; if(c->m_Active) { m_Snap.m_pLocalCharacter = &c->m_Cur; m_Snap.m_pLocalPrevCharacter = &c->m_Prev; m_LocalCharacterPos = vec2(m_Snap.m_pLocalCharacter->m_X, m_Snap.m_pLocalCharacter->m_Y); } else if(Client()->SnapFindItem(IClient::SNAP_PREV, NETOBJTYPE_CHARACTER, m_LocalClientID)) { // player died m_pControls->OnPlayerDeath(); } } else { m_Snap.m_SpecInfo.m_Active = true; if(Client()->State() == IClient::STATE_DEMOPLAYBACK && DemoPlayer()->GetDemoType() == IDemoPlayer::DEMOTYPE_SERVER && m_DemoSpecID != SPEC_FREEVIEW && m_Snap.m_aCharacters[m_DemoSpecID].m_Active) m_Snap.m_SpecInfo.m_SpectatorID = m_DemoSpecID; else m_Snap.m_SpecInfo.m_SpectatorID = SPEC_FREEVIEW; } // sort player infos by score for(int k = 0; k < MAX_CLIENTS-1; k++) // ffs, bubblesort { for(int i = 0; i < MAX_CLIENTS-k-1; i++) { if(m_Snap.m_aInfoByScore[i+1].m_pPlayerInfo && (!m_Snap.m_aInfoByScore[i].m_pPlayerInfo || m_Snap.m_aInfoByScore[i].m_pPlayerInfo->m_Score < m_Snap.m_aInfoByScore[i+1].m_pPlayerInfo->m_Score)) { CPlayerInfoItem Tmp = m_Snap.m_aInfoByScore[i]; m_Snap.m_aInfoByScore[i] = m_Snap.m_aInfoByScore[i+1]; m_Snap.m_aInfoByScore[i+1] = Tmp; } } } // calc some player stats for(int i = 0; i < MAX_CLIENTS; ++i) { if(!m_Snap.m_paPlayerInfos[i]) continue; // count not ready players if((m_Snap.m_pGameData->m_GameStateFlags&(GAMESTATEFLAG_STARTCOUNTDOWN|GAMESTATEFLAG_PAUSED|GAMESTATEFLAG_WARMUP)) && m_Snap.m_pGameData->m_GameStateEndTick == 0 && m_aClients[i].m_Team != TEAM_SPECTATORS && !(m_Snap.m_paPlayerInfos[i]->m_PlayerFlags&PLAYERFLAG_READY)) m_Snap.m_NotReadyCount++; // count alive players per team if((m_GameInfo.m_GameFlags&GAMEFLAG_SURVIVAL) && m_aClients[i].m_Team != TEAM_SPECTATORS && !(m_Snap.m_paPlayerInfos[i]->m_PlayerFlags&PLAYERFLAG_DEAD)) m_Snap.m_AliveCount[m_aClients[i].m_Team]++; } if(Client()->State() == IClient::STATE_DEMOPLAYBACK) { for(int i = 0; i < MAX_CLIENTS; ++i) { if(m_aClients[i].m_Active) m_aClients[i].UpdateRenderInfo(this, true); } } CServerInfo CurrentServerInfo; Client()->GetServerInfo(&CurrentServerInfo); if(CurrentServerInfo.m_aGameType[0] != '0') { if(str_comp(CurrentServerInfo.m_aGameType, "DM") != 0 && str_comp(CurrentServerInfo.m_aGameType, "TDM") != 0 && str_comp(CurrentServerInfo.m_aGameType, "CTF") != 0 && str_comp(CurrentServerInfo.m_aGameType, "LMS") != 0 && str_comp(CurrentServerInfo.m_aGameType, "SUR") != 0) m_ServerMode = SERVERMODE_MOD; else if(mem_comp(&StandardTuning, &m_Tuning, sizeof(CTuningParams)) == 0) m_ServerMode = SERVERMODE_PURE; else m_ServerMode = SERVERMODE_PUREMOD; } } void CGameClient::OnDemoRecSnap() { // add client info for(int i = 0; i < MAX_CLIENTS; ++i) { if(!m_aClients[i].m_Active) continue; CNetObj_De_ClientInfo *pClientInfo = static_cast<CNetObj_De_ClientInfo *>(Client()->SnapNewItem(NETOBJTYPE_DE_CLIENTINFO, i, sizeof(CNetObj_De_ClientInfo))); if(!pClientInfo) return; pClientInfo->m_Local = i==m_LocalClientID ? 1 : 0; pClientInfo->m_Team = m_aClients[i].m_Team; StrToInts(pClientInfo->m_aName, 4, m_aClients[i].m_aName); StrToInts(pClientInfo->m_aClan, 3, m_aClients[i].m_aClan); pClientInfo->m_Country = m_aClients[i].m_Country; for(int p = 0; p < 6; p++) { StrToInts(pClientInfo->m_aaSkinPartNames[p], 6, m_aClients[i].m_aaSkinPartNames[p]); pClientInfo->m_aUseCustomColors[p] = m_aClients[i].m_aUseCustomColors[p]; pClientInfo->m_aSkinPartColors[p] = m_aClients[i].m_aSkinPartColors[p]; } } // add tuning CTuningParams StandardTuning; if(mem_comp(&StandardTuning, &m_Tuning, sizeof(CTuningParams)) != 0) { CNetObj_De_TuneParams *pTuneParams = static_cast<CNetObj_De_TuneParams *>(Client()->SnapNewItem(NETOBJTYPE_DE_TUNEPARAMS, 0, sizeof(CNetObj_De_TuneParams))); if(!pTuneParams) return; mem_copy(pTuneParams->m_aTuneParams, &m_Tuning, sizeof(pTuneParams->m_aTuneParams)); } // add game info CNetObj_De_GameInfo *pGameInfo = static_cast<CNetObj_De_GameInfo *>(Client()->SnapNewItem(NETOBJTYPE_DE_GAMEINFO, 0, sizeof(CNetObj_De_GameInfo))); if(!pGameInfo) return; pGameInfo->m_GameFlags = m_GameInfo.m_GameFlags; pGameInfo->m_ScoreLimit = m_GameInfo.m_ScoreLimit; pGameInfo->m_TimeLimit = m_GameInfo.m_TimeLimit; pGameInfo->m_MatchNum = m_GameInfo.m_MatchNum; pGameInfo->m_MatchCurrent = m_GameInfo.m_MatchCurrent; } void CGameClient::OnPredict() { // store the previous values so we can detect prediction errors CCharacterCore BeforePrevChar = m_PredictedPrevChar; CCharacterCore BeforeChar = m_PredictedChar; // we can't predict without our own id or own character if(m_LocalClientID == -1 || !m_Snap.m_aCharacters[m_LocalClientID].m_Active) return; // don't predict anything if we are paused or round/game is over if(m_Snap.m_pGameData && m_Snap.m_pGameData->m_GameStateFlags&(GAMESTATEFLAG_PAUSED|GAMESTATEFLAG_ROUNDOVER|GAMESTATEFLAG_GAMEOVER)) { if(m_Snap.m_pLocalCharacter) m_PredictedChar.Read(m_Snap.m_pLocalCharacter); if(m_Snap.m_pLocalPrevCharacter) m_PredictedPrevChar.Read(m_Snap.m_pLocalPrevCharacter); return; } // repredict character CWorldCore World; World.m_Tuning = m_Tuning; // search for players for(int i = 0; i < MAX_CLIENTS; i++) { if(!m_Snap.m_aCharacters[i].m_Active) continue; m_aClients[i].m_Predicted.Init(&World, Collision()); World.m_apCharacters[i] = &m_aClients[i].m_Predicted; m_aClients[i].m_Predicted.Read(&m_Snap.m_aCharacters[i].m_Cur); } // predict for(int Tick = Client()->GameTick()+1; Tick <= Client()->PredGameTick(); Tick++) { // fetch the local if(Tick == Client()->PredGameTick() && World.m_apCharacters[m_LocalClientID]) m_PredictedPrevChar = *World.m_apCharacters[m_LocalClientID]; // first calculate where everyone should move for(int c = 0; c < MAX_CLIENTS; c++) { if(!World.m_apCharacters[c]) continue; mem_zero(&World.m_apCharacters[c]->m_Input, sizeof(World.m_apCharacters[c]->m_Input)); if(m_LocalClientID == c) { // apply player input int *pInput = Client()->GetInput(Tick); if(pInput) World.m_apCharacters[c]->m_Input = *((CNetObj_PlayerInput*)pInput); World.m_apCharacters[c]->Tick(true); } else World.m_apCharacters[c]->Tick(false); } // move all players and quantize their data for(int c = 0; c < MAX_CLIENTS; c++) { if(!World.m_apCharacters[c]) continue; World.m_apCharacters[c]->Move(); World.m_apCharacters[c]->Quantize(); } // check if we want to trigger effects if(Tick > m_LastNewPredictedTick) { m_LastNewPredictedTick = Tick; if(m_LocalClientID != -1 && World.m_apCharacters[m_LocalClientID]) ProcessTriggeredEvents(World.m_apCharacters[m_LocalClientID]->m_TriggeredEvents, World.m_apCharacters[m_LocalClientID]->m_Pos); } if(Tick == Client()->PredGameTick() && World.m_apCharacters[m_LocalClientID]) m_PredictedChar = *World.m_apCharacters[m_LocalClientID]; } if(g_Config.m_Debug && g_Config.m_ClPredict && m_PredictedTick == Client()->PredGameTick()) { CNetObj_CharacterCore Before = {0}, Now = {0}, BeforePrev = {0}, NowPrev = {0}; BeforeChar.Write(&Before); BeforePrevChar.Write(&BeforePrev); m_PredictedChar.Write(&Now); m_PredictedPrevChar.Write(&NowPrev); if(mem_comp(&Before, &Now, sizeof(CNetObj_CharacterCore)) != 0) { Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "client", "prediction error"); for(unsigned i = 0; i < sizeof(CNetObj_CharacterCore)/sizeof(int); i++) if(((int *)&Before)[i] != ((int *)&Now)[i]) { char aBuf[256]; str_format(aBuf, sizeof(aBuf), " %d %d %d (%d %d)", i, ((int *)&Before)[i], ((int *)&Now)[i], ((int *)&BeforePrev)[i], ((int *)&NowPrev)[i]); Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "client", aBuf); } } } m_PredictedTick = Client()->PredGameTick(); } void CGameClient::OnActivateEditor() { OnRelease(); } void CGameClient::CClientData::UpdateRenderInfo(CGameClient *pGameClient, bool UpdateSkinInfo) { // update skin info if(UpdateSkinInfo) { m_SkinInfo.m_Size = 64; for(int p = 0; p < CSkins::NUM_SKINPARTS; p++) { int ID = pGameClient->m_pSkins->FindSkinPart(p, m_aaSkinPartNames[p], false); if(ID < 0) { if(p == CSkins::SKINPART_TATTOO || p == CSkins::SKINPART_DECORATION) ID = pGameClient->m_pSkins->FindSkinPart(p, "", false); else ID = pGameClient->m_pSkins->FindSkinPart(p, "standard", false); if(ID < 0) m_SkinPartIDs[p] = 0; else m_SkinPartIDs[p] = ID; } else m_SkinPartIDs[p] = ID; const CSkins::CSkinPart *pSkinPart = pGameClient->m_pSkins->GetSkinPart(p, m_SkinPartIDs[p]); if(m_aUseCustomColors[p]) { m_SkinInfo.m_aTextures[p] = pSkinPart->m_ColorTexture; m_SkinInfo.m_aColors[p] = pGameClient->m_pSkins->GetColorV4(m_aSkinPartColors[p], p==CSkins::SKINPART_TATTOO); } else { m_SkinInfo.m_aTextures[p] = pSkinPart->m_OrgTexture; m_SkinInfo.m_aColors[p] = vec4(1.0f, 1.0f, 1.0f, 1.0f); } } } m_RenderInfo = m_SkinInfo; // force team colors if(pGameClient->m_GameInfo.m_GameFlags&GAMEFLAG_TEAMS) { for(int p = 0; p < CSkins::NUM_SKINPARTS; p++) { m_RenderInfo.m_aTextures[p] = pGameClient->m_pSkins->GetSkinPart(p, m_SkinPartIDs[p])->m_ColorTexture; int ColorVal = pGameClient->m_pSkins->GetTeamColor(m_aUseCustomColors[p], m_aSkinPartColors[p], m_Team, p); m_RenderInfo.m_aColors[p] = pGameClient->m_pSkins->GetColorV4(ColorVal, p==CSkins::SKINPART_TATTOO); } } } void CGameClient::CClientData::Reset(CGameClient *pGameClient) { m_aName[0] = 0; m_aClan[0] = 0; m_Country = -1; m_Team = 0; m_Angle = 0; m_Emoticon = 0; m_EmoticonStart = -1; m_Active = false; m_ChatIgnore = false; m_Friend = false; for(int p = 0; p < CSkins::NUM_SKINPARTS; p++) { m_SkinPartIDs[p] = 0; m_SkinInfo.m_aTextures[p] = pGameClient->m_pSkins->GetSkinPart(p, 0)->m_ColorTexture; m_SkinInfo.m_aColors[p] = vec4(1.0f, 1.0f, 1.0f , 1.0f); } UpdateRenderInfo(pGameClient, false); } void CGameClient::DoEnterMessage(const char *pName, int Team) { char aBuf[128]; str_format(aBuf, sizeof(aBuf), Localize("'%s' entered and joined the %s"), pName, GetTeamName(Team, m_GameInfo.m_GameFlags&GAMEFLAG_TEAMS)); m_pChat->AddLine(-1, 0, aBuf); } void CGameClient::DoLeaveMessage(const char *pName, const char *pReason) { char aBuf[128]; if(pReason[0]) str_format(aBuf, sizeof(aBuf), Localize("'%s' has left the game (%s)"), pName, pReason); else str_format(aBuf, sizeof(aBuf), Localize("'%s' has left the game"), pName); m_pChat->AddLine(-1, 0, aBuf); } void CGameClient::DoTeamChangeMessage(const char *pName, int Team) { char aBuf[128]; str_format(aBuf, sizeof(aBuf), Localize("'%s' joined the %s"), pName, GetTeamName(Team, m_GameInfo.m_GameFlags&GAMEFLAG_TEAMS)); m_pChat->AddLine(-1, 0, aBuf); } void CGameClient::SendSwitchTeam(int Team) { CNetMsg_Cl_SetTeam Msg; Msg.m_Team = Team; Client()->SendPackMsg(&Msg, MSGFLAG_VITAL); } void CGameClient::SendStartInfo() { CNetMsg_Cl_StartInfo Msg; Msg.m_pName = g_Config.m_PlayerName; Msg.m_pClan = g_Config.m_PlayerClan; Msg.m_Country = g_Config.m_PlayerCountry; for(int p = 0; p < CSkins::NUM_SKINPARTS; p++) { Msg.m_apSkinPartNames[p] = CSkins::ms_apSkinVariables[p]; Msg.m_aUseCustomColors[p] = *CSkins::ms_apUCCVariables[p]; Msg.m_aSkinPartColors[p] = *CSkins::ms_apColorVariables[p]; } Client()->SendPackMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_FLUSH); } void CGameClient::SendKill() { CNetMsg_Cl_Kill Msg; Client()->SendPackMsg(&Msg, MSGFLAG_VITAL); } void CGameClient::SendReadyChange() { CNetMsg_Cl_ReadyChange Msg; Client()->SendPackMsg(&Msg, MSGFLAG_VITAL); } void CGameClient::ConKill(IConsole::IResult *pResult, void *pUserData) { ((CGameClient*)pUserData)->SendKill(); } void CGameClient::ConReadyChange(IConsole::IResult *pResult, void *pUserData) { ((CGameClient*)pUserData)->SendReadyChange(); } void CGameClient::ConchainFriendUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData) { pfnCallback(pResult, pCallbackUserData); CGameClient *pClient = static_cast<CGameClient *>(pUserData); for(int i = 0; i < MAX_CLIENTS; ++i) { if(pClient->m_aClients[i].m_Active) pClient->m_aClients[i].m_Friend = pClient->Friends()->IsFriend(pClient->m_aClients[i].m_aName, pClient->m_aClients[i].m_aClan, true); } } IGameClient *CreateGameClient() { return new CGameClient(); } ================================================ FILE: src/game/client/gameclient.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_CLIENT_GAMECLIENT_H #define GAME_CLIENT_GAMECLIENT_H #include <base/vmath.h> #include <engine/client.h> #include <engine/console.h> #include <game/layers.h> #include <game/gamecore.h> #include "render.h" class CGameClient : public IGameClient { class CStack { public: enum { MAX_COMPONENTS = 64, }; CStack(); void Add(class CComponent *pComponent); class CComponent *m_paComponents[MAX_COMPONENTS]; int m_Num; }; CStack m_All; CStack m_Input; CNetObjHandler m_NetObjHandler; class IEngine *m_pEngine; class IInput *m_pInput; class IGraphics *m_pGraphics; class ITextRender *m_pTextRender; class IClient *m_pClient; class ISound *m_pSound; class IConsole *m_pConsole; class IStorage *m_pStorage; class IDemoPlayer *m_pDemoPlayer; class IDemoRecorder *m_pDemoRecorder; class IServerBrowser *m_pServerBrowser; class IEditor *m_pEditor; class IFriends *m_pFriends; CLayers m_Layers; class CCollision m_Collision; CUI m_UI; void DispatchInput(); void ProcessEvents(); void ProcessTriggeredEvents(int Events, vec2 Pos); void UpdatePositions(); int m_PredictedTick; int m_LastNewPredictedTick; static void ConKill(IConsole::IResult *pResult, void *pUserData); static void ConReadyChange(IConsole::IResult *pResult, void *pUserData); static void ConchainFriendUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData); void EvolveCharacter(CNetObj_Character *pCharacter, int Tick); public: IKernel *Kernel() { return IInterface::Kernel(); } IEngine *Engine() const { return m_pEngine; } class IGraphics *Graphics() const { return m_pGraphics; } class IClient *Client() const { return m_pClient; } class CUI *UI() { return &m_UI; } class ISound *Sound() const { return m_pSound; } class IInput *Input() const { return m_pInput; } class IStorage *Storage() const { return m_pStorage; } class IConsole *Console() { return m_pConsole; } class ITextRender *TextRender() const { return m_pTextRender; } class IDemoPlayer *DemoPlayer() const { return m_pDemoPlayer; } class IDemoRecorder *DemoRecorder() const { return m_pDemoRecorder; } class IServerBrowser *ServerBrowser() const { return m_pServerBrowser; } class CRenderTools *RenderTools() { return &m_RenderTools; } class CLayers *Layers() { return &m_Layers; }; class CCollision *Collision() { return &m_Collision; }; class IEditor *Editor() { return m_pEditor; } class IFriends *Friends() { return m_pFriends; } int NetobjNumCorrections() { return m_NetObjHandler.NumObjCorrections(); } const char *NetobjCorrectedOn() { return m_NetObjHandler.CorrectedObjOn(); } bool m_SuppressEvents; // TODO: move this CTuningParams m_Tuning; enum { SERVERMODE_PURE=0, SERVERMODE_MOD, SERVERMODE_PUREMOD, }; int m_ServerMode; int m_DemoSpecID; vec2 m_LocalCharacterPos; // predicted players CCharacterCore m_PredictedPrevChar; CCharacterCore m_PredictedChar; struct CPlayerInfoItem { const CNetObj_PlayerInfo *m_pPlayerInfo; int m_ClientID; }; // snap pointers struct CSnapState { const CNetObj_Character *m_pLocalCharacter; const CNetObj_Character *m_pLocalPrevCharacter; const CNetObj_PlayerInfo *m_pLocalInfo; const CNetObj_SpectatorInfo *m_pSpectatorInfo; const CNetObj_SpectatorInfo *m_pPrevSpectatorInfo; const CNetObj_Flag *m_paFlags[2]; const CNetObj_GameData *m_pGameData; const CNetObj_GameDataTeam *m_pGameDataTeam; const CNetObj_GameDataFlag *m_pGameDataFlag; int m_GameDataFlagSnapID; int m_NotReadyCount; int m_AliveCount[NUM_TEAMS]; const CNetObj_PlayerInfo *m_paPlayerInfos[MAX_CLIENTS]; CPlayerInfoItem m_aInfoByScore[MAX_CLIENTS]; // spectate data struct CSpectateInfo { bool m_Active; int m_SpectatorID; bool m_UsePosition; vec2 m_Position; } m_SpecInfo; // struct CCharacterInfo { bool m_Active; // snapshots CNetObj_Character m_Prev; CNetObj_Character m_Cur; // interpolated position vec2 m_Position; }; CCharacterInfo m_aCharacters[MAX_CLIENTS]; }; CSnapState m_Snap; // client data struct CClientData { char m_aName[MAX_NAME_LENGTH]; char m_aClan[MAX_CLAN_LENGTH]; int m_Country; char m_aaSkinPartNames[6][24]; int m_aUseCustomColors[6]; int m_aSkinPartColors[6]; int m_SkinPartIDs[6]; int m_Team; int m_Emoticon; int m_EmoticonStart; CCharacterCore m_Predicted; CTeeRenderInfo m_SkinInfo; // this is what the server reports CTeeRenderInfo m_RenderInfo; // this is what we use float m_Angle; bool m_Active; bool m_ChatIgnore; bool m_Friend; void UpdateRenderInfo(CGameClient *pGameClient, bool UpdateSkinInfo); void Reset(CGameClient *pGameClient); }; CClientData m_aClients[MAX_CLIENTS]; int m_LocalClientID; int m_TeamCooldownTick; struct CGameInfo { int m_GameFlags; int m_ScoreLimit; int m_TimeLimit; int m_MatchNum; int m_MatchCurrent; int m_NumPlayers; int m_aTeamSize[NUM_TEAMS]; }; CGameInfo m_GameInfo; struct CServerSettings { bool m_KickVote; int m_KickMin; bool m_SpecVote; bool m_TeamLock; bool m_TeamBalance; int m_PlayerSlots; } m_ServerSettings; CRenderTools m_RenderTools; void OnReset(); // hooks virtual void OnConnected(); virtual void OnRender(); virtual void OnRelease(); virtual void OnInit(); virtual void OnConsoleInit(); virtual void OnStateChange(int NewState, int OldState); virtual void OnMessage(int MsgId, CUnpacker *pUnpacker); virtual void OnNewSnapshot(); virtual void OnDemoRecSnap(); virtual void OnPredict(); virtual void OnActivateEditor(); virtual int OnSnapInput(int *pData); virtual void OnShutdown(); virtual void OnEnterGame(); virtual void OnRconLine(const char *pLine); virtual void OnGameOver(); virtual void OnStartGame(); virtual const char *GetItemName(int Type); virtual const char *Version(); virtual const char *NetVersion(); const char *GetTeamName(int Team, bool Teamplay) const; // void DoEnterMessage(const char *pName, int Team); void DoLeaveMessage(const char *pName, const char *pReason); void DoTeamChangeMessage(const char *pName, int Team); // actions // TODO: move these void SendSwitchTeam(int Team); void SendStartInfo(); void SendKill(); void SendReadyChange(); // pointers to all systems class CGameConsole *m_pGameConsole; class CBinds *m_pBinds; class CBroadcast *m_pBroadcast; class CParticles *m_pParticles; class CMenus *m_pMenus; class CSkins *m_pSkins; class CCountryFlags *m_pCountryFlags; class CFlow *m_pFlow; class CChat *m_pChat; class CDamageInd *m_pDamageind; class CCamera *m_pCamera; class CControls *m_pControls; class CEffects *m_pEffects; class CSounds *m_pSounds; class CMotd *m_pMotd; class CMapImages *m_pMapimages; class CVoting *m_pVoting; class CScoreboard *m_pScoreboard; class CItems *m_pItems; class CMapLayers *m_pMapLayersBackGround; class CMapLayers *m_pMapLayersForeGround; }; inline float HueToRgb(float v1, float v2, float h) { if(h < 0.0f) h += 1; if(h > 1.0f) h -= 1; if((6.0f * h) < 1.0f) return v1 + (v2 - v1) * 6.0f * h; if((2.0f * h) < 1.0f) return v2; if((3.0f * h) < 2.0f) return v1 + (v2 - v1) * ((2.0f/3.0f) - h) * 6.0f; return v1; } inline vec3 HslToRgb(vec3 HSL) { if(HSL.s == 0.0f) return vec3(HSL.l, HSL.l, HSL.l); else { float v2 = HSL.l < 0.5f ? HSL.l * (1.0f + HSL.s) : (HSL.l+HSL.s) - (HSL.s*HSL.l); float v1 = 2.0f * HSL.l - v2; return vec3(HueToRgb(v1, v2, HSL.h + (1.0f/3.0f)), HueToRgb(v1, v2, HSL.h), HueToRgb(v1, v2, HSL.h - (1.0f/3.0f))); } } extern const char *Localize(const char *Str, const char *pContext=""); #endif ================================================ FILE: src/game/client/lineinput.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <engine/keys.h> #include "lineinput.h" CLineInput::CLineInput() { Clear(); } void CLineInput::Clear() { mem_zero(m_Str, sizeof(m_Str)); m_Len = 0; m_CursorPos = 0; } void CLineInput::Set(const char *pString) { str_copy(m_Str, pString, sizeof(m_Str)); m_Len = str_length(m_Str); m_CursorPos = m_Len; } bool CLineInput::Manipulate(IInput::CEvent e, char *pStr, int StrMaxSize, int *pStrLenPtr, int *pCursorPosPtr) { int CursorPos = *pCursorPosPtr; int Len = *pStrLenPtr; bool Changes = false; if(CursorPos > Len) CursorPos = Len; int Code = e.m_Unicode; int k = e.m_Key; // 127 is produced on Mac OS X and corresponds to the delete key if (!(Code >= 0 && Code < 32) && Code != 127) { char Tmp[8]; int CharSize = str_utf8_encode(Tmp, Code); if (Len < StrMaxSize - CharSize && CursorPos < StrMaxSize - CharSize) { mem_move(pStr + CursorPos + CharSize, pStr + CursorPos, Len-CursorPos+1); // +1 == null term for(int i = 0; i < CharSize; i++) pStr[CursorPos+i] = Tmp[i]; CursorPos += CharSize; Len += CharSize; Changes = true; } } if(e.m_Flags&IInput::FLAG_PRESS) { if (k == KEY_BACKSPACE && CursorPos > 0) { int NewCursorPos = str_utf8_rewind(pStr, CursorPos); int CharSize = CursorPos-NewCursorPos; mem_move(pStr+NewCursorPos, pStr+CursorPos, Len - NewCursorPos - CharSize + 1); // +1 == null term CursorPos = NewCursorPos; Len -= CharSize; Changes = true; } else if (k == KEY_DELETE && CursorPos < Len) { int p = str_utf8_forward(pStr, CursorPos); int CharSize = p-CursorPos; mem_move(pStr + CursorPos, pStr + CursorPos + CharSize, Len - CursorPos - CharSize + 1); // +1 == null term Len -= CharSize; Changes = true; } else if (k == KEY_LEFT && CursorPos > 0) CursorPos = str_utf8_rewind(pStr, CursorPos); else if (k == KEY_RIGHT && CursorPos < Len) CursorPos = str_utf8_forward(pStr, CursorPos); else if (k == KEY_HOME) CursorPos = 0; else if (k == KEY_END) CursorPos = Len; } *pCursorPosPtr = CursorPos; *pStrLenPtr = Len; return Changes; } void CLineInput::ProcessInput(IInput::CEvent e) { Manipulate(e, m_Str, sizeof(m_Str), &m_Len, &m_CursorPos); } ================================================ FILE: src/game/client/lineinput.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_CLIENT_LINEINPUT_H #define GAME_CLIENT_LINEINPUT_H #include <engine/input.h> // line input helter class CLineInput { char m_Str[256]; int m_Len; int m_CursorPos; public: static bool Manipulate(IInput::CEvent e, char *pStr, int StrMaxSize, int *pStrLenPtr, int *pCursorPosPtr); class CCallback { public: virtual ~CCallback() {} virtual bool Event(IInput::CEvent e) = 0; }; CLineInput(); void Clear(); void ProcessInput(IInput::CEvent e); void Set(const char *pString); const char *GetString() const { return m_Str; } int GetLength() const { return m_Len; } int GetCursorOffset() const { return m_CursorPos; } void SetCursorOffset(int Offset) { m_CursorPos = Offset > m_Len ? m_Len : Offset < 0 ? 0 : Offset; } }; #endif ================================================ FILE: src/game/client/localization.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include "localization.h" #include <base/tl/algorithm.h> #include <engine/external/json-parser/json.h> #include <engine/console.h> #include <engine/storage.h> const char *Localize(const char *pStr, const char *pContext) { const char *pNewStr = g_Localization.FindString(str_quickhash(pStr), str_quickhash(pContext)); return pNewStr ? pNewStr : pStr; } CLocConstString::CLocConstString(const char *pStr, const char *pContext) { m_pDefaultStr = pStr; m_Hash = str_quickhash(m_pDefaultStr); m_ContextHash = str_quickhash(pContext); m_Version = -1; } void CLocConstString::Reload() { m_Version = g_Localization.Version(); const char *pNewStr = g_Localization.FindString(m_Hash, m_ContextHash); m_pCurrentStr = pNewStr; if(!m_pCurrentStr) m_pCurrentStr = m_pDefaultStr; } CLocalizationDatabase::CLocalizationDatabase() { m_VersionCounter = 0; m_CurrentVersion = 0; } void CLocalizationDatabase::AddString(const char *pOrgStr, const char *pNewStr, const char *pContext) { CString s; s.m_Hash = str_quickhash(pOrgStr); s.m_ContextHash = str_quickhash(pContext); s.m_Replacement = *pNewStr ? pNewStr : pOrgStr; m_Strings.add(s); } bool CLocalizationDatabase::Load(const char *pFilename, IStorage *pStorage, IConsole *pConsole) { // empty string means unload if(pFilename[0] == 0) { m_Strings.clear(); m_CurrentVersion = 0; return true; } // read file data into buffer IOHANDLE File = pStorage->OpenFile(pFilename, IOFLAG_READ, IStorage::TYPE_ALL); if(!File) return false; int FileSize = (int)io_length(File); char *pFileData = (char *)mem_alloc(FileSize+1, 1); io_read(File, pFileData, FileSize); pFileData[FileSize] = 0; io_close(File); // init char aBuf[64]; str_format(aBuf, sizeof(aBuf), "loaded '%s'", pFilename); pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "localization", aBuf); m_Strings.clear(); // parse json data json_settings JsonSettings; mem_zero(&JsonSettings, sizeof(JsonSettings)); char aError[256]; json_value *pJsonData = json_parse_ex(&JsonSettings, pFileData, aError); if(pJsonData == 0) { pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, pFilename, aError); mem_free(pFileData); return false; } // extract data const json_value &rStart = (*pJsonData)["translated strings"]; if(rStart.type == json_array) { for(unsigned i = 0; i < rStart.u.array.length; ++i) AddString((const char *)rStart[i]["or"], (const char *)rStart[i]["tr"], (const char *)rStart[i]["context"]); } // clean up json_value_free(pJsonData); mem_free(pFileData); m_CurrentVersion = ++m_VersionCounter; return true; } const char *CLocalizationDatabase::FindString(unsigned Hash, unsigned ContextHash) { CString String; String.m_Hash = Hash; sorted_array<CString>::range r = ::find_binary(m_Strings.all(), String); if(r.empty()) return 0; unsigned DefaultHash = str_quickhash(""); unsigned DefaultIndex = 0; for(unsigned i = 0; i < r.size(); ++i) { const CString &rStr = r.index(i); if(rStr.m_ContextHash == ContextHash) return rStr.m_Replacement; else if(rStr.m_ContextHash == DefaultHash) DefaultIndex = i; } return r.index(DefaultIndex).m_Replacement; } CLocalizationDatabase g_Localization; ================================================ FILE: src/game/client/localization.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_LOCALIZATION_H #define GAME_LOCALIZATION_H #include <base/tl/string.h> #include <base/tl/sorted_array.h> class CLocalizationDatabase { class CString { public: unsigned m_Hash; unsigned m_ContextHash; // TODO: do this as an const char * and put everything on a incremental heap string m_Replacement; bool operator <(const CString &Other) const { return m_Hash < Other.m_Hash; } bool operator <=(const CString &Other) const { return m_Hash <= Other.m_Hash; } bool operator ==(const CString &Other) const { return m_Hash == Other.m_Hash; } }; sorted_array<CString> m_Strings; int m_VersionCounter; int m_CurrentVersion; public: CLocalizationDatabase(); bool Load(const char *pFilename, class IStorage *pStorage, class IConsole *pConsole); int Version() { return m_CurrentVersion; } void AddString(const char *pOrgStr, const char *pNewStr, const char *pContext); const char *FindString(unsigned Hash, unsigned ContextHash); }; extern CLocalizationDatabase g_Localization; class CLocConstString { const char *m_pDefaultStr; const char *m_pCurrentStr; unsigned m_Hash; unsigned m_ContextHash; int m_Version; public: CLocConstString(const char *pStr, const char *pContext=""); void Reload(); inline operator const char *() { if(m_Version != g_Localization.Version()) Reload(); return m_pCurrentStr; } }; extern const char *Localize(const char *pStr, const char *pContext); #endif ================================================ FILE: src/game/client/render.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <math.h> #include <base/math.h> #include <engine/shared/config.h> #include <engine/graphics.h> #include <engine/map.h> #include <game/generated/client_data.h> #include <game/generated/protocol.h> #include <game/layers.h> #include "animstate.h" #include "render.h" static float gs_SpriteWScale; static float gs_SpriteHScale; /* static void layershot_begin() { if(!config.cl_layershot) return; Graphics()->Clear(0,0,0); } static void layershot_end() { if(!config.cl_layershot) return; char buf[256]; str_format(buf, sizeof(buf), "screenshots/layers_%04d.png", config.cl_layershot); gfx_screenshot_direct(buf); config.cl_layershot++; }*/ void CRenderTools::SelectSprite(CDataSprite *pSpr, int Flags, int sx, int sy) { int x = pSpr->m_X+sx; int y = pSpr->m_Y+sy; int w = pSpr->m_W; int h = pSpr->m_H; int cx = pSpr->m_pSet->m_Gridx; int cy = pSpr->m_pSet->m_Gridy; float f = sqrtf(h*h + w*w); gs_SpriteWScale = w/f; gs_SpriteHScale = h/f; float x1 = x/(float)cx; float x2 = (x+w)/(float)cx; float y1 = y/(float)cy; float y2 = (y+h)/(float)cy; float Temp = 0; if(Flags&SPRITE_FLAG_FLIP_Y) { Temp = y1; y1 = y2; y2 = Temp; } if(Flags&SPRITE_FLAG_FLIP_X) { Temp = x1; x1 = x2; x2 = Temp; } Graphics()->QuadsSetSubset(x1, y1, x2, y2); } void CRenderTools::SelectSprite(int Id, int Flags, int sx, int sy) { if(Id < 0 || Id >= g_pData->m_NumSprites) return; SelectSprite(&g_pData->m_aSprites[Id], Flags, sx, sy); } void CRenderTools::DrawSprite(float x, float y, float Size) { IGraphics::CQuadItem QuadItem(x, y, Size*gs_SpriteWScale, Size*gs_SpriteHScale); Graphics()->QuadsDraw(&QuadItem, 1); } void CRenderTools::DrawRoundRectExt(float x, float y, float w, float h, float r, int Corners) { IGraphics::CFreeformItem ArrayF[32]; int NumItems = 0; int Num = 8; for(int i = 0; i < Num; i+=2) { float a1 = i/(float)Num * pi/2; float a2 = (i+1)/(float)Num * pi/2; float a3 = (i+2)/(float)Num * pi/2; float Ca1 = cosf(a1); float Ca2 = cosf(a2); float Ca3 = cosf(a3); float Sa1 = sinf(a1); float Sa2 = sinf(a2); float Sa3 = sinf(a3); if(Corners&1) // TL ArrayF[NumItems++] = IGraphics::CFreeformItem( x+r, y+r, x+(1-Ca1)*r, y+(1-Sa1)*r, x+(1-Ca3)*r, y+(1-Sa3)*r, x+(1-Ca2)*r, y+(1-Sa2)*r); if(Corners&2) // TR ArrayF[NumItems++] = IGraphics::CFreeformItem( x+w-r, y+r, x+w-r+Ca1*r, y+(1-Sa1)*r, x+w-r+Ca3*r, y+(1-Sa3)*r, x+w-r+Ca2*r, y+(1-Sa2)*r); if(Corners&4) // BL ArrayF[NumItems++] = IGraphics::CFreeformItem( x+r, y+h-r, x+(1-Ca1)*r, y+h-r+Sa1*r, x+(1-Ca3)*r, y+h-r+Sa3*r, x+(1-Ca2)*r, y+h-r+Sa2*r); if(Corners&8) // BR ArrayF[NumItems++] = IGraphics::CFreeformItem( x+w-r, y+h-r, x+w-r+Ca1*r, y+h-r+Sa1*r, x+w-r+Ca3*r, y+h-r+Sa3*r, x+w-r+Ca2*r, y+h-r+Sa2*r); if(Corners&16) // ITL ArrayF[NumItems++] = IGraphics::CFreeformItem( x, y, x+(1-Ca1)*r, y-r+Sa1*r, x+(1-Ca3)*r, y-r+Sa3*r, x+(1-Ca2)*r, y-r+Sa2*r); if(Corners&32) // ITR ArrayF[NumItems++] = IGraphics::CFreeformItem( x+w, y, x+w-r+Ca1*r, y-r+Sa1*r, x+w-r+Ca3*r, y-r+Sa3*r, x+w-r+Ca2*r, y-r+Sa2*r); if(Corners&64) // IBL ArrayF[NumItems++] = IGraphics::CFreeformItem( x, y+h, x+(1-Ca1)*r, y+h+(1-Sa1)*r, x+(1-Ca3)*r, y+h+(1-Sa3)*r, x+(1-Ca2)*r, y+h+(1-Sa2)*r); if(Corners&128) // IBR ArrayF[NumItems++] = IGraphics::CFreeformItem( x+w, y+h, x+w-r+Ca1*r, y+h+(1-Sa1)*r, x+w-r+Ca3*r, y+h+(1-Sa3)*r, x+w-r+Ca2*r, y+h+(1-Sa2)*r); } Graphics()->QuadsDrawFreeform(ArrayF, NumItems); IGraphics::CQuadItem ArrayQ[9]; NumItems = 0; ArrayQ[NumItems++] = IGraphics::CQuadItem(x+r, y+r, w-r*2, h-r*2); // center ArrayQ[NumItems++] = IGraphics::CQuadItem(x+r, y, w-r*2, r); // top ArrayQ[NumItems++] = IGraphics::CQuadItem(x+r, y+h-r, w-r*2, r); // bottom ArrayQ[NumItems++] = IGraphics::CQuadItem(x, y+r, r, h-r*2); // left ArrayQ[NumItems++] = IGraphics::CQuadItem(x+w-r, y+r, r, h-r*2); // right if(!(Corners&1)) ArrayQ[NumItems++] = IGraphics::CQuadItem(x, y, r, r); // TL if(!(Corners&2)) ArrayQ[NumItems++] = IGraphics::CQuadItem(x+w, y, -r, r); // TR if(!(Corners&4)) ArrayQ[NumItems++] = IGraphics::CQuadItem(x, y+h, r, -r); // BL if(!(Corners&8)) ArrayQ[NumItems++] = IGraphics::CQuadItem(x+w, y+h, -r, -r); // BR Graphics()->QuadsDrawTL(ArrayQ, NumItems); } void CRenderTools::DrawRoundRectExt4(float x, float y, float w, float h, vec4 ColorTopLeft, vec4 ColorTopRight, vec4 ColorBottomLeft, vec4 ColorBottomRight, float r, int Corners) { int Num = 8; for(int i = 0; i < Num; i+=2) { float a1 = i/(float)Num * pi/2; float a2 = (i+1)/(float)Num * pi/2; float a3 = (i+2)/(float)Num * pi/2; float Ca1 = cosf(a1); float Ca2 = cosf(a2); float Ca3 = cosf(a3); float Sa1 = sinf(a1); float Sa2 = sinf(a2); float Sa3 = sinf(a3); if(Corners&1) // TL { Graphics()->SetColor(ColorTopLeft.r, ColorTopLeft.g, ColorTopLeft.b, ColorTopLeft.a); IGraphics::CFreeformItem ItemF = IGraphics::CFreeformItem( x+r, y+r, x+(1-Ca1)*r, y+(1-Sa1)*r, x+(1-Ca3)*r, y+(1-Sa3)*r, x+(1-Ca2)*r, y+(1-Sa2)*r); Graphics()->QuadsDrawFreeform(&ItemF, 1); } if(Corners&2) // TR { Graphics()->SetColor(ColorTopRight.r, ColorTopRight.g, ColorTopRight.b, ColorTopRight.a); IGraphics::CFreeformItem ItemF = IGraphics::CFreeformItem( x+w-r, y+r, x+w-r+Ca1*r, y+(1-Sa1)*r, x+w-r+Ca3*r, y+(1-Sa3)*r, x+w-r+Ca2*r, y+(1-Sa2)*r); Graphics()->QuadsDrawFreeform(&ItemF, 1); } if(Corners&4) // BL { Graphics()->SetColor(ColorBottomLeft.r, ColorBottomLeft.g, ColorBottomLeft.b, ColorBottomLeft.a); IGraphics::CFreeformItem ItemF = IGraphics::CFreeformItem( x+r, y+h-r, x+(1-Ca1)*r, y+h-r+Sa1*r, x+(1-Ca3)*r, y+h-r+Sa3*r, x+(1-Ca2)*r, y+h-r+Sa2*r); Graphics()->QuadsDrawFreeform(&ItemF, 1); } if(Corners&8) // BR { Graphics()->SetColor(ColorBottomRight.r, ColorBottomRight.g, ColorBottomRight.b, ColorBottomRight.a); IGraphics::CFreeformItem ItemF = IGraphics::CFreeformItem( x+w-r, y+h-r, x+w-r+Ca1*r, y+h-r+Sa1*r, x+w-r+Ca3*r, y+h-r+Sa3*r, x+w-r+Ca2*r, y+h-r+Sa2*r); Graphics()->QuadsDrawFreeform(&ItemF, 1); } if(Corners&16) // ITL { Graphics()->SetColor(ColorTopLeft.r, ColorTopLeft.g, ColorTopLeft.b, ColorTopLeft.a); IGraphics::CFreeformItem ItemF = IGraphics::CFreeformItem( x, y, x+(1-Ca1)*r, y-r+Sa1*r, x+(1-Ca3)*r, y-r+Sa3*r, x+(1-Ca2)*r, y-r+Sa2*r); Graphics()->QuadsDrawFreeform(&ItemF, 1); } if(Corners&32) // ITR { Graphics()->SetColor(ColorTopRight.r, ColorTopRight.g, ColorTopRight.b, ColorTopRight.a); IGraphics::CFreeformItem ItemF = IGraphics::CFreeformItem( x+w, y, x+w-r+Ca1*r, y-r+Sa1*r, x+w-r+Ca3*r, y-r+Sa3*r, x+w-r+Ca2*r, y-r+Sa2*r); Graphics()->QuadsDrawFreeform(&ItemF, 1); } if(Corners&64) // IBL { Graphics()->SetColor(ColorBottomLeft.r, ColorBottomLeft.g, ColorBottomLeft.b, ColorBottomLeft.a); IGraphics::CFreeformItem ItemF = IGraphics::CFreeformItem( x, y+h, x+(1-Ca1)*r, y+h+(1-Sa1)*r, x+(1-Ca3)*r, y+h+(1-Sa3)*r, x+(1-Ca2)*r, y+h+(1-Sa2)*r); Graphics()->QuadsDrawFreeform(&ItemF, 1); } if(Corners&128) // IBR { Graphics()->SetColor(ColorBottomRight.r, ColorBottomRight.g, ColorBottomRight.b, ColorBottomRight.a); IGraphics::CFreeformItem ItemF = IGraphics::CFreeformItem( x+w, y+h, x+w-r+Ca1*r, y+h+(1-Sa1)*r, x+w-r+Ca3*r, y+h+(1-Sa3)*r, x+w-r+Ca2*r, y+h+(1-Sa2)*r); Graphics()->QuadsDrawFreeform(&ItemF, 1); } } Graphics()->SetColor4(ColorTopLeft, ColorTopRight, ColorBottomLeft, ColorBottomRight); IGraphics::CQuadItem ItemQ = IGraphics::CQuadItem(x+r, y+r, w-r*2, h-r*2); // center Graphics()->QuadsDrawTL(&ItemQ, 1); Graphics()->SetColor4(ColorTopLeft, ColorTopRight, ColorTopLeft, ColorTopRight); ItemQ = IGraphics::CQuadItem(x+r, y, w-r*2, r); // top Graphics()->QuadsDrawTL(&ItemQ, 1); Graphics()->SetColor4(ColorBottomLeft, ColorBottomRight, ColorBottomLeft, ColorBottomRight); ItemQ = IGraphics::CQuadItem(x+r, y+h-r, w-r*2, r); // bottom Graphics()->QuadsDrawTL(&ItemQ, 1); Graphics()->SetColor4(ColorTopLeft, ColorTopLeft, ColorBottomLeft, ColorBottomLeft); ItemQ = IGraphics::CQuadItem(x, y+r, r, h-r*2); // left Graphics()->QuadsDrawTL(&ItemQ, 1); Graphics()->SetColor4(ColorTopRight, ColorTopRight, ColorBottomRight, ColorBottomRight); ItemQ = IGraphics::CQuadItem(x+w-r, y+r, r, h-r*2); // right Graphics()->QuadsDrawTL(&ItemQ, 1); if(!(Corners&1)) { Graphics()->SetColor(ColorTopLeft.r, ColorTopLeft.g, ColorTopLeft.b, ColorTopLeft.a); IGraphics::CQuadItem ItemQ = IGraphics::CQuadItem(x, y, r, r); // TL Graphics()->QuadsDrawTL(&ItemQ, 1); } if(!(Corners&2)) { Graphics()->SetColor(ColorTopRight.r, ColorTopRight.g, ColorTopRight.b, ColorTopRight.a); IGraphics::CQuadItem ItemQ = IGraphics::CQuadItem(x+w, y, -r, r); // TR Graphics()->QuadsDrawTL(&ItemQ, 1); } if(!(Corners&4)) { Graphics()->SetColor(ColorBottomLeft.r, ColorBottomLeft.g, ColorBottomLeft.b, ColorBottomLeft.a); IGraphics::CQuadItem ItemQ = IGraphics::CQuadItem(x, y+h, r, -r); // BL Graphics()->QuadsDrawTL(&ItemQ, 1); } if(!(Corners&8)) { Graphics()->SetColor(ColorBottomRight.r, ColorBottomRight.g, ColorBottomRight.b, ColorBottomRight.a); IGraphics::CQuadItem ItemQ = IGraphics::CQuadItem(x+w, y+h, -r, -r); // BR Graphics()->QuadsDrawTL(&ItemQ, 1); } } void CRenderTools::DrawRoundRect(float x, float y, float w, float h, float r) { DrawRoundRectExt(x,y,w,h,r,0xf); } void CRenderTools::DrawUIRect(const CUIRect *r, vec4 Color, int Corners, float Rounding) { Graphics()->TextureClear(); // TODO: FIX US Graphics()->QuadsBegin(); Graphics()->SetColor(Color.r, Color.g, Color.b, Color.a); DrawRoundRectExt(r->x,r->y,r->w,r->h,Rounding*UI()->Scale(), Corners); Graphics()->QuadsEnd(); } void CRenderTools::DrawUIRect4(const CUIRect *r, vec4 ColorTopLeft, vec4 ColorTopRight, vec4 ColorBottomLeft, vec4 ColorBottomRight, int Corners, float Rounding) { Graphics()->TextureClear(); Graphics()->QuadsBegin(); DrawRoundRectExt4(r->x,r->y,r->w,r->h,ColorTopLeft,ColorTopRight,ColorBottomLeft,ColorBottomRight,Rounding*UI()->Scale(), Corners); Graphics()->QuadsEnd(); } void CRenderTools::RenderTee(CAnimState *pAnim, CTeeRenderInfo *pInfo, int Emote, vec2 Dir, vec2 Pos) { vec2 Direction = Dir; vec2 Position = Pos; //Graphics()->TextureSet(data->images[IMAGE_CHAR_DEFAULT].id); // TODO: FIX ME //Graphics()->QuadsDraw(pos.x, pos.y-128, 128, 128); // first pass we draw the outline // second pass we draw the filling for(int p = 0; p < 2; p++) { bool OutLine = p==0; for(int f = 0; f < 2; f++) { float AnimScale = pInfo->m_Size * 1.0f/64.0f; float BaseSize = pInfo->m_Size; if(f == 1) { vec2 BodyPos = Position + vec2(pAnim->GetBody()->m_X, pAnim->GetBody()->m_Y)*AnimScale; IGraphics::CQuadItem BodyItem(BodyPos.x, BodyPos.y, BaseSize, BaseSize); IGraphics::CQuadItem Item; // draw decoration if(pInfo->m_aTextures[2].IsValid()) { Graphics()->TextureSet(pInfo->m_aTextures[2]); Graphics()->QuadsBegin(); Graphics()->QuadsSetRotation(pAnim->GetBody()->m_Angle*pi*2); Graphics()->SetColor(pInfo->m_aColors[2].r, pInfo->m_aColors[2].g, pInfo->m_aColors[2].b, pInfo->m_aColors[2].a); SelectSprite(OutLine?SPRITE_TEE_DECORATION_OUTLINE:SPRITE_TEE_DECORATION, 0, 0, 0); Item = BodyItem; Graphics()->QuadsDraw(&Item, 1); Graphics()->QuadsEnd(); } // draw body (behind tattoo) Graphics()->TextureSet(pInfo->m_aTextures[0]); Graphics()->QuadsBegin(); Graphics()->QuadsSetRotation(pAnim->GetBody()->m_Angle*pi*2); if(OutLine) { Graphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f); SelectSprite(SPRITE_TEE_BODY_OUTLINE, 0, 0, 0); } else { Graphics()->SetColor(pInfo->m_aColors[0].r, pInfo->m_aColors[0].g, pInfo->m_aColors[0].b, pInfo->m_aColors[0].a); SelectSprite(SPRITE_TEE_BODY, 0, 0, 0); } Item = BodyItem; Graphics()->QuadsDraw(&Item, 1); Graphics()->QuadsEnd(); // draw tattoo if(pInfo->m_aTextures[1].IsValid() && !OutLine) { Graphics()->TextureSet(pInfo->m_aTextures[1]); Graphics()->QuadsBegin(); Graphics()->QuadsSetRotation(pAnim->GetBody()->m_Angle*pi*2); Graphics()->SetColor(pInfo->m_aColors[1].r, pInfo->m_aColors[1].g, pInfo->m_aColors[1].b, pInfo->m_aColors[1].a); SelectSprite(SPRITE_TEE_TATTOO, 0, 0, 0); Item = BodyItem; Graphics()->QuadsDraw(&Item, 1); Graphics()->QuadsEnd(); } // draw body (in front of tattoo) if(!OutLine) { Graphics()->TextureSet(pInfo->m_aTextures[0]); Graphics()->QuadsBegin(); Graphics()->QuadsSetRotation(pAnim->GetBody()->m_Angle*pi*2); Graphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f); for(int t = 0; t < 2; t++) { SelectSprite(t==0?SPRITE_TEE_BODY_SHADOW:SPRITE_TEE_BODY_UPPER_OUTLINE, 0, 0, 0); Item = BodyItem; Graphics()->QuadsDraw(&Item, 1); } Graphics()->QuadsEnd(); } // draw eyes Graphics()->TextureSet(pInfo->m_aTextures[5]); Graphics()->QuadsBegin(); Graphics()->QuadsSetRotation(pAnim->GetBody()->m_Angle*pi*2); Graphics()->SetColor(pInfo->m_aColors[5].r, pInfo->m_aColors[5].g, pInfo->m_aColors[5].b, pInfo->m_aColors[5].a); if(p == 1) { switch (Emote) { case EMOTE_PAIN: SelectSprite(SPRITE_TEE_EYES_PAIN, 0, 0, 0); break; case EMOTE_HAPPY: SelectSprite(SPRITE_TEE_EYES_HAPPY, 0, 0, 0); break; case EMOTE_SURPRISE: SelectSprite(SPRITE_TEE_EYES_SURPRISE, 0, 0, 0); break; case EMOTE_ANGRY: SelectSprite(SPRITE_TEE_EYES_ANGRY, 0, 0, 0); break; default: SelectSprite(SPRITE_TEE_EYES_NORMAL, 0, 0, 0); break; } float EyeScale = BaseSize*0.60f; float h = Emote == EMOTE_BLINK ? BaseSize*0.15f/2.0f : EyeScale/2.0f; vec2 Offset = vec2(Direction.x*0.125f, -0.05f+Direction.y*0.10f)*BaseSize; IGraphics::CQuadItem QuadItem(BodyPos.x+Offset.x, BodyPos.y+Offset.y, EyeScale, h); Graphics()->QuadsDraw(&QuadItem, 1); } Graphics()->QuadsEnd(); } // draw feet Graphics()->TextureSet(pInfo->m_aTextures[4]); Graphics()->QuadsBegin(); CAnimKeyframe *pFoot = f ? pAnim->GetFrontFoot() : pAnim->GetBackFoot(); float w = BaseSize/2.25f; float h = w; Graphics()->QuadsSetRotation(pFoot->m_Angle*pi*2); if(OutLine) { Graphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f); SelectSprite(SPRITE_TEE_FOOT_OUTLINE, 0, 0, 0); } else { bool Indicate = !pInfo->m_GotAirJump && g_Config.m_ClAirjumpindicator; float cs = 1.0f; // color scale if(Indicate) cs = 0.5f; Graphics()->SetColor(pInfo->m_aColors[4].r*cs, pInfo->m_aColors[4].g*cs, pInfo->m_aColors[4].b*cs, pInfo->m_aColors[4].a); SelectSprite(SPRITE_TEE_FOOT, 0, 0, 0); } IGraphics::CQuadItem QuadItem(Position.x+pFoot->m_X*AnimScale, Position.y+pFoot->m_Y*AnimScale, w, h); Graphics()->QuadsDraw(&QuadItem, 1); Graphics()->QuadsEnd(); } } } static void CalcScreenParams(float Amount, float WMax, float HMax, float Aspect, float *w, float *h) { float f = sqrtf(Amount) / sqrtf(Aspect); *w = f*Aspect; *h = f; // limit the view if(*w > WMax) { *w = WMax; *h = *w/Aspect; } if(*h > HMax) { *h = HMax; *w = *h*Aspect; } } void CRenderTools::MapscreenToWorld(float CenterX, float CenterY, float ParallaxX, float ParallaxY, float OffsetX, float OffsetY, float Aspect, float Zoom, float *pPoints) { float Width, Height; CalcScreenParams(1150*1000, 1500, 1050, Aspect, &Width, &Height); CenterX *= ParallaxX; CenterY *= ParallaxY; Width *= Zoom; Height *= Zoom; pPoints[0] = OffsetX+CenterX-Width/2; pPoints[1] = OffsetY+CenterY-Height/2; pPoints[2] = pPoints[0]+Width; pPoints[3] = pPoints[1]+Height; } void CRenderTools::RenderTilemapGenerateSkip(class CLayers *pLayers) { for(int g = 0; g < pLayers->NumGroups(); g++) { CMapItemGroup *pGroup = pLayers->GetGroup(g); for(int l = 0; l < pGroup->m_NumLayers; l++) { CMapItemLayer *pLayer = pLayers->GetLayer(pGroup->m_StartLayer+l); if(pLayer->m_Type == LAYERTYPE_TILES) { CMapItemLayerTilemap *pTmap = (CMapItemLayerTilemap *)pLayer; CTile *pTiles = (CTile *)pLayers->Map()->GetData(pTmap->m_Data); for(int y = 0; y < pTmap->m_Height; y++) { for(int x = 1; x < pTmap->m_Width;) { int sx; for(sx = 1; x+sx < pTmap->m_Width && sx < 255; sx++) { if(pTiles[y*pTmap->m_Width+x+sx].m_Index) break; } pTiles[y*pTmap->m_Width+x].m_Skip = sx-1; x += sx; } } } } } } ================================================ FILE: src/game/client/render.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_CLIENT_RENDER_H #define GAME_CLIENT_RENDER_H #include <engine/graphics.h> #include <base/vmath.h> #include <game/mapitems.h> #include "ui.h" class CTeeRenderInfo { public: CTeeRenderInfo() { for(int i = 0; i < 6; i++) m_aColors[i] = vec4(1,1,1,1); m_Size = 1.0f; m_GotAirJump = 1; }; IGraphics::CTextureHandle m_aTextures[6]; vec4 m_aColors[6]; float m_Size; int m_GotAirJump; }; // sprite renderings enum { SPRITE_FLAG_FLIP_Y=1, SPRITE_FLAG_FLIP_X=2, LAYERRENDERFLAG_OPAQUE=1, LAYERRENDERFLAG_TRANSPARENT=2, TILERENDERFLAG_EXTEND=4, }; typedef void (*ENVELOPE_EVAL)(float TimeOffset, int Env, float *pChannels, void *pUser); class CRenderTools { public: class IGraphics *m_pGraphics; class CUI *m_pUI; class IGraphics *Graphics() const { return m_pGraphics; } class CUI *UI() const { return m_pUI; } //typedef struct SPRITE; void SelectSprite(struct CDataSprite *pSprite, int Flags=0, int sx=0, int sy=0); void SelectSprite(int id, int Flags=0, int sx=0, int sy=0); void DrawSprite(float x, float y, float size); // rects void DrawRoundRect(float x, float y, float w, float h, float r); void DrawRoundRectExt(float x, float y, float w, float h, float r, int Corners); void DrawRoundRectExt4(float x, float y, float w, float h, vec4 ColorTopLeft, vec4 ColorTopRight, vec4 ColorBottomLeft, vec4 ColorBottomRight, float r, int Corners); void DrawUIRect(const CUIRect *pRect, vec4 Color, int Corners, float Rounding); void DrawUIRect4(const CUIRect *pRect, vec4 ColorTopLeft, vec4 ColorTopRight, vec4 ColorBottomLeft, vec4 ColorBottomRight, int Corners, float Rounding); // larger rendering methods void RenderTilemapGenerateSkip(class CLayers *pLayers); // object render methods (gc_render_obj.cpp) void RenderTee(class CAnimState *pAnim, CTeeRenderInfo *pInfo, int Emote, vec2 Dir, vec2 Pos); // map render methods (gc_render_map.cpp) static void RenderEvalEnvelope(CEnvPoint *pPoints, int NumPoints, int Channels, float Time, float *pResult); void RenderQuads(CQuad *pQuads, int NumQuads, int Flags, ENVELOPE_EVAL pfnEval, void *pUser); void RenderTilemap(CTile *pTiles, int w, int h, float Scale, vec4 Color, int RenderFlags, ENVELOPE_EVAL pfnEval, void *pUser, int ColorEnv, int ColorEnvOffset); // helpers void MapscreenToWorld(float CenterX, float CenterY, float ParallaxX, float ParallaxY, float OffsetX, float OffsetY, float Aspect, float Zoom, float *pPoints); }; #endif ================================================ FILE: src/game/client/render_map.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <math.h> #include <base/math.h> #include <engine/graphics.h> #include "render.h" void CRenderTools::RenderEvalEnvelope(CEnvPoint *pPoints, int NumPoints, int Channels, float Time, float *pResult) { if(NumPoints == 0) { pResult[0] = 0; pResult[1] = 0; pResult[2] = 0; pResult[3] = 0; return; } if(NumPoints == 1) { pResult[0] = fx2f(pPoints[0].m_aValues[0]); pResult[1] = fx2f(pPoints[0].m_aValues[1]); pResult[2] = fx2f(pPoints[0].m_aValues[2]); pResult[3] = fx2f(pPoints[0].m_aValues[3]); return; } Time = fmod(Time, pPoints[NumPoints-1].m_Time/1000.0f)*1000.0f; for(int i = 0; i < NumPoints-1; i++) { if(Time >= pPoints[i].m_Time && Time <= pPoints[i+1].m_Time) { float Delta = pPoints[i+1].m_Time-pPoints[i].m_Time; float a = (Time-pPoints[i].m_Time)/Delta; if(pPoints[i].m_Curvetype == CURVETYPE_SMOOTH) a = -2*a*a*a + 3*a*a; // second hermite basis else if(pPoints[i].m_Curvetype == CURVETYPE_SLOW) a = a*a*a; else if(pPoints[i].m_Curvetype == CURVETYPE_FAST) { a = 1-a; a = 1-a*a*a; } else if (pPoints[i].m_Curvetype == CURVETYPE_STEP) a = 0; else { // linear } for(int c = 0; c < Channels; c++) { float v0 = fx2f(pPoints[i].m_aValues[c]); float v1 = fx2f(pPoints[i+1].m_aValues[c]); pResult[c] = v0 + (v1-v0) * a; } return; } } pResult[0] = fx2f(pPoints[NumPoints-1].m_aValues[0]); pResult[1] = fx2f(pPoints[NumPoints-1].m_aValues[1]); pResult[2] = fx2f(pPoints[NumPoints-1].m_aValues[2]); pResult[3] = fx2f(pPoints[NumPoints-1].m_aValues[3]); return; } static void Rotate(CPoint *pCenter, CPoint *pPoint, float Rotation) { int x = pPoint->x - pCenter->x; int y = pPoint->y - pCenter->y; pPoint->x = (int)(x * cosf(Rotation) - y * sinf(Rotation) + pCenter->x); pPoint->y = (int)(x * sinf(Rotation) + y * cosf(Rotation) + pCenter->y); } void CRenderTools::RenderQuads(CQuad *pQuads, int NumQuads, int RenderFlags, ENVELOPE_EVAL pfnEval, void *pUser) { Graphics()->QuadsBegin(); float Conv = 1/255.0f; for(int i = 0; i < NumQuads; i++) { CQuad *q = &pQuads[i]; float r=1, g=1, b=1, a=1; if(q->m_ColorEnv >= 0) { float aChannels[4]; pfnEval(q->m_ColorEnvOffset/1000.0f, q->m_ColorEnv, aChannels, pUser); r = aChannels[0]; g = aChannels[1]; b = aChannels[2]; a = aChannels[3]; } bool Opaque = false; /* TODO: Analyze quadtexture if(a < 0.01f || (q->m_aColors[0].a < 0.01f && q->m_aColors[1].a < 0.01f && q->m_aColors[2].a < 0.01f && q->m_aColors[3].a < 0.01f)) Opaque = true; */ if(Opaque && !(RenderFlags&LAYERRENDERFLAG_OPAQUE)) continue; if(!Opaque && !(RenderFlags&LAYERRENDERFLAG_TRANSPARENT)) continue; Graphics()->QuadsSetSubsetFree( fx2f(q->m_aTexcoords[0].x), fx2f(q->m_aTexcoords[0].y), fx2f(q->m_aTexcoords[1].x), fx2f(q->m_aTexcoords[1].y), fx2f(q->m_aTexcoords[2].x), fx2f(q->m_aTexcoords[2].y), fx2f(q->m_aTexcoords[3].x), fx2f(q->m_aTexcoords[3].y) ); float OffsetX = 0; float OffsetY = 0; float Rot = 0; // TODO: fix this if(q->m_PosEnv >= 0) { float aChannels[4]; pfnEval(q->m_PosEnvOffset/1000.0f, q->m_PosEnv, aChannels, pUser); OffsetX = aChannels[0]; OffsetY = aChannels[1]; Rot = aChannels[2]/360.0f*pi*2; } IGraphics::CColorVertex Array[4] = { IGraphics::CColorVertex(0, q->m_aColors[0].r*Conv*r, q->m_aColors[0].g*Conv*g, q->m_aColors[0].b*Conv*b, q->m_aColors[0].a*Conv*a), IGraphics::CColorVertex(1, q->m_aColors[1].r*Conv*r, q->m_aColors[1].g*Conv*g, q->m_aColors[1].b*Conv*b, q->m_aColors[1].a*Conv*a), IGraphics::CColorVertex(2, q->m_aColors[2].r*Conv*r, q->m_aColors[2].g*Conv*g, q->m_aColors[2].b*Conv*b, q->m_aColors[2].a*Conv*a), IGraphics::CColorVertex(3, q->m_aColors[3].r*Conv*r, q->m_aColors[3].g*Conv*g, q->m_aColors[3].b*Conv*b, q->m_aColors[3].a*Conv*a)}; Graphics()->SetColorVertex(Array, 4); CPoint *pPoints = q->m_aPoints; if(Rot != 0) { static CPoint aRotated[4]; aRotated[0] = q->m_aPoints[0]; aRotated[1] = q->m_aPoints[1]; aRotated[2] = q->m_aPoints[2]; aRotated[3] = q->m_aPoints[3]; pPoints = aRotated; Rotate(&q->m_aPoints[4], &aRotated[0], Rot); Rotate(&q->m_aPoints[4], &aRotated[1], Rot); Rotate(&q->m_aPoints[4], &aRotated[2], Rot); Rotate(&q->m_aPoints[4], &aRotated[3], Rot); } IGraphics::CFreeformItem Freeform( fx2f(pPoints[0].x)+OffsetX, fx2f(pPoints[0].y)+OffsetY, fx2f(pPoints[1].x)+OffsetX, fx2f(pPoints[1].y)+OffsetY, fx2f(pPoints[2].x)+OffsetX, fx2f(pPoints[2].y)+OffsetY, fx2f(pPoints[3].x)+OffsetX, fx2f(pPoints[3].y)+OffsetY); Graphics()->QuadsDrawFreeform(&Freeform, 1); } Graphics()->QuadsEnd(); } void CRenderTools::RenderTilemap(CTile *pTiles, int w, int h, float Scale, vec4 Color, int RenderFlags, ENVELOPE_EVAL pfnEval, void *pUser, int ColorEnv, int ColorEnvOffset) { //Graphics()->TextureSet(img_get(tmap->image)); float ScreenX0, ScreenY0, ScreenX1, ScreenY1; Graphics()->GetScreen(&ScreenX0, &ScreenY0, &ScreenX1, &ScreenY1); //Graphics()->MapScreen(screen_x0-50, screen_y0-50, screen_x1+50, screen_y1+50); // calculate the final pixelsize for the tiles float TilePixelSize = 1024/32.0f; float FinalTileSize = Scale/(ScreenX1-ScreenX0) * Graphics()->ScreenWidth(); float FinalTilesetScale = FinalTileSize/TilePixelSize; float r=1, g=1, b=1, a=1; if(ColorEnv >= 0) { float aChannels[4]; pfnEval(ColorEnvOffset/1000.0f, ColorEnv, aChannels, pUser); r = aChannels[0]; g = aChannels[1]; b = aChannels[2]; a = aChannels[3]; } Graphics()->QuadsBegin(); Graphics()->SetColor(Color.r*r, Color.g*g, Color.b*b, Color.a*a); int StartY = (int)(ScreenY0/Scale)-1; int StartX = (int)(ScreenX0/Scale)-1; int EndY = (int)(ScreenY1/Scale)+1; int EndX = (int)(ScreenX1/Scale)+1; // adjust the texture shift according to mipmap level float TexSize = 1024.0f; float Frac = (1.25f/TexSize) * (1/FinalTilesetScale); float Nudge = (0.5f/TexSize) * (1/FinalTilesetScale); for(int y = StartY; y < EndY; y++) for(int x = StartX; x < EndX; x++) { int mx = x; int my = y; if(RenderFlags&TILERENDERFLAG_EXTEND) { if(mx<0) mx = 0; if(mx>=w) mx = w-1; if(my<0) my = 0; if(my>=h) my = h-1; } else { if(mx<0) continue; // mx = 0; if(mx>=w) continue; // mx = w-1; if(my<0) continue; // my = 0; if(my>=h) continue; // my = h-1; } int c = mx + my*w; unsigned char Index = pTiles[c].m_Index; if(Index) { unsigned char Flags = pTiles[c].m_Flags; bool Render = false; if(Flags&TILEFLAG_OPAQUE && Color.a*a > 254.0f/255.0f) { if(RenderFlags&LAYERRENDERFLAG_OPAQUE) Render = true; } else { if(RenderFlags&LAYERRENDERFLAG_TRANSPARENT) Render = true; } if(Render) { int tx = Index%16; int ty = Index/16; int Px0 = tx*(1024/16); int Py0 = ty*(1024/16); int Px1 = Px0+(1024/16)-1; int Py1 = Py0+(1024/16)-1; float x0 = Nudge + Px0/TexSize+Frac; float y0 = Nudge + Py0/TexSize+Frac; float x1 = Nudge + Px1/TexSize-Frac; float y1 = Nudge + Py0/TexSize+Frac; float x2 = Nudge + Px1/TexSize-Frac; float y2 = Nudge + Py1/TexSize-Frac; float x3 = Nudge + Px0/TexSize+Frac; float y3 = Nudge + Py1/TexSize-Frac; if(Flags&TILEFLAG_VFLIP) { x0 = x2; x1 = x3; x2 = x3; x3 = x0; } if(Flags&TILEFLAG_HFLIP) { y0 = y3; y2 = y1; y3 = y1; y1 = y0; } if(Flags&TILEFLAG_ROTATE) { float Tmp = x0; x0 = x3; x3 = x2; x2 = x1; x1 = Tmp; Tmp = y0; y0 = y3; y3 = y2; y2 = y1; y1 = Tmp; } Graphics()->QuadsSetSubsetFree(x0, y0, x1, y1, x2, y2, x3, y3); IGraphics::CQuadItem QuadItem(x*Scale, y*Scale, Scale, Scale); Graphics()->QuadsDrawTL(&QuadItem, 1); } } x += pTiles[c].m_Skip; } Graphics()->QuadsEnd(); Graphics()->MapScreen(ScreenX0, ScreenY0, ScreenX1, ScreenY1); } ================================================ FILE: src/game/client/ui.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <base/system.h> #include <engine/shared/config.h> #include <engine/graphics.h> #include <engine/textrender.h> #include "ui.h" /******************************************************** UI *********************************************************/ CUI::CUI() { m_pHotItem = 0; m_pActiveItem = 0; m_pLastActiveItem = 0; m_pBecommingHotItem = 0; m_MouseX = 0; m_MouseY = 0; m_MouseWorldX = 0; m_MouseWorldY = 0; m_MouseButtons = 0; m_LastMouseButtons = 0; m_Screen.x = 0; m_Screen.y = 0; m_Screen.w = 848.0f; m_Screen.h = 480.0f; } int CUI::Update(float Mx, float My, float Mwx, float Mwy, int Buttons) { m_MouseX = Mx; m_MouseY = My; m_MouseWorldX = Mwx; m_MouseWorldY = Mwy; m_LastMouseButtons = m_MouseButtons; m_MouseButtons = Buttons; m_pHotItem = m_pBecommingHotItem; if(m_pActiveItem) m_pHotItem = m_pActiveItem; m_pBecommingHotItem = 0; return 0; } int CUI::MouseInside(const CUIRect *r) { if(m_MouseX >= r->x && m_MouseX < r->x+r->w && m_MouseY >= r->y && m_MouseY < r->y+r->h) return 1; return 0; } void CUI::ConvertMouseMove(float *x, float *y) { float Fac = (float)(g_Config.m_UiMousesens)/g_Config.m_InpMousesens; *x = *x*Fac; *y = *y*Fac; } CUIRect *CUI::Screen() { float Aspect = Graphics()->ScreenAspect(); float w, h; h = 600; w = Aspect*h; m_Screen.w = w; m_Screen.h = h; return &m_Screen; } float CUI::PixelSize() { return Screen()->w/Graphics()->ScreenWidth(); } float CUI::Scale() { return 1.0f; } float CUIRect::Scale() const { return 1.0f; } void CUI::ClipEnable(const CUIRect *r) { float XScale = Graphics()->ScreenWidth()/Screen()->w; float YScale = Graphics()->ScreenHeight()/Screen()->h; Graphics()->ClipEnable((int)(r->x*XScale), (int)(r->y*YScale), (int)(r->w*XScale), (int)(r->h*YScale)); } void CUI::ClipDisable() { Graphics()->ClipDisable(); } void CUIRect::HSplitMid(CUIRect *pTop, CUIRect *pBottom) const { CUIRect r = *this; float Cut = r.h/2; if(pTop) { pTop->x = r.x; pTop->y = r.y; pTop->w = r.w; pTop->h = Cut; } if(pBottom) { pBottom->x = r.x; pBottom->y = r.y + Cut; pBottom->w = r.w; pBottom->h = r.h - Cut; } } void CUIRect::HSplitTop(float Cut, CUIRect *pTop, CUIRect *pBottom) const { CUIRect r = *this; Cut *= Scale(); if (pTop) { pTop->x = r.x; pTop->y = r.y; pTop->w = r.w; pTop->h = Cut; } if (pBottom) { pBottom->x = r.x; pBottom->y = r.y + Cut; pBottom->w = r.w; pBottom->h = r.h - Cut; } } void CUIRect::HSplitBottom(float Cut, CUIRect *pTop, CUIRect *pBottom) const { CUIRect r = *this; Cut *= Scale(); if (pTop) { pTop->x = r.x; pTop->y = r.y; pTop->w = r.w; pTop->h = r.h - Cut; } if (pBottom) { pBottom->x = r.x; pBottom->y = r.y + r.h - Cut; pBottom->w = r.w; pBottom->h = Cut; } } void CUIRect::VSplitMid(CUIRect *pLeft, CUIRect *pRight) const { CUIRect r = *this; float Cut = r.w/2; // Cut *= Scale(); if (pLeft) { pLeft->x = r.x; pLeft->y = r.y; pLeft->w = Cut; pLeft->h = r.h; } if (pRight) { pRight->x = r.x + Cut; pRight->y = r.y; pRight->w = r.w - Cut; pRight->h = r.h; } } void CUIRect::VSplitLeft(float Cut, CUIRect *pLeft, CUIRect *pRight) const { CUIRect r = *this; Cut *= Scale(); if (pLeft) { pLeft->x = r.x; pLeft->y = r.y; pLeft->w = Cut; pLeft->h = r.h; } if (pRight) { pRight->x = r.x + Cut; pRight->y = r.y; pRight->w = r.w - Cut; pRight->h = r.h; } } void CUIRect::VSplitRight(float Cut, CUIRect *pLeft, CUIRect *pRight) const { CUIRect r = *this; Cut *= Scale(); if (pLeft) { pLeft->x = r.x; pLeft->y = r.y; pLeft->w = r.w - Cut; pLeft->h = r.h; } if (pRight) { pRight->x = r.x + r.w - Cut; pRight->y = r.y; pRight->w = Cut; pRight->h = r.h; } } void CUIRect::Margin(float Cut, CUIRect *pOtherRect) const { CUIRect r = *this; Cut *= Scale(); pOtherRect->x = r.x + Cut; pOtherRect->y = r.y + Cut; pOtherRect->w = r.w - 2*Cut; pOtherRect->h = r.h - 2*Cut; } void CUIRect::VMargin(float Cut, CUIRect *pOtherRect) const { CUIRect r = *this; Cut *= Scale(); pOtherRect->x = r.x + Cut; pOtherRect->y = r.y; pOtherRect->w = r.w - 2*Cut; pOtherRect->h = r.h; } void CUIRect::HMargin(float Cut, CUIRect *pOtherRect) const { CUIRect r = *this; Cut *= Scale(); pOtherRect->x = r.x; pOtherRect->y = r.y + Cut; pOtherRect->w = r.w; pOtherRect->h = r.h - 2*Cut; } int CUI::DoButtonLogic(const void *pID, const char *pText, int Checked, const CUIRect *pRect) { // logic int ReturnValue = 0; int Inside = MouseInside(pRect); static int ButtonUsed = 0; if(ActiveItem() == pID) { if(!MouseButton(ButtonUsed)) { if(Inside && Checked >= 0) ReturnValue = 1+ButtonUsed; SetActiveItem(0); } } else if(HotItem() == pID) { if(MouseButton(0)) { SetActiveItem(pID); ButtonUsed = 0; } if(MouseButton(1)) { SetActiveItem(pID); ButtonUsed = 1; } } if(Inside) SetHotItem(pID); return ReturnValue; } int CUI::DoPickerLogic(const void *pID, const CUIRect *pRect, float *pX, float *pY) { int Inside = MouseInside(pRect); if(ActiveItem() == pID) { if(!MouseButton(0)) SetActiveItem(0); } else if(HotItem() == pID) { if(MouseButton(0)) SetActiveItem(pID); } else if(Inside) SetHotItem(pID); if(ActiveItem() != pID) return 0; if(pX) *pX = clamp(m_MouseX - pRect->x, 0.0f, pRect->w) / Scale(); if(pY) *pY = clamp(m_MouseY - pRect->y, 0.0f, pRect->h) / Scale(); return 1; } int CUI::DoColorSelectionLogic(const CUIRect *pRect, const CUIRect *pButton) // it's counter logic! FIXME { if(MouseButtonClicked(0) && MouseInside(pRect) && !MouseInside(pButton)) return 1; else return 0; } /* int CUI::DoButton(const void *id, const char *text, int checked, const CUIRect *r, ui_draw_button_func draw_func, const void *extra) { // logic int ret = 0; int inside = ui_MouseInside(r); static int button_used = 0; if(ui_ActiveItem() == id) { if(!ui_MouseButton(button_used)) { if(inside && checked >= 0) ret = 1+button_used; ui_SetActiveItem(0); } } else if(ui_HotItem() == id) { if(ui_MouseButton(0)) { ui_SetActiveItem(id); button_used = 0; } if(ui_MouseButton(1)) { ui_SetActiveItem(id); button_used = 1; } } if(inside) ui_SetHotItem(id); if(draw_func) draw_func(id, text, checked, r, extra); return ret; }*/ void CUI::DoLabel(const CUIRect *r, const char *pText, float Size, int Align, int MaxWidth) { // TODO: FIX ME!!!! //Graphics()->BlendNormal(); if(Align == 0) { float tw = TextRender()->TextWidth(0, Size, pText, MaxWidth); TextRender()->Text(0, r->x + r->w/2-tw/2, r->y - Size/10, Size, pText, MaxWidth); } else if(Align < 0) TextRender()->Text(0, r->x, r->y - Size/10, Size, pText, MaxWidth); else if(Align > 0) { float tw = TextRender()->TextWidth(0, Size, pText, MaxWidth); TextRender()->Text(0, r->x + r->w-tw, r->y - Size/10, Size, pText, MaxWidth); } } void CUI::DoLabelScaled(const CUIRect *r, const char *pText, float Size, int Align, int MaxWidth) { DoLabel(r, pText, Size*Scale(), Align, MaxWidth); } ================================================ FILE: src/game/client/ui.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_CLIENT_UI_H #define GAME_CLIENT_UI_H class CUIRect { // TODO: Refactor: Redo UI scaling float Scale() const; public: float x, y, w, h; void HSplitMid(CUIRect *pTop, CUIRect *pBottom) const; void HSplitTop(float Cut, CUIRect *pTop, CUIRect *pBottom) const; void HSplitBottom(float Cut, CUIRect *pTop, CUIRect *pBottom) const; void VSplitMid(CUIRect *pLeft, CUIRect *pRight) const; void VSplitLeft(float Cut, CUIRect *pLeft, CUIRect *pRight) const; void VSplitRight(float Cut, CUIRect *pLeft, CUIRect *pRight) const; void Margin(float Cut, CUIRect *pOtherRect) const; void VMargin(float Cut, CUIRect *pOtherRect) const; void HMargin(float Cut, CUIRect *pOtherRect) const; }; class CUI { const void *m_pHotItem; const void *m_pActiveItem; const void *m_pLastActiveItem; const void *m_pBecommingHotItem; float m_MouseX, m_MouseY; // in gui space float m_MouseWorldX, m_MouseWorldY; // in world space unsigned m_MouseButtons; unsigned m_LastMouseButtons; CUIRect m_Screen; class IGraphics *m_pGraphics; class ITextRender *m_pTextRender; public: // TODO: Refactor: Fill this in void SetGraphics(class IGraphics *pGraphics, class ITextRender *pTextRender) { m_pGraphics = pGraphics; m_pTextRender = pTextRender;} class IGraphics *Graphics() { return m_pGraphics; } class ITextRender *TextRender() { return m_pTextRender; } CUI(); enum { CORNER_TL=1, CORNER_TR=2, CORNER_BL=4, CORNER_BR=8, CORNER_ITL=16, CORNER_ITR=32, CORNER_IBL=64, CORNER_IBR=128, CORNER_T=CORNER_TL|CORNER_TR, CORNER_B=CORNER_BL|CORNER_BR, CORNER_R=CORNER_TR|CORNER_BR, CORNER_L=CORNER_TL|CORNER_BL, CORNER_IT=CORNER_ITL|CORNER_ITR, CORNER_IB=CORNER_IBL|CORNER_IBR, CORNER_IR=CORNER_ITR|CORNER_IBR, CORNER_IL=CORNER_ITL|CORNER_IBL, CORNER_ALL=CORNER_T|CORNER_B, CORNER_INV_ALL=CORNER_IT|CORNER_IB }; int Update(float mx, float my, float Mwx, float Mwy, int m_Buttons); float MouseX() const { return m_MouseX; } float MouseY() const { return m_MouseY; } float MouseWorldX() const { return m_MouseWorldX; } float MouseWorldY() const { return m_MouseWorldY; } int MouseButton(int Index) const { return (m_MouseButtons>>Index)&1; } int MouseButtonClicked(int Index) { return MouseButton(Index) && !((m_LastMouseButtons>>Index)&1) ; } void SetHotItem(const void *pID) { m_pBecommingHotItem = pID; } void SetActiveItem(const void *pID) { m_pActiveItem = pID; if (pID) m_pLastActiveItem = pID; } void ClearLastActiveItem() { m_pLastActiveItem = 0; } const void *HotItem() const { return m_pHotItem; } const void *NextHotItem() const { return m_pBecommingHotItem; } const void *ActiveItem() const { return m_pActiveItem; } const void *LastActiveItem() const { return m_pLastActiveItem; } int MouseInside(const CUIRect *pRect); void ConvertMouseMove(float *x, float *y); CUIRect *Screen(); float PixelSize(); void ClipEnable(const CUIRect *pRect); void ClipDisable(); // TODO: Refactor: Redo UI scaling float Scale(); int DoButtonLogic(const void *pID, const char *pText /* TODO: Refactor: Remove */, int Checked, const CUIRect *pRect); int DoPickerLogic(const void *pID, const CUIRect *pRect, float *pX, float *pY); int DoColorSelectionLogic(const CUIRect *pRect, const CUIRect *pButton); // TODO: Refactor: Remove this? void DoLabel(const CUIRect *pRect, const char *pText, float Size, int Align, int MaxWidth = -1); void DoLabelScaled(const CUIRect *pRect, const char *pText, float Size, int Align, int MaxWidth = -1); }; #endif ================================================ FILE: src/game/collision.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <base/system.h> #include <base/math.h> #include <base/vmath.h> #include <math.h> #include <engine/map.h> #include <engine/kernel.h> #include <game/mapitems.h> #include <game/layers.h> #include <game/collision.h> CCollision::CCollision() { m_pTiles = 0; m_Width = 0; m_Height = 0; m_pLayers = 0; } void CCollision::Init(class CLayers *pLayers) { m_pLayers = pLayers; m_Width = m_pLayers->GameLayer()->m_Width; m_Height = m_pLayers->GameLayer()->m_Height; m_pTiles = static_cast<CTile *>(m_pLayers->Map()->GetData(m_pLayers->GameLayer()->m_Data)); for(int i = 0; i < m_Width*m_Height; i++) { int Index = m_pTiles[i].m_Index; if(Index > 128) continue; switch(Index) { case TILE_DEATH: m_pTiles[i].m_Index = COLFLAG_DEATH; break; case TILE_SOLID: m_pTiles[i].m_Index = COLFLAG_SOLID; break; case TILE_NOHOOK: m_pTiles[i].m_Index = COLFLAG_SOLID|COLFLAG_NOHOOK; break; default: m_pTiles[i].m_Index = 0; } } } int CCollision::GetTile(int x, int y) { int Nx = clamp(x/32, 0, m_Width-1); int Ny = clamp(y/32, 0, m_Height-1); return m_pTiles[Ny*m_Width+Nx].m_Index > 128 ? 0 : m_pTiles[Ny*m_Width+Nx].m_Index; } bool CCollision::IsTileSolid(int x, int y) { return GetTile(x, y)&COLFLAG_SOLID; } // TODO: rewrite this smarter! int CCollision::IntersectLine(vec2 Pos0, vec2 Pos1, vec2 *pOutCollision, vec2 *pOutBeforeCollision) { float Distance = distance(Pos0, Pos1); int End(Distance+1); vec2 Last = Pos0; for(int i = 0; i < End; i++) { float a = i/Distance; vec2 Pos = mix(Pos0, Pos1, a); if(CheckPoint(Pos.x, Pos.y)) { if(pOutCollision) *pOutCollision = Pos; if(pOutBeforeCollision) *pOutBeforeCollision = Last; return GetCollisionAt(Pos.x, Pos.y); } Last = Pos; } if(pOutCollision) *pOutCollision = Pos1; if(pOutBeforeCollision) *pOutBeforeCollision = Pos1; return 0; } // TODO: OPT: rewrite this smarter! void CCollision::MovePoint(vec2 *pInoutPos, vec2 *pInoutVel, float Elasticity, int *pBounces) { if(pBounces) *pBounces = 0; vec2 Pos = *pInoutPos; vec2 Vel = *pInoutVel; if(CheckPoint(Pos + Vel)) { int Affected = 0; if(CheckPoint(Pos.x + Vel.x, Pos.y)) { pInoutVel->x *= -Elasticity; if(pBounces) (*pBounces)++; Affected++; } if(CheckPoint(Pos.x, Pos.y + Vel.y)) { pInoutVel->y *= -Elasticity; if(pBounces) (*pBounces)++; Affected++; } if(Affected == 0) { pInoutVel->x *= -Elasticity; pInoutVel->y *= -Elasticity; } } else { *pInoutPos = Pos + Vel; } } bool CCollision::TestBox(vec2 Pos, vec2 Size) { Size *= 0.5f; if(CheckPoint(Pos.x-Size.x, Pos.y-Size.y)) return true; if(CheckPoint(Pos.x+Size.x, Pos.y-Size.y)) return true; if(CheckPoint(Pos.x-Size.x, Pos.y+Size.y)) return true; if(CheckPoint(Pos.x+Size.x, Pos.y+Size.y)) return true; return false; } void CCollision::MoveBox(vec2 *pInoutPos, vec2 *pInoutVel, vec2 Size, float Elasticity) { // do the move vec2 Pos = *pInoutPos; vec2 Vel = *pInoutVel; float Distance = length(Vel); int Max = (int)Distance; if(Distance > 0.00001f) { //vec2 old_pos = pos; float Fraction = 1.0f/(float)(Max+1); for(int i = 0; i <= Max; i++) { //float amount = i/(float)max; //if(max == 0) //amount = 0; vec2 NewPos = Pos + Vel*Fraction; // TODO: this row is not nice if(TestBox(vec2(NewPos.x, NewPos.y), Size)) { int Hits = 0; if(TestBox(vec2(Pos.x, NewPos.y), Size)) { NewPos.y = Pos.y; Vel.y *= -Elasticity; Hits++; } if(TestBox(vec2(NewPos.x, Pos.y), Size)) { NewPos.x = Pos.x; Vel.x *= -Elasticity; Hits++; } // neither of the tests got a collision. // this is a real _corner case_! if(Hits == 0) { NewPos.y = Pos.y; Vel.y *= -Elasticity; NewPos.x = Pos.x; Vel.x *= -Elasticity; } } Pos = NewPos; } } *pInoutPos = Pos; *pInoutVel = Vel; } ================================================ FILE: src/game/collision.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_COLLISION_H #define GAME_COLLISION_H #include <base/vmath.h> class CCollision { class CTile *m_pTiles; int m_Width; int m_Height; class CLayers *m_pLayers; bool IsTileSolid(int x, int y); int GetTile(int x, int y); public: enum { COLFLAG_SOLID=1, COLFLAG_DEATH=2, COLFLAG_NOHOOK=4, }; CCollision(); void Init(class CLayers *pLayers); bool CheckPoint(float x, float y) { return IsTileSolid(round(x), round(y)); } bool CheckPoint(vec2 Pos) { return CheckPoint(Pos.x, Pos.y); } int GetCollisionAt(float x, float y) { return GetTile(round(x), round(y)); } int GetWidth() { return m_Width; }; int GetHeight() { return m_Height; }; int IntersectLine(vec2 Pos0, vec2 Pos1, vec2 *pOutCollision, vec2 *pOutBeforeCollision); void MovePoint(vec2 *pInoutPos, vec2 *pInoutVel, float Elasticity, int *pBounces); void MoveBox(vec2 *pInoutPos, vec2 *pInoutVel, vec2 Size, float Elasticity); bool TestBox(vec2 Pos, vec2 Size); }; #endif ================================================ FILE: src/game/editor/auto_map.cpp ================================================ #include <engine/console.h> #include <engine/storage.h> #include "auto_map.h" #include "editor.h" void CTilesetMapper::Load(const json_value &rElement) { for(unsigned i = 0; i < rElement.u.array.length; ++i) { if(rElement[i].u.object.length != 1) continue; // new rule set CRuleSet NewRuleSet; const char* pConfName = rElement[i].u.object.values[0].name; str_copy(NewRuleSet.m_aName, pConfName, sizeof(NewRuleSet.m_aName)); const json_value &rStart = *(rElement[i].u.object.values[0].value); // get basetile const json_value &rBasetile = rStart["basetile"]; if(rBasetile.type == json_integer) NewRuleSet.m_BaseTile = clamp((int)rBasetile.u.integer, 0, 255); else NewRuleSet.m_BaseTile = 1; // get rules const json_value &rRuleNode = rStart["rules"]; for(unsigned j = 0; j < rRuleNode.u.array.length && j < MAX_RULES; j++) { // create a new rule CRule NewRule; // index const json_value &rIndex = rRuleNode[j]["index"]; if(rIndex.type == json_integer) NewRule.m_Index = clamp((int)rIndex.u.integer, 0, 255); else NewRule.m_Index = 1; // random const json_value &rRandom = rRuleNode[j]["random"]; if(rRandom.type == json_integer) NewRule.m_Random = clamp((int)rRandom.u.integer, 0, 99999); else NewRule.m_Random = 0; // rotate const json_value &rRotate = rRuleNode[j]["rotate"]; if(rRotate.type == json_integer && (rRotate.u.integer == 90 || rRotate.u.integer == 180 || rRotate.u.integer == 270)) NewRule.m_Rotation = rRotate.u.integer; else NewRule.m_Rotation = 0; // hflip const json_value &rHFlip = rRuleNode[j]["hflip"]; if(rHFlip.type == json_integer) NewRule.m_HFlip = clamp((int)rHFlip.u.integer, 0, 1); else NewRule.m_HFlip = 0; // vflip const json_value &rVFlip = rRuleNode[j]["vflip"]; if(rVFlip.type == json_integer) NewRule.m_VFlip = clamp((int)rVFlip.u.integer, 0, 1); else NewRule.m_VFlip = 0; // get rule's content const json_value &rCondition = rRuleNode[j]["condition"]; if(rCondition.type == json_array) { for(unsigned k = 0; k < rCondition.u.array.length; k++) { CRuleCondition Condition; Condition.m_X = rCondition[k]["x"].u.integer; Condition.m_Y = rCondition[k]["y"].u.integer; const json_value &rValue = rCondition[k]["value"]; if(rValue.type == json_string) { // the value is not an index, check if it's full or empty if(str_comp((const char *)rValue, "full") == 0) Condition.m_Value = CRuleCondition::FULL; else Condition.m_Value = CRuleCondition::EMPTY; } else if(rValue.type == json_integer) Condition.m_Value = clamp((int)rValue.u.integer, (int)CRuleCondition::EMPTY, 255); else Condition.m_Value = CRuleCondition::EMPTY; NewRule.m_aConditions.add(Condition); } } NewRuleSet.m_aRules.add(NewRule); } m_aRuleSets.add(NewRuleSet); } } const char* CTilesetMapper::GetRuleSetName(int Index) { if(Index < 0 || Index >= m_aRuleSets.size()) return ""; return m_aRuleSets[Index].m_aName; } void CTilesetMapper::Proceed(CLayerTiles *pLayer, int ConfigID) { if(pLayer->m_Readonly || ConfigID < 0 || ConfigID >= m_aRuleSets.size()) return; CRuleSet *pConf = &m_aRuleSets[ConfigID]; if(!pConf->m_aRules.size()) return; int BaseTile = pConf->m_BaseTile; // auto map ! int MaxIndex = pLayer->m_Width*pLayer->m_Height; for(int y = 0; y < pLayer->m_Height; y++) for(int x = 0; x < pLayer->m_Width; x++) { CTile *pTile = &(pLayer->m_pTiles[y*pLayer->m_Width+x]); if(pTile->m_Index == 0) continue; pTile->m_Index = BaseTile; if(y == 0 || y == pLayer->m_Height-1 || x == 0 || x == pLayer->m_Width-1) continue; for(int i = 0; i < pConf->m_aRules.size(); ++i) { bool RespectRules = true; for(int j = 0; j < pConf->m_aRules[i].m_aConditions.size() && RespectRules; ++j) { CRuleCondition *pCondition = &pConf->m_aRules[i].m_aConditions[j]; int CheckIndex = (y+pCondition->m_Y)*pLayer->m_Width+(x+pCondition->m_X); if(CheckIndex < 0 || CheckIndex >= MaxIndex) RespectRules = false; else { if(pCondition->m_Value == CRuleCondition::EMPTY || pCondition->m_Value == CRuleCondition::FULL) { if(pLayer->m_pTiles[CheckIndex].m_Index > 0 && pCondition->m_Value == CRuleCondition::EMPTY) RespectRules = false; if(pLayer->m_pTiles[CheckIndex].m_Index == 0 && pCondition->m_Value == CRuleCondition::FULL) RespectRules = false; } else { if(pLayer->m_pTiles[CheckIndex].m_Index != pCondition->m_Value) RespectRules = false; } } } if(RespectRules && (pConf->m_aRules[i].m_Random <= 1 || (int)((float)rand() / ((float)RAND_MAX + 1) * pConf->m_aRules[i].m_Random) == 1)) { pTile->m_Index = pConf->m_aRules[i].m_Index; // rotate if(pConf->m_aRules[i].m_Rotation == 90) pTile->m_Flags ^= TILEFLAG_ROTATE; else if(pConf->m_aRules[i].m_Rotation == 180) pTile->m_Flags ^= (TILEFLAG_HFLIP|TILEFLAG_VFLIP); else if(pConf->m_aRules[i].m_Rotation == 270) pTile->m_Flags ^= (TILEFLAG_HFLIP|TILEFLAG_VFLIP|TILEFLAG_ROTATE); // flip if(pConf->m_aRules[i].m_HFlip) pTile->m_Flags ^= pTile->m_Flags&TILEFLAG_ROTATE ? TILEFLAG_HFLIP : TILEFLAG_VFLIP; if(pConf->m_aRules[i].m_VFlip) pTile->m_Flags ^= pTile->m_Flags&TILEFLAG_ROTATE ? TILEFLAG_VFLIP : TILEFLAG_HFLIP; } } } m_pEditor->m_Map.m_Modified = true; } int CompareRules(const void *a, const void *b) { CDoodadsMapper::CRule *ra = (CDoodadsMapper::CRule*)a; CDoodadsMapper::CRule *rb = (CDoodadsMapper::CRule*)b; if((ra->m_Location == CDoodadsMapper::CRule::FLOOR && rb->m_Location == CDoodadsMapper::CRule::FLOOR) || (ra->m_Location == CDoodadsMapper::CRule::CEILING && rb->m_Location == CDoodadsMapper::CRule::CEILING)) { if(ra->m_Size.x < rb->m_Size.x) return +1; if(rb->m_Size.x < ra->m_Size.x) return -1; } else if(ra->m_Location == CDoodadsMapper::CRule::WALLS && rb->m_Location == CDoodadsMapper::CRule::WALLS) { if(ra->m_Size.y < rb->m_Size.y) return +1; if(rb->m_Size.y < ra->m_Size.y) return -1; } return 0; } void CDoodadsMapper::Load(const json_value &rElement) { for(unsigned i = 0; i < rElement.u.array.length; ++i) { if(rElement[i].u.object.length != 1) continue; // new rule set CRuleSet NewRuleSet; const char* pConfName = rElement[i].u.object.values[0].name; str_copy(NewRuleSet.m_aName, pConfName, sizeof(NewRuleSet.m_aName)); const json_value &rStart = *(rElement[i].u.object.values[0].value); // get rules const json_value &rRuleNode = rStart["rules"]; for(unsigned j = 0; j < rRuleNode.u.array.length && j < MAX_RULES; j++) { // create a new rule CRule NewRule; // startid const json_value &rStartid = rRuleNode[j]["startid"]; if(rStartid.type == json_integer) NewRule.m_Rect.x = clamp((int)rStartid.u.integer, 0, 255); else NewRule.m_Rect.x = 1; // endid const json_value &rEndid = rRuleNode[j]["endid"]; if(rEndid.type == json_integer) NewRule.m_Rect.y = clamp((int)rEndid.u.integer, 0, 255); else NewRule.m_Rect.y = 1; // broken, skip if(NewRule.m_Rect.x > NewRule.m_Rect.y) continue; // rx const json_value &rRx = rRuleNode[j]["rx"]; if(rRx.type == json_integer) NewRule.m_RelativePos.x = rRx.u.integer; else NewRule.m_RelativePos.x = 0; // ry const json_value &rRy = rRuleNode[j]["ry"]; if(rRy.type == json_integer) NewRule.m_RelativePos.y = rRy.u.integer; else NewRule.m_RelativePos.y = 0; // width NewRule.m_Size.x = absolute(NewRule.m_Rect.x-NewRule.m_Rect.y)%16+1; // height NewRule.m_Size.y = floor((float)absolute(NewRule.m_Rect.x-NewRule.m_Rect.y)/16)+1; // random const json_value &rRandom = rRuleNode[j]["random"]; if(rRandom.type == json_integer) NewRule.m_Random = clamp((int)rRandom.u.integer, 1, 99999); else NewRule.m_Random = 1; // hflip const json_value &rHFlip = rRuleNode[j]["hflip"]; if(rHFlip.type == json_integer) NewRule.m_HFlip = clamp((int)rHFlip.u.integer, 0, 1); else NewRule.m_HFlip = 0; // vflip const json_value &rVFlip = rRuleNode[j]["vflip"]; if(rVFlip.type == json_integer) NewRule.m_VFlip = clamp((int)rVFlip.u.integer, 0, 1); else NewRule.m_VFlip = 0; // location NewRule.m_Location = CRule::FLOOR; const json_value &rLocation = rRuleNode[j]["location"]; if(rLocation.type == json_string) { if(str_comp((const char *)rLocation, "ceiling") == 0) NewRule.m_Location = CRule::CEILING; else if(str_comp((const char *)rLocation, "walls") == 0) NewRule.m_Location = CRule::WALLS; } NewRuleSet.m_aRules.add(NewRule); } m_aRuleSets.add(NewRuleSet); } // sort for(int i = 0; i < m_aRuleSets.size(); i++) qsort(m_aRuleSets[i].m_aRules.base_ptr(), m_aRuleSets[i].m_aRules.size(), sizeof(m_aRuleSets[i].m_aRules[0]), CompareRules); } const char* CDoodadsMapper::GetRuleSetName(int Index) { if(Index < 0 || Index >= m_aRuleSets.size()) return ""; return m_aRuleSets[Index].m_aName; } void CDoodadsMapper::AnalyzeGameLayer() { // the purpose of this is to detect game layer collision's edges to place doodads according to them // clear existing edges m_FloorIDs.clear(); m_CeilingIDs.clear(); m_RightWallIDs.clear(); m_LeftWallIDs.clear(); CLayerGame *pLayer = m_pEditor->m_Map.m_pGameLayer; bool FloorKeepChaining = false; bool CeilingKeepChaining = false; int FloorChainID = 0; int CeilingChainID = 0; // floors and ceilings // browse up to down for(int y = 1; y < pLayer->m_Height-1; y++) { FloorKeepChaining = false; CeilingKeepChaining = false; for(int x = 1; x < pLayer->m_Width-1; x++) { CTile *pTile = &(pLayer->m_pTiles[y*pLayer->m_Width+x]); // empty, skip if(pTile->m_Index == 0) { FloorKeepChaining = false; CeilingKeepChaining = false; continue; } // check up int CheckIndex = (y-1)*pLayer->m_Width+x; // add a floor part if(pTile->m_Index == 1 && (pLayer->m_pTiles[CheckIndex].m_Index == 0 || pLayer->m_pTiles[CheckIndex].m_Index > ENTITY_OFFSET)) { // create an new chain if(!FloorKeepChaining) { array<int> aChain; aChain.add(y*pLayer->m_Width+x); FloorChainID = m_FloorIDs.add(aChain); FloorKeepChaining = true; } else { // keep chaining m_FloorIDs[FloorChainID].add(y*pLayer->m_Width+x); } } else FloorKeepChaining = false; // check down CheckIndex = (y+1)*pLayer->m_Width+x; // add a ceiling part if(pTile->m_Index == 1 && (pLayer->m_pTiles[CheckIndex].m_Index == 0 || pLayer->m_pTiles[CheckIndex].m_Index > ENTITY_OFFSET)) { // create an new chain if(!CeilingKeepChaining) { array<int> aChain; aChain.add(y*pLayer->m_Width+x); CeilingChainID = m_CeilingIDs.add(aChain); CeilingKeepChaining = true; } else { // keep chaining m_CeilingIDs[CeilingChainID].add(y*pLayer->m_Width+x); } } else CeilingKeepChaining = false; } } bool RWallKeepChaining = false; bool LWallKeepChaining = false; int RWallChainID = 0; int LWallChainID = 0; // walls // browse left to right for(int x = 1; x < pLayer->m_Width-1; x++) { RWallKeepChaining = false; LWallKeepChaining = false; for(int y = 1; y < pLayer->m_Height-1; y++) { CTile *pTile = &(pLayer->m_pTiles[y*pLayer->m_Width+x]); if(pTile->m_Index == 0) { RWallKeepChaining = false; LWallKeepChaining = false; continue; } // check right int CheckIndex = y*pLayer->m_Width+(x+1); // add a right wall part if(pTile->m_Index == 1 && (pLayer->m_pTiles[CheckIndex].m_Index == 0 || pLayer->m_pTiles[CheckIndex].m_Index > ENTITY_OFFSET)) { // create an new chain if(!RWallKeepChaining) { array<int> aChain; aChain.add(y*pLayer->m_Width+x); RWallChainID = m_RightWallIDs.add(aChain); RWallKeepChaining = true; } else { // keep chaining m_RightWallIDs[RWallChainID].add(y*pLayer->m_Width+x); } } else RWallKeepChaining = false; // check left CheckIndex = y*pLayer->m_Width+(x-1); // add a left wall part if(pTile->m_Index == 1 && (pLayer->m_pTiles[CheckIndex].m_Index == 0 || pLayer->m_pTiles[CheckIndex].m_Index > ENTITY_OFFSET)) { // create an new chain if(!LWallKeepChaining) { array<int> aChain; aChain.add(y*pLayer->m_Width+x); LWallChainID = m_LeftWallIDs.add(aChain); LWallKeepChaining = true; } else { // keep chaining m_LeftWallIDs[LWallChainID].add(y*pLayer->m_Width+x); } } else LWallKeepChaining = false; } } // clean up too small chains for(int i = 0; i < m_FloorIDs.size(); i++) { if(m_FloorIDs[i].size() < 3) { m_FloorIDs.remove_index_fast(i); i--; } } for(int i = 0; i < m_CeilingIDs.size(); i++) { if(m_CeilingIDs[i].size() < 3) { m_CeilingIDs.remove_index_fast(i); i--; } } for(int i = 0; i < m_RightWallIDs.size(); i++) { if(m_RightWallIDs[i].size() < 3) { m_RightWallIDs.remove_index_fast(i); i--; } } for(int i = 0; i < m_LeftWallIDs.size(); i++) { if(m_LeftWallIDs[i].size() < 3) { m_LeftWallIDs.remove_index_fast(i); i--; } } } void CDoodadsMapper::PlaceDoodads(CLayerTiles *pLayer, CRule *pRule, array<array<int> > *pPositions, int Amount, int LeftWall) { if(pRule->m_Location == CRule::CEILING) pRule->m_RelativePos.y++; else if(pRule->m_Location == CRule::WALLS) pRule->m_RelativePos.x++; // left walls if(LeftWall) { pRule->m_HFlip ^= LeftWall; pRule->m_RelativePos.x--; pRule->m_RelativePos.x = -pRule->m_RelativePos.x; pRule->m_RelativePos.x -= pRule->m_Size.x-1; } int MaxIndex = pLayer->m_Width*pLayer->m_Height; int RandomValue = pRule->m_Random*((101.f-Amount)/100.0f); if(pRule->m_Random == 1) RandomValue = 1; // allow diversity with high Amount if(pRule->m_Random > 1 && RandomValue <= 1) RandomValue = 2; for(int f = 0; f < pPositions->size(); f++) for(int c = 0; c < (*pPositions)[f].size(); c += pRule->m_Size.x) { if((pRule->m_Location == CRule::FLOOR || pRule->m_Location == CRule::CEILING) && (*pPositions)[f].size()-c < pRule->m_Size.x) break; if(pRule->m_Location == CRule::WALLS && (*pPositions)[f].size()-c < pRule->m_Size.y) break; if(RandomValue > 1 && !IAutoMapper::Random(RandomValue)) continue; // where to put it int ID = (*pPositions)[f][c]; // relative position ID += pRule->m_RelativePos.x; ID += pRule->m_RelativePos.y*pLayer->m_Width; for(int y = 0; y < pRule->m_Size.y; y++) for(int x = 0; x < pRule->m_Size.x; x++) { int Index = y*pLayer->m_Width+x+ID; if(Index <= 0 || Index >= MaxIndex) continue; pLayer->m_pTiles[Index].m_Index = pRule->m_Rect.x+y*16+x; } // hflip if(pRule->m_HFlip) { for(int y = 0; y < pRule->m_Size.y; y++) for(int x = 0; x < pRule->m_Size.x/2; x++) { int Index = y*pLayer->m_Width+x+ID; if(Index <= 0 || Index >= MaxIndex) continue; int CheckIndex = Index+pRule->m_Size.x-1-x*2; if(CheckIndex <= 0 || CheckIndex >= MaxIndex) continue; CTile Tmp = pLayer->m_pTiles[Index]; pLayer->m_pTiles[Index] = pLayer->m_pTiles[CheckIndex]; pLayer->m_pTiles[CheckIndex] = Tmp; } for(int y = 0; y < pRule->m_Size.y; y++) for(int x = 0; x < pRule->m_Size.x; x++) { int Index = y*pLayer->m_Width+x+ID; if(Index <= 0 || Index >= MaxIndex) continue; pLayer->m_pTiles[Index].m_Flags ^= TILEFLAG_VFLIP; } } // vflip if(pRule->m_VFlip) { for(int y = 0; y < pRule->m_Size.y/2; y++) for(int x = 0; x < pRule->m_Size.x; x++) { int Index = y*pLayer->m_Width+x+ID; if(Index <= 0 || Index >= MaxIndex) continue; int CheckIndex = Index+(pRule->m_Size.y-1-y*2)*pLayer->m_Width; if(CheckIndex <= 0 || CheckIndex >= MaxIndex) continue; CTile Tmp = pLayer->m_pTiles[Index]; pLayer->m_pTiles[Index] = pLayer->m_pTiles[CheckIndex]; pLayer->m_pTiles[CheckIndex] = Tmp; } for(int y = 0; y < pRule->m_Size.y; y++) for(int x = 0; x < pRule->m_Size.x; x++) { int Index = y*pLayer->m_Width+x+ID; if(Index <= 0 || Index >= MaxIndex) continue; pLayer->m_pTiles[Index].m_Flags ^= TILEFLAG_HFLIP; } } // make the place occupied if(RandomValue > 1) { array<int> aChainBefore; array<int> aChainAfter; for(int j = 0; j < c; j++) aChainBefore.add((*pPositions)[f][j]); int Size = pRule->m_Size.x; if(pRule->m_Location == CRule::WALLS) Size = pRule->m_Size.y; for(int j = c+Size; j < (*pPositions)[f].size(); j++) aChainAfter.add((*pPositions)[f][j]); pPositions->remove_index(f); // f changes, reset c c = -1; if(aChainBefore.size() > 1) pPositions->add(aChainBefore); if(aChainAfter.size() > 1) pPositions->add(aChainAfter); } } } void CDoodadsMapper::Proceed(CLayerTiles *pLayer, int ConfigID, int Amount) { if(pLayer->m_Readonly || ConfigID < 0 || ConfigID >= m_aRuleSets.size()) return; AnalyzeGameLayer(); CRuleSet *pConf = &m_aRuleSets[ConfigID]; if(!pConf->m_aRules.size()) return; int MaxIndex = pLayer->m_Width*pLayer->m_Height; // clear tiles for(int i = 0 ; i < MaxIndex; i++) { pLayer->m_pTiles[i].m_Index = 0; pLayer->m_pTiles[i].m_Flags = 0; } // place doodads for(int i = 0 ; i < pConf->m_aRules.size(); i++) { CRule *pRule = &pConf->m_aRules[i]; // floors if(pRule->m_Location == CRule::FLOOR && m_FloorIDs.size() > 0) { PlaceDoodads(pLayer, pRule, &m_FloorIDs, Amount); } // ceilings if(pRule->m_Location == CRule::CEILING && m_CeilingIDs.size() > 0) { PlaceDoodads(pLayer, pRule, &m_CeilingIDs, Amount); } // right walls if(pRule->m_Location == CRule::WALLS && m_RightWallIDs.size() > 0) { PlaceDoodads(pLayer, pRule, &m_RightWallIDs, Amount); } // left walls if(pRule->m_Location == CRule::WALLS && m_LeftWallIDs.size() > 0) { PlaceDoodads(pLayer, pRule, &m_LeftWallIDs, Amount, 1); } } m_pEditor->m_Map.m_Modified = true; } ================================================ FILE: src/game/editor/auto_map.h ================================================ #ifndef GAME_EDITOR_AUTO_MAP_H #define GAME_EDITOR_AUTO_MAP_H #include <stdlib.h> // rand #include <base/tl/array.h> #include <base/vmath.h> #include <engine/external/json-parser/json.h> class IAutoMapper { protected: class CEditor *m_pEditor; int m_Type; public: enum { TYPE_TILESET, TYPE_DOODADS, MAX_RULES=256 }; // IAutoMapper(class CEditor *pEditor, int Type) : m_pEditor(pEditor), m_Type(Type) {} virtual ~IAutoMapper() {}; virtual void Load(const json_value &rElement) = 0; virtual void Proceed(class CLayerTiles *pLayer, int ConfigID) {} virtual void Proceed(class CLayerTiles *pLayer, int ConfigID, int Ammount) {} // for convenience purposes virtual int RuleSetNum() = 0; virtual const char* GetRuleSetName(int Index) = 0; // int GetType() { return m_Type; } static bool Random(int Value) { return ((int)((float)rand() / ((float)RAND_MAX + 1) * Value) == 1); } static const char *GetTypeName(int Type) { if(Type == TYPE_TILESET) return "tileset"; else if(Type == TYPE_DOODADS) return "doodads"; else return ""; } }; class CTilesetMapper: public IAutoMapper { struct CRuleCondition { int m_X; int m_Y; int m_Value; enum { EMPTY=-2, FULL=-1 }; }; struct CRule { int m_Index; int m_HFlip; int m_VFlip; int m_Random; int m_Rotation; array<CRuleCondition> m_aConditions; }; struct CRuleSet { char m_aName[128]; int m_BaseTile; array<CRule> m_aRules; }; array<CRuleSet> m_aRuleSets; public: CTilesetMapper(class CEditor *pEditor) : IAutoMapper(pEditor, TYPE_TILESET) { m_aRuleSets.clear(); } virtual void Load(const json_value &rElement); virtual void Proceed(class CLayerTiles *pLayer, int ConfigID); virtual int RuleSetNum() { return m_aRuleSets.size(); } virtual const char* GetRuleSetName(int Index); }; class CDoodadsMapper: public IAutoMapper { public: struct CRule { ivec2 m_Rect; ivec2 m_Size; ivec2 m_RelativePos; int m_Location; int m_Random; int m_HFlip; int m_VFlip; enum { FLOOR=0, CEILING, WALLS }; }; struct CRuleSet { char m_aName[128]; array<CRule> m_aRules; }; CDoodadsMapper(class CEditor *pEditor) : IAutoMapper(pEditor, TYPE_DOODADS) { m_aRuleSets.clear(); } virtual void Load(const json_value &rElement); virtual void Proceed(class CLayerTiles *pLayer, int ConfigID, int Amount); void AnalyzeGameLayer(); virtual int RuleSetNum() { return m_aRuleSets.size(); } virtual const char* GetRuleSetName(int Index); private: void PlaceDoodads(CLayerTiles *pLayer, CRule *pRule, array<array<int> > *pPositions, int Amount, int LeftWall = 0); array<CRuleSet> m_aRuleSets; array<array<int> > m_FloorIDs; array<array<int> > m_CeilingIDs; array<array<int> > m_RightWallIDs; array<array<int> > m_LeftWallIDs; }; #endif ================================================ FILE: src/game/editor/editor.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <base/system.h> #include <engine/shared/datafile.h> #include <engine/shared/config.h> #include <engine/client.h> #include <engine/console.h> #include <engine/graphics.h> #include <engine/input.h> #include <engine/keys.h> #include <engine/storage.h> #include <engine/textrender.h> #include <game/gamecore.h> #include <game/client/lineinput.h> #include <game/client/localization.h> #include <game/client/render.h> #include <game/client/ui.h> #include <game/generated/client_data.h> #include "auto_map.h" #include "editor.h" const void* CEditor::ms_pUiGotContext; enum { BUTTON_CONTEXT=1, }; CEditorImage::~CEditorImage() { m_pEditor->Graphics()->UnloadTexture(m_Texture); if(m_pData) { mem_free(m_pData); m_pData = 0; } if(m_pAutoMapper) { delete m_pAutoMapper; m_pAutoMapper = 0; } } CLayerGroup::CLayerGroup() { m_aName[0] = 0; m_Visible = true; m_SaveToMap = true; m_Collapse = false; m_GameGroup = false; m_OffsetX = 0; m_OffsetY = 0; m_ParallaxX = 100; m_ParallaxY = 100; m_UseClipping = 0; m_ClipX = 0; m_ClipY = 0; m_ClipW = 0; m_ClipH = 0; } CLayerGroup::~CLayerGroup() { Clear(); } void CLayerGroup::Convert(CUIRect *pRect) { pRect->x += m_OffsetX; pRect->y += m_OffsetY; } void CLayerGroup::Mapping(float *pPoints) { m_pMap->m_pEditor->RenderTools()->MapscreenToWorld( m_pMap->m_pEditor->m_WorldOffsetX, m_pMap->m_pEditor->m_WorldOffsetY, m_ParallaxX/100.0f, m_ParallaxY/100.0f, m_OffsetX, m_OffsetY, m_pMap->m_pEditor->Graphics()->ScreenAspect(), m_pMap->m_pEditor->m_WorldZoom, pPoints); pPoints[0] += m_pMap->m_pEditor->m_EditorOffsetX; pPoints[1] += m_pMap->m_pEditor->m_EditorOffsetY; pPoints[2] += m_pMap->m_pEditor->m_EditorOffsetX; pPoints[3] += m_pMap->m_pEditor->m_EditorOffsetY; } void CLayerGroup::MapScreen() { float aPoints[4]; Mapping(aPoints); m_pMap->m_pEditor->Graphics()->MapScreen(aPoints[0], aPoints[1], aPoints[2], aPoints[3]); } void CLayerGroup::Render() { MapScreen(); IGraphics *pGraphics = m_pMap->m_pEditor->Graphics(); if(m_UseClipping) { float aPoints[4]; m_pMap->m_pGameGroup->Mapping(aPoints); float x0 = (m_ClipX - aPoints[0]) / (aPoints[2]-aPoints[0]); float y0 = (m_ClipY - aPoints[1]) / (aPoints[3]-aPoints[1]); float x1 = ((m_ClipX+m_ClipW) - aPoints[0]) / (aPoints[2]-aPoints[0]); float y1 = ((m_ClipY+m_ClipH) - aPoints[1]) / (aPoints[3]-aPoints[1]); pGraphics->ClipEnable((int)(x0*pGraphics->ScreenWidth()), (int)(y0*pGraphics->ScreenHeight()), (int)((x1-x0)*pGraphics->ScreenWidth()), (int)((y1-y0)*pGraphics->ScreenHeight())); } for(int i = 0; i < m_lLayers.size(); i++) { if(m_lLayers[i]->m_Visible && m_lLayers[i] != m_pMap->m_pGameLayer) { if(m_pMap->m_pEditor->m_ShowDetail || !(m_lLayers[i]->m_Flags&LAYERFLAG_DETAIL)) m_lLayers[i]->Render(); } } pGraphics->ClipDisable(); } void CLayerGroup::AddLayer(CLayer *l) { m_pMap->m_Modified = true; m_lLayers.add(l); } void CLayerGroup::DeleteLayer(int Index) { if(Index < 0 || Index >= m_lLayers.size()) return; delete m_lLayers[Index]; m_lLayers.remove_index(Index); m_pMap->m_Modified = true; } void CLayerGroup::GetSize(float *w, float *h) { *w = 0; *h = 0; for(int i = 0; i < m_lLayers.size(); i++) { float lw, lh; m_lLayers[i]->GetSize(&lw, &lh); *w = max(*w, lw); *h = max(*h, lh); } } int CLayerGroup::SwapLayers(int Index0, int Index1) { if(Index0 < 0 || Index0 >= m_lLayers.size()) return Index0; if(Index1 < 0 || Index1 >= m_lLayers.size()) return Index0; if(Index0 == Index1) return Index0; m_pMap->m_Modified = true; swap(m_lLayers[Index0], m_lLayers[Index1]); return Index1; } void CEditorImage::AnalyseTileFlags() { if(m_Format == CImageInfo::FORMAT_RGB) { for(int i = 0; i < 256; ++i) m_aTileFlags[i] = TILEFLAG_OPAQUE; } else { mem_zero(m_aTileFlags, sizeof(m_aTileFlags)); int tw = m_Width/16; // tilesizes int th = m_Height/16; if(tw == th) { unsigned char *pPixelData = (unsigned char *)m_pData; int TileID = 0; for(int ty = 0; ty < 16; ty++) for(int tx = 0; tx < 16; tx++, TileID++) { bool Opaque = true; for(int x = 0; x < tw; x++) for(int y = 0; y < th; y++) { int p = (ty*tw+y)*m_Width + tx*tw+x; if(pPixelData[p*4+3] < 250) { Opaque = false; break; } } if(Opaque) m_aTileFlags[TileID] |= TILEFLAG_OPAQUE; } } } } void CEditorImage::LoadAutoMapper() { if(m_pAutoMapper) return; // read file data into buffer char aBuf[256]; str_format(aBuf, sizeof(aBuf), "editor/automap/%s.json", m_aName); IOHANDLE File = m_pEditor->Storage()->OpenFile(aBuf, IOFLAG_READ, IStorage::TYPE_ALL); if(!File) return; int FileSize = (int)io_length(File); char *pFileData = (char *)mem_alloc(FileSize+1, 1); io_read(File, pFileData, FileSize); pFileData[FileSize] = 0; io_close(File); // parse json data json_settings JsonSettings; mem_zero(&JsonSettings, sizeof(JsonSettings)); char aError[256]; json_value *pJsonData = json_parse_ex(&JsonSettings, pFileData, aError); if(pJsonData == 0) { m_pEditor->Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, aBuf, aError); mem_free(pFileData); return; } // generate configurations const json_value &rTileset = (*pJsonData)[(const char *)IAutoMapper::GetTypeName(IAutoMapper::TYPE_TILESET)]; if(rTileset.type == json_array) { m_pAutoMapper = new CTilesetMapper(m_pEditor); m_pAutoMapper->Load(rTileset); } else { const json_value &rDoodads = (*pJsonData)[(const char *)IAutoMapper::GetTypeName(IAutoMapper::TYPE_DOODADS)]; if(rDoodads.type == json_array) { m_pAutoMapper = new CDoodadsMapper(m_pEditor); m_pAutoMapper->Load(rDoodads); } } // clean up json_value_free(pJsonData); mem_free(pFileData); if(m_pAutoMapper && g_Config.m_Debug) { str_format(aBuf, sizeof(aBuf),"loaded %s.json (%s)", m_aName, IAutoMapper::GetTypeName(m_pAutoMapper->GetType())); m_pEditor->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "editor", aBuf); } } void CEditor::EnvelopeEval(float TimeOffset, int Env, float *pChannels, void *pUser) { CEditor *pThis = (CEditor *)pUser; if(Env < 0 || Env >= pThis->m_Map.m_lEnvelopes.size()) { pChannels[0] = 0; pChannels[1] = 0; pChannels[2] = 0; pChannels[3] = 0; return; } CEnvelope *e = pThis->m_Map.m_lEnvelopes[Env]; float t = pThis->m_AnimateTime+TimeOffset; t *= pThis->m_AnimateSpeed; e->Eval(t, pChannels); } /******************************************************** OTHER *********************************************************/ // copied from gc_menu.cpp, should be more generalized //extern int ui_do_edit_box(void *id, const CUIRect *rect, char *str, int str_size, float font_size, bool hidden=false); int CEditor::DoEditBox(void *pID, const CUIRect *pRect, char *pStr, unsigned StrSize, float FontSize, float *Offset, bool Hidden, int Corners) { int Inside = UI()->MouseInside(pRect); bool ReturnValue = false; bool UpdateOffset = false; static int s_AtIndex = 0; static bool s_DoScroll = false; static float s_ScrollStart = 0.0f; FontSize *= UI()->Scale(); if(UI()->LastActiveItem() == pID) { m_EditBoxActive = 2; int Len = str_length(pStr); if(Len == 0) s_AtIndex = 0; if(Inside && UI()->MouseButton(0)) { s_DoScroll = true; s_ScrollStart = UI()->MouseX(); int MxRel = (int)(UI()->MouseX() - pRect->x); for(int i = 1; i <= Len; i++) { if(TextRender()->TextWidth(0, FontSize, pStr, i) - *Offset > MxRel) { s_AtIndex = i - 1; break; } if(i == Len) s_AtIndex = Len; } } else if(!UI()->MouseButton(0)) s_DoScroll = false; else if(s_DoScroll) { // do scrolling if(UI()->MouseX() < pRect->x && s_ScrollStart-UI()->MouseX() > 10.0f) { s_AtIndex = max(0, s_AtIndex-1); s_ScrollStart = UI()->MouseX(); UpdateOffset = true; } else if(UI()->MouseX() > pRect->x+pRect->w && UI()->MouseX()-s_ScrollStart > 10.0f) { s_AtIndex = min(Len, s_AtIndex+1); s_ScrollStart = UI()->MouseX(); UpdateOffset = true; } } for(int i = 0; i < Input()->NumEvents(); i++) { Len = str_length(pStr); ReturnValue |= CLineInput::Manipulate(Input()->GetEvent(i), pStr, StrSize, &Len, &s_AtIndex); } } bool JustGotActive = false; if(UI()->ActiveItem() == pID) { if(!UI()->MouseButton(0)) { s_AtIndex = min(s_AtIndex, str_length(pStr)); s_DoScroll = false; UI()->SetActiveItem(0); } } else if(UI()->HotItem() == pID) { if(UI()->MouseButton(0)) { if (UI()->LastActiveItem() != pID) JustGotActive = true; UI()->SetActiveItem(pID); } } if(Inside) UI()->SetHotItem(pID); CUIRect Textbox = *pRect; RenderTools()->DrawUIRect(&Textbox, vec4(1, 1, 1, 0.5f), Corners, 3.0f); Textbox.VMargin(2.0f, &Textbox); const char *pDisplayStr = pStr; char aStars[128]; if(Hidden) { unsigned s = str_length(pStr); if(s >= sizeof(aStars)) s = sizeof(aStars)-1; for(unsigned int i = 0; i < s; ++i) aStars[i] = '*'; aStars[s] = 0; pDisplayStr = aStars; } // check if the text has to be moved if(UI()->LastActiveItem() == pID && !JustGotActive && (UpdateOffset || Input()->NumEvents())) { float w = TextRender()->TextWidth(0, FontSize, pDisplayStr, s_AtIndex); if(w-*Offset > Textbox.w) { // move to the left float wt = TextRender()->TextWidth(0, FontSize, pDisplayStr, -1); do { *Offset += min(wt-*Offset-Textbox.w, Textbox.w/3); } while(w-*Offset > Textbox.w); } else if(w-*Offset < 0.0f) { // move to the right do { *Offset = max(0.0f, *Offset-Textbox.w/3); } while(w-*Offset < 0.0f); } } UI()->ClipEnable(pRect); Textbox.x -= *Offset; UI()->DoLabel(&Textbox, pDisplayStr, FontSize, -1); // render the cursor if(UI()->LastActiveItem() == pID && !JustGotActive) { float w = TextRender()->TextWidth(0, FontSize, pDisplayStr, s_AtIndex); Textbox = *pRect; Textbox.VSplitLeft(2.0f, 0, &Textbox); Textbox.x += (w-*Offset-TextRender()->TextWidth(0, FontSize, "|", -1)/2); if((2*time_get()/time_freq()) % 2) // make it blink UI()->DoLabel(&Textbox, "|", FontSize, -1); } UI()->ClipDisable(); return ReturnValue; } vec4 CEditor::ButtonColorMul(const void *pID) { if(UI()->ActiveItem() == pID) return vec4(1,1,1,0.5f); else if(UI()->HotItem() == pID) return vec4(1,1,1,1.5f); return vec4(1,1,1,1); } float CEditor::UiDoScrollbarV(const void *pID, const CUIRect *pRect, float Current) { CUIRect Handle; static float s_OffsetY; pRect->HSplitTop(33, &Handle, 0); Handle.y += (pRect->h-Handle.h)*Current; // logic float Ret = Current; int Inside = UI()->MouseInside(&Handle); if(UI()->ActiveItem() == pID) { if(!UI()->MouseButton(0)) UI()->SetActiveItem(0); float Min = pRect->y; float Max = pRect->h-Handle.h; float Cur = UI()->MouseY()-s_OffsetY; Ret = (Cur-Min)/Max; if(Ret < 0.0f) Ret = 0.0f; if(Ret > 1.0f) Ret = 1.0f; } else if(UI()->HotItem() == pID) { if(UI()->MouseButton(0)) { UI()->SetActiveItem(pID); s_OffsetY = UI()->MouseY()-Handle.y; } } if(Inside) UI()->SetHotItem(pID); // render CUIRect Rail; pRect->VMargin(5.0f, &Rail); RenderTools()->DrawUIRect(&Rail, vec4(1,1,1,0.25f), 0, 0.0f); CUIRect Slider = Handle; Slider.w = Rail.x-Slider.x; RenderTools()->DrawUIRect(&Slider, vec4(1,1,1,0.25f), CUI::CORNER_L, 2.5f); Slider.x = Rail.x+Rail.w; RenderTools()->DrawUIRect(&Slider, vec4(1,1,1,0.25f), CUI::CORNER_R, 2.5f); Slider = Handle; Slider.Margin(5.0f, &Slider); RenderTools()->DrawUIRect(&Slider, vec4(1,1,1,0.25f)*ButtonColorMul(pID), CUI::CORNER_ALL, 2.5f); return Ret; } vec4 CEditor::GetButtonColor(const void *pID, int Checked) { if(Checked < 0) return vec4(0,0,0,0.5f); if(Checked > 0) { if(UI()->HotItem() == pID) return vec4(1,0,0,0.75f); return vec4(1,0,0,0.5f); } if(UI()->HotItem() == pID) return vec4(1,1,1,0.75f); return vec4(1,1,1,0.5f); } int CEditor::DoButton_Editor_Common(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip) { if(UI()->MouseInside(pRect)) { if(Flags&BUTTON_CONTEXT) ms_pUiGotContext = pID; if(m_pTooltip) m_pTooltip = pToolTip; } if(UI()->HotItem() == pID && pToolTip) m_pTooltip = (const char *)pToolTip; return UI()->DoButtonLogic(pID, pText, Checked, pRect); // Draw here //return UI()->DoButton(id, text, checked, r, draw_func, 0); } int CEditor::DoButton_Editor(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip) { RenderTools()->DrawUIRect(pRect, GetButtonColor(pID, Checked), CUI::CORNER_ALL, 3.0f); CUIRect NewRect = *pRect; NewRect.y += NewRect.h/2.0f-7.0f; float tw = min(TextRender()->TextWidth(0, 10.0f, pText, -1), NewRect.w); CTextCursor Cursor; TextRender()->SetCursor(&Cursor, NewRect.x + NewRect.w/2-tw/2, NewRect.y - 1.0f, 10.0f, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); Cursor.m_LineWidth = NewRect.w; TextRender()->TextEx(&Cursor, pText, -1); return DoButton_Editor_Common(pID, pText, Checked, pRect, Flags, pToolTip); } int CEditor::DoButton_File(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip) { if(Checked) RenderTools()->DrawUIRect(pRect, GetButtonColor(pID, Checked), CUI::CORNER_ALL, 3.0f); CUIRect t = *pRect; t.VMargin(5.0f, &t); UI()->DoLabel(&t, pText, 10, -1, -1); return DoButton_Editor_Common(pID, pText, Checked, pRect, Flags, pToolTip); } int CEditor::DoButton_Menu(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip) { CUIRect r = *pRect; RenderTools()->DrawUIRect(&r, vec4(0.5f, 0.5f, 0.5f, 1.0f), CUI::CORNER_T, 3.0f); r = *pRect; r.VMargin(5.0f, &r); UI()->DoLabel(&r, pText, 10, -1, -1); return DoButton_Editor_Common(pID, pText, Checked, pRect, Flags, pToolTip); } int CEditor::DoButton_MenuItem(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip) { if(UI()->HotItem() == pID || Checked) RenderTools()->DrawUIRect(pRect, GetButtonColor(pID, Checked), CUI::CORNER_ALL, 3.0f); CUIRect t = *pRect; t.VMargin(5.0f, &t); CTextCursor Cursor; TextRender()->SetCursor(&Cursor, t.x, t.y - 1.0f, 10.0f, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END); Cursor.m_LineWidth = t.w; TextRender()->TextEx(&Cursor, pText, -1); return DoButton_Editor_Common(pID, pText, Checked, pRect, Flags, pToolTip); } int CEditor::DoButton_Tab(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip) { RenderTools()->DrawUIRect(pRect, GetButtonColor(pID, Checked), CUI::CORNER_T, 5.0f); CUIRect NewRect = *pRect; NewRect.y += NewRect.h/2.0f-7.0f; UI()->DoLabel(&NewRect, pText, 10, 0, -1); return DoButton_Editor_Common(pID, pText, Checked, pRect, Flags, pToolTip); } int CEditor::DoButton_Ex(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip, int Corners, float FontSize) { RenderTools()->DrawUIRect(pRect, GetButtonColor(pID, Checked), Corners, 3.0f); CUIRect NewRect = *pRect; NewRect.HMargin(NewRect.h/2.0f-FontSize/2.0f-1.0f, &NewRect); UI()->DoLabel(&NewRect, pText, FontSize, 0, -1); return DoButton_Editor_Common(pID, pText, Checked, pRect, Flags, pToolTip); } int CEditor::DoButton_ButtonInc(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip) { RenderTools()->DrawUIRect(pRect, GetButtonColor(pID, Checked), CUI::CORNER_R, 3.0f); UI()->DoLabel(pRect, pText?pText:"+", 10, 0, -1); return DoButton_Editor_Common(pID, pText, Checked, pRect, Flags, pToolTip); } int CEditor::DoButton_ButtonDec(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip) { RenderTools()->DrawUIRect(pRect, GetButtonColor(pID, Checked), CUI::CORNER_L, 3.0f); UI()->DoLabel(pRect, pText?pText:"-", 10, 0, -1); return DoButton_Editor_Common(pID, pText, Checked, pRect, Flags, pToolTip); } void CEditor::RenderGrid(CLayerGroup *pGroup) { if(!m_GridActive) return; float aGroupPoints[4]; pGroup->Mapping(aGroupPoints); float w = UI()->Screen()->w; float h = UI()->Screen()->h; int LineDistance = GetLineDistance(); int XOffset = aGroupPoints[0]/LineDistance; int YOffset = aGroupPoints[1]/LineDistance; int XGridOffset = XOffset % m_GridFactor; int YGridOffset = YOffset % m_GridFactor; Graphics()->TextureClear(); Graphics()->LinesBegin(); for(int i = 0; i < (int)w; i++) { if((i+YGridOffset) % m_GridFactor == 0) Graphics()->SetColor(1.0f, 0.3f, 0.3f, 0.3f); else Graphics()->SetColor(1.0f, 1.0f, 1.0f, 0.15f); IGraphics::CLineItem Line = IGraphics::CLineItem(LineDistance*XOffset, LineDistance*i+LineDistance*YOffset, w+aGroupPoints[2], LineDistance*i+LineDistance*YOffset); Graphics()->LinesDraw(&Line, 1); if((i+XGridOffset) % m_GridFactor == 0) Graphics()->SetColor(1.0f, 0.3f, 0.3f, 0.3f); else Graphics()->SetColor(1.0f, 1.0f, 1.0f, 0.15f); Line = IGraphics::CLineItem(LineDistance*i+LineDistance*XOffset, LineDistance*YOffset, LineDistance*i+LineDistance*XOffset, h+aGroupPoints[3]); Graphics()->LinesDraw(&Line, 1); } Graphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f); Graphics()->LinesEnd(); } void CEditor::RenderBackground(CUIRect View, IGraphics::CTextureHandle Texture, float Size, float Brightness) { Graphics()->TextureSet(Texture); Graphics()->BlendNormal(); Graphics()->QuadsBegin(); Graphics()->SetColor(Brightness, Brightness, Brightness, 1.0f); Graphics()->QuadsSetSubset(0,0, View.w/Size, View.h/Size); IGraphics::CQuadItem QuadItem(View.x, View.y, View.w, View.h); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); } int CEditor::UiDoValueSelector(void *pID, CUIRect *pRect, const char *pLabel, int Current, int Min, int Max, int Step, float Scale, const char *pToolTip) { // logic static float s_Value; int Inside = UI()->MouseInside(pRect); if(UI()->ActiveItem() == pID) { if(!UI()->MouseButton(0)) { m_LockMouse = false; UI()->SetActiveItem(0); } else { if(Input()->KeyPressed(KEY_LSHIFT) || Input()->KeyPressed(KEY_RSHIFT)) s_Value += m_MouseDeltaX*0.05f; else s_Value += m_MouseDeltaX; if(absolute(s_Value) > Scale) { int Count = (int)(s_Value/Scale); s_Value = fmod(s_Value, Scale); Current += Step*Count; if(Current < Min) Current = Min; if(Current > Max) Current = Max; } } if(pToolTip) m_pTooltip = pToolTip; } else if(UI()->HotItem() == pID) { if(UI()->MouseButton(0)) { m_LockMouse = true; s_Value = 0; UI()->SetActiveItem(pID); } if(pToolTip) m_pTooltip = pToolTip; } if(Inside) UI()->SetHotItem(pID); // render char aBuf[128]; str_format(aBuf, sizeof(aBuf),"%s %d", pLabel, Current); RenderTools()->DrawUIRect(pRect, GetButtonColor(pID, 0), CUI::CORNER_ALL, 5.0f); pRect->y += pRect->h/2.0f-7.0f; UI()->DoLabel(pRect, aBuf, 10, 0, -1); return Current; } CLayerGroup *CEditor::GetSelectedGroup() { if(m_SelectedGroup >= 0 && m_SelectedGroup < m_Map.m_lGroups.size()) return m_Map.m_lGroups[m_SelectedGroup]; return 0x0; } CLayer *CEditor::GetSelectedLayer(int Index) { CLayerGroup *pGroup = GetSelectedGroup(); if(!pGroup) return 0x0; if(m_SelectedLayer >= 0 && m_SelectedLayer < m_Map.m_lGroups[m_SelectedGroup]->m_lLayers.size()) return pGroup->m_lLayers[m_SelectedLayer]; return 0x0; } CLayer *CEditor::GetSelectedLayerType(int Index, int Type) { CLayer *p = GetSelectedLayer(Index); if(p && p->m_Type == Type) return p; return 0x0; } CQuad *CEditor::GetSelectedQuad() { CLayerQuads *ql = (CLayerQuads *)GetSelectedLayerType(0, LAYERTYPE_QUADS); if(!ql) return 0; if(m_SelectedQuad >= 0 && m_SelectedQuad < ql->m_lQuads.size()) return &ql->m_lQuads[m_SelectedQuad]; return 0; } void CEditor::CallbackOpenMap(const char *pFileName, int StorageType, void *pUser) { CEditor *pEditor = (CEditor*)pUser; if(pEditor->Load(pFileName, StorageType)) { str_copy(pEditor->m_aFileName, pFileName, 512); pEditor->m_ValidSaveFilename = StorageType == IStorage::TYPE_SAVE && pEditor->m_pFileDialogPath == pEditor->m_aFileDialogCurrentFolder; pEditor->SortImages(); pEditor->m_Dialog = DIALOG_NONE; pEditor->m_Map.m_Modified = false; } else { pEditor->Reset(); pEditor->m_aFileName[0] = 0; } } void CEditor::CallbackAppendMap(const char *pFileName, int StorageType, void *pUser) { CEditor *pEditor = (CEditor*)pUser; if(pEditor->Append(pFileName, StorageType)) pEditor->m_aFileName[0] = 0; else pEditor->SortImages(); pEditor->m_Dialog = DIALOG_NONE; } void CEditor::CallbackSaveMap(const char *pFileName, int StorageType, void *pUser) { CEditor *pEditor = static_cast<CEditor*>(pUser); char aBuf[1024]; const int Length = str_length(pFileName); // add map extension if(Length <= 4 || pFileName[Length-4] != '.' || str_comp_nocase(pFileName+Length-3, "map")) { str_format(aBuf, sizeof(aBuf), "%s.map", pFileName); pFileName = aBuf; } if(pEditor->Save(pFileName)) { str_copy(pEditor->m_aFileName, pFileName, sizeof(pEditor->m_aFileName)); pEditor->m_ValidSaveFilename = StorageType == IStorage::TYPE_SAVE && pEditor->m_pFileDialogPath == pEditor->m_aFileDialogCurrentFolder; pEditor->m_Map.m_Modified = false; } pEditor->m_Dialog = DIALOG_NONE; } void CEditor::DoToolbar(CUIRect ToolBar) { CUIRect TB_Top, TB_Bottom; CUIRect Button; ToolBar.HSplitTop(ToolBar.h/2.0f, &TB_Top, &TB_Bottom); TB_Top.HSplitBottom(2.5f, &TB_Top, 0); TB_Bottom.HSplitTop(2.5f, 0, &TB_Bottom); // ctrl+o to open if(Input()->KeyDown('o') && (Input()->KeyPressed(KEY_LCTRL) || Input()->KeyPressed(KEY_RCTRL)) && m_Dialog == DIALOG_NONE) { if(HasUnsavedData()) { if(!m_PopupEventWasActivated) { m_PopupEventType = POPEVENT_LOAD; m_PopupEventActivated = true; } } else InvokeFileDialog(IStorage::TYPE_ALL, FILETYPE_MAP, "Load map", "Load", "maps", "", CallbackOpenMap, this); } // ctrl+s to save if(Input()->KeyDown('s') && (Input()->KeyPressed(KEY_LCTRL) || Input()->KeyPressed(KEY_RCTRL)) && m_Dialog == DIALOG_NONE) { if(m_aFileName[0] && m_ValidSaveFilename) { if(!m_PopupEventWasActivated) { str_copy(m_aFileSaveName, m_aFileName, sizeof(m_aFileSaveName)); m_PopupEventType = POPEVENT_SAVE; m_PopupEventActivated = true; } } else InvokeFileDialog(IStorage::TYPE_SAVE, FILETYPE_MAP, "Save map", "Save", "maps", "", CallbackSaveMap, this); } // detail button TB_Top.VSplitLeft(30.0f, &Button, &TB_Top); static int s_HqButton = 0; if(DoButton_Editor(&s_HqButton, "HD", m_ShowDetail, &Button, 0, "[ctrl+h] Toggle High Detail") || (Input()->KeyDown('h') && (Input()->KeyPressed(KEY_LCTRL) || Input()->KeyPressed(KEY_RCTRL)))) { m_ShowDetail = !m_ShowDetail; } TB_Top.VSplitLeft(5.0f, 0, &TB_Top); // animation button TB_Top.VSplitLeft(40.0f, &Button, &TB_Top); static int s_AnimateButton = 0; if(DoButton_Editor(&s_AnimateButton, "Anim", m_Animate, &Button, 0, "[ctrl+m] Toggle animation") || (Input()->KeyDown('m') && (Input()->KeyPressed(KEY_LCTRL) || Input()->KeyPressed(KEY_RCTRL)))) { m_AnimateStart = time_get(); m_Animate = !m_Animate; } TB_Top.VSplitLeft(5.0f, 0, &TB_Top); // proof button TB_Top.VSplitLeft(40.0f, &Button, &TB_Top); static int s_ProofButton = 0; if(DoButton_Editor(&s_ProofButton, "Proof", m_ProofBorders, &Button, 0, "[ctrl+p] Toggles proof borders. These borders represent what a player maximum can see.") || (Input()->KeyDown('p') && (Input()->KeyPressed(KEY_LCTRL) || Input()->KeyPressed(KEY_RCTRL)))) { m_ProofBorders = !m_ProofBorders; } TB_Top.VSplitLeft(5.0f, 0, &TB_Top); // tile info button TB_Top.VSplitLeft(40.0f, &Button, &TB_Top); static int s_TileInfoButton = 0; if(DoButton_Editor(&s_TileInfoButton, "Info", m_ShowTileInfo, &Button, 0, "[ctrl+i] Show tile informations") || (Input()->KeyDown('i') && (Input()->KeyPressed(KEY_LCTRL) || Input()->KeyPressed(KEY_RCTRL)))) { m_ShowTileInfo = !m_ShowTileInfo; m_ShowEnvelopePreview = 0; } TB_Top.VSplitLeft(15.0f, 0, &TB_Top); // zoom group TB_Top.VSplitLeft(30.0f, &Button, &TB_Top); static int s_ZoomOutButton = 0; if(DoButton_Ex(&s_ZoomOutButton, "ZO", 0, &Button, 0, "[NumPad-] Zoom out", CUI::CORNER_L)) m_ZoomLevel += 50; TB_Top.VSplitLeft(30.0f, &Button, &TB_Top); static int s_ZoomNormalButton = 0; if(DoButton_Ex(&s_ZoomNormalButton, "1:1", 0, &Button, 0, "[NumPad*] Zoom to normal and remove editor offset", 0)) { m_EditorOffsetX = 0; m_EditorOffsetY = 0; m_ZoomLevel = 100; } TB_Top.VSplitLeft(30.0f, &Button, &TB_Top); static int s_ZoomInButton = 0; if(DoButton_Ex(&s_ZoomInButton, "ZI", 0, &Button, 0, "[NumPad+] Zoom in", CUI::CORNER_R)) m_ZoomLevel -= 50; TB_Top.VSplitLeft(10.0f, 0, &TB_Top); // animation speed TB_Top.VSplitLeft(30.0f, &Button, &TB_Top); static int s_AnimFasterButton = 0; if(DoButton_Ex(&s_AnimFasterButton, "A+", 0, &Button, 0, "Increase animation speed", CUI::CORNER_L)) m_AnimateSpeed += 0.5f; TB_Top.VSplitLeft(30.0f, &Button, &TB_Top); static int s_AnimNormalButton = 0; if(DoButton_Ex(&s_AnimNormalButton, "1", 0, &Button, 0, "Normal animation speed", 0)) m_AnimateSpeed = 1.0f; TB_Top.VSplitLeft(30.0f, &Button, &TB_Top); static int s_AnimSlowerButton = 0; if(DoButton_Ex(&s_AnimSlowerButton, "A-", 0, &Button, 0, "Decrease animation speed", CUI::CORNER_R)) { if(m_AnimateSpeed > 0.5f) m_AnimateSpeed -= 0.5f; } TB_Top.VSplitLeft(10.0f, &Button, &TB_Top); // brush manipulation { int Enabled = m_Brush.IsEmpty()?-1:0; // flip buttons TB_Top.VSplitLeft(30.0f, &Button, &TB_Top); static int s_FlipXButton = 0; if(DoButton_Ex(&s_FlipXButton, "X/X", Enabled, &Button, 0, "[N] Flip brush horizontal", CUI::CORNER_L) || Input()->KeyDown('n')) { for(int i = 0; i < m_Brush.m_lLayers.size(); i++) m_Brush.m_lLayers[i]->BrushFlipX(); } TB_Top.VSplitLeft(30.0f, &Button, &TB_Top); static int s_FlipyButton = 0; if(DoButton_Ex(&s_FlipyButton, "Y/Y", Enabled, &Button, 0, "[M] Flip brush vertical", CUI::CORNER_R) || Input()->KeyDown('m')) { for(int i = 0; i < m_Brush.m_lLayers.size(); i++) m_Brush.m_lLayers[i]->BrushFlipY(); } // rotate buttons TB_Top.VSplitLeft(15.0f, &Button, &TB_Top); TB_Top.VSplitLeft(30.0f, &Button, &TB_Top); static int s_RotationAmount = 90; bool TileLayer = false; // check for tile layers in brush selection for(int i = 0; i < m_Brush.m_lLayers.size(); i++) if(m_Brush.m_lLayers[i]->m_Type == LAYERTYPE_TILES) { TileLayer = true; s_RotationAmount = max(90, (s_RotationAmount/90)*90); break; } s_RotationAmount = UiDoValueSelector(&s_RotationAmount, &Button, "", s_RotationAmount, TileLayer?90:1, 359, TileLayer?90:1, TileLayer?10.0f:2.0f, "Rotation of the brush in degrees. Use left mouse button to drag and change the value. Hold shift to be more precise."); TB_Top.VSplitLeft(5.0f, &Button, &TB_Top); TB_Top.VSplitLeft(30.0f, &Button, &TB_Top); static int s_CcwButton = 0; if(DoButton_Ex(&s_CcwButton, "CCW", Enabled, &Button, 0, "[R] Rotates the brush counter clockwise", CUI::CORNER_L) || Input()->KeyDown('r')) { for(int i = 0; i < m_Brush.m_lLayers.size(); i++) m_Brush.m_lLayers[i]->BrushRotate(-s_RotationAmount/360.0f*pi*2); } TB_Top.VSplitLeft(30.0f, &Button, &TB_Top); static int s_CwButton = 0; if(DoButton_Ex(&s_CwButton, "CW", Enabled, &Button, 0, "[T] Rotates the brush clockwise", CUI::CORNER_R) || Input()->KeyDown('t')) { for(int i = 0; i < m_Brush.m_lLayers.size(); i++) m_Brush.m_lLayers[i]->BrushRotate(s_RotationAmount/360.0f*pi*2); } } // quad manipulation { // do add button TB_Top.VSplitLeft(10.0f, &Button, &TB_Top); TB_Top.VSplitLeft(60.0f, &Button, &TB_Top); static int s_NewButton = 0; CLayerQuads *pQLayer = (CLayerQuads *)GetSelectedLayerType(0, LAYERTYPE_QUADS); //CLayerTiles *tlayer = (CLayerTiles *)get_selected_layer_type(0, LAYERTYPE_TILES); if(DoButton_Editor(&s_NewButton, "Add Quad", pQLayer?0:-1, &Button, 0, "Adds a new quad")) { if(pQLayer) { float Mapping[4]; CLayerGroup *g = GetSelectedGroup(); g->Mapping(Mapping); int AddX = f2fx(Mapping[0] + (Mapping[2]-Mapping[0])/2); int AddY = f2fx(Mapping[1] + (Mapping[3]-Mapping[1])/2); CQuad *q = pQLayer->NewQuad(); for(int i = 0; i < 5; i++) { q->m_aPoints[i].x += AddX; q->m_aPoints[i].y += AddY; } } } } // tile manipulation { TB_Bottom.VSplitLeft(40.0f, &Button, &TB_Bottom); static int s_BorderBut = 0; CLayerTiles *pT = (CLayerTiles *)GetSelectedLayerType(0, LAYERTYPE_TILES); if(DoButton_Editor(&s_BorderBut, "Border", pT?0:-1, &Button, 0, "Adds border tiles")) { if(pT) DoMapBorder(); } } TB_Bottom.VSplitLeft(5.0f, 0, &TB_Bottom); // refocus button TB_Bottom.VSplitLeft(50.0f, &Button, &TB_Bottom); static int s_RefocusButton = 0; if(DoButton_Editor(&s_RefocusButton, "Refocus", m_WorldOffsetX&&m_WorldOffsetY?0:-1, &Button, 0, "[HOME] Restore map focus") || (m_EditBoxActive == 0 && Input()->KeyDown(KEY_HOME))) { m_WorldOffsetX = 0; m_WorldOffsetY = 0; } TB_Bottom.VSplitLeft(5.0f, 0, &TB_Bottom); // grid button TB_Bottom.VSplitLeft(50.0f, &Button, &TB_Bottom); static int s_GridButton = 0; if(DoButton_Editor(&s_GridButton, "Grid", m_GridActive, &Button, 0, "Toggle Grid")) { m_GridActive = !m_GridActive; } TB_Bottom.VSplitLeft(30.0f, 0, &TB_Bottom); // grid zoom TB_Bottom.VSplitLeft(30.0f, &Button, &TB_Bottom); static int s_GridIncreaseButton = 0; if(DoButton_Ex(&s_GridIncreaseButton, "G-", 0, &Button, 0, "Decrease grid", CUI::CORNER_L)) { if(m_GridFactor > 1) m_GridFactor--; } TB_Bottom.VSplitLeft(30.0f, &Button, &TB_Bottom); static int s_GridNormalButton = 0; if(DoButton_Ex(&s_GridNormalButton, "1", 0, &Button, 0, "Normal grid", 0)) m_GridFactor = 1; TB_Bottom.VSplitLeft(30.0f, &Button, &TB_Bottom); static int s_GridDecreaseButton = 0; if(DoButton_Ex(&s_GridDecreaseButton, "G+", 0, &Button, 0, "Increase grid", CUI::CORNER_R)) { if(m_GridFactor < 15) m_GridFactor++; } } static void Rotate(const CPoint *pCenter, CPoint *pPoint, float Rotation) { int x = pPoint->x - pCenter->x; int y = pPoint->y - pCenter->y; pPoint->x = (int)(x * cosf(Rotation) - y * sinf(Rotation) + pCenter->x); pPoint->y = (int)(x * sinf(Rotation) + y * cosf(Rotation) + pCenter->y); } void CEditor::DoQuad(CQuad *q, int Index) { enum { OP_NONE=0, OP_MOVE_ALL, OP_MOVE_PIVOT, OP_ROTATE, OP_CONTEXT_MENU, }; // some basic values void *pID = &q->m_aPoints[4]; // use pivot addr as id static CPoint s_RotatePoints[4]; static float s_LastWx; static float s_LastWy; static int s_Operation = OP_NONE; static float s_RotateAngle = 0; float wx = UI()->MouseWorldX(); float wy = UI()->MouseWorldY(); // get pivot float CenterX = fx2f(q->m_aPoints[4].x); float CenterY = fx2f(q->m_aPoints[4].y); float dx = (CenterX - wx)/m_WorldZoom; float dy = (CenterY - wy)/m_WorldZoom; if(dx*dx+dy*dy < 50) UI()->SetHotItem(pID); bool IgnoreGrid; if(Input()->KeyPressed(KEY_LALT) || Input()->KeyPressed(KEY_RALT)) IgnoreGrid = true; else IgnoreGrid = false; // draw selection background if(m_SelectedQuad == Index) { Graphics()->SetColor(0,0,0,1); IGraphics::CQuadItem QuadItem(CenterX, CenterY, 7.0f, 7.0f); Graphics()->QuadsDraw(&QuadItem, 1); } if(UI()->ActiveItem() == pID) { if(m_MouseDeltaWx*m_MouseDeltaWx+m_MouseDeltaWy*m_MouseDeltaWy > 0.5f) { // check if we only should move pivot if(s_Operation == OP_MOVE_PIVOT) { if(m_GridActive && !IgnoreGrid) { int LineDistance = GetLineDistance(); float x = 0.0f; float y = 0.0f; if(wx >= 0) x = (int)((wx+(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); else x = (int)((wx-(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); if(wy >= 0) y = (int)((wy+(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); else y = (int)((wy-(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); q->m_aPoints[4].x = f2fx(x); q->m_aPoints[4].y = f2fx(y); } else { q->m_aPoints[4].x += f2fx(wx-s_LastWx); q->m_aPoints[4].y += f2fx(wy-s_LastWy); } } else if(s_Operation == OP_MOVE_ALL) { // move all points including pivot if(m_GridActive && !IgnoreGrid) { int LineDistance = GetLineDistance(); float x = 0.0f; float y = 0.0f; if(wx >= 0) x = (int)((wx+(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); else x = (int)((wx-(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); if(wy >= 0) y = (int)((wy+(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); else y = (int)((wy-(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); int OldX = q->m_aPoints[4].x; int OldY = q->m_aPoints[4].y; q->m_aPoints[4].x = f2fx(x); q->m_aPoints[4].y = f2fx(y); int DiffX = q->m_aPoints[4].x - OldX; int DiffY = q->m_aPoints[4].y - OldY; for(int v = 0; v < 4; v++) { q->m_aPoints[v].x += DiffX; q->m_aPoints[v].y += DiffY; } } else { for(int v = 0; v < 5; v++) { q->m_aPoints[v].x += f2fx(wx-s_LastWx); q->m_aPoints[v].y += f2fx(wy-s_LastWy); } } } else if(s_Operation == OP_ROTATE) { for(int v = 0; v < 4; v++) { q->m_aPoints[v] = s_RotatePoints[v]; Rotate(&q->m_aPoints[4], &q->m_aPoints[v], s_RotateAngle); } } } s_RotateAngle += (m_MouseDeltaX) * 0.002f; s_LastWx = wx; s_LastWy = wy; if(s_Operation == OP_CONTEXT_MENU) { if(!UI()->MouseButton(1)) { static int s_QuadPopupID = 0; UiInvokePopupMenu(&s_QuadPopupID, 0, UI()->MouseX(), UI()->MouseY(), 120, 180, PopupQuad); m_LockMouse = false; s_Operation = OP_NONE; UI()->SetActiveItem(0); } } else { if(!UI()->MouseButton(0)) { m_LockMouse = false; s_Operation = OP_NONE; UI()->SetActiveItem(0); } } Graphics()->SetColor(1,1,1,1); } else if(UI()->HotItem() == pID) { ms_pUiGotContext = pID; Graphics()->SetColor(1,1,1,1); m_pTooltip = "Left mouse button to move. Hold shift to move pivot. Hold ctrl to rotate. Hold alt to ignore grid."; if(UI()->MouseButton(0)) { if(Input()->KeyPressed(KEY_LSHIFT) || Input()->KeyPressed(KEY_RSHIFT)) s_Operation = OP_MOVE_PIVOT; else if(Input()->KeyPressed(KEY_LCTRL) || Input()->KeyPressed(KEY_RCTRL)) { m_LockMouse = true; s_Operation = OP_ROTATE; s_RotateAngle = 0; s_RotatePoints[0] = q->m_aPoints[0]; s_RotatePoints[1] = q->m_aPoints[1]; s_RotatePoints[2] = q->m_aPoints[2]; s_RotatePoints[3] = q->m_aPoints[3]; } else s_Operation = OP_MOVE_ALL; UI()->SetActiveItem(pID); if(m_SelectedQuad != Index) m_SelectedPoints = 0; m_SelectedQuad = Index; s_LastWx = wx; s_LastWy = wy; } if(UI()->MouseButton(1)) { if(m_SelectedQuad != Index) m_SelectedPoints = 0; m_SelectedQuad = Index; s_Operation = OP_CONTEXT_MENU; UI()->SetActiveItem(pID); } } else Graphics()->SetColor(0,1,0,1); IGraphics::CQuadItem QuadItem(CenterX, CenterY, 5.0f*m_WorldZoom, 5.0f*m_WorldZoom); Graphics()->QuadsDraw(&QuadItem, 1); } void CEditor::DoQuadPoint(CQuad *pQuad, int QuadIndex, int V) { void *pID = &pQuad->m_aPoints[V]; float wx = UI()->MouseWorldX(); float wy = UI()->MouseWorldY(); float px = fx2f(pQuad->m_aPoints[V].x); float py = fx2f(pQuad->m_aPoints[V].y); float dx = (px - wx)/m_WorldZoom; float dy = (py - wy)/m_WorldZoom; if(dx*dx+dy*dy < 50) UI()->SetHotItem(pID); // draw selection background if(m_SelectedQuad == QuadIndex && m_SelectedPoints&(1<<V)) { Graphics()->SetColor(0,0,0,1); IGraphics::CQuadItem QuadItem(px, py, 7.0f, 7.0f); Graphics()->QuadsDraw(&QuadItem, 1); } enum { OP_NONE=0, OP_MOVEPOINT, OP_MOVEUV, OP_CONTEXT_MENU }; static bool s_Moved; static int s_Operation = OP_NONE; bool IgnoreGrid; if(Input()->KeyPressed(KEY_LALT) || Input()->KeyPressed(KEY_RALT)) IgnoreGrid = true; else IgnoreGrid = false; if(UI()->ActiveItem() == pID) { float dx = m_MouseDeltaWx; float dy = m_MouseDeltaWy; if(!s_Moved) { if(dx*dx+dy*dy > 0.5f) s_Moved = true; } if(s_Moved) { if(s_Operation == OP_MOVEPOINT) { if(m_GridActive && !IgnoreGrid) { for(int m = 0; m < 4; m++) if(m_SelectedPoints&(1<<m)) { int LineDistance = GetLineDistance(); float x = 0.0f; float y = 0.0f; if(wx >= 0) x = (int)((wx+(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); else x = (int)((wx-(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); if(wy >= 0) y = (int)((wy+(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); else y = (int)((wy-(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); pQuad->m_aPoints[m].x = f2fx(x); pQuad->m_aPoints[m].y = f2fx(y); } } else { for(int m = 0; m < 4; m++) if(m_SelectedPoints&(1<<m)) { pQuad->m_aPoints[m].x += f2fx(dx); pQuad->m_aPoints[m].y += f2fx(dy); } } } else if(s_Operation == OP_MOVEUV) { for(int m = 0; m < 4; m++) if(m_SelectedPoints&(1<<m)) { // 0,2;1,3 - line x // 0,1;2,3 - line y pQuad->m_aTexcoords[m].x += f2fx(dx*0.001f); pQuad->m_aTexcoords[(m+2)%4].x += f2fx(dx*0.001f); pQuad->m_aTexcoords[m].y += f2fx(dy*0.001f); pQuad->m_aTexcoords[m^1].y += f2fx(dy*0.001f); } } } if(s_Operation == OP_CONTEXT_MENU) { if(!UI()->MouseButton(1)) { static int s_PointPopupID = 0; UiInvokePopupMenu(&s_PointPopupID, 0, UI()->MouseX(), UI()->MouseY(), 120, 150, PopupPoint); UI()->SetActiveItem(0); } } else { if(!UI()->MouseButton(0)) { if(!s_Moved) { if(Input()->KeyPressed(KEY_LSHIFT) || Input()->KeyPressed(KEY_RSHIFT)) m_SelectedPoints ^= 1<<V; else m_SelectedPoints = 1<<V; } m_LockMouse = false; UI()->SetActiveItem(0); } } Graphics()->SetColor(1,1,1,1); } else if(UI()->HotItem() == pID) { ms_pUiGotContext = pID; Graphics()->SetColor(1,1,1,1); m_pTooltip = "Left mouse button to move. Hold shift to move the texture. Hold alt to ignore grid."; if(UI()->MouseButton(0)) { UI()->SetActiveItem(pID); s_Moved = false; if(Input()->KeyPressed(KEY_LSHIFT) || Input()->KeyPressed(KEY_RSHIFT)) { s_Operation = OP_MOVEUV; m_LockMouse = true; } else s_Operation = OP_MOVEPOINT; if(!(m_SelectedPoints&(1<<V))) { if(Input()->KeyPressed(KEY_LSHIFT) || Input()->KeyPressed(KEY_RSHIFT)) m_SelectedPoints |= 1<<V; else m_SelectedPoints = 1<<V; s_Moved = true; } m_SelectedQuad = QuadIndex; } else if(UI()->MouseButton(1)) { s_Operation = OP_CONTEXT_MENU; m_SelectedQuad = QuadIndex; UI()->SetActiveItem(pID); if(!(m_SelectedPoints&(1<<V))) { if(Input()->KeyPressed(KEY_LSHIFT) || Input()->KeyPressed(KEY_RSHIFT)) m_SelectedPoints |= 1<<V; else m_SelectedPoints = 1<<V; s_Moved = true; } } } else Graphics()->SetColor(1,0,0,1); IGraphics::CQuadItem QuadItem(px, py, 5.0f*m_WorldZoom, 5.0f*m_WorldZoom); Graphics()->QuadsDraw(&QuadItem, 1); } void CEditor::DoQuadEnvelopes(const array<CQuad> &lQuads, IGraphics::CTextureHandle Texture) { int Num = lQuads.size(); CEnvelope **apEnvelope = new CEnvelope*[Num]; mem_zero(apEnvelope, sizeof(CEnvelope*)*Num); for(int i = 0; i < Num; i++) { if((m_ShowEnvelopePreview == 1 && lQuads[i].m_PosEnv == m_SelectedEnvelope) || m_ShowEnvelopePreview == 2) if(lQuads[i].m_PosEnv >= 0 && lQuads[i].m_PosEnv < m_Map.m_lEnvelopes.size()) apEnvelope[i] = m_Map.m_lEnvelopes[lQuads[i].m_PosEnv]; } //Draw Lines Graphics()->TextureClear(); Graphics()->LinesBegin(); Graphics()->SetColor(80.0f/255, 150.0f/255, 230.f/255, 0.5f); for(int j = 0; j < Num; j++) { if(!apEnvelope[j]) continue; //QuadParams const CPoint *pPoints = lQuads[j].m_aPoints; for(int i = 0; i < apEnvelope[j]->m_lPoints.size()-1; i++) { float OffsetX = fx2f(apEnvelope[j]->m_lPoints[i].m_aValues[0]); float OffsetY = fx2f(apEnvelope[j]->m_lPoints[i].m_aValues[1]); vec2 Pos0 = vec2(fx2f(pPoints[4].x)+OffsetX, fx2f(pPoints[4].y)+OffsetY); OffsetX = fx2f(apEnvelope[j]->m_lPoints[i+1].m_aValues[0]); OffsetY = fx2f(apEnvelope[j]->m_lPoints[i+1].m_aValues[1]); vec2 Pos1 = vec2(fx2f(pPoints[4].x)+OffsetX, fx2f(pPoints[4].y)+OffsetY); IGraphics::CLineItem Line = IGraphics::CLineItem(Pos0.x, Pos0.y, Pos1.x, Pos1.y); Graphics()->LinesDraw(&Line, 1); } } Graphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f); Graphics()->LinesEnd(); //Draw Quads Graphics()->TextureSet(Texture); Graphics()->QuadsBegin(); for(int j = 0; j < Num; j++) { if(!apEnvelope[j]) continue; //QuadParams const CPoint *pPoints = lQuads[j].m_aPoints; for(int i = 0; i < apEnvelope[j]->m_lPoints.size(); i++) { //Calc Env Position float OffsetX = fx2f(apEnvelope[j]->m_lPoints[i].m_aValues[0]); float OffsetY = fx2f(apEnvelope[j]->m_lPoints[i].m_aValues[1]); float Rot = fx2f(apEnvelope[j]->m_lPoints[i].m_aValues[2])/360.0f*pi*2; //Set Colours float Alpha = (m_SelectedQuadEnvelope == lQuads[j].m_PosEnv && m_SelectedEnvelopePoint == i) ? 0.65f : 0.35f; IGraphics::CColorVertex aArray[4] = { IGraphics::CColorVertex(0, lQuads[j].m_aColors[0].r, lQuads[j].m_aColors[0].g, lQuads[j].m_aColors[0].b, Alpha), IGraphics::CColorVertex(1, lQuads[j].m_aColors[1].r, lQuads[j].m_aColors[1].g, lQuads[j].m_aColors[1].b, Alpha), IGraphics::CColorVertex(2, lQuads[j].m_aColors[2].r, lQuads[j].m_aColors[2].g, lQuads[j].m_aColors[2].b, Alpha), IGraphics::CColorVertex(3, lQuads[j].m_aColors[3].r, lQuads[j].m_aColors[3].g, lQuads[j].m_aColors[3].b, Alpha)}; Graphics()->SetColorVertex(aArray, 4); //Rotation if(Rot != 0) { static CPoint aRotated[4]; aRotated[0] = lQuads[j].m_aPoints[0]; aRotated[1] = lQuads[j].m_aPoints[1]; aRotated[2] = lQuads[j].m_aPoints[2]; aRotated[3] = lQuads[j].m_aPoints[3]; pPoints = aRotated; Rotate(&lQuads[j].m_aPoints[4], &aRotated[0], Rot); Rotate(&lQuads[j].m_aPoints[4], &aRotated[1], Rot); Rotate(&lQuads[j].m_aPoints[4], &aRotated[2], Rot); Rotate(&lQuads[j].m_aPoints[4], &aRotated[3], Rot); } //Set Texture Coords Graphics()->QuadsSetSubsetFree( fx2f(lQuads[j].m_aTexcoords[0].x), fx2f(lQuads[j].m_aTexcoords[0].y), fx2f(lQuads[j].m_aTexcoords[1].x), fx2f(lQuads[j].m_aTexcoords[1].y), fx2f(lQuads[j].m_aTexcoords[2].x), fx2f(lQuads[j].m_aTexcoords[2].y), fx2f(lQuads[j].m_aTexcoords[3].x), fx2f(lQuads[j].m_aTexcoords[3].y) ); //Set Quad Coords & Draw IGraphics::CFreeformItem Freeform( fx2f(pPoints[0].x)+OffsetX, fx2f(pPoints[0].y)+OffsetY, fx2f(pPoints[1].x)+OffsetX, fx2f(pPoints[1].y)+OffsetY, fx2f(pPoints[2].x)+OffsetX, fx2f(pPoints[2].y)+OffsetY, fx2f(pPoints[3].x)+OffsetX, fx2f(pPoints[3].y)+OffsetY); Graphics()->QuadsDrawFreeform(&Freeform, 1); } } Graphics()->QuadsEnd(); Graphics()->TextureClear(); Graphics()->QuadsBegin(); // Draw QuadPoints for(int j = 0; j < Num; j++) { if(!apEnvelope[j]) continue; for(int i = 0; i < apEnvelope[j]->m_lPoints.size(); i++) DoQuadEnvPoint(&lQuads[j], j, i); } Graphics()->QuadsEnd(); delete[] apEnvelope; } void CEditor::DoQuadEnvPoint(const CQuad *pQuad, int QIndex, int PIndex) { enum { OP_NONE=0, OP_MOVE, OP_ROTATE, }; // some basic values static float s_LastWx; static float s_LastWy; static int s_Operation = OP_NONE; float wx = UI()->MouseWorldX(); float wy = UI()->MouseWorldY(); CEnvelope *pEnvelope = m_Map.m_lEnvelopes[pQuad->m_PosEnv]; void *pID = &pEnvelope->m_lPoints[PIndex]; static int s_ActQIndex = -1; // get pivot float CenterX = fx2f(pQuad->m_aPoints[4].x)+fx2f(pEnvelope->m_lPoints[PIndex].m_aValues[0]); float CenterY = fx2f(pQuad->m_aPoints[4].y)+fx2f(pEnvelope->m_lPoints[PIndex].m_aValues[1]); float dx = (CenterX - wx)/m_WorldZoom; float dy = (CenterY - wy)/m_WorldZoom; if(dx*dx+dy*dy < 50.0f && UI()->ActiveItem() == 0) { UI()->SetHotItem(pID); s_ActQIndex = QIndex; } bool IgnoreGrid; if(Input()->KeyPressed(KEY_LALT) || Input()->KeyPressed(KEY_RALT)) IgnoreGrid = true; else IgnoreGrid = false; if(UI()->ActiveItem() == pID && s_ActQIndex == QIndex) { if(s_Operation == OP_MOVE) { if(m_GridActive && !IgnoreGrid) { int LineDistance = GetLineDistance(); float x = 0.0f; float y = 0.0f; if(wx >= 0) x = (int)((wx+(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); else x = (int)((wx-(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); if(wy >= 0) y = (int)((wy+(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); else y = (int)((wy-(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor); pEnvelope->m_lPoints[PIndex].m_aValues[0] = f2fx(x); pEnvelope->m_lPoints[PIndex].m_aValues[1] = f2fx(y); } else { pEnvelope->m_lPoints[PIndex].m_aValues[0] += f2fx(wx-s_LastWx); pEnvelope->m_lPoints[PIndex].m_aValues[1] += f2fx(wy-s_LastWy); } } else if(s_Operation == OP_ROTATE) pEnvelope->m_lPoints[PIndex].m_aValues[2] += 10*m_MouseDeltaX; s_LastWx = wx; s_LastWy = wy; if(!UI()->MouseButton(0)) { m_LockMouse = false; s_Operation = OP_NONE; UI()->SetActiveItem(0); } Graphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f); } else if(UI()->HotItem() == pID && s_ActQIndex == QIndex) { ms_pUiGotContext = pID; Graphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f); m_pTooltip = "Left mouse button to move. Hold ctrl to rotate. Hold alt to ignore grid."; if(UI()->MouseButton(0)) { if(Input()->KeyPressed(KEY_LCTRL) || Input()->KeyPressed(KEY_RCTRL)) { m_LockMouse = true; s_Operation = OP_ROTATE; } else s_Operation = OP_MOVE; m_SelectedEnvelopePoint = PIndex; m_SelectedQuadEnvelope = pQuad->m_PosEnv; UI()->SetActiveItem(pID); if(m_SelectedQuad != QIndex) m_SelectedPoints = 0; m_SelectedQuad = QIndex; s_LastWx = wx; s_LastWy = wy; } else { m_SelectedEnvelopePoint = -1; m_SelectedQuadEnvelope = -1; } } else Graphics()->SetColor(0.0f, 1.0f, 0.0f, 1.0f); IGraphics::CQuadItem QuadItem(CenterX, CenterY, 5.0f*m_WorldZoom, 5.0f*m_WorldZoom); Graphics()->QuadsDraw(&QuadItem, 1); } void CEditor::DoMapEditor(CUIRect View, CUIRect ToolBar) { // render all good stuff if(!m_ShowPicker) { for(int g = 0; g < m_Map.m_lGroups.size(); g++) { if(m_Map.m_lGroups[g]->m_Visible) m_Map.m_lGroups[g]->Render(); //UI()->ClipEnable(&view); } // render the game above everything else if(m_Map.m_pGameGroup->m_Visible && m_Map.m_pGameLayer->m_Visible) { m_Map.m_pGameGroup->MapScreen(); m_Map.m_pGameLayer->Render(); } CLayerTiles *pT = static_cast<CLayerTiles *>(GetSelectedLayerType(0, LAYERTYPE_TILES)); if(m_ShowTileInfo && pT && pT->m_Visible && m_ZoomLevel <= 300) { GetSelectedGroup()->MapScreen(); pT->ShowInfo(); } } else { // fix aspect ratio of the image in the picker float Max = min(View.w, View.h); View.w = View.h = Max; } static void *s_pEditorID = (void *)&s_pEditorID; int Inside = UI()->MouseInside(&View); // fetch mouse position float wx = UI()->MouseWorldX(); float wy = UI()->MouseWorldY(); float mx = UI()->MouseX(); float my = UI()->MouseY(); static float s_StartWx = 0; static float s_StartWy = 0; enum { OP_NONE=0, OP_BRUSH_GRAB, OP_BRUSH_DRAW, OP_BRUSH_PAINT, OP_PAN_WORLD, OP_PAN_EDITOR, }; // remap the screen so it can display the whole tileset if(m_ShowPicker) { CUIRect Screen = *UI()->Screen(); float Size = 32.0*16.0f; float w = Size*(Screen.w/View.w); float h = Size*(Screen.h/View.h); float x = -(View.x/Screen.w)*w; float y = -(View.y/Screen.h)*h; wx = x+w*mx/Screen.w; wy = y+h*my/Screen.h; Graphics()->MapScreen(x, y, x+w, y+h); CLayerTiles *t = (CLayerTiles *)GetSelectedLayerType(0, LAYERTYPE_TILES); if(t) { m_TilesetPicker.m_Image = t->m_Image; m_TilesetPicker.m_Texture = t->m_Texture; m_TilesetPicker.Render(); if(m_ShowTileInfo) m_TilesetPicker.ShowInfo(); } } static int s_Operation = OP_NONE; // draw layer borders CLayer *pEditLayers[16]; int NumEditLayers = 0; NumEditLayers = 0; if(m_ShowPicker) { pEditLayers[0] = &m_TilesetPicker; NumEditLayers++; } else { pEditLayers[0] = GetSelectedLayer(0); if(pEditLayers[0]) NumEditLayers++; CLayerGroup *g = GetSelectedGroup(); if(g) { g->MapScreen(); RenderGrid(g); for(int i = 0; i < NumEditLayers; i++) { if(pEditLayers[i]->m_Type != LAYERTYPE_TILES) continue; float w, h; pEditLayers[i]->GetSize(&w, &h); IGraphics::CLineItem Array[4] = { IGraphics::CLineItem(0, 0, w, 0), IGraphics::CLineItem(w, 0, w, h), IGraphics::CLineItem(w, h, 0, h), IGraphics::CLineItem(0, h, 0, 0)}; Graphics()->TextureClear(); Graphics()->LinesBegin(); Graphics()->LinesDraw(Array, 4); Graphics()->LinesEnd(); } } } if(Inside) { UI()->SetHotItem(s_pEditorID); // do global operations like pan and zoom if(UI()->ActiveItem() == 0 && (UI()->MouseButton(0) || UI()->MouseButton(2))) { s_StartWx = wx; s_StartWy = wy; if(Input()->KeyPressed(KEY_LCTRL) || Input()->KeyPressed(KEY_RCTRL) || UI()->MouseButton(2)) { if(Input()->KeyPressed(KEY_LSHIFT)) s_Operation = OP_PAN_EDITOR; else s_Operation = OP_PAN_WORLD; UI()->SetActiveItem(s_pEditorID); } } // brush editing if(UI()->HotItem() == s_pEditorID) { if(m_Brush.IsEmpty()) m_pTooltip = "Use left mouse button to drag and create a brush."; else m_pTooltip = "Use left mouse button to paint with the brush. Right button clears the brush."; if(UI()->ActiveItem() == s_pEditorID) { CUIRect r; r.x = s_StartWx; r.y = s_StartWy; r.w = wx-s_StartWx; r.h = wy-s_StartWy; if(r.w < 0) { r.x += r.w; r.w = -r.w; } if(r.h < 0) { r.y += r.h; r.h = -r.h; } if(s_Operation == OP_BRUSH_DRAW) { if(!m_Brush.IsEmpty()) { // draw with brush for(int k = 0; k < NumEditLayers; k++) { if(pEditLayers[k]->m_Type == m_Brush.m_lLayers[0]->m_Type) pEditLayers[k]->BrushDraw(m_Brush.m_lLayers[0], wx, wy); } } } else if(s_Operation == OP_BRUSH_GRAB) { if(!UI()->MouseButton(0)) { // grab brush char aBuf[256]; str_format(aBuf, sizeof(aBuf),"grabbing %f %f %f %f", r.x, r.y, r.w, r.h); Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "editor", aBuf); // TODO: do all layers int Grabs = 0; for(int k = 0; k < NumEditLayers; k++) Grabs += pEditLayers[k]->BrushGrab(&m_Brush, r); if(Grabs == 0) m_Brush.Clear(); } else { //editor.map.groups[selected_group]->mapscreen(); for(int k = 0; k < NumEditLayers; k++) pEditLayers[k]->BrushSelecting(r); Graphics()->MapScreen(UI()->Screen()->x, UI()->Screen()->y, UI()->Screen()->w, UI()->Screen()->h); } } else if(s_Operation == OP_BRUSH_PAINT) { if(!UI()->MouseButton(0)) { for(int k = 0; k < NumEditLayers; k++) pEditLayers[k]->FillSelection(m_Brush.IsEmpty(), m_Brush.m_lLayers[0], r); } else { //editor.map.groups[selected_group]->mapscreen(); for(int k = 0; k < NumEditLayers; k++) pEditLayers[k]->BrushSelecting(r); Graphics()->MapScreen(UI()->Screen()->x, UI()->Screen()->y, UI()->Screen()->w, UI()->Screen()->h); } } } else { if(UI()->MouseButton(1)) m_Brush.Clear(); if(UI()->MouseButton(0) && s_Operation == OP_NONE) { UI()->SetActiveItem(s_pEditorID); if(m_Brush.IsEmpty()) s_Operation = OP_BRUSH_GRAB; else { s_Operation = OP_BRUSH_DRAW; for(int k = 0; k < NumEditLayers; k++) { if(pEditLayers[k]->m_Type == m_Brush.m_lLayers[0]->m_Type) pEditLayers[k]->BrushPlace(m_Brush.m_lLayers[0], wx, wy); } } CLayerTiles *pLayer = (CLayerTiles*)GetSelectedLayerType(0, LAYERTYPE_TILES); if((Input()->KeyPressed(KEY_LSHIFT) || Input()->KeyPressed(KEY_RSHIFT)) && pLayer) s_Operation = OP_BRUSH_PAINT; } if(!m_Brush.IsEmpty()) { m_Brush.m_OffsetX = -(int)wx; m_Brush.m_OffsetY = -(int)wy; for(int i = 0; i < m_Brush.m_lLayers.size(); i++) { if(m_Brush.m_lLayers[i]->m_Type == LAYERTYPE_TILES) { m_Brush.m_OffsetX = -(int)(wx/32.0f)*32; m_Brush.m_OffsetY = -(int)(wy/32.0f)*32; break; } } CLayerGroup *g = GetSelectedGroup(); if(g) { m_Brush.m_OffsetX += g->m_OffsetX; m_Brush.m_OffsetY += g->m_OffsetY; m_Brush.m_ParallaxX = g->m_ParallaxX; m_Brush.m_ParallaxY = g->m_ParallaxY; m_Brush.Render(); float w, h; m_Brush.GetSize(&w, &h); IGraphics::CLineItem Array[4] = { IGraphics::CLineItem(0, 0, w, 0), IGraphics::CLineItem(w, 0, w, h), IGraphics::CLineItem(w, h, 0, h), IGraphics::CLineItem(0, h, 0, 0)}; Graphics()->TextureClear(); Graphics()->LinesBegin(); Graphics()->LinesDraw(Array, 4); Graphics()->LinesEnd(); } } } } // quad editing { if(!m_ShowPicker && m_Brush.IsEmpty()) { // fetch layers CLayerGroup *g = GetSelectedGroup(); if(g) g->MapScreen(); for(int k = 0; k < NumEditLayers; k++) { if(pEditLayers[k]->m_Type == LAYERTYPE_QUADS) { CLayerQuads *pLayer = (CLayerQuads *)pEditLayers[k]; if(!m_ShowEnvelopePreview) m_ShowEnvelopePreview = 2; Graphics()->TextureClear(); Graphics()->QuadsBegin(); for(int i = 0; i < pLayer->m_lQuads.size(); i++) { for(int v = 0; v < 4; v++) DoQuadPoint(&pLayer->m_lQuads[i], i, v); DoQuad(&pLayer->m_lQuads[i], i); } Graphics()->QuadsEnd(); } } Graphics()->MapScreen(UI()->Screen()->x, UI()->Screen()->y, UI()->Screen()->w, UI()->Screen()->h); } // do panning if(UI()->ActiveItem() == s_pEditorID) { if(s_Operation == OP_PAN_WORLD) { m_WorldOffsetX -= m_MouseDeltaX*m_WorldZoom; m_WorldOffsetY -= m_MouseDeltaY*m_WorldZoom; } else if(s_Operation == OP_PAN_EDITOR) { m_EditorOffsetX -= m_MouseDeltaX*m_WorldZoom; m_EditorOffsetY -= m_MouseDeltaY*m_WorldZoom; } // release mouse if(!UI()->MouseButton(0)) { s_Operation = OP_NONE; UI()->SetActiveItem(0); } } } } else if(UI()->ActiveItem() == s_pEditorID) { // release mouse if(!UI()->MouseButton(0)) { s_Operation = OP_NONE; UI()->SetActiveItem(0); } } if(!m_ShowPicker && GetSelectedGroup() && GetSelectedGroup()->m_UseClipping) { CLayerGroup *g = m_Map.m_pGameGroup; g->MapScreen(); Graphics()->TextureClear(); Graphics()->LinesBegin(); CUIRect r; r.x = GetSelectedGroup()->m_ClipX; r.y = GetSelectedGroup()->m_ClipY; r.w = GetSelectedGroup()->m_ClipW; r.h = GetSelectedGroup()->m_ClipH; IGraphics::CLineItem Array[4] = { IGraphics::CLineItem(r.x, r.y, r.x+r.w, r.y), IGraphics::CLineItem(r.x+r.w, r.y, r.x+r.w, r.y+r.h), IGraphics::CLineItem(r.x+r.w, r.y+r.h, r.x, r.y+r.h), IGraphics::CLineItem(r.x, r.y+r.h, r.x, r.y)}; Graphics()->SetColor(1,0,0,1); Graphics()->LinesDraw(Array, 4); Graphics()->LinesEnd(); } // render screen sizes if(m_ProofBorders) { CLayerGroup *g = m_Map.m_pGameGroup; g->MapScreen(); Graphics()->TextureClear(); Graphics()->LinesBegin(); float aLastPoints[4]; float Start = 1.0f; //9.0f/16.0f; float End = 16.0f/9.0f; const int NumSteps = 20; for(int i = 0; i <= NumSteps; i++) { float aPoints[4]; float Aspect = Start + (End-Start)*(i/(float)NumSteps); RenderTools()->MapscreenToWorld( m_WorldOffsetX, m_WorldOffsetY, 1.0f, 1.0f, 0.0f, 0.0f, Aspect, 1.0f, aPoints); if(i == 0) { IGraphics::CLineItem Array[2] = { IGraphics::CLineItem(aPoints[0], aPoints[1], aPoints[2], aPoints[1]), IGraphics::CLineItem(aPoints[0], aPoints[3], aPoints[2], aPoints[3])}; Graphics()->LinesDraw(Array, 2); } if(i != 0) { IGraphics::CLineItem Array[4] = { IGraphics::CLineItem(aPoints[0], aPoints[1], aLastPoints[0], aLastPoints[1]), IGraphics::CLineItem(aPoints[2], aPoints[1], aLastPoints[2], aLastPoints[1]), IGraphics::CLineItem(aPoints[0], aPoints[3], aLastPoints[0], aLastPoints[3]), IGraphics::CLineItem(aPoints[2], aPoints[3], aLastPoints[2], aLastPoints[3])}; Graphics()->LinesDraw(Array, 4); } if(i == NumSteps) { IGraphics::CLineItem Array[2] = { IGraphics::CLineItem(aPoints[0], aPoints[1], aPoints[0], aPoints[3]), IGraphics::CLineItem(aPoints[2], aPoints[1], aPoints[2], aPoints[3])}; Graphics()->LinesDraw(Array, 2); } mem_copy(aLastPoints, aPoints, sizeof(aPoints)); } if(1) { Graphics()->SetColor(1,0,0,1); for(int i = 0; i < 2; i++) { float aPoints[4]; float aAspects[] = {4.0f/3.0f, 16.0f/10.0f, 5.0f/4.0f, 16.0f/9.0f}; float Aspect = aAspects[i]; RenderTools()->MapscreenToWorld( m_WorldOffsetX, m_WorldOffsetY, 1.0f, 1.0f, 0.0f, 0.0f, Aspect, 1.0f, aPoints); CUIRect r; r.x = aPoints[0]; r.y = aPoints[1]; r.w = aPoints[2]-aPoints[0]; r.h = aPoints[3]-aPoints[1]; IGraphics::CLineItem Array[4] = { IGraphics::CLineItem(r.x, r.y, r.x+r.w, r.y), IGraphics::CLineItem(r.x+r.w, r.y, r.x+r.w, r.y+r.h), IGraphics::CLineItem(r.x+r.w, r.y+r.h, r.x, r.y+r.h), IGraphics::CLineItem(r.x, r.y+r.h, r.x, r.y)}; Graphics()->LinesDraw(Array, 4); Graphics()->SetColor(0,1,0,1); } } Graphics()->LinesEnd(); } if (!m_ShowPicker && m_ShowTileInfo && m_ShowEnvelopePreview != 0 && GetSelectedLayer(0) && GetSelectedLayer(0)->m_Type == LAYERTYPE_QUADS) { GetSelectedGroup()->MapScreen(); CLayerQuads *pLayer = (CLayerQuads*)GetSelectedLayer(0); IGraphics::CTextureHandle Texture; if(pLayer->m_Image >= 0 && pLayer->m_Image < m_Map.m_lImages.size()) Texture = m_Map.m_lImages[pLayer->m_Image]->m_Texture; DoQuadEnvelopes(pLayer->m_lQuads, Texture); m_ShowEnvelopePreview = 0; } Graphics()->MapScreen(UI()->Screen()->x, UI()->Screen()->y, UI()->Screen()->w, UI()->Screen()->h); //UI()->ClipDisable(); } int CEditor::DoProperties(CUIRect *pToolBox, CProperty *pProps, int *pIDs, int *pNewVal) { int Change = -1; for(int i = 0; pProps[i].m_pName; i++) { CUIRect Slot; pToolBox->HSplitTop(13.0f, &Slot, pToolBox); CUIRect Label, Shifter; Slot.VSplitMid(&Label, &Shifter); Shifter.HMargin(1.0f, &Shifter); UI()->DoLabel(&Label, pProps[i].m_pName, 10.0f, -1, -1); if(pProps[i].m_Type == PROPTYPE_INT_STEP) { CUIRect Inc, Dec; char aBuf[64]; Shifter.VSplitRight(10.0f, &Shifter, &Inc); Shifter.VSplitLeft(10.0f, &Dec, &Shifter); str_format(aBuf, sizeof(aBuf),"%d", pProps[i].m_Value); RenderTools()->DrawUIRect(&Shifter, vec4(1,1,1,0.5f), 0, 0.0f); UI()->DoLabel(&Shifter, aBuf, 10.0f, 0, -1); if(DoButton_ButtonDec(&pIDs[i], 0, 0, &Dec, 0, "Decrease")) { *pNewVal = pProps[i].m_Value-1; Change = i; } if(DoButton_ButtonInc(((char *)&pIDs[i])+1, 0, 0, &Inc, 0, "Increase")) { *pNewVal = pProps[i].m_Value+1; Change = i; } } else if(pProps[i].m_Type == PROPTYPE_BOOL) { CUIRect No, Yes; Shifter.VSplitMid(&No, &Yes); if(DoButton_ButtonDec(&pIDs[i], "No", !pProps[i].m_Value, &No, 0, "")) { *pNewVal = 0; Change = i; } if(DoButton_ButtonInc(((char *)&pIDs[i])+1, "Yes", pProps[i].m_Value, &Yes, 0, "")) { *pNewVal = 1; Change = i; } } else if(pProps[i].m_Type == PROPTYPE_INT_SCROLL) { int NewValue = UiDoValueSelector(&pIDs[i], &Shifter, "", pProps[i].m_Value, pProps[i].m_Min, pProps[i].m_Max, 1, 1.0f, "Use left mouse button to drag and change the value. Hold shift to be more precise."); if(NewValue != pProps[i].m_Value) { *pNewVal = NewValue; Change = i; } } else if(pProps[i].m_Type == PROPTYPE_COLOR) { static const char *s_paTexts[4] = {"R", "G", "B", "A"}; static int s_aShift[] = {24, 16, 8, 0}; int NewColor = 0; for(int c = 0; c < 4; c++) { int v = (pProps[i].m_Value >> s_aShift[c])&0xff; NewColor |= UiDoValueSelector(((char *)&pIDs[i])+c, &Shifter, s_paTexts[c], v, 0, 255, 1, 1.0f, "Use left mouse button to drag and change the color value. Hold shift to be more precise.")<<s_aShift[c]; if(c != 3) { pToolBox->HSplitTop(13.0f, &Slot, pToolBox); Slot.VSplitMid(0, &Shifter); Shifter.HMargin(1.0f, &Shifter); } } if(NewColor != pProps[i].m_Value) { *pNewVal = NewColor; Change = i; } } else if(pProps[i].m_Type == PROPTYPE_IMAGE) { char aBuf[64]; if(pProps[i].m_Value < 0) str_copy(aBuf, "None", sizeof(aBuf)); else str_format(aBuf, sizeof(aBuf),"%s", m_Map.m_lImages[pProps[i].m_Value]->m_aName); if(DoButton_Editor(&pIDs[i], aBuf, 0, &Shifter, 0, 0)) PopupSelectImageInvoke(pProps[i].m_Value, UI()->MouseX(), UI()->MouseY()); int r = PopupSelectImageResult(); if(r >= -1) { *pNewVal = r; Change = i; } } else if(pProps[i].m_Type == PROPTYPE_SHIFT) { CUIRect Left, Right, Up, Down; Shifter.VSplitMid(&Left, &Up); Left.VSplitRight(1.0f, &Left, 0); Up.VSplitLeft(1.0f, 0, &Up); Left.VSplitLeft(10.0f, &Left, &Shifter); Shifter.VSplitRight(10.0f, &Shifter, &Right); RenderTools()->DrawUIRect(&Shifter, vec4(1,1,1,0.5f), 0, 0.0f); UI()->DoLabel(&Shifter, "X", 10.0f, 0, -1); Up.VSplitLeft(10.0f, &Up, &Shifter); Shifter.VSplitRight(10.0f, &Shifter, &Down); RenderTools()->DrawUIRect(&Shifter, vec4(1,1,1,0.5f), 0, 0.0f); UI()->DoLabel(&Shifter, "Y", 10.0f, 0, -1); if(DoButton_ButtonDec(&pIDs[i], "-", 0, &Left, 0, "Left")) { *pNewVal = 1; Change = i; } if(DoButton_ButtonInc(((char *)&pIDs[i])+3, "+", 0, &Right, 0, "Right")) { *pNewVal = 2; Change = i; } if(DoButton_ButtonDec(((char *)&pIDs[i])+1, "-", 0, &Up, 0, "Up")) { *pNewVal = 4; Change = i; } if(DoButton_ButtonInc(((char *)&pIDs[i])+2, "+", 0, &Down, 0, "Down")) { *pNewVal = 8; Change = i; } } } return Change; } void CEditor::RenderLayers(CUIRect ToolBox, CUIRect ToolBar, CUIRect View) { CUIRect LayersBox = ToolBox; if(!m_GuiActive) return; CUIRect Slot, Button; char aBuf[64]; float LayersHeight = 12.0f; // Height of AddGroup button static int s_ScrollBar = 0; static float s_ScrollValue = 0; for(int g = 0; g < m_Map.m_lGroups.size(); g++) { // Each group is 19.0f // Each layer is 14.0f LayersHeight += 19.0f; if(!m_Map.m_lGroups[g]->m_Collapse) LayersHeight += m_Map.m_lGroups[g]->m_lLayers.size() * 14.0f; } float ScrollDifference = LayersHeight - LayersBox.h; if(LayersHeight > LayersBox.h) // Do we even need a scrollbar? { CUIRect Scroll; LayersBox.VSplitRight(15.0f, &LayersBox, &Scroll); LayersBox.VSplitRight(3.0f, &LayersBox, 0); // extra spacing Scroll.HMargin(5.0f, &Scroll); s_ScrollValue = UiDoScrollbarV(&s_ScrollBar, &Scroll, s_ScrollValue); if(UI()->MouseInside(&Scroll) || UI()->MouseInside(&LayersBox)) { int ScrollNum = (int)((LayersHeight-LayersBox.h)/15.0f)+1; if(ScrollNum > 0) { if(Input()->KeyPresses(KEY_MOUSE_WHEEL_UP)) s_ScrollValue = clamp(s_ScrollValue - 1.0f/ScrollNum, 0.0f, 1.0f); if(Input()->KeyPresses(KEY_MOUSE_WHEEL_DOWN)) s_ScrollValue = clamp(s_ScrollValue + 1.0f/ScrollNum, 0.0f, 1.0f); } } } float LayerStartAt = ScrollDifference * s_ScrollValue; if(LayerStartAt < 0.0f) LayerStartAt = 0.0f; float LayerStopAt = LayersHeight - ScrollDifference * (1 - s_ScrollValue); float LayerCur = 0; // render layers { for(int g = 0; g < m_Map.m_lGroups.size(); g++) { if(LayerCur > LayerStopAt) break; else if(LayerCur + m_Map.m_lGroups[g]->m_lLayers.size() * 14.0f + 19.0f < LayerStartAt) { LayerCur += m_Map.m_lGroups[g]->m_lLayers.size() * 14.0f + 19.0f; continue; } CUIRect VisibleToggle, SaveCheck; if(LayerCur >= LayerStartAt) { LayersBox.HSplitTop(12.0f, &Slot, &LayersBox); Slot.VSplitLeft(12, &VisibleToggle, &Slot); if(DoButton_Ex(&m_Map.m_lGroups[g]->m_Visible, m_Map.m_lGroups[g]->m_Visible?"V":"H", m_Map.m_lGroups[g]->m_Collapse ? 1 : 0, &VisibleToggle, 0, "Toggle group visibility", CUI::CORNER_L)) m_Map.m_lGroups[g]->m_Visible = !m_Map.m_lGroups[g]->m_Visible; Slot.VSplitRight(12.0f, &Slot, &SaveCheck); if(DoButton_Ex(&m_Map.m_lGroups[g]->m_SaveToMap, "S", m_Map.m_lGroups[g]->m_SaveToMap, &SaveCheck, 0, "Enable/disable group for saving", CUI::CORNER_R)) if(!m_Map.m_lGroups[g]->m_GameGroup) m_Map.m_lGroups[g]->m_SaveToMap = !m_Map.m_lGroups[g]->m_SaveToMap; str_format(aBuf, sizeof(aBuf),"#%d %s", g, m_Map.m_lGroups[g]->m_aName); float FontSize = 10.0f; while(TextRender()->TextWidth(0, FontSize, aBuf, -1) > Slot.w) FontSize--; if(int Result = DoButton_Ex(&m_Map.m_lGroups[g], aBuf, g==m_SelectedGroup, &Slot, BUTTON_CONTEXT, m_Map.m_lGroups[g]->m_Collapse ? "Select group. Double click to expand." : "Select group. Double click to collapse.", 0, FontSize)) { m_SelectedGroup = g; m_SelectedLayer = 0; static int s_GroupPopupId = 0; if(Result == 2) UiInvokePopupMenu(&s_GroupPopupId, 0, UI()->MouseX(), UI()->MouseY(), 145, 220, PopupGroup); if(m_Map.m_lGroups[g]->m_lLayers.size() && Input()->MouseDoubleClick()) m_Map.m_lGroups[g]->m_Collapse ^= 1; } LayersBox.HSplitTop(2.0f, &Slot, &LayersBox); } LayerCur += 14.0f; for(int i = 0; i < m_Map.m_lGroups[g]->m_lLayers.size(); i++) { if(LayerCur > LayerStopAt) break; else if(LayerCur < LayerStartAt) { LayerCur += 14.0f; continue; } if(m_Map.m_lGroups[g]->m_Collapse) continue; //visible LayersBox.HSplitTop(12.0f, &Slot, &LayersBox); Slot.VSplitLeft(12.0f, 0, &Button); Button.VSplitLeft(15, &VisibleToggle, &Button); if(DoButton_Ex(&m_Map.m_lGroups[g]->m_lLayers[i]->m_Visible, m_Map.m_lGroups[g]->m_lLayers[i]->m_Visible?"V":"H", 0, &VisibleToggle, 0, "Toggle layer visibility", CUI::CORNER_L)) m_Map.m_lGroups[g]->m_lLayers[i]->m_Visible = !m_Map.m_lGroups[g]->m_lLayers[i]->m_Visible; Button.VSplitRight(12.0f, &Button, &SaveCheck); if(DoButton_Ex(&m_Map.m_lGroups[g]->m_lLayers[i]->m_SaveToMap, "S", m_Map.m_lGroups[g]->m_lLayers[i]->m_SaveToMap, &SaveCheck, 0, "Enable/disable layer for saving", CUI::CORNER_R)) if(m_Map.m_lGroups[g]->m_lLayers[i] != m_Map.m_pGameLayer) m_Map.m_lGroups[g]->m_lLayers[i]->m_SaveToMap = !m_Map.m_lGroups[g]->m_lLayers[i]->m_SaveToMap; if(m_Map.m_lGroups[g]->m_lLayers[i]->m_aName[0]) str_format(aBuf, sizeof(aBuf), "%s", m_Map.m_lGroups[g]->m_lLayers[i]->m_aName); else if(m_Map.m_lGroups[g]->m_lLayers[i]->m_Type == LAYERTYPE_TILES) str_copy(aBuf, "Tiles", sizeof(aBuf)); else str_copy(aBuf, "Quads", sizeof(aBuf)); float FontSize = 10.0f; while(TextRender()->TextWidth(0, FontSize, aBuf, -1) > Button.w) FontSize--; if(int Result = DoButton_Ex(m_Map.m_lGroups[g]->m_lLayers[i], aBuf, g==m_SelectedGroup&&i==m_SelectedLayer, &Button, BUTTON_CONTEXT, "Select layer.", 0, FontSize)) { m_SelectedLayer = i; m_SelectedGroup = g; static int s_LayerPopupID = 0; if(Result == 2) UiInvokePopupMenu(&s_LayerPopupID, 0, UI()->MouseX(), UI()->MouseY(), 120, 245, PopupLayer); } LayerCur += 14.0f; LayersBox.HSplitTop(2.0f, &Slot, &LayersBox); } if(LayerCur > LayerStartAt && LayerCur < LayerStopAt) LayersBox.HSplitTop(5.0f, &Slot, &LayersBox); LayerCur += 5.0f; } } if(LayerCur <= LayerStopAt) { LayersBox.HSplitTop(12.0f, &Slot, &LayersBox); static int s_NewGroupButton = 0; if(DoButton_Editor(&s_NewGroupButton, "Add group", 0, &Slot, 0, "Adds a new group")) { m_Map.NewGroup(); m_SelectedGroup = m_Map.m_lGroups.size()-1; } } } void CEditor::ReplaceImage(const char *pFileName, int StorageType, void *pUser) { CEditor *pEditor = (CEditor *)pUser; CEditorImage ImgInfo(pEditor); if(!pEditor->Graphics()->LoadPNG(&ImgInfo, pFileName, StorageType)) return; CEditorImage *pImg = pEditor->m_Map.m_lImages[pEditor->m_SelectedImage]; int External = pImg->m_External; pEditor->Graphics()->UnloadTexture(pImg->m_Texture); pImg->m_Texture = IGraphics::CTextureHandle(); if(pImg->m_pData) { mem_free(pImg->m_pData); pImg->m_pData = 0; } if(pImg->m_pAutoMapper) { delete pImg->m_pAutoMapper; pImg->m_pAutoMapper = 0; } *pImg = ImgInfo; pImg->m_External = External; pEditor->ExtractName(pFileName, pImg->m_aName, sizeof(pImg->m_aName)); pImg->LoadAutoMapper(); pImg->m_Texture = pEditor->Graphics()->LoadTextureRaw(ImgInfo.m_Width, ImgInfo.m_Height, ImgInfo.m_Format, ImgInfo.m_pData, CImageInfo::FORMAT_AUTO, 0); ImgInfo.m_pData = 0; pEditor->SortImages(); for(int i = 0; i < pEditor->m_Map.m_lImages.size(); ++i) { if(!str_comp(pEditor->m_Map.m_lImages[i]->m_aName, pImg->m_aName)) pEditor->m_SelectedImage = i; } pEditor->m_Dialog = DIALOG_NONE; } void CEditor::AddImage(const char *pFileName, int StorageType, void *pUser) { CEditor *pEditor = (CEditor *)pUser; CEditorImage ImgInfo(pEditor); if(!pEditor->Graphics()->LoadPNG(&ImgInfo, pFileName, StorageType)) return; // check if we have that image already char aBuf[128]; ExtractName(pFileName, aBuf, sizeof(aBuf)); for(int i = 0; i < pEditor->m_Map.m_lImages.size(); ++i) { if(!str_comp(pEditor->m_Map.m_lImages[i]->m_aName, aBuf)) return; } CEditorImage *pImg = new CEditorImage(pEditor); *pImg = ImgInfo; pImg->m_Texture = pEditor->Graphics()->LoadTextureRaw(ImgInfo.m_Width, ImgInfo.m_Height, ImgInfo.m_Format, ImgInfo.m_pData, CImageInfo::FORMAT_AUTO, 0); ImgInfo.m_pData = 0; pImg->m_External = 1; // external by default str_copy(pImg->m_aName, aBuf, sizeof(pImg->m_aName)); pImg->LoadAutoMapper(); pEditor->m_Map.m_lImages.add(pImg); pEditor->SortImages(); if(pEditor->m_SelectedImage > -1 && pEditor->m_SelectedImage < pEditor->m_Map.m_lImages.size()) { for(int i = 0; i <= pEditor->m_SelectedImage; ++i) if(!str_comp(pEditor->m_Map.m_lImages[i]->m_aName, aBuf)) { pEditor->m_SelectedImage++; break; } } pEditor->m_Dialog = DIALOG_NONE; } static int gs_ModifyIndexDeletedIndex; static void ModifyIndexDeleted(int *pIndex) { if(*pIndex == gs_ModifyIndexDeletedIndex) *pIndex = -1; else if(*pIndex > gs_ModifyIndexDeletedIndex) *pIndex = *pIndex - 1; } int CEditor::PopupImage(CEditor *pEditor, CUIRect View) { static int s_ReplaceButton = 0; static int s_RemoveButton = 0; CUIRect Slot; View.HSplitTop(2.0f, &Slot, &View); View.HSplitTop(12.0f, &Slot, &View); CEditorImage *pImg = pEditor->m_Map.m_lImages[pEditor->m_SelectedImage]; static int s_ExternalButton = 0; if(pImg->m_External) { if(pEditor->DoButton_MenuItem(&s_ExternalButton, "Embed", 0, &Slot, 0, "Embeds the image into the map file.")) { pImg->m_External = 0; return 1; } } else { if(pEditor->DoButton_MenuItem(&s_ExternalButton, "Make external", 0, &Slot, 0, "Removes the image from the map file.")) { pImg->m_External = 1; return 1; } } View.HSplitTop(10.0f, &Slot, &View); View.HSplitTop(12.0f, &Slot, &View); if(pEditor->DoButton_MenuItem(&s_ReplaceButton, "Replace", 0, &Slot, 0, "Replaces the image with a new one")) { pEditor->InvokeFileDialog(IStorage::TYPE_ALL, FILETYPE_IMG, "Replace Image", "Replace", "mapres", "", ReplaceImage, pEditor); return 1; } View.HSplitTop(10.0f, &Slot, &View); View.HSplitTop(12.0f, &Slot, &View); if(pEditor->DoButton_MenuItem(&s_RemoveButton, "Remove", 0, &Slot, 0, "Removes the image from the map")) { delete pImg; pEditor->m_Map.m_lImages.remove_index(pEditor->m_SelectedImage); gs_ModifyIndexDeletedIndex = pEditor->m_SelectedImage; pEditor->m_Map.ModifyImageIndex(ModifyIndexDeleted); return 1; } return 0; } static int CompareImageName(const void *pObject1, const void *pObject2) { CEditorImage *pImage1 = *(CEditorImage**)pObject1; CEditorImage *pImage2 = *(CEditorImage**)pObject2; return str_comp(pImage1->m_aName, pImage2->m_aName); } static int *gs_pSortedIndex = 0; static void ModifySortedIndex(int *pIndex) { if(*pIndex > -1) *pIndex = gs_pSortedIndex[*pIndex]; } void CEditor::SortImages() { bool Sorted = true; for(int i = 1; i < m_Map.m_lImages.size(); i++) if( str_comp(m_Map.m_lImages[i]->m_aName, m_Map.m_lImages[i-1]->m_aName) < 0 ) { Sorted = false; break; } if(!Sorted) { array<CEditorImage*> lTemp = array<CEditorImage*>(m_Map.m_lImages); gs_pSortedIndex = new int[lTemp.size()]; qsort(m_Map.m_lImages.base_ptr(), m_Map.m_lImages.size(), sizeof(CEditorImage*), CompareImageName); for(int OldIndex = 0; OldIndex < lTemp.size(); OldIndex++) for(int NewIndex = 0; NewIndex < m_Map.m_lImages.size(); NewIndex++) if(lTemp[OldIndex] == m_Map.m_lImages[NewIndex]) gs_pSortedIndex[OldIndex] = NewIndex; m_Map.ModifyImageIndex(ModifySortedIndex); delete [] gs_pSortedIndex; gs_pSortedIndex = 0; } } void CEditor::RenderImages(CUIRect ToolBox, CUIRect ToolBar, CUIRect View) { static int s_ScrollBar = 0; static float s_ScrollValue = 0; float ImagesHeight = 30.0f + 14.0f * m_Map.m_lImages.size() + 27.0f; float ScrollDifference = ImagesHeight - ToolBox.h; if(ImagesHeight > ToolBox.h) // Do we even need a scrollbar? { CUIRect Scroll; ToolBox.VSplitRight(15.0f, &ToolBox, &Scroll); ToolBox.VSplitRight(3.0f, &ToolBox, 0); // extra spacing Scroll.HMargin(5.0f, &Scroll); s_ScrollValue = UiDoScrollbarV(&s_ScrollBar, &Scroll, s_ScrollValue); if(UI()->MouseInside(&Scroll) || UI()->MouseInside(&ToolBox)) { int ScrollNum = (int)((ImagesHeight-ToolBox.h)/14.0f)+1; if(ScrollNum > 0) { if(Input()->KeyPresses(KEY_MOUSE_WHEEL_UP)) s_ScrollValue = clamp(s_ScrollValue - 1.0f/ScrollNum, 0.0f, 1.0f); if(Input()->KeyPresses(KEY_MOUSE_WHEEL_DOWN)) s_ScrollValue = clamp(s_ScrollValue + 1.0f/ScrollNum, 0.0f, 1.0f); } } } float ImageStartAt = ScrollDifference * s_ScrollValue; if(ImageStartAt < 0.0f) ImageStartAt = 0.0f; float ImageStopAt = ImagesHeight - ScrollDifference * (1 - s_ScrollValue); float ImageCur = 0.0f; for(int e = 0; e < 2; e++) // two passes, first embedded, then external { CUIRect Slot; if(ImageCur > ImageStopAt) break; else if(ImageCur >= ImageStartAt) { ToolBox.HSplitTop(15.0f, &Slot, &ToolBox); if(e == 0) UI()->DoLabel(&Slot, "Embedded", 12.0f, 0); else UI()->DoLabel(&Slot, "External", 12.0f, 0); } ImageCur += 15.0f; for(int i = 0; i < m_Map.m_lImages.size(); i++) { if((e && !m_Map.m_lImages[i]->m_External) || (!e && m_Map.m_lImages[i]->m_External)) { continue; } if(ImageCur > ImageStopAt) break; else if(ImageCur < ImageStartAt) { ImageCur += 14.0f; continue; } ImageCur += 14.0f; char aBuf[128]; str_copy(aBuf, m_Map.m_lImages[i]->m_aName, sizeof(aBuf)); ToolBox.HSplitTop(12.0f, &Slot, &ToolBox); if(int Result = DoButton_Editor(&m_Map.m_lImages[i], aBuf, m_SelectedImage == i, &Slot, BUTTON_CONTEXT, "Select image")) { m_SelectedImage = i; static int s_PopupImageID = 0; if(Result == 2) UiInvokePopupMenu(&s_PopupImageID, 0, UI()->MouseX(), UI()->MouseY(), 120, 80, PopupImage); } ToolBox.HSplitTop(2.0f, 0, &ToolBox); // render image if(m_SelectedImage == i) { CUIRect r; View.Margin(10.0f, &r); if(r.h < r.w) r.w = r.h; else r.h = r.w; float Max = (float)(max(m_Map.m_lImages[i]->m_Width, m_Map.m_lImages[i]->m_Height)); r.w *= m_Map.m_lImages[i]->m_Width/Max; r.h *= m_Map.m_lImages[i]->m_Height/Max; Graphics()->TextureSet(m_Map.m_lImages[i]->m_Texture); Graphics()->BlendNormal(); Graphics()->WrapClamp(); Graphics()->QuadsBegin(); IGraphics::CQuadItem QuadItem(r.x, r.y, r.w, r.h); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); Graphics()->WrapNormal(); } } // separator ToolBox.HSplitTop(5.0f, &Slot, &ToolBox); ImageCur += 5.0f; IGraphics::CLineItem LineItem(Slot.x, Slot.y+Slot.h/2, Slot.x+Slot.w, Slot.y+Slot.h/2); Graphics()->TextureClear(); Graphics()->LinesBegin(); Graphics()->LinesDraw(&LineItem, 1); Graphics()->LinesEnd(); } if(ImageCur + 27.0f > ImageStopAt) return; CUIRect Slot; ToolBox.HSplitTop(5.0f, &Slot, &ToolBox); // new image static int s_NewImageButton = 0; ToolBox.HSplitTop(12.0f, &Slot, &ToolBox); if(DoButton_Editor(&s_NewImageButton, "Add", 0, &Slot, 0, "Load a new image to use in the map")) InvokeFileDialog(IStorage::TYPE_ALL, FILETYPE_IMG, "Add Image", "Add", "mapres", "", AddImage, this); } static int EditorListdirCallback(const char *pName, int IsDir, int StorageType, void *pUser) { CEditor *pEditor = (CEditor*)pUser; int Length = str_length(pName); if((pName[0] == '.' && (pName[1] == 0 || (pName[1] == '.' && pName[2] == 0 && (!str_comp(pEditor->m_pFileDialogPath, "maps") || !str_comp(pEditor->m_pFileDialogPath, "mapres"))))) || (!IsDir && ((pEditor->m_FileDialogFileType == CEditor::FILETYPE_MAP && (Length < 4 || str_comp(pName+Length-4, ".map"))) || (pEditor->m_FileDialogFileType == CEditor::FILETYPE_IMG && (Length < 4 || str_comp(pName+Length-4, ".png")))))) return 0; CEditor::CFilelistItem Item; str_copy(Item.m_aFilename, pName, sizeof(Item.m_aFilename)); if(IsDir) str_format(Item.m_aName, sizeof(Item.m_aName), "%s/", pName); else str_copy(Item.m_aName, pName, min(static_cast<int>(sizeof(Item.m_aName)), Length-3)); Item.m_IsDir = IsDir != 0; Item.m_IsLink = false; Item.m_StorageType = StorageType; pEditor->m_FileList.add(Item); return 0; } void CEditor::AddFileDialogEntry(int Index, CUIRect *pView) { m_FilesCur++; if(m_FilesCur-1 < m_FilesStartAt || m_FilesCur >= m_FilesStopAt) return; CUIRect Button, FileIcon; pView->HSplitTop(15.0f, &Button, pView); pView->HSplitTop(2.0f, 0, pView); Button.VSplitLeft(Button.h, &FileIcon, &Button); Button.VSplitLeft(5.0f, 0, &Button); Graphics()->TextureSet(g_pData->m_aImages[IMAGE_FILEICONS].m_Id); Graphics()->QuadsBegin(); RenderTools()->SelectSprite(m_FileList[Index].m_IsDir?SPRITE_FILE_FOLDER:SPRITE_FILE_MAP2); IGraphics::CQuadItem QuadItem(FileIcon.x, FileIcon.y, FileIcon.w, FileIcon.h); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); if(DoButton_File(&m_FileList[Index], m_FileList[Index].m_aName, m_FilesSelectedIndex == Index, &Button, 0, 0)) { if(!m_FileList[Index].m_IsDir) str_copy(m_aFileDialogFileName, m_FileList[Index].m_aFilename, sizeof(m_aFileDialogFileName)); else m_aFileDialogFileName[0] = 0; m_FilesSelectedIndex = Index; if(Input()->MouseDoubleClick()) m_aFileDialogActivate = true; } } void CEditor::RenderFileDialog() { // GUI coordsys Graphics()->MapScreen(UI()->Screen()->x, UI()->Screen()->y, UI()->Screen()->w, UI()->Screen()->h); CUIRect View = *UI()->Screen(); float Width = View.w, Height = View.h; RenderTools()->DrawUIRect(&View, vec4(0,0,0,0.25f), 0, 0); View.VMargin(150.0f, &View); View.HMargin(50.0f, &View); RenderTools()->DrawUIRect(&View, vec4(0,0,0,0.75f), CUI::CORNER_ALL, 5.0f); View.Margin(10.0f, &View); CUIRect Title, FileBox, FileBoxLabel, ButtonBar, Scroll, PathBox; View.HSplitTop(18.0f, &Title, &View); View.HSplitTop(5.0f, 0, &View); // some spacing View.HSplitBottom(14.0f, &View, &ButtonBar); View.HSplitBottom(10.0f, &View, 0); // some spacing View.HSplitBottom(14.0f, &View, &PathBox); View.HSplitBottom(5.0f, &View, 0); // some spacing View.HSplitBottom(14.0f, &View, &FileBox); FileBox.VSplitLeft(55.0f, &FileBoxLabel, &FileBox); View.HSplitBottom(10.0f, &View, 0); // some spacing View.VSplitRight(15.0f, &View, &Scroll); // title RenderTools()->DrawUIRect(&Title, vec4(1, 1, 1, 0.25f), CUI::CORNER_ALL, 4.0f); Title.VMargin(10.0f, &Title); UI()->DoLabel(&Title, m_pFileDialogTitle, 12.0f, -1, -1); // pathbox char aPath[128], aBuf[128]; if(m_FilesSelectedIndex != -1) Storage()->GetCompletePath(m_FileList[m_FilesSelectedIndex].m_StorageType, m_pFileDialogPath, aPath, sizeof(aPath)); else aPath[0] = 0; str_format(aBuf, sizeof(aBuf), "Current path: %s", aPath); UI()->DoLabel(&PathBox, aBuf, 10.0f, -1, -1); // filebox if(m_FileDialogStorageType == IStorage::TYPE_SAVE) { static float s_FileBoxID = 0; UI()->DoLabel(&FileBoxLabel, "Filename:", 10.0f, -1, -1); if(DoEditBox(&s_FileBoxID, &FileBox, m_aFileDialogFileName, sizeof(m_aFileDialogFileName), 10.0f, &s_FileBoxID)) { // remove '/' and '\' for(int i = 0; m_aFileDialogFileName[i]; ++i) if(m_aFileDialogFileName[i] == '/' || m_aFileDialogFileName[i] == '\\') str_copy(&m_aFileDialogFileName[i], &m_aFileDialogFileName[i+1], (int)(sizeof(m_aFileDialogFileName))-i); m_FilesSelectedIndex = -1; } } int Num = (int)(View.h/17.0f)+1; static int ScrollBar = 0; Scroll.HMargin(5.0f, &Scroll); m_FileDialogScrollValue = UiDoScrollbarV(&ScrollBar, &Scroll, m_FileDialogScrollValue); int ScrollNum = m_FileList.size()-Num+1; if(ScrollNum > 0) { if(Input()->KeyPresses(KEY_MOUSE_WHEEL_UP)) m_FileDialogScrollValue -= 3.0f/ScrollNum; if(Input()->KeyPresses(KEY_MOUSE_WHEEL_DOWN)) m_FileDialogScrollValue += 3.0f/ScrollNum; } else ScrollNum = 0; if(m_FilesSelectedIndex > -1) { for(int i = 0; i < Input()->NumEvents(); i++) { int NewIndex = -1; if(Input()->GetEvent(i).m_Flags&IInput::FLAG_PRESS) { if(Input()->GetEvent(i).m_Key == KEY_DOWN) NewIndex = m_FilesSelectedIndex + 1; if(Input()->GetEvent(i).m_Key == KEY_UP) NewIndex = m_FilesSelectedIndex - 1; } if(NewIndex > -1 && NewIndex < m_FileList.size()) { //scroll float IndexY = View.y - m_FileDialogScrollValue*ScrollNum*17.0f + NewIndex*17.0f; int Scroll = View.y > IndexY ? -1 : View.y+View.h < IndexY+17.0f ? 1 : 0; if(Scroll) { if(Scroll < 0) m_FileDialogScrollValue = ((float)(NewIndex)+0.5f)/ScrollNum; else m_FileDialogScrollValue = ((float)(NewIndex-Num)+2.5f)/ScrollNum; } if(!m_FileList[NewIndex].m_IsDir) str_copy(m_aFileDialogFileName, m_FileList[NewIndex].m_aFilename, sizeof(m_aFileDialogFileName)); else m_aFileDialogFileName[0] = 0; m_FilesSelectedIndex = NewIndex; } } } for(int i = 0; i < Input()->NumEvents(); i++) { if(Input()->GetEvent(i).m_Flags&IInput::FLAG_PRESS) { if(Input()->GetEvent(i).m_Key == KEY_RETURN || Input()->GetEvent(i).m_Key == KEY_KP_ENTER) m_aFileDialogActivate = true; } } if(m_FileDialogScrollValue < 0) m_FileDialogScrollValue = 0; if(m_FileDialogScrollValue > 1) m_FileDialogScrollValue = 1; m_FilesStartAt = (int)(ScrollNum*m_FileDialogScrollValue); if(m_FilesStartAt < 0) m_FilesStartAt = 0; m_FilesStopAt = m_FilesStartAt+Num; m_FilesCur = 0; // set clipping UI()->ClipEnable(&View); for(int i = 0; i < m_FileList.size(); i++) AddFileDialogEntry(i, &View); // disable clipping again UI()->ClipDisable(); // the buttons static int s_OkButton = 0; static int s_CancelButton = 0; static int s_NewFolderButton = 0; static int s_MapInfoButton = 0; CUIRect Button; ButtonBar.VSplitRight(50.0f, &ButtonBar, &Button); bool IsDir = m_FilesSelectedIndex >= 0 && m_FileList[m_FilesSelectedIndex].m_IsDir; if(DoButton_Editor(&s_OkButton, IsDir ? "Open" : m_pFileDialogButtonText, 0, &Button, 0, 0) || m_aFileDialogActivate) { m_aFileDialogActivate = false; if(IsDir) // folder { if(str_comp(m_FileList[m_FilesSelectedIndex].m_aFilename, "..") == 0) // parent folder { if(fs_parent_dir(m_pFileDialogPath)) m_pFileDialogPath = m_aFileDialogCurrentFolder; // leave the link } else // sub folder { if(m_FileList[m_FilesSelectedIndex].m_IsLink) { m_pFileDialogPath = m_aFileDialogCurrentLink; // follow the link str_copy(m_aFileDialogCurrentLink, m_FileList[m_FilesSelectedIndex].m_aFilename, sizeof(m_aFileDialogCurrentLink)); } else { char aTemp[MAX_PATH_LENGTH]; str_copy(aTemp, m_pFileDialogPath, sizeof(aTemp)); str_format(m_pFileDialogPath, MAX_PATH_LENGTH, "%s/%s", aTemp, m_FileList[m_FilesSelectedIndex].m_aFilename); } } FilelistPopulate(!str_comp(m_pFileDialogPath, "maps") || !str_comp(m_pFileDialogPath, "mapres") ? m_FileDialogStorageType : m_FileList[m_FilesSelectedIndex].m_StorageType); if(m_FilesSelectedIndex >= 0 && !m_FileList[m_FilesSelectedIndex].m_IsDir) str_copy(m_aFileDialogFileName, m_FileList[m_FilesSelectedIndex].m_aFilename, sizeof(m_aFileDialogFileName)); else m_aFileDialogFileName[0] = 0; } else // file { str_format(m_aFileSaveName, sizeof(m_aFileSaveName), "%s/%s", m_pFileDialogPath, m_aFileDialogFileName); if(!str_comp(m_pFileDialogButtonText, "Save")) { IOHANDLE File = Storage()->OpenFile(m_aFileSaveName, IOFLAG_READ, IStorage::TYPE_SAVE); if(File) { io_close(File); m_PopupEventType = POPEVENT_SAVE; m_PopupEventActivated = true; } else if(m_pfnFileDialogFunc) m_pfnFileDialogFunc(m_aFileSaveName, m_FilesSelectedIndex >= 0 ? m_FileList[m_FilesSelectedIndex].m_StorageType : m_FileDialogStorageType, m_pFileDialogUser); } else if(m_pfnFileDialogFunc) m_pfnFileDialogFunc(m_aFileSaveName, m_FilesSelectedIndex >= 0 ? m_FileList[m_FilesSelectedIndex].m_StorageType : m_FileDialogStorageType, m_pFileDialogUser); } } ButtonBar.VSplitRight(40.0f, &ButtonBar, &Button); ButtonBar.VSplitRight(50.0f, &ButtonBar, &Button); if(DoButton_Editor(&s_CancelButton, "Cancel", 0, &Button, 0, 0) || Input()->KeyPressed(KEY_ESCAPE)) m_Dialog = DIALOG_NONE; if(m_FileDialogStorageType == IStorage::TYPE_SAVE) { ButtonBar.VSplitLeft(40.0f, 0, &ButtonBar); ButtonBar.VSplitLeft(70.0f, &Button, &ButtonBar); if(DoButton_Editor(&s_NewFolderButton, "New folder", 0, &Button, 0, 0)) { m_FileDialogNewFolderName[0] = 0; m_FileDialogErrString[0] = 0; static int s_NewFolderPopupID = 0; UiInvokePopupMenu(&s_NewFolderPopupID, 0, Width/2.0f-200.0f, Height/2.0f-100.0f, 400.0f, 200.0f, PopupNewFolder); UI()->SetActiveItem(0); } } if(m_FileDialogStorageType == IStorage::TYPE_SAVE) { ButtonBar.VSplitLeft(40.0f, 0, &ButtonBar); ButtonBar.VSplitLeft(70.0f, &Button, &ButtonBar); if(DoButton_Editor(&s_MapInfoButton, "Map details", 0, &Button, 0, 0)) { str_copy(m_Map.m_MapInfo.m_aAuthorTmp, m_Map.m_MapInfo.m_aAuthor, sizeof(m_Map.m_MapInfo.m_aAuthorTmp)); str_copy(m_Map.m_MapInfo.m_aVersionTmp, m_Map.m_MapInfo.m_aVersion, sizeof(m_Map.m_MapInfo.m_aVersionTmp)); str_copy(m_Map.m_MapInfo.m_aCreditsTmp, m_Map.m_MapInfo.m_aCredits, sizeof(m_Map.m_MapInfo.m_aCreditsTmp)); str_copy(m_Map.m_MapInfo.m_aLicenseTmp, m_Map.m_MapInfo.m_aLicense, sizeof(m_Map.m_MapInfo.m_aLicenseTmp)); static int s_MapInfoPopupID = 0; UiInvokePopupMenu(&s_MapInfoPopupID, 0, Width/2.0f-200.0f, Height/2.0f-100.0f, 400.0f, 200.0f, PopupMapInfo); UI()->SetActiveItem(0); } } } void CEditor::FilelistPopulate(int StorageType) { m_FileList.clear(); if(m_FileDialogStorageType != IStorage::TYPE_SAVE && !str_comp(m_pFileDialogPath, "maps")) { CFilelistItem Item; str_copy(Item.m_aFilename, "downloadedmaps", sizeof(Item.m_aFilename)); str_copy(Item.m_aName, "downloadedmaps/", sizeof(Item.m_aName)); Item.m_IsDir = true; Item.m_IsLink = true; Item.m_StorageType = IStorage::TYPE_SAVE; m_FileList.add(Item); } Storage()->ListDirectory(StorageType, m_pFileDialogPath, EditorListdirCallback, this); m_FilesSelectedIndex = m_FileList.size() ? 0 : -1; m_aFileDialogActivate = false; } void CEditor::InvokeFileDialog(int StorageType, int FileType, const char *pTitle, const char *pButtonText, const char *pBasePath, const char *pDefaultName, void (*pfnFunc)(const char *pFileName, int StorageType, void *pUser), void *pUser) { m_FileDialogStorageType = StorageType; m_pFileDialogTitle = pTitle; m_pFileDialogButtonText = pButtonText; m_pfnFileDialogFunc = pfnFunc; m_pFileDialogUser = pUser; m_aFileDialogFileName[0] = 0; m_aFileDialogCurrentFolder[0] = 0; m_aFileDialogCurrentLink[0] = 0; m_pFileDialogPath = m_aFileDialogCurrentFolder; m_FileDialogFileType = FileType; m_FileDialogScrollValue = 0.0f; if(pDefaultName) str_copy(m_aFileDialogFileName, pDefaultName, sizeof(m_aFileDialogFileName)); if(pBasePath) str_copy(m_aFileDialogCurrentFolder, pBasePath, sizeof(m_aFileDialogCurrentFolder)); FilelistPopulate(m_FileDialogStorageType); m_Dialog = DIALOG_FILE; } void CEditor::RenderModebar(CUIRect View) { CUIRect Button; // mode buttons { View.VSplitLeft(65.0f, &Button, &View); Button.HSplitTop(30.0f, 0, &Button); static int s_Button = 0; const char *pButName = m_Mode == MODE_LAYERS ? "Layers" : "Images"; if(DoButton_Tab(&s_Button, pButName, 0, &Button, 0, "Switch between images and layers managment.")) { if(m_Mode == MODE_LAYERS) m_Mode = MODE_IMAGES; else m_Mode = MODE_LAYERS; } } View.VSplitLeft(5.0f, 0, &View); } void CEditor::RenderStatusbar(CUIRect View) { CUIRect Button; View.VSplitRight(60.0f, &View, &Button); static int s_EnvelopeButton = 0; if(DoButton_Editor(&s_EnvelopeButton, "Envelopes", m_ShowEnvelopeEditor, &Button, 0, "Toggles the envelope editor.")) m_ShowEnvelopeEditor = (m_ShowEnvelopeEditor+1)%4; if(m_pTooltip) { if(ms_pUiGotContext && ms_pUiGotContext == UI()->HotItem()) { char aBuf[512]; str_format(aBuf, sizeof(aBuf), "%s Right click for context menu.", m_pTooltip); UI()->DoLabel(&View, aBuf, 10.0f, -1, -1); } else UI()->DoLabel(&View, m_pTooltip, 10.0f, -1, -1); } } void CEditor::RenderEnvelopeEditor(CUIRect View) { if(m_SelectedEnvelope < 0) m_SelectedEnvelope = 0; if(m_SelectedEnvelope >= m_Map.m_lEnvelopes.size()) m_SelectedEnvelope = m_Map.m_lEnvelopes.size()-1; CEnvelope *pEnvelope = 0; if(m_SelectedEnvelope >= 0 && m_SelectedEnvelope < m_Map.m_lEnvelopes.size()) pEnvelope = m_Map.m_lEnvelopes[m_SelectedEnvelope]; CUIRect ToolBar, CurveBar, ColorBar; View.HSplitTop(15.0f, &ToolBar, &View); View.HSplitTop(15.0f, &CurveBar, &View); ToolBar.Margin(2.0f, &ToolBar); CurveBar.Margin(2.0f, &CurveBar); // do the toolbar { CUIRect Button; CEnvelope *pNewEnv = 0; ToolBar.VSplitRight(50.0f, &ToolBar, &Button); static int s_New4dButton = 0; if(DoButton_Editor(&s_New4dButton, "Color+", 0, &Button, 0, "Creates a new color envelope")) { m_Map.m_Modified = true; pNewEnv = m_Map.NewEnvelope(4); } ToolBar.VSplitRight(5.0f, &ToolBar, &Button); ToolBar.VSplitRight(50.0f, &ToolBar, &Button); static int s_New2dButton = 0; if(DoButton_Editor(&s_New2dButton, "Pos.+", 0, &Button, 0, "Creates a new pos envelope")) { m_Map.m_Modified = true; pNewEnv = m_Map.NewEnvelope(3); } // Delete button if(m_SelectedEnvelope >= 0) { ToolBar.VSplitRight(10.0f, &ToolBar, &Button); ToolBar.VSplitRight(50.0f, &ToolBar, &Button); static int s_DelButton = 0; if(DoButton_Editor(&s_DelButton, "Delete", 0, &Button, 0, "Delete this envelope")) { m_Map.m_Modified = true; m_Map.DeleteEnvelope(m_SelectedEnvelope); if(m_SelectedEnvelope >= m_Map.m_lEnvelopes.size()) m_SelectedEnvelope = m_Map.m_lEnvelopes.size()-1; pEnvelope = m_SelectedEnvelope >= 0 ? m_Map.m_lEnvelopes[m_SelectedEnvelope] : 0; } } if(pNewEnv) // add the default points { if(pNewEnv->m_Channels == 4) { pNewEnv->AddPoint(0, 1,1,1,1); pNewEnv->AddPoint(1000, 1,1,1,1); } else { pNewEnv->AddPoint(0, 0); pNewEnv->AddPoint(1000, 0); } } CUIRect Shifter, Inc, Dec; ToolBar.VSplitLeft(60.0f, &Shifter, &ToolBar); Shifter.VSplitRight(15.0f, &Shifter, &Inc); Shifter.VSplitLeft(15.0f, &Dec, &Shifter); char aBuf[512]; str_format(aBuf, sizeof(aBuf),"%d/%d", m_SelectedEnvelope+1, m_Map.m_lEnvelopes.size()); RenderTools()->DrawUIRect(&Shifter, vec4(1,1,1,0.5f), 0, 0.0f); UI()->DoLabel(&Shifter, aBuf, 10.0f, 0, -1); static int s_PrevButton = 0; if(DoButton_ButtonDec(&s_PrevButton, 0, 0, &Dec, 0, "Previous Envelope")) m_SelectedEnvelope--; static int s_NextButton = 0; if(DoButton_ButtonInc(&s_NextButton, 0, 0, &Inc, 0, "Next Envelope")) m_SelectedEnvelope++; if(pEnvelope) { ToolBar.VSplitLeft(15.0f, &Button, &ToolBar); ToolBar.VSplitLeft(35.0f, &Button, &ToolBar); UI()->DoLabel(&Button, "Name:", 10.0f, -1, -1); ToolBar.VSplitLeft(80.0f, &Button, &ToolBar); static float s_NameBox = 0; if(DoEditBox(&s_NameBox, &Button, pEnvelope->m_aName, sizeof(pEnvelope->m_aName), 10.0f, &s_NameBox)) m_Map.m_Modified = true; } } bool ShowColorBar = false; if(pEnvelope && pEnvelope->m_Channels == 4) { ShowColorBar = true; View.HSplitTop(20.0f, &ColorBar, &View); ColorBar.Margin(2.0f, &ColorBar); RenderBackground(ColorBar, m_CheckerTexture, 16.0f, 1.0f); } RenderBackground(View, m_CheckerTexture, 32.0f, 0.1f); if(pEnvelope) { static array<int> Selection; static int sEnvelopeEditorID = 0; static int s_ActiveChannels = 0xf; if(pEnvelope) { CUIRect Button; ToolBar.VSplitLeft(15.0f, &Button, &ToolBar); static const char *s_paNames[2][4] = { {"X", "Y", "R", ""}, {"R", "G", "B", "A"}, }; const char *paDescriptions[2][4] = { {"X-axis of the envelope", "Y-axis of the envelope", "Rotation of the envelope", ""}, {"Red value of the envelope", "Green value of the envelope", "Blue value of the envelope", "Alpha value of the envelope"}, }; static int s_aChannelButtons[4] = {0}; int Bit = 1; //ui_draw_button_func draw_func; for(int i = 0; i < pEnvelope->m_Channels; i++, Bit<<=1) { ToolBar.VSplitLeft(15.0f, &Button, &ToolBar); /*if(i == 0) draw_func = draw_editor_button_l; else if(i == envelope->channels-1) draw_func = draw_editor_button_r; else draw_func = draw_editor_button_m;*/ if(DoButton_Editor(&s_aChannelButtons[i], s_paNames[pEnvelope->m_Channels-3][i], s_ActiveChannels&Bit, &Button, 0, paDescriptions[pEnvelope->m_Channels-3][i])) s_ActiveChannels ^= Bit; } // sync checkbox ToolBar.VSplitLeft(15.0f, &Button, &ToolBar); ToolBar.VSplitLeft(12.0f, &Button, &ToolBar); static int s_SyncButton; if(DoButton_Editor(&s_SyncButton, pEnvelope->m_Synchronized?"X":"", 0, &Button, 0, "Enable envelope synchronization between clients")) pEnvelope->m_Synchronized = !pEnvelope->m_Synchronized; ToolBar.VSplitLeft(4.0f, &Button, &ToolBar); ToolBar.VSplitLeft(80.0f, &Button, &ToolBar); UI()->DoLabel(&Button, "Synchronized", 10.0f, -1, -1); } float EndTime = pEnvelope->EndTime(); if(EndTime < 1) EndTime = 1; pEnvelope->FindTopBottom(s_ActiveChannels); float Top = pEnvelope->m_Top; float Bottom = pEnvelope->m_Bottom; if(Top < 1) Top = 1; if(Bottom >= 0) Bottom = 0; float TimeScale = EndTime/View.w; float ValueScale = (Top-Bottom)/View.h; if(UI()->MouseInside(&View)) UI()->SetHotItem(&sEnvelopeEditorID); if(UI()->HotItem() == &sEnvelopeEditorID) { // do stuff if(pEnvelope) { if(UI()->MouseButtonClicked(1)) { // add point int Time = (int)(((UI()->MouseX()-View.x)*TimeScale)*1000.0f); //float env_y = (UI()->MouseY()-view.y)/TimeScale; float aChannels[4]; pEnvelope->Eval(Time, aChannels); pEnvelope->AddPoint(Time, f2fx(aChannels[0]), f2fx(aChannels[1]), f2fx(aChannels[2]), f2fx(aChannels[3])); m_Map.m_Modified = true; } m_ShowEnvelopePreview = 1; m_pTooltip = "Press right mouse button to create a new point"; } } vec3 aColors[] = {vec3(1,0.2f,0.2f), vec3(0.2f,1,0.2f), vec3(0.2f,0.2f,1), vec3(1,1,0.2f)}; // render lines { UI()->ClipEnable(&View); Graphics()->TextureClear(); Graphics()->LinesBegin(); for(int c = 0; c < pEnvelope->m_Channels; c++) { if(s_ActiveChannels&(1<<c)) Graphics()->SetColor(aColors[c].r,aColors[c].g,aColors[c].b,1); else Graphics()->SetColor(aColors[c].r*0.5f,aColors[c].g*0.5f,aColors[c].b*0.5f,1); float PrevX = 0; float aResults[4]; pEnvelope->Eval(0.000001f, aResults); float PrevValue = aResults[c]; int Steps = (int)((View.w/UI()->Screen()->w) * Graphics()->ScreenWidth()); for(int i = 1; i <= Steps; i++) { float a = i/(float)Steps; pEnvelope->Eval(a*EndTime, aResults); float v = aResults[c]; v = (v-Bottom)/(Top-Bottom); IGraphics::CLineItem LineItem(View.x + PrevX*View.w, View.y+View.h - PrevValue*View.h, View.x + a*View.w, View.y+View.h - v*View.h); Graphics()->LinesDraw(&LineItem, 1); PrevX = a; PrevValue = v; } } Graphics()->LinesEnd(); UI()->ClipDisable(); } // render curve options { for(int i = 0; i < pEnvelope->m_lPoints.size()-1; i++) { float t0 = pEnvelope->m_lPoints[i].m_Time/1000.0f/EndTime; float t1 = pEnvelope->m_lPoints[i+1].m_Time/1000.0f/EndTime; //dbg_msg("", "%f", end_time); CUIRect v; v.x = CurveBar.x + (t0+(t1-t0)*0.5f) * CurveBar.w; v.y = CurveBar.y; v.h = CurveBar.h; v.w = CurveBar.h; v.x -= v.w/2; void *pID = &pEnvelope->m_lPoints[i].m_Curvetype; const char *paTypeName[] = { "N", "L", "S", "F", "M" }; if(DoButton_Editor(pID, paTypeName[pEnvelope->m_lPoints[i].m_Curvetype], 0, &v, 0, "Switch curve type")) pEnvelope->m_lPoints[i].m_Curvetype = (pEnvelope->m_lPoints[i].m_Curvetype+1)%NUM_CURVETYPES; } } // render colorbar if(ShowColorBar) { Graphics()->TextureClear(); Graphics()->QuadsBegin(); for(int i = 0; i < pEnvelope->m_lPoints.size()-1; i++) { float r0 = fx2f(pEnvelope->m_lPoints[i].m_aValues[0]); float g0 = fx2f(pEnvelope->m_lPoints[i].m_aValues[1]); float b0 = fx2f(pEnvelope->m_lPoints[i].m_aValues[2]); float a0 = fx2f(pEnvelope->m_lPoints[i].m_aValues[3]); float r1 = fx2f(pEnvelope->m_lPoints[i+1].m_aValues[0]); float g1 = fx2f(pEnvelope->m_lPoints[i+1].m_aValues[1]); float b1 = fx2f(pEnvelope->m_lPoints[i+1].m_aValues[2]); float a1 = fx2f(pEnvelope->m_lPoints[i+1].m_aValues[3]); IGraphics::CColorVertex Array[4] = {IGraphics::CColorVertex(0, r0, g0, b0, a0), IGraphics::CColorVertex(1, r1, g1, b1, a1), IGraphics::CColorVertex(2, r1, g1, b1, a1), IGraphics::CColorVertex(3, r0, g0, b0, a0)}; Graphics()->SetColorVertex(Array, 4); float x0 = pEnvelope->m_lPoints[i].m_Time/1000.0f/EndTime; // float y0 = (fx2f(envelope->points[i].values[c])-bottom)/(top-bottom); float x1 = pEnvelope->m_lPoints[i+1].m_Time/1000.0f/EndTime; //float y1 = (fx2f(envelope->points[i+1].values[c])-bottom)/(top-bottom); CUIRect v; v.x = ColorBar.x + x0*ColorBar.w; v.y = ColorBar.y; v.w = (x1-x0)*ColorBar.w; v.h = ColorBar.h; IGraphics::CQuadItem QuadItem(v.x, v.y, v.w, v.h); Graphics()->QuadsDrawTL(&QuadItem, 1); } Graphics()->QuadsEnd(); } // render handles { int CurrentValue = 0, CurrentTime = 0; Graphics()->TextureClear(); Graphics()->QuadsBegin(); for(int c = 0; c < pEnvelope->m_Channels; c++) { if(!(s_ActiveChannels&(1<<c))) continue; for(int i = 0; i < pEnvelope->m_lPoints.size(); i++) { float x0 = pEnvelope->m_lPoints[i].m_Time/1000.0f/EndTime; float y0 = (fx2f(pEnvelope->m_lPoints[i].m_aValues[c])-Bottom)/(Top-Bottom); CUIRect Final; Final.x = View.x + x0*View.w; Final.y = View.y+View.h - y0*View.h; Final.x -= 2.0f; Final.y -= 2.0f; Final.w = 4.0f; Final.h = 4.0f; void *pID = &pEnvelope->m_lPoints[i].m_aValues[c]; if(UI()->MouseInside(&Final)) UI()->SetHotItem(pID); float ColorMod = 1.0f; if(UI()->ActiveItem() == pID) { if(!UI()->MouseButton(0)) { m_SelectedQuadEnvelope = -1; m_SelectedEnvelopePoint = -1; UI()->SetActiveItem(0); } else { if(Input()->KeyPressed(KEY_LSHIFT) || Input()->KeyPressed(KEY_RSHIFT)) { if(i != 0) { if((Input()->KeyPressed(KEY_LCTRL) || Input()->KeyPressed(KEY_RCTRL))) pEnvelope->m_lPoints[i].m_Time += (int)((m_MouseDeltaX)); else pEnvelope->m_lPoints[i].m_Time += (int)((m_MouseDeltaX*TimeScale)*1000.0f); if(pEnvelope->m_lPoints[i].m_Time < pEnvelope->m_lPoints[i-1].m_Time) pEnvelope->m_lPoints[i].m_Time = pEnvelope->m_lPoints[i-1].m_Time + 1; if(i+1 != pEnvelope->m_lPoints.size() && pEnvelope->m_lPoints[i].m_Time > pEnvelope->m_lPoints[i+1].m_Time) pEnvelope->m_lPoints[i].m_Time = pEnvelope->m_lPoints[i+1].m_Time - 1; } } else { if((Input()->KeyPressed(KEY_LCTRL) || Input()->KeyPressed(KEY_RCTRL))) pEnvelope->m_lPoints[i].m_aValues[c] -= f2fx(m_MouseDeltaY*0.001f); else pEnvelope->m_lPoints[i].m_aValues[c] -= f2fx(m_MouseDeltaY*ValueScale); } m_SelectedQuadEnvelope = m_SelectedEnvelope; m_ShowEnvelopePreview = 1; m_SelectedEnvelopePoint = i; m_Map.m_Modified = true; } ColorMod = 100.0f; Graphics()->SetColor(1,1,1,1); } else if(UI()->HotItem() == pID) { if(UI()->MouseButton(0)) { Selection.clear(); Selection.add(i); UI()->SetActiveItem(pID); } // remove point if(UI()->MouseButtonClicked(1)) { pEnvelope->m_lPoints.remove_index(i); m_Map.m_Modified = true; } m_ShowEnvelopePreview = 1; ColorMod = 100.0f; Graphics()->SetColor(1,0.75f,0.75f,1); m_pTooltip = "Left mouse to drag. Hold ctrl to be more precise. Hold shift to alter time point aswell. Right click to delete."; } if(UI()->ActiveItem() == pID || UI()->HotItem() == pID) { CurrentTime = pEnvelope->m_lPoints[i].m_Time; CurrentValue = pEnvelope->m_lPoints[i].m_aValues[c]; } if (m_SelectedQuadEnvelope == m_SelectedEnvelope && m_SelectedEnvelopePoint == i) Graphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f); else Graphics()->SetColor(aColors[c].r*ColorMod, aColors[c].g*ColorMod, aColors[c].b*ColorMod, 1.0f); IGraphics::CQuadItem QuadItem(Final.x, Final.y, Final.w, Final.h); Graphics()->QuadsDrawTL(&QuadItem, 1); } } Graphics()->QuadsEnd(); char aBuf[512]; str_format(aBuf, sizeof(aBuf),"%.3f %.3f", CurrentTime/1000.0f, fx2f(CurrentValue)); UI()->DoLabel(&ToolBar, aBuf, 10.0f, 0, -1); } } } int CEditor::PopupMenuFile(CEditor *pEditor, CUIRect View) { static int s_NewMapButton = 0; static int s_SaveButton = 0; static int s_SaveAsButton = 0; static int s_OpenButton = 0; static int s_AppendButton = 0; static int s_ExitButton = 0; CUIRect Slot; View.HSplitTop(2.0f, &Slot, &View); View.HSplitTop(12.0f, &Slot, &View); if(pEditor->DoButton_MenuItem(&s_NewMapButton, "New", 0, &Slot, 0, "Creates a new map")) { if(pEditor->HasUnsavedData()) { pEditor->m_PopupEventType = POPEVENT_NEW; pEditor->m_PopupEventActivated = true; } else { pEditor->Reset(); pEditor->m_aFileName[0] = 0; } return 1; } View.HSplitTop(10.0f, &Slot, &View); View.HSplitTop(12.0f, &Slot, &View); if(pEditor->DoButton_MenuItem(&s_OpenButton, "Load", 0, &Slot, 0, "Opens a map for editing")) { if(pEditor->HasUnsavedData()) { pEditor->m_PopupEventType = POPEVENT_LOAD; pEditor->m_PopupEventActivated = true; } else pEditor->InvokeFileDialog(IStorage::TYPE_ALL, FILETYPE_MAP, "Load map", "Load", "maps", "", pEditor->CallbackOpenMap, pEditor); return 1; } View.HSplitTop(10.0f, &Slot, &View); View.HSplitTop(12.0f, &Slot, &View); if(pEditor->DoButton_MenuItem(&s_AppendButton, "Append", 0, &Slot, 0, "Opens a map and adds everything from that map to the current one")) { pEditor->InvokeFileDialog(IStorage::TYPE_ALL, FILETYPE_MAP, "Append map", "Append", "maps", "", pEditor->CallbackAppendMap, pEditor); return 1; } View.HSplitTop(10.0f, &Slot, &View); View.HSplitTop(12.0f, &Slot, &View); if(pEditor->DoButton_MenuItem(&s_SaveButton, "Save", 0, &Slot, 0, "Saves the current map")) { if(pEditor->m_aFileName[0] && pEditor->m_ValidSaveFilename) { str_copy(pEditor->m_aFileSaveName, pEditor->m_aFileName, sizeof(pEditor->m_aFileSaveName)); pEditor->m_PopupEventType = POPEVENT_SAVE; pEditor->m_PopupEventActivated = true; } else pEditor->InvokeFileDialog(IStorage::TYPE_SAVE, FILETYPE_MAP, "Save map", "Save", "maps", "", pEditor->CallbackSaveMap, pEditor); return 1; } View.HSplitTop(2.0f, &Slot, &View); View.HSplitTop(12.0f, &Slot, &View); if(pEditor->DoButton_MenuItem(&s_SaveAsButton, "Save As", 0, &Slot, 0, "Saves the current map under a new name")) { pEditor->InvokeFileDialog(IStorage::TYPE_SAVE, FILETYPE_MAP, "Save map", "Save", "maps", "", pEditor->CallbackSaveMap, pEditor); return 1; } View.HSplitTop(10.0f, &Slot, &View); View.HSplitTop(12.0f, &Slot, &View); if(pEditor->DoButton_MenuItem(&s_ExitButton, "Exit", 0, &Slot, 0, "Exits from the editor")) { if(pEditor->HasUnsavedData()) { pEditor->m_PopupEventType = POPEVENT_EXIT; pEditor->m_PopupEventActivated = true; } else g_Config.m_ClEditor = 0; return 1; } return 0; } void CEditor::RenderMenubar(CUIRect MenuBar) { static CUIRect s_File /*, view, help*/; MenuBar.VSplitLeft(60.0f, &s_File, &MenuBar); if(DoButton_Menu(&s_File, "File", 0, &s_File, 0, 0)) UiInvokePopupMenu(&s_File, 1, s_File.x, s_File.y+s_File.h-1.0f, 120, 150, PopupMenuFile, this); /* menubar.VSplitLeft(5.0f, 0, &menubar); menubar.VSplitLeft(60.0f, &view, &menubar); if(do_editor_button(&view, "View", 0, &view, draw_editor_button_menu, 0, 0)) (void)0; menubar.VSplitLeft(5.0f, 0, &menubar); menubar.VSplitLeft(60.0f, &help, &menubar); if(do_editor_button(&help, "Help", 0, &help, draw_editor_button_menu, 0, 0)) (void)0; */ CUIRect Info; MenuBar.VSplitLeft(40.0f, 0, &MenuBar); MenuBar.VSplitLeft(MenuBar.w*0.75f, &MenuBar, &Info); char aBuf[128]; str_format(aBuf, sizeof(aBuf), "File: %s", m_aFileName); UI()->DoLabel(&MenuBar, aBuf, 10.0f, -1, -1); str_format(aBuf, sizeof(aBuf), "Z: %i, A: %.1f, G: %i", m_ZoomLevel, m_AnimateSpeed, m_GridFactor); UI()->DoLabel(&Info, aBuf, 10.0f, 1, -1); } void CEditor::Render() { // basic start Graphics()->Clear(1.0f, 0.0f, 1.0f); CUIRect View = *UI()->Screen(); Graphics()->MapScreen(UI()->Screen()->x, UI()->Screen()->y, UI()->Screen()->w, UI()->Screen()->h); float Width = View.w; float Height = View.h; // reset tip m_pTooltip = 0; if(m_EditBoxActive) --m_EditBoxActive; // render checker RenderBackground(View, m_CheckerTexture, 32.0f, 1.0f); CUIRect MenuBar, CModeBar, ToolBar, StatusBar, EnvelopeEditor, ToolBox; m_ShowPicker = Input()->KeyPressed(KEY_SPACE) != 0 && m_Dialog == DIALOG_NONE; if(m_GuiActive) { View.HSplitTop(16.0f, &MenuBar, &View); View.HSplitTop(53.0f, &ToolBar, &View); View.VSplitLeft(100.0f, &ToolBox, &View); View.HSplitBottom(16.0f, &View, &StatusBar); if(m_ShowEnvelopeEditor && !m_ShowPicker) { float size = 125.0f; if(m_ShowEnvelopeEditor == 2) size *= 2.0f; else if(m_ShowEnvelopeEditor == 3) size *= 3.0f; View.HSplitBottom(size, &View, &EnvelopeEditor); } } // a little hack for now if(m_Mode == MODE_LAYERS) DoMapEditor(View, ToolBar); // do zooming if(Input()->KeyDown(KEY_KP_MINUS)) m_ZoomLevel += 50; if(Input()->KeyDown(KEY_KP_PLUS)) m_ZoomLevel -= 50; if(Input()->KeyDown(KEY_KP_MULTIPLY)) { m_EditorOffsetX = 0; m_EditorOffsetY = 0; m_ZoomLevel = 100; } if(m_Dialog == DIALOG_NONE && UI()->MouseInside(&View)) { if(Input()->KeyPresses(KEY_MOUSE_WHEEL_UP)) m_ZoomLevel -= 20; if(Input()->KeyPresses(KEY_MOUSE_WHEEL_DOWN)) m_ZoomLevel += 20; } m_ZoomLevel = clamp(m_ZoomLevel, 50, 2000); m_WorldZoom = m_ZoomLevel/100.0f; if(m_GuiActive) { float Brightness = 0.25f; RenderBackground(MenuBar, m_BackgroundTexture, 128.0f, Brightness*0); MenuBar.Margin(2.0f, &MenuBar); RenderBackground(ToolBox, m_BackgroundTexture, 128.0f, Brightness); ToolBox.Margin(2.0f, &ToolBox); RenderBackground(ToolBar, m_BackgroundTexture, 128.0f, Brightness); ToolBar.Margin(2.0f, &ToolBar); ToolBar.VSplitLeft(100.0f, &CModeBar, &ToolBar); RenderBackground(StatusBar, m_BackgroundTexture, 128.0f, Brightness); StatusBar.Margin(2.0f, &StatusBar); // do the toolbar if(m_Mode == MODE_LAYERS) DoToolbar(ToolBar); if(m_ShowEnvelopeEditor) { RenderBackground(EnvelopeEditor, m_BackgroundTexture, 128.0f, Brightness); EnvelopeEditor.Margin(2.0f, &EnvelopeEditor); } } if(m_Mode == MODE_LAYERS) RenderLayers(ToolBox, ToolBar, View); else if(m_Mode == MODE_IMAGES) RenderImages(ToolBox, ToolBar, View); Graphics()->MapScreen(UI()->Screen()->x, UI()->Screen()->y, UI()->Screen()->w, UI()->Screen()->h); if(m_GuiActive) { RenderMenubar(MenuBar); RenderModebar(CModeBar); if(m_ShowEnvelopeEditor) RenderEnvelopeEditor(EnvelopeEditor); } if(m_Dialog == DIALOG_FILE) { static int s_NullUiTarget = 0; UI()->SetHotItem(&s_NullUiTarget); RenderFileDialog(); } if(m_PopupEventActivated) { static int s_PopupID = 0; UiInvokePopupMenu(&s_PopupID, 0, Width/2.0f-200.0f, Height/2.0f-100.0f, 400.0f, 200.0f, PopupEvent); m_PopupEventActivated = false; m_PopupEventWasActivated = true; } UiDoPopupMenu(); if(m_GuiActive) RenderStatusbar(StatusBar); // if(g_Config.m_EdShowkeys) { Graphics()->MapScreen(UI()->Screen()->x, UI()->Screen()->y, UI()->Screen()->w, UI()->Screen()->h); CTextCursor Cursor; TextRender()->SetCursor(&Cursor, View.x+10, View.y+View.h-24-10, 24.0f, TEXTFLAG_RENDER); int NKeys = 0; for(int i = 0; i < KEY_LAST; i++) { if(Input()->KeyPressed(i)) { if(NKeys) TextRender()->TextEx(&Cursor, " + ", -1); TextRender()->TextEx(&Cursor, Input()->KeyName(i), -1); NKeys++; } } } if(m_ShowMousePointer) { // render butt ugly mouse cursor float mx = UI()->MouseX(); float my = UI()->MouseY(); Graphics()->TextureSet(m_CursorTexture); Graphics()->QuadsBegin(); if(ms_pUiGotContext == UI()->HotItem()) Graphics()->SetColor(1,0,0,1); IGraphics::CQuadItem QuadItem(mx,my, 16.0f, 16.0f); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); } } void CEditor::Reset(bool CreateDefault) { m_Map.Clean(); // create default layers if(CreateDefault) m_Map.CreateDefault(m_EntitiesTexture); /* { }*/ m_SelectedLayer = 0; m_SelectedGroup = 0; m_SelectedQuad = -1; m_SelectedPoints = 0; m_SelectedEnvelope = 0; m_SelectedImage = 0; m_WorldOffsetX = 0; m_WorldOffsetY = 0; m_EditorOffsetX = 0.0f; m_EditorOffsetY = 0.0f; m_WorldZoom = 1.0f; m_ZoomLevel = 200; m_MouseDeltaX = 0; m_MouseDeltaY = 0; m_MouseDeltaWx = 0; m_MouseDeltaWy = 0; m_Map.m_Modified = false; m_ShowEnvelopePreview = 0; } int CEditor::GetLineDistance() { int LineDistance = 512; if(m_ZoomLevel <= 100) LineDistance = 16; else if(m_ZoomLevel <= 250) LineDistance = 32; else if(m_ZoomLevel <= 450) LineDistance = 64; else if(m_ZoomLevel <= 850) LineDistance = 128; else if(m_ZoomLevel <= 1550) LineDistance = 256; return LineDistance; } void CEditorMap::DeleteEnvelope(int Index) { if(Index < 0 || Index >= m_lEnvelopes.size()) return; m_Modified = true; // fix links between envelopes and quads for(int i = 0; i < m_lGroups.size(); ++i) for(int j = 0; j < m_lGroups[i]->m_lLayers.size(); ++j) if(m_lGroups[i]->m_lLayers[j]->m_Type == LAYERTYPE_QUADS) { CLayerQuads *pLayer = static_cast<CLayerQuads *>(m_lGroups[i]->m_lLayers[j]); for(int k = 0; k < pLayer->m_lQuads.size(); ++k) { if(pLayer->m_lQuads[k].m_PosEnv == Index) pLayer->m_lQuads[k].m_PosEnv = -1; else if(pLayer->m_lQuads[k].m_PosEnv > Index) pLayer->m_lQuads[k].m_PosEnv--; if(pLayer->m_lQuads[k].m_ColorEnv == Index) pLayer->m_lQuads[k].m_ColorEnv = -1; else if(pLayer->m_lQuads[k].m_ColorEnv > Index) pLayer->m_lQuads[k].m_ColorEnv--; } } else if(m_lGroups[i]->m_lLayers[j]->m_Type == LAYERTYPE_TILES) { CLayerTiles *pLayer = static_cast<CLayerTiles *>(m_lGroups[i]->m_lLayers[j]); if(pLayer->m_ColorEnv == Index) pLayer->m_ColorEnv = -1; if(pLayer->m_ColorEnv > Index) pLayer->m_ColorEnv--; } m_lEnvelopes.remove_index(Index); } void CEditorMap::MakeGameLayer(CLayer *pLayer) { m_pGameLayer = (CLayerGame *)pLayer; m_pGameLayer->m_pEditor = m_pEditor; m_pGameLayer->m_Texture = m_pEditor->m_EntitiesTexture; } void CEditorMap::MakeGameGroup(CLayerGroup *pGroup) { m_pGameGroup = pGroup; m_pGameGroup->m_GameGroup = true; str_copy(m_pGameGroup->m_aName, "Game", sizeof(m_pGameGroup->m_aName)); } void CEditorMap::Clean() { m_lGroups.delete_all(); m_lEnvelopes.delete_all(); m_lImages.delete_all(); m_MapInfo.Reset(); m_pGameLayer = 0x0; m_pGameGroup = 0x0; m_Modified = false; } void CEditorMap::CreateDefault(IGraphics::CTextureHandle EntitiesTexture) { // add background CLayerGroup *pGroup = NewGroup(); pGroup->m_ParallaxX = 0; pGroup->m_ParallaxY = 0; CLayerQuads *pLayer = new CLayerQuads; pLayer->m_pEditor = m_pEditor; CQuad *pQuad = pLayer->NewQuad(); const int Width = 800000; const int Height = 600000; pQuad->m_aPoints[0].x = pQuad->m_aPoints[2].x = -Width; pQuad->m_aPoints[1].x = pQuad->m_aPoints[3].x = Width; pQuad->m_aPoints[0].y = pQuad->m_aPoints[1].y = -Height; pQuad->m_aPoints[2].y = pQuad->m_aPoints[3].y = Height; pQuad->m_aPoints[4].x = pQuad->m_aPoints[4].y = 0; pQuad->m_aColors[0].r = pQuad->m_aColors[1].r = 94; pQuad->m_aColors[0].g = pQuad->m_aColors[1].g = 132; pQuad->m_aColors[0].b = pQuad->m_aColors[1].b = 174; pQuad->m_aColors[2].r = pQuad->m_aColors[3].r = 204; pQuad->m_aColors[2].g = pQuad->m_aColors[3].g = 232; pQuad->m_aColors[2].b = pQuad->m_aColors[3].b = 255; pGroup->AddLayer(pLayer); // add game layer MakeGameGroup(NewGroup()); MakeGameLayer(new CLayerGame(50, 50)); m_pGameGroup->AddLayer(m_pGameLayer); } void CEditor::Init() { m_pInput = Kernel()->RequestInterface<IInput>(); m_pClient = Kernel()->RequestInterface<IClient>(); m_pConsole = Kernel()->RequestInterface<IConsole>(); m_pGraphics = Kernel()->RequestInterface<IGraphics>(); m_pTextRender = Kernel()->RequestInterface<ITextRender>(); m_pStorage = Kernel()->RequestInterface<IStorage>(); m_RenderTools.m_pGraphics = m_pGraphics; m_RenderTools.m_pUI = &m_UI; m_UI.SetGraphics(m_pGraphics, m_pTextRender); m_Map.m_pEditor = this; m_CheckerTexture = Graphics()->LoadTexture("editor/checker.png", IStorage::TYPE_ALL, CImageInfo::FORMAT_AUTO, 0); m_BackgroundTexture = Graphics()->LoadTexture("editor/background.png", IStorage::TYPE_ALL, CImageInfo::FORMAT_AUTO, 0); m_CursorTexture = Graphics()->LoadTexture("editor/cursor.png", IStorage::TYPE_ALL, CImageInfo::FORMAT_AUTO, 0); m_EntitiesTexture = Graphics()->LoadTexture("editor/entities.png", IStorage::TYPE_ALL, CImageInfo::FORMAT_AUTO, 0); m_TilesetPicker.m_pEditor = this; m_TilesetPicker.MakePalette(); m_TilesetPicker.m_Readonly = true; m_Brush.m_pMap = &m_Map; Reset(); m_Map.m_Modified = false; } void CEditor::DoMapBorder() { CLayerTiles *pT = (CLayerTiles *)GetSelectedLayerType(0, LAYERTYPE_TILES); for(int i = 0; i < pT->m_Width*2; ++i) pT->m_pTiles[i].m_Index = 1; for(int i = 0; i < pT->m_Width*pT->m_Height; ++i) { if(i%pT->m_Width < 2 || i%pT->m_Width > pT->m_Width-3) pT->m_pTiles[i].m_Index = 1; } for(int i = (pT->m_Width*(pT->m_Height-2)); i < pT->m_Width*pT->m_Height; ++i) pT->m_pTiles[i].m_Index = 1; } void CEditor::UpdateAndRender() { static float s_MouseX = 0.0f; static float s_MouseY = 0.0f; if(m_Animate) m_AnimateTime = (time_get()-m_AnimateStart)/(float)time_freq(); else m_AnimateTime = 0; ms_pUiGotContext = 0; // handle mouse movement float mx, my, Mwx, Mwy; float rx, ry; { Input()->MouseRelative(&rx, &ry); UI()->ConvertMouseMove(&rx, &ry); m_MouseDeltaX = rx; m_MouseDeltaY = ry; if(!m_LockMouse) { s_MouseX += rx; s_MouseY += ry; } s_MouseX = clamp(s_MouseX, 0.0f, UI()->Screen()->w); s_MouseY = clamp(s_MouseY, 0.0f, UI()->Screen()->h); // update the ui mx = s_MouseX; my = s_MouseY; Mwx = 0; Mwy = 0; // fix correct world x and y CLayerGroup *g = GetSelectedGroup(); if(g) { float aPoints[4]; g->Mapping(aPoints); float WorldWidth = aPoints[2]-aPoints[0]; float WorldHeight = aPoints[3]-aPoints[1]; Mwx = aPoints[0] + WorldWidth * (s_MouseX/UI()->Screen()->w); Mwy = aPoints[1] + WorldHeight * (s_MouseY/UI()->Screen()->h); m_MouseDeltaWx = m_MouseDeltaX*(WorldWidth / UI()->Screen()->w); m_MouseDeltaWy = m_MouseDeltaY*(WorldHeight / UI()->Screen()->h); } int Buttons = 0; if(Input()->KeyPressed(KEY_MOUSE_1)) Buttons |= 1; if(Input()->KeyPressed(KEY_MOUSE_2)) Buttons |= 2; if(Input()->KeyPressed(KEY_MOUSE_3)) Buttons |= 4; UI()->Update(mx,my,Mwx,Mwy,Buttons); } // toggle gui if(Input()->KeyDown(KEY_TAB)) m_GuiActive = !m_GuiActive; if(Input()->KeyDown(KEY_F10)) m_ShowMousePointer = false; Render(); if(Input()->KeyDown(KEY_F10)) { Graphics()->TakeScreenshot(0); m_ShowMousePointer = true; } Input()->ClearEvents(); } IEditor *CreateEditor() { return new CEditor; } ================================================ FILE: src/game/editor/editor.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_EDITOR_EDITOR_H #define GAME_EDITOR_EDITOR_H #include <math.h> #include <base/math.h> #include <base/system.h> #include <base/tl/algorithm.h> #include <base/tl/array.h> #include <base/tl/sorted_array.h> #include <base/tl/string.h> #include <game/client/ui.h> #include <game/mapitems.h> #include <game/client/render.h> #include <engine/shared/config.h> #include <engine/shared/datafile.h> #include <engine/editor.h> #include <engine/graphics.h> #include "auto_map.h" typedef void (*INDEX_MODIFY_FUNC)(int *pIndex); //CRenderTools m_RenderTools; // CEditor SPECIFIC enum { MODE_LAYERS=0, MODE_IMAGES, DIALOG_NONE=0, DIALOG_FILE, }; struct CEntity { CPoint m_Position; int m_Type; }; class CEnvelope { public: int m_Channels; array<CEnvPoint> m_lPoints; char m_aName[32]; float m_Bottom, m_Top; bool m_Synchronized; CEnvelope(int Chan) { m_Channels = Chan; m_aName[0] = 0; m_Bottom = 0; m_Top = 0; m_Synchronized = true; } void Resort() { sort(m_lPoints.all()); FindTopBottom(0xf); } void FindTopBottom(int ChannelMask) { m_Top = -1000000000.0f; m_Bottom = 1000000000.0f; for(int i = 0; i < m_lPoints.size(); i++) { for(int c = 0; c < m_Channels; c++) { if(ChannelMask&(1<<c)) { float v = fx2f(m_lPoints[i].m_aValues[c]); if(v > m_Top) m_Top = v; if(v < m_Bottom) m_Bottom = v; } } } } int Eval(float Time, float *pResult) { CRenderTools::RenderEvalEnvelope(m_lPoints.base_ptr(), m_lPoints.size(), m_Channels, Time, pResult); return m_Channels; } void AddPoint(int Time, int v0, int v1=0, int v2=0, int v3=0) { CEnvPoint p; p.m_Time = Time; p.m_aValues[0] = v0; p.m_aValues[1] = v1; p.m_aValues[2] = v2; p.m_aValues[3] = v3; p.m_Curvetype = CURVETYPE_LINEAR; m_lPoints.add(p); Resort(); } float EndTime() { if(m_lPoints.size()) return m_lPoints[m_lPoints.size()-1].m_Time*(1.0f/1000.0f); return 0; } }; class CLayer; class CLayerGroup; class CEditorMap; class CLayer { public: class CEditor *m_pEditor; class IGraphics *Graphics(); class ITextRender *TextRender(); CLayer() { m_Type = LAYERTYPE_INVALID; str_copy(m_aName, "(invalid)", sizeof(m_aName)); m_Visible = true; m_Readonly = false; m_SaveToMap = true; m_Flags = 0; m_pEditor = 0; } virtual ~CLayer() { } virtual void BrushSelecting(CUIRect Rect) {} virtual int BrushGrab(CLayerGroup *pBrush, CUIRect Rect) { return 0; } virtual void FillSelection(bool Empty, CLayer *pBrush, CUIRect Rect) {} virtual void BrushDraw(CLayer *pBrush, float x, float y) {} virtual void BrushPlace(CLayer *pBrush, float x, float y) {} virtual void BrushFlipX() {} virtual void BrushFlipY() {} virtual void BrushRotate(float Amount) {} virtual void Render() {} virtual int RenderProperties(CUIRect *pToolbox) { return 0; } virtual void ModifyImageIndex(INDEX_MODIFY_FUNC pfnFunc) {} virtual void ModifyEnvelopeIndex(INDEX_MODIFY_FUNC pfnFunc) {} virtual void GetSize(float *w, float *h) { *w = 0; *h = 0;} char m_aName[12]; int m_Type; int m_Flags; bool m_Readonly; bool m_Visible; bool m_SaveToMap; }; class CLayerGroup { public: class CEditorMap *m_pMap; array<CLayer*> m_lLayers; int m_OffsetX; int m_OffsetY; int m_ParallaxX; int m_ParallaxY; int m_UseClipping; int m_ClipX; int m_ClipY; int m_ClipW; int m_ClipH; char m_aName[12]; bool m_GameGroup; bool m_Visible; bool m_SaveToMap; bool m_Collapse; CLayerGroup(); ~CLayerGroup(); void Convert(CUIRect *pRect); void Render(); void MapScreen(); void Mapping(float *pPoints); void GetSize(float *w, float *h); void DeleteLayer(int Index); int SwapLayers(int Index0, int Index1); bool IsEmpty() const { return m_lLayers.size() == 0; } void Clear() { m_lLayers.delete_all(); } void AddLayer(CLayer *l); void ModifyImageIndex(INDEX_MODIFY_FUNC Func) { for(int i = 0; i < m_lLayers.size(); i++) m_lLayers[i]->ModifyImageIndex(Func); } void ModifyEnvelopeIndex(INDEX_MODIFY_FUNC Func) { for(int i = 0; i < m_lLayers.size(); i++) m_lLayers[i]->ModifyEnvelopeIndex(Func); } }; class CEditorImage : public CImageInfo { public: CEditor *m_pEditor; CEditorImage(CEditor *pEditor) { m_pEditor = pEditor; m_aName[0] = 0; m_External = 0; m_Width = 0; m_Height = 0; m_pData = 0; m_Format = 0; m_pAutoMapper = 0; } ~CEditorImage(); void AnalyseTileFlags(); void LoadAutoMapper(); IGraphics::CTextureHandle m_Texture; int m_External; char m_aName[128]; unsigned char m_aTileFlags[256]; class IAutoMapper *m_pAutoMapper; }; class CEditorMap { void MakeGameGroup(CLayerGroup *pGroup); void MakeGameLayer(CLayer *pLayer); public: CEditor *m_pEditor; bool m_Modified; CEditorMap() { Clean(); } array<CLayerGroup*> m_lGroups; array<CEditorImage*> m_lImages; array<CEnvelope*> m_lEnvelopes; class CMapInfo { public: char m_aAuthorTmp[32]; char m_aVersionTmp[16]; char m_aCreditsTmp[128]; char m_aLicenseTmp[32]; char m_aAuthor[32]; char m_aVersion[16]; char m_aCredits[128]; char m_aLicense[32]; void Reset() { m_aAuthorTmp[0] = 0; m_aVersionTmp[0] = 0; m_aCreditsTmp[0] = 0; m_aLicenseTmp[0] = 0; m_aAuthor[0] = 0; m_aVersion[0] = 0; m_aCredits[0] = 0; m_aLicense[0] = 0; } }; CMapInfo m_MapInfo; class CLayerGame *m_pGameLayer; CLayerGroup *m_pGameGroup; CEnvelope *NewEnvelope(int Channels) { m_Modified = true; CEnvelope *e = new CEnvelope(Channels); m_lEnvelopes.add(e); return e; } void DeleteEnvelope(int Index); CLayerGroup *NewGroup() { m_Modified = true; CLayerGroup *g = new CLayerGroup; g->m_pMap = this; m_lGroups.add(g); return g; } int SwapGroups(int Index0, int Index1) { if(Index0 < 0 || Index0 >= m_lGroups.size()) return Index0; if(Index1 < 0 || Index1 >= m_lGroups.size()) return Index0; if(Index0 == Index1) return Index0; m_Modified = true; swap(m_lGroups[Index0], m_lGroups[Index1]); return Index1; } void DeleteGroup(int Index) { if(Index < 0 || Index >= m_lGroups.size()) return; m_Modified = true; delete m_lGroups[Index]; m_lGroups.remove_index(Index); } void ModifyImageIndex(INDEX_MODIFY_FUNC pfnFunc) { m_Modified = true; for(int i = 0; i < m_lGroups.size(); i++) m_lGroups[i]->ModifyImageIndex(pfnFunc); } void ModifyEnvelopeIndex(INDEX_MODIFY_FUNC pfnFunc) { m_Modified = true; for(int i = 0; i < m_lGroups.size(); i++) m_lGroups[i]->ModifyEnvelopeIndex(pfnFunc); } void Clean(); void CreateDefault(IGraphics::CTextureHandle EntitiesTexture); // io int Save(class IStorage *pStorage, const char *pFilename); int Load(class IStorage *pStorage, const char *pFilename, int StorageType); }; struct CProperty { const char *m_pName; int m_Value; int m_Type; int m_Min; int m_Max; }; enum { PROPTYPE_NULL=0, PROPTYPE_BOOL, PROPTYPE_INT_STEP, PROPTYPE_INT_SCROLL, PROPTYPE_COLOR, PROPTYPE_IMAGE, PROPTYPE_ENVELOPE, PROPTYPE_SHIFT, }; typedef struct { int x, y; int w, h; } RECTi; class CLayerTiles : public CLayer { public: CLayerTiles(int w, int h); ~CLayerTiles(); void Resize(int NewW, int NewH); void Shift(int Direction); void MakePalette(); virtual void Render(); int ConvertX(float x) const; int ConvertY(float y) const; void Convert(CUIRect Rect, RECTi *pOut); void Snap(CUIRect *pRect); void Clamp(RECTi *pRect); virtual void BrushSelecting(CUIRect Rect); virtual int BrushGrab(CLayerGroup *pBrush, CUIRect Rect); virtual void FillSelection(bool Empty, CLayer *pBrush, CUIRect Rect); virtual void BrushDraw(CLayer *pBrush, float wx, float wy); virtual void BrushFlipX(); virtual void BrushFlipY(); virtual void BrushRotate(float Amount); virtual void ShowInfo(); virtual int RenderProperties(CUIRect *pToolbox); virtual void ModifyImageIndex(INDEX_MODIFY_FUNC pfnFunc); virtual void ModifyEnvelopeIndex(INDEX_MODIFY_FUNC pfnFunc); void PrepareForSave(); void GetSize(float *w, float *h) { *w = m_Width*32.0f; *h = m_Height*32.0f; } IGraphics::CTextureHandle m_Texture; int m_Game; int m_Image; int m_Width; int m_Height; CColor m_Color; int m_ColorEnv; int m_ColorEnvOffset; CTile *m_pTiles; int m_SelectedRuleSet; int m_SelectedAmount; }; class CLayerQuads : public CLayer { public: CLayerQuads(); ~CLayerQuads(); virtual void Render(); CQuad *NewQuad(); virtual void BrushSelecting(CUIRect Rect); virtual int BrushGrab(CLayerGroup *pBrush, CUIRect Rect); virtual void BrushPlace(CLayer *pBrush, float wx, float wy); virtual void BrushFlipX(); virtual void BrushFlipY(); virtual void BrushRotate(float Amount); virtual int RenderProperties(CUIRect *pToolbox); virtual void ModifyImageIndex(INDEX_MODIFY_FUNC pfnFunc); virtual void ModifyEnvelopeIndex(INDEX_MODIFY_FUNC pfnFunc); void GetSize(float *w, float *h); int m_Image; array<CQuad> m_lQuads; }; class CLayerGame : public CLayerTiles { public: CLayerGame(int w, int h); ~CLayerGame(); virtual int RenderProperties(CUIRect *pToolbox); }; class CEditor : public IEditor { class IInput *m_pInput; class IClient *m_pClient; class IConsole *m_pConsole; class IGraphics *m_pGraphics; class ITextRender *m_pTextRender; class IStorage *m_pStorage; CRenderTools m_RenderTools; CUI m_UI; public: class IInput *Input() { return m_pInput; }; class IClient *Client() { return m_pClient; }; class IConsole *Console() { return m_pConsole; }; class IGraphics *Graphics() { return m_pGraphics; }; class ITextRender *TextRender() { return m_pTextRender; }; class IStorage *Storage() { return m_pStorage; }; CUI *UI() { return &m_UI; } CRenderTools *RenderTools() { return &m_RenderTools; } CEditor() : m_TilesetPicker(16, 16) { m_pInput = 0; m_pClient = 0; m_pGraphics = 0; m_pTextRender = 0; m_Mode = MODE_LAYERS; m_Dialog = 0; m_EditBoxActive = 0; m_pTooltip = 0; m_GridActive = false; m_GridFactor = 1; m_aFileName[0] = 0; m_aFileSaveName[0] = 0; m_ValidSaveFilename = false; m_PopupEventActivated = false; m_PopupEventWasActivated = false; m_FileDialogStorageType = 0; m_pFileDialogTitle = 0; m_pFileDialogButtonText = 0; m_pFileDialogUser = 0; m_aFileDialogFileName[0] = 0; m_aFileDialogCurrentFolder[0] = 0; m_aFileDialogCurrentLink[0] = 0; m_pFileDialogPath = m_aFileDialogCurrentFolder; m_aFileDialogActivate = false; m_FileDialogScrollValue = 0.0f; m_FilesSelectedIndex = -1; m_FilesStartAt = 0; m_FilesCur = 0; m_FilesStopAt = 999; m_WorldOffsetX = 0; m_WorldOffsetY = 0; m_EditorOffsetX = 0.0f; m_EditorOffsetY = 0.0f; m_WorldZoom = 1.0f; m_ZoomLevel = 200; m_LockMouse = false; m_ShowMousePointer = true; m_MouseDeltaX = 0; m_MouseDeltaY = 0; m_MouseDeltaWx = 0; m_MouseDeltaWy = 0; m_GuiActive = true; m_ProofBorders = false; m_ShowTileInfo = false; m_ShowDetail = true; m_Animate = false; m_AnimateStart = 0; m_AnimateTime = 0; m_AnimateSpeed = 1; m_ShowEnvelopeEditor = 0; m_ShowEnvelopePreview = 0; m_SelectedQuadEnvelope = -1; m_SelectedEnvelopePoint = -1; ms_pUiGotContext = 0; } virtual void Init(); virtual void UpdateAndRender(); virtual bool HasUnsavedData() { return m_Map.m_Modified; } void FilelistPopulate(int StorageType); void InvokeFileDialog(int StorageType, int FileType, const char *pTitle, const char *pButtonText, const char *pBasepath, const char *pDefaultName, void (*pfnFunc)(const char *pFilename, int StorageType, void *pUser), void *pUser); void Reset(bool CreateDefault=true); int Save(const char *pFilename); int Load(const char *pFilename, int StorageType); int Append(const char *pFilename, int StorageType); void Render(); CQuad *GetSelectedQuad(); CLayer *GetSelectedLayerType(int Index, int Type); CLayer *GetSelectedLayer(int Index); CLayerGroup *GetSelectedGroup(); int DoProperties(CUIRect *pToolbox, CProperty *pProps, int *pIDs, int *pNewVal); int m_Mode; int m_Dialog; int m_EditBoxActive; const char *m_pTooltip; bool m_GridActive; int m_GridFactor; char m_aFileName[512]; char m_aFileSaveName[512]; bool m_ValidSaveFilename; enum { POPEVENT_EXIT=0, POPEVENT_LOAD, POPEVENT_NEW, POPEVENT_SAVE, }; int m_PopupEventType; int m_PopupEventActivated; int m_PopupEventWasActivated; enum { FILETYPE_MAP, FILETYPE_IMG, MAX_PATH_LENGTH = 512 }; int m_FileDialogStorageType; const char *m_pFileDialogTitle; const char *m_pFileDialogButtonText; void (*m_pfnFileDialogFunc)(const char *pFileName, int StorageType, void *pUser); void *m_pFileDialogUser; char m_aFileDialogFileName[MAX_PATH_LENGTH]; char m_aFileDialogCurrentFolder[MAX_PATH_LENGTH]; char m_aFileDialogCurrentLink[MAX_PATH_LENGTH]; char *m_pFileDialogPath; bool m_aFileDialogActivate; int m_FileDialogFileType; float m_FileDialogScrollValue; int m_FilesSelectedIndex; char m_FileDialogNewFolderName[64]; char m_FileDialogErrString[64]; struct CFilelistItem { char m_aFilename[128]; char m_aName[128]; bool m_IsDir; bool m_IsLink; int m_StorageType; bool operator<(const CFilelistItem &Other) { return !str_comp(m_aFilename, "..") ? true : !str_comp(Other.m_aFilename, "..") ? false : m_IsDir && !Other.m_IsDir ? true : !m_IsDir && Other.m_IsDir ? false : str_comp_filenames(m_aFilename, Other.m_aFilename) < 0; } }; sorted_array<CFilelistItem> m_FileList; int m_FilesStartAt; int m_FilesCur; int m_FilesStopAt; float m_WorldOffsetX; float m_WorldOffsetY; float m_EditorOffsetX; float m_EditorOffsetY; float m_WorldZoom; int m_ZoomLevel; bool m_LockMouse; bool m_ShowMousePointer; bool m_GuiActive; bool m_ProofBorders; float m_MouseDeltaX; float m_MouseDeltaY; float m_MouseDeltaWx; float m_MouseDeltaWy; bool m_ShowTileInfo; bool m_ShowDetail; bool m_Animate; int64 m_AnimateStart; float m_AnimateTime; float m_AnimateSpeed; int m_ShowEnvelopeEditor; int m_ShowEnvelopePreview; //Values: 0-Off|1-Selected Envelope|2-All bool m_ShowPicker; int m_SelectedLayer; int m_SelectedGroup; int m_SelectedQuad; int m_SelectedPoints; int m_SelectedEnvelope; int m_SelectedEnvelopePoint; int m_SelectedQuadEnvelope; int m_SelectedImage; IGraphics::CTextureHandle m_CheckerTexture; IGraphics::CTextureHandle m_BackgroundTexture; IGraphics::CTextureHandle m_CursorTexture; IGraphics::CTextureHandle m_EntitiesTexture; CLayerGroup m_Brush; CLayerTiles m_TilesetPicker; static const void *ms_pUiGotContext; CEditorMap m_Map; static void EnvelopeEval(float TimeOffset, int Env, float *pChannels, void *pUser); void DoMapBorder(); int DoButton_Editor_Common(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip); int DoButton_Editor(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip); int DoButton_Tab(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip); int DoButton_Ex(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip, int Corners, float FontSize=10.0f); int DoButton_ButtonDec(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip); int DoButton_ButtonInc(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip); int DoButton_File(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip); int DoButton_Menu(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip); int DoButton_MenuItem(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags=0, const char *pToolTip=0); int DoEditBox(void *pID, const CUIRect *pRect, char *pStr, unsigned StrSize, float FontSize, float *Offset, bool Hidden=false, int Corners=CUI::CORNER_ALL); void RenderBackground(CUIRect View, IGraphics::CTextureHandle Texture, float Size, float Brightness); void RenderGrid(CLayerGroup *pGroup); void UiInvokePopupMenu(void *pID, int Flags, float X, float Y, float W, float H, int (*pfnFunc)(CEditor *pEditor, CUIRect Rect), void *pExtra=0); void UiDoPopupMenu(); int UiDoValueSelector(void *pID, CUIRect *pRect, const char *pLabel, int Current, int Min, int Max, int Step, float Scale, const char *pToolTip); static int PopupGroup(CEditor *pEditor, CUIRect View); static int PopupLayer(CEditor *pEditor, CUIRect View); static int PopupQuad(CEditor *pEditor, CUIRect View); static int PopupPoint(CEditor *pEditor, CUIRect View); static int PopupNewFolder(CEditor *pEditor, CUIRect View); static int PopupMapInfo(CEditor *pEditor, CUIRect View); static int PopupEvent(CEditor *pEditor, CUIRect View); static int PopupSelectImage(CEditor *pEditor, CUIRect View); static int PopupSelectGametileOp(CEditor *pEditor, CUIRect View); static int PopupImage(CEditor *pEditor, CUIRect View); static int PopupMenuFile(CEditor *pEditor, CUIRect View); static int PopupSelectConfigAutoMap(CEditor *pEditor, CUIRect View); static int PopupSelectDoodadRuleSet(CEditor *pEditor, CUIRect View); static int PopupDoodadAutoMap(CEditor *pEditor, CUIRect View); static void CallbackOpenMap(const char *pFileName, int StorageType, void *pUser); static void CallbackAppendMap(const char *pFileName, int StorageType, void *pUser); static void CallbackSaveMap(const char *pFileName, int StorageType, void *pUser); void PopupSelectImageInvoke(int Current, float x, float y); int PopupSelectImageResult(); void PopupSelectGametileOpInvoke(float x, float y); int PopupSelectGameTileOpResult(); void PopupSelectConfigAutoMapInvoke(float x, float y); bool PopupAutoMapProceedOrder(); vec4 ButtonColorMul(const void *pID); void DoQuadEnvelopes(const array<CQuad> &m_lQuads, IGraphics::CTextureHandle Texture); void DoQuadEnvPoint(const CQuad *pQuad, int QIndex, int pIndex); void DoQuadPoint(CQuad *pQuad, int QuadIndex, int v); void DoMapEditor(CUIRect View, CUIRect Toolbar); void DoToolbar(CUIRect Toolbar); void DoQuad(CQuad *pQuad, int Index); float UiDoScrollbarV(const void *pID, const CUIRect *pRect, float Current); vec4 GetButtonColor(const void *pID, int Checked); static void ReplaceImage(const char *pFilename, int StorageType, void *pUser); static void AddImage(const char *pFilename, int StorageType, void *pUser); void RenderImages(CUIRect Toolbox, CUIRect Toolbar, CUIRect View); void RenderLayers(CUIRect Toolbox, CUIRect Toolbar, CUIRect View); void RenderModebar(CUIRect View); void RenderStatusbar(CUIRect View); void RenderEnvelopeEditor(CUIRect View); void RenderMenubar(CUIRect Menubar); void RenderFileDialog(); void AddFileDialogEntry(int Index, CUIRect *pView); void SortImages(); static void ExtractName(const char *pFileName, char *pName, int BufferSize) { const char *pExtractedName = pFileName; const char *pEnd = 0; for(; *pFileName; ++pFileName) { if(*pFileName == '/' || *pFileName == '\\') pExtractedName = pFileName+1; else if(*pFileName == '.') pEnd = pFileName; } int Length = pEnd > pExtractedName ? min(BufferSize, (int)(pEnd-pExtractedName+1)) : BufferSize; str_copy(pName, pExtractedName, Length); } int GetLineDistance(); }; // make sure to inline this function inline class IGraphics *CLayer::Graphics() { return m_pEditor->Graphics(); } inline class ITextRender *CLayer::TextRender() { return m_pEditor->TextRender(); } #endif ================================================ FILE: src/game/editor/io.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <engine/client.h> #include <engine/console.h> #include <engine/graphics.h> #include <engine/serverbrowser.h> #include <engine/storage.h> #include <game/gamecore.h> #include "editor.h" template<typename T> static int MakeVersion(int i, const T &v) { return (i<<16)+sizeof(T); } // backwards compatiblity /* void editor_load_old(DATAFILE *df, MAP *map) { class mapres_image { public: int width; int height; int image_data; }; struct mapres_tilemap { int image; int width; int height; int x, y; int scale; int data; int main; }; struct mapres_entity { int x, y; int data[1]; }; struct mapres_spawnpoint { int x, y; }; struct mapres_item { int x, y; int type; }; struct mapres_flagstand { int x, y; }; enum { MAPRES_ENTS_START=1, MAPRES_SPAWNPOINT=1, MAPRES_ITEM=2, MAPRES_SPAWNPOINT_RED=3, MAPRES_SPAWNPOINT_BLUE=4, MAPRES_FLAGSTAND_RED=5, MAPRES_FLAGSTAND_BLUE=6, MAPRES_ENTS_END, ITEM_NULL=0, ITEM_WEAPON_GUN=0x00010001, ITEM_WEAPON_SHOTGUN=0x00010002, ITEM_WEAPON_ROCKET=0x00010003, ITEM_WEAPON_SNIPER=0x00010004, ITEM_WEAPON_HAMMER=0x00010005, ITEM_HEALTH =0x00020001, ITEM_ARMOR=0x00030001, ITEM_NINJA=0x00040001, }; enum { MAPRES_REGISTERED=0x8000, MAPRES_IMAGE=0x8001, MAPRES_TILEMAP=0x8002, MAPRES_COLLISIONMAP=0x8003, MAPRES_TEMP_THEME=0x8fff, }; // load tilemaps int game_width = 0; int game_height = 0; { int start, num; datafile_get_type(df, MAPRES_TILEMAP, &start, &num); for(int t = 0; t < num; t++) { mapres_tilemap *tmap = (mapres_tilemap *)datafile_get_item(df, start+t,0,0); CLayerTiles *l = new CLayerTiles(tmap->width, tmap->height); if(tmap->main) { // move game layer to correct position for(int i = 0; i < map->groups[0]->layers.len()-1; i++) { if(map->groups[0]->layers[i] == pEditor->map.game_layer) map->groups[0]->swap_layers(i, i+1); } game_width = tmap->width; game_height = tmap->height; } // add new layer map->groups[0]->add_layer(l); // process the data unsigned char *src_data = (unsigned char *)datafile_get_data(df, tmap->data); CTile *dst_data = l->tiles; for(int y = 0; y < tmap->height; y++) for(int x = 0; x < tmap->width; x++, dst_data++, src_data+=2) { dst_data->index = src_data[0]; dst_data->flags = src_data[1]; } l->image = tmap->image; } } // load images { int start, count; datafile_get_type(df, MAPRES_IMAGE, &start, &count); for(int i = 0; i < count; i++) { mapres_image *imgres = (mapres_image *)datafile_get_item(df, start+i, 0, 0); void *data = datafile_get_data(df, imgres->image_data); EDITOR_IMAGE *img = new EDITOR_IMAGE; img->width = imgres->width; img->height = imgres->height; img->format = CImageInfo::FORMAT_RGBA; // copy image data img->data = mem_alloc(img->width*img->height*4, 1); mem_copy(img->data, data, img->width*img->height*4); img->tex_id = Graphics()->LoadTextureRaw(img->width, img->height, img->format, img->data, CImageInfo::FORMAT_AUTO, 0); map->images.add(img); // unload image datafile_unload_data(df, imgres->image_data); } } // load entities { CLayerGame *g = map->game_layer; g->resize(game_width, game_height); for(int t = MAPRES_ENTS_START; t < MAPRES_ENTS_END; t++) { // fetch entities of this class int start, num; datafile_get_type(df, t, &start, &num); for(int i = 0; i < num; i++) { mapres_entity *e = (mapres_entity *)datafile_get_item(df, start+i,0,0); int x = e->x/32; int y = e->y/32; int id = -1; if(t == MAPRES_SPAWNPOINT) id = ENTITY_SPAWN; else if(t == MAPRES_SPAWNPOINT_RED) id = ENTITY_SPAWN_RED; else if(t == MAPRES_SPAWNPOINT_BLUE) id = ENTITY_SPAWN_BLUE; else if(t == MAPRES_FLAGSTAND_RED) id = ENTITY_FLAGSTAND_RED; else if(t == MAPRES_FLAGSTAND_BLUE) id = ENTITY_FLAGSTAND_BLUE; else if(t == MAPRES_ITEM) { if(e->data[0] == ITEM_WEAPON_SHOTGUN) id = ENTITY_WEAPON_SHOTGUN; else if(e->data[0] == ITEM_WEAPON_ROCKET) id = ENTITY_WEAPON_GRENADE; else if(e->data[0] == ITEM_NINJA) id = ENTITY_POWERUP_NINJA; else if(e->data[0] == ITEM_ARMOR) id = ENTITY_ARMOR_1; else if(e->data[0] == ITEM_HEALTH) id = ENTITY_HEALTH_1; } if(id > 0 && x >= 0 && x < g->width && y >= 0 && y < g->height) g->tiles[y*g->width+x].index = id+ENTITY_OFFSET; } } } }*/ int CEditor::Save(const char *pFilename) { return m_Map.Save(Kernel()->RequestInterface<IStorage>(), pFilename); } int CEditorMap::Save(class IStorage *pStorage, const char *pFileName) { char aBuf[256]; str_format(aBuf, sizeof(aBuf), "saving to '%s'...", pFileName); m_pEditor->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "editor", aBuf); CDataFileWriter df; if(!df.Open(pStorage, pFileName)) { str_format(aBuf, sizeof(aBuf), "failed to open file '%s'...", pFileName); m_pEditor->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "editor", aBuf); return 0; } // save version { CMapItemVersion Item; Item.m_Version = 1; df.AddItem(MAPITEMTYPE_VERSION, 0, sizeof(Item), &Item); } // save map info { CMapItemInfo Item; Item.m_Version = 1; if(m_MapInfo.m_aAuthor[0]) Item.m_Author = df.AddData(str_length(m_MapInfo.m_aAuthor)+1, m_MapInfo.m_aAuthor); else Item.m_Author = -1; if(m_MapInfo.m_aVersion[0]) Item.m_MapVersion = df.AddData(str_length(m_MapInfo.m_aVersion)+1, m_MapInfo.m_aVersion); else Item.m_MapVersion = -1; if(m_MapInfo.m_aCredits[0]) Item.m_Credits = df.AddData(str_length(m_MapInfo.m_aCredits)+1, m_MapInfo.m_aCredits); else Item.m_Credits = -1; if(m_MapInfo.m_aLicense[0]) Item.m_License = df.AddData(str_length(m_MapInfo.m_aLicense)+1, m_MapInfo.m_aLicense); else Item.m_License = -1; df.AddItem(MAPITEMTYPE_INFO, 0, sizeof(Item), &Item); } // save images for(int i = 0; i < m_lImages.size(); i++) { CEditorImage *pImg = m_lImages[i]; // analyse the image for when saving (should be done when we load the image) // TODO! pImg->AnalyseTileFlags(); CMapItemImage Item; Item.m_Version = CMapItemImage::CURRENT_VERSION; Item.m_Width = pImg->m_Width; Item.m_Height = pImg->m_Height; Item.m_External = pImg->m_External; Item.m_ImageName = df.AddData(str_length(pImg->m_aName)+1, pImg->m_aName); if(pImg->m_External) Item.m_ImageData = -1; else { int PixelSize = pImg->m_Format == CImageInfo::FORMAT_RGB ? 3 : 4; Item.m_ImageData = df.AddData(Item.m_Width*Item.m_Height*PixelSize, pImg->m_pData); } Item.m_Format = pImg->m_Format; df.AddItem(MAPITEMTYPE_IMAGE, i, sizeof(Item), &Item); } // save layers int LayerCount = 0, GroupCount = 0; for(int g = 0; g < m_lGroups.size(); g++) { CLayerGroup *pGroup = m_lGroups[g]; if(!pGroup->m_SaveToMap) continue; CMapItemGroup GItem; GItem.m_Version = CMapItemGroup::CURRENT_VERSION; GItem.m_ParallaxX = pGroup->m_ParallaxX; GItem.m_ParallaxY = pGroup->m_ParallaxY; GItem.m_OffsetX = pGroup->m_OffsetX; GItem.m_OffsetY = pGroup->m_OffsetY; GItem.m_UseClipping = pGroup->m_UseClipping; GItem.m_ClipX = pGroup->m_ClipX; GItem.m_ClipY = pGroup->m_ClipY; GItem.m_ClipW = pGroup->m_ClipW; GItem.m_ClipH = pGroup->m_ClipH; GItem.m_StartLayer = LayerCount; GItem.m_NumLayers = 0; // save group name StrToInts(GItem.m_aName, sizeof(GItem.m_aName)/sizeof(int), pGroup->m_aName); for(int l = 0; l < pGroup->m_lLayers.size(); l++) { if(!pGroup->m_lLayers[l]->m_SaveToMap) continue; if(pGroup->m_lLayers[l]->m_Type == LAYERTYPE_TILES) { m_pEditor->Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "editor", "saving tiles layer"); CLayerTiles *pLayer = (CLayerTiles *)pGroup->m_lLayers[l]; pLayer->PrepareForSave(); CMapItemLayerTilemap Item; Item.m_Version = 3; Item.m_Layer.m_Flags = pLayer->m_Flags; Item.m_Layer.m_Type = pLayer->m_Type; Item.m_Color = pLayer->m_Color; Item.m_ColorEnv = pLayer->m_ColorEnv; Item.m_ColorEnvOffset = pLayer->m_ColorEnvOffset; Item.m_Width = pLayer->m_Width; Item.m_Height = pLayer->m_Height; Item.m_Flags = pLayer->m_Game ? TILESLAYERFLAG_GAME : 0; Item.m_Image = pLayer->m_Image; Item.m_Data = df.AddData(pLayer->m_Width*pLayer->m_Height*sizeof(CTile), pLayer->m_pTiles); // save layer name StrToInts(Item.m_aName, sizeof(Item.m_aName)/sizeof(int), pLayer->m_aName); df.AddItem(MAPITEMTYPE_LAYER, LayerCount, sizeof(Item), &Item); GItem.m_NumLayers++; LayerCount++; } else if(pGroup->m_lLayers[l]->m_Type == LAYERTYPE_QUADS) { m_pEditor->Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "editor", "saving quads layer"); CLayerQuads *pLayer = (CLayerQuads *)pGroup->m_lLayers[l]; if(pLayer->m_lQuads.size()) { CMapItemLayerQuads Item; Item.m_Version = 2; Item.m_Layer.m_Flags = pLayer->m_Flags; Item.m_Layer.m_Type = pLayer->m_Type; Item.m_Image = pLayer->m_Image; // add the data Item.m_NumQuads = pLayer->m_lQuads.size(); Item.m_Data = df.AddDataSwapped(pLayer->m_lQuads.size()*sizeof(CQuad), pLayer->m_lQuads.base_ptr()); // save layer name StrToInts(Item.m_aName, sizeof(Item.m_aName)/sizeof(int), pLayer->m_aName); df.AddItem(MAPITEMTYPE_LAYER, LayerCount, sizeof(Item), &Item); // clean up //mem_free(quads); GItem.m_NumLayers++; LayerCount++; } } } df.AddItem(MAPITEMTYPE_GROUP, GroupCount++, sizeof(GItem), &GItem); } // save envelopes int PointCount = 0; for(int e = 0; e < m_lEnvelopes.size(); e++) { CMapItemEnvelope Item; Item.m_Version = CMapItemEnvelope::CURRENT_VERSION; Item.m_Channels = m_lEnvelopes[e]->m_Channels; Item.m_StartPoint = PointCount; Item.m_NumPoints = m_lEnvelopes[e]->m_lPoints.size(); Item.m_Synchronized = m_lEnvelopes[e]->m_Synchronized; StrToInts(Item.m_aName, sizeof(Item.m_aName)/sizeof(int), m_lEnvelopes[e]->m_aName); df.AddItem(MAPITEMTYPE_ENVELOPE, e, sizeof(Item), &Item); PointCount += Item.m_NumPoints; } // save points int TotalSize = sizeof(CEnvPoint) * PointCount; CEnvPoint *pPoints = (CEnvPoint *)mem_alloc(TotalSize, 1); PointCount = 0; for(int e = 0; e < m_lEnvelopes.size(); e++) { int Count = m_lEnvelopes[e]->m_lPoints.size(); mem_copy(&pPoints[PointCount], m_lEnvelopes[e]->m_lPoints.base_ptr(), sizeof(CEnvPoint)*Count); PointCount += Count; } df.AddItem(MAPITEMTYPE_ENVPOINTS, 0, TotalSize, pPoints); mem_free(pPoints); // finish the data file df.Finish(); m_pEditor->Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "editor", "saving done"); // send rcon.. if we can if(m_pEditor->Client()->RconAuthed()) { CServerInfo CurrentServerInfo; m_pEditor->Client()->GetServerInfo(&CurrentServerInfo); char aMapName[128]; m_pEditor->ExtractName(pFileName, aMapName, sizeof(aMapName)); if(!str_comp(aMapName, CurrentServerInfo.m_aMap)) m_pEditor->Client()->Rcon("reload"); } return 1; } int CEditor::Load(const char *pFileName, int StorageType) { Reset(); return m_Map.Load(Kernel()->RequestInterface<IStorage>(), pFileName, StorageType); } int CEditorMap::Load(class IStorage *pStorage, const char *pFileName, int StorageType) { CDataFileReader DataFile; //DATAFILE *df = datafile_load(filename); if(!DataFile.Open(pStorage, pFileName, StorageType)) return 0; Clean(); // check version CMapItemVersion *pItem = (CMapItemVersion *)DataFile.FindItem(MAPITEMTYPE_VERSION, 0); if(!pItem) { // import old map /*MAP old_mapstuff; editor->reset(); editor_load_old(df, this); */ return 0; } else if(pItem->m_Version == CMapItemVersion::CURRENT_VERSION) { //editor.reset(false); // load map info { CMapItemInfo *pItem = (CMapItemInfo *)DataFile.FindItem(MAPITEMTYPE_INFO, 0); if(pItem && pItem->m_Version == 1) { if(pItem->m_Author > -1) str_copy(m_MapInfo.m_aAuthor, (char *)DataFile.GetData(pItem->m_Author), sizeof(m_MapInfo.m_aAuthor)); if(pItem->m_MapVersion > -1) str_copy(m_MapInfo.m_aVersion, (char *)DataFile.GetData(pItem->m_MapVersion), sizeof(m_MapInfo.m_aVersion)); if(pItem->m_Credits > -1) str_copy(m_MapInfo.m_aCredits, (char *)DataFile.GetData(pItem->m_Credits), sizeof(m_MapInfo.m_aCredits)); if(pItem->m_License > -1) str_copy(m_MapInfo.m_aLicense, (char *)DataFile.GetData(pItem->m_License), sizeof(m_MapInfo.m_aLicense)); } } // load images { int Start, Num; DataFile.GetType( MAPITEMTYPE_IMAGE, &Start, &Num); for(int i = 0; i < Num; i++) { CMapItemImage *pItem = (CMapItemImage *)DataFile.GetItem(Start+i, 0, 0); char *pName = (char *)DataFile.GetData(pItem->m_ImageName); // copy base info CEditorImage *pImg = new CEditorImage(m_pEditor); pImg->m_External = pItem->m_External; if(pItem->m_External || (pItem->m_Version > 1 && pItem->m_Format != CImageInfo::FORMAT_RGB && pItem->m_Format != CImageInfo::FORMAT_RGBA)) { char aBuf[256]; str_format(aBuf, sizeof(aBuf),"mapres/%s.png", pName); // load external CEditorImage ImgInfo(m_pEditor); if(m_pEditor->Graphics()->LoadPNG(&ImgInfo, aBuf, IStorage::TYPE_ALL)) { *pImg = ImgInfo; pImg->m_Texture = m_pEditor->Graphics()->LoadTextureRaw(ImgInfo.m_Width, ImgInfo.m_Height, ImgInfo.m_Format, ImgInfo.m_pData, CImageInfo::FORMAT_AUTO, 0); ImgInfo.m_pData = 0; pImg->m_External = 1; } } else { pImg->m_Width = pItem->m_Width; pImg->m_Height = pItem->m_Height; pImg->m_Format = pItem->m_Version == 1 ? CImageInfo::FORMAT_RGBA : pItem->m_Format; int PixelSize = pImg->m_Format == CImageInfo::FORMAT_RGB ? 3 : 4; // copy image data void *pData = DataFile.GetData(pItem->m_ImageData); pImg->m_pData = mem_alloc(pImg->m_Width*pImg->m_Height*PixelSize, 1); mem_copy(pImg->m_pData, pData, pImg->m_Width*pImg->m_Height*PixelSize); pImg->m_Texture = m_pEditor->Graphics()->LoadTextureRaw(pImg->m_Width, pImg->m_Height, pImg->m_Format, pImg->m_pData, CImageInfo::FORMAT_AUTO, 0); } // copy image name if(pName) str_copy(pImg->m_aName, pName, 128); // load auto mapper file pImg->LoadAutoMapper(); m_lImages.add(pImg); // unload image DataFile.UnloadData(pItem->m_ImageData); DataFile.UnloadData(pItem->m_ImageName); } } // load groups { int LayersStart, LayersNum; DataFile.GetType(MAPITEMTYPE_LAYER, &LayersStart, &LayersNum); int Start, Num; DataFile.GetType(MAPITEMTYPE_GROUP, &Start, &Num); for(int g = 0; g < Num; g++) { CMapItemGroup *pGItem = (CMapItemGroup *)DataFile.GetItem(Start+g, 0, 0); if(pGItem->m_Version < 1 || pGItem->m_Version > CMapItemGroup::CURRENT_VERSION) continue; CLayerGroup *pGroup = NewGroup(); pGroup->m_ParallaxX = pGItem->m_ParallaxX; pGroup->m_ParallaxY = pGItem->m_ParallaxY; pGroup->m_OffsetX = pGItem->m_OffsetX; pGroup->m_OffsetY = pGItem->m_OffsetY; if(pGItem->m_Version >= 2) { pGroup->m_UseClipping = pGItem->m_UseClipping; pGroup->m_ClipX = pGItem->m_ClipX; pGroup->m_ClipY = pGItem->m_ClipY; pGroup->m_ClipW = pGItem->m_ClipW; pGroup->m_ClipH = pGItem->m_ClipH; } // load group name if(pGItem->m_Version >= 3) IntsToStr(pGItem->m_aName, sizeof(pGroup->m_aName)/sizeof(int), pGroup->m_aName); for(int l = 0; l < pGItem->m_NumLayers; l++) { CLayer *pLayer = 0; CMapItemLayer *pLayerItem = (CMapItemLayer *)DataFile.GetItem(LayersStart+pGItem->m_StartLayer+l, 0, 0); if(!pLayerItem) continue; if(pLayerItem->m_Type == LAYERTYPE_TILES) { CMapItemLayerTilemap *pTilemapItem = (CMapItemLayerTilemap *)pLayerItem; CLayerTiles *pTiles = 0; if(pTilemapItem->m_Flags&TILESLAYERFLAG_GAME) { pTiles = new CLayerGame(pTilemapItem->m_Width, pTilemapItem->m_Height); MakeGameLayer(pTiles); MakeGameGroup(pGroup); } else { pTiles = new CLayerTiles(pTilemapItem->m_Width, pTilemapItem->m_Height); pTiles->m_pEditor = m_pEditor; pTiles->m_Color = pTilemapItem->m_Color; pTiles->m_ColorEnv = pTilemapItem->m_ColorEnv; pTiles->m_ColorEnvOffset = pTilemapItem->m_ColorEnvOffset; } pLayer = pTiles; pGroup->AddLayer(pTiles); void *pData = DataFile.GetData(pTilemapItem->m_Data); pTiles->m_Image = pTilemapItem->m_Image; pTiles->m_Game = pTilemapItem->m_Flags&TILESLAYERFLAG_GAME; // load layer name if(pTilemapItem->m_Version >= 3) IntsToStr(pTilemapItem->m_aName, sizeof(pTiles->m_aName)/sizeof(int), pTiles->m_aName); mem_copy(pTiles->m_pTiles, pData, pTiles->m_Width*pTiles->m_Height*sizeof(CTile)); if(pTiles->m_Game && pTilemapItem->m_Version == MakeVersion(1, *pTilemapItem)) { for(int i = 0; i < pTiles->m_Width*pTiles->m_Height; i++) { if(pTiles->m_pTiles[i].m_Index) pTiles->m_pTiles[i].m_Index += ENTITY_OFFSET; } } DataFile.UnloadData(pTilemapItem->m_Data); } else if(pLayerItem->m_Type == LAYERTYPE_QUADS) { CMapItemLayerQuads *pQuadsItem = (CMapItemLayerQuads *)pLayerItem; CLayerQuads *pQuads = new CLayerQuads; pQuads->m_pEditor = m_pEditor; pLayer = pQuads; pQuads->m_Image = pQuadsItem->m_Image; if(pQuads->m_Image < -1 || pQuads->m_Image >= m_lImages.size()) pQuads->m_Image = -1; // load layer name if(pQuadsItem->m_Version >= 2) IntsToStr(pQuadsItem->m_aName, sizeof(pQuads->m_aName)/sizeof(int), pQuads->m_aName); void *pData = DataFile.GetDataSwapped(pQuadsItem->m_Data); pGroup->AddLayer(pQuads); pQuads->m_lQuads.set_size(pQuadsItem->m_NumQuads); mem_copy(pQuads->m_lQuads.base_ptr(), pData, sizeof(CQuad)*pQuadsItem->m_NumQuads); DataFile.UnloadData(pQuadsItem->m_Data); } if(pLayer) pLayer->m_Flags = pLayerItem->m_Flags; } } } // load envelopes { CEnvPoint *pPoints = 0; { int Start, Num; DataFile.GetType(MAPITEMTYPE_ENVPOINTS, &Start, &Num); if(Num) pPoints = (CEnvPoint *)DataFile.GetItem(Start, 0, 0); } int Start, Num; DataFile.GetType(MAPITEMTYPE_ENVELOPE, &Start, &Num); for(int e = 0; e < Num; e++) { CMapItemEnvelope *pItem = (CMapItemEnvelope *)DataFile.GetItem(Start+e, 0, 0); CEnvelope *pEnv = new CEnvelope(pItem->m_Channels); pEnv->m_lPoints.set_size(pItem->m_NumPoints); mem_copy(pEnv->m_lPoints.base_ptr(), &pPoints[pItem->m_StartPoint], sizeof(CEnvPoint)*pItem->m_NumPoints); if(pItem->m_aName[0] != -1) // compatibility with old maps IntsToStr(pItem->m_aName, sizeof(pItem->m_aName)/sizeof(int), pEnv->m_aName); m_lEnvelopes.add(pEnv); if(pItem->m_Version >= 2) pEnv->m_Synchronized = pItem->m_Synchronized; } } } else return 0; return 1; } static int gs_ModifyAddAmount = 0; static void ModifyAdd(int *pIndex) { if(*pIndex >= 0) *pIndex += gs_ModifyAddAmount; } int CEditor::Append(const char *pFileName, int StorageType) { CEditorMap NewMap; NewMap.m_pEditor = this; int Err; Err = NewMap.Load(Kernel()->RequestInterface<IStorage>(), pFileName, StorageType); if(!Err) return Err; // modify indecies gs_ModifyAddAmount = m_Map.m_lImages.size(); NewMap.ModifyImageIndex(ModifyAdd); gs_ModifyAddAmount = m_Map.m_lEnvelopes.size(); NewMap.ModifyEnvelopeIndex(ModifyAdd); // transfer images for(int i = 0; i < NewMap.m_lImages.size(); i++) m_Map.m_lImages.add(NewMap.m_lImages[i]); NewMap.m_lImages.clear(); // transfer envelopes for(int i = 0; i < NewMap.m_lEnvelopes.size(); i++) m_Map.m_lEnvelopes.add(NewMap.m_lEnvelopes[i]); NewMap.m_lEnvelopes.clear(); // transfer groups for(int i = 0; i < NewMap.m_lGroups.size(); i++) { if(NewMap.m_lGroups[i] == NewMap.m_pGameGroup) delete NewMap.m_lGroups[i]; else { NewMap.m_lGroups[i]->m_pMap = &m_Map; m_Map.m_lGroups.add(NewMap.m_lGroups[i]); } } NewMap.m_lGroups.clear(); // all done \o/ return 0; } ================================================ FILE: src/game/editor/layer_game.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include "editor.h" CLayerGame::CLayerGame(int w, int h) : CLayerTiles(w, h) { str_copy(m_aName, "Game", sizeof(m_aName)); m_Game = 1; } CLayerGame::~CLayerGame() { } int CLayerGame::RenderProperties(CUIRect *pToolbox) { int r = CLayerTiles::RenderProperties(pToolbox); m_Image = -1; return r; } ================================================ FILE: src/game/editor/layer_quads.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <base/math.h> #include <engine/console.h> #include <engine/graphics.h> #include "editor.h" #include <game/generated/client_data.h> #include <game/client/localization.h> #include <game/client/render.h> CLayerQuads::CLayerQuads() { m_Type = LAYERTYPE_QUADS; str_copy(m_aName, "Quads", sizeof(m_aName)); m_Image = -1; } CLayerQuads::~CLayerQuads() { } void CLayerQuads::Render() { Graphics()->TextureClear(); if(m_Image >= 0 && m_Image < m_pEditor->m_Map.m_lImages.size()) Graphics()->TextureSet(m_pEditor->m_Map.m_lImages[m_Image]->m_Texture); Graphics()->BlendNone(); m_pEditor->RenderTools()->RenderQuads(m_lQuads.base_ptr(), m_lQuads.size(), LAYERRENDERFLAG_OPAQUE, m_pEditor->EnvelopeEval, m_pEditor); Graphics()->BlendNormal(); m_pEditor->RenderTools()->RenderQuads(m_lQuads.base_ptr(), m_lQuads.size(), LAYERRENDERFLAG_TRANSPARENT, m_pEditor->EnvelopeEval, m_pEditor); } CQuad *CLayerQuads::NewQuad() { m_pEditor->m_Map.m_Modified = true; CQuad *q = &m_lQuads[m_lQuads.add(CQuad())]; q->m_PosEnv = -1; q->m_ColorEnv = -1; q->m_PosEnvOffset = 0; q->m_ColorEnvOffset = 0; int x = 0, y = 0; q->m_aPoints[0].x = x; q->m_aPoints[0].y = y; q->m_aPoints[1].x = x+64; q->m_aPoints[1].y = y; q->m_aPoints[2].x = x; q->m_aPoints[2].y = y+64; q->m_aPoints[3].x = x+64; q->m_aPoints[3].y = y+64; q->m_aPoints[4].x = x+32; // pivot q->m_aPoints[4].y = y+32; for(int i = 0; i < 5; i++) { q->m_aPoints[i].x <<= 10; q->m_aPoints[i].y <<= 10; } q->m_aTexcoords[0].x = 0; q->m_aTexcoords[0].y = 0; q->m_aTexcoords[1].x = 1<<10; q->m_aTexcoords[1].y = 0; q->m_aTexcoords[2].x = 0; q->m_aTexcoords[2].y = 1<<10; q->m_aTexcoords[3].x = 1<<10; q->m_aTexcoords[3].y = 1<<10; q->m_aColors[0].r = 255; q->m_aColors[0].g = 255; q->m_aColors[0].b = 255; q->m_aColors[0].a = 255; q->m_aColors[1].r = 255; q->m_aColors[1].g = 255; q->m_aColors[1].b = 255; q->m_aColors[1].a = 255; q->m_aColors[2].r = 255; q->m_aColors[2].g = 255; q->m_aColors[2].b = 255; q->m_aColors[2].a = 255; q->m_aColors[3].r = 255; q->m_aColors[3].g = 255; q->m_aColors[3].b = 255; q->m_aColors[3].a = 255; return q; } void CLayerQuads::BrushSelecting(CUIRect Rect) { // draw selection rectangle IGraphics::CLineItem Array[4] = { IGraphics::CLineItem(Rect.x, Rect.y, Rect.x+Rect.w, Rect.y), IGraphics::CLineItem(Rect.x+Rect.w, Rect.y, Rect.x+Rect.w, Rect.y+Rect.h), IGraphics::CLineItem(Rect.x+Rect.w, Rect.y+Rect.h, Rect.x, Rect.y+Rect.h), IGraphics::CLineItem(Rect.x, Rect.y+Rect.h, Rect.x, Rect.y)}; Graphics()->TextureClear(); Graphics()->LinesBegin(); Graphics()->LinesDraw(Array, 4); Graphics()->LinesEnd(); } int CLayerQuads::BrushGrab(CLayerGroup *pBrush, CUIRect Rect) { // create new layers CLayerQuads *pGrabbed = new CLayerQuads(); pGrabbed->m_pEditor = m_pEditor; pGrabbed->m_Image = m_Image; pBrush->AddLayer(pGrabbed); //dbg_msg("", "%f %f %f %f", rect.x, rect.y, rect.w, rect.h); for(int i = 0; i < m_lQuads.size(); i++) { CQuad *q = &m_lQuads[i]; float px = fx2f(q->m_aPoints[4].x); float py = fx2f(q->m_aPoints[4].y); if(px > Rect.x && px < Rect.x+Rect.w && py > Rect.y && py < Rect.y+Rect.h) { CQuad n; n = *q; for(int p = 0; p < 5; p++) { n.m_aPoints[p].x -= f2fx(Rect.x); n.m_aPoints[p].y -= f2fx(Rect.y); } pGrabbed->m_lQuads.add(n); } } return pGrabbed->m_lQuads.size()?1:0; } void CLayerQuads::BrushPlace(CLayer *pBrush, float wx, float wy) { CLayerQuads *l = (CLayerQuads *)pBrush; for(int i = 0; i < l->m_lQuads.size(); i++) { CQuad n = l->m_lQuads[i]; for(int p = 0; p < 5; p++) { n.m_aPoints[p].x += f2fx(wx); n.m_aPoints[p].y += f2fx(wy); } m_lQuads.add(n); } m_pEditor->m_Map.m_Modified = true; } void CLayerQuads::BrushFlipX() { } void CLayerQuads::BrushFlipY() { } void Rotate(vec2 *pCenter, vec2 *pPoint, float Rotation) { float x = pPoint->x - pCenter->x; float y = pPoint->y - pCenter->y; pPoint->x = x * cosf(Rotation) - y * sinf(Rotation) + pCenter->x; pPoint->y = x * sinf(Rotation) + y * cosf(Rotation) + pCenter->y; } void CLayerQuads::BrushRotate(float Amount) { vec2 Center; GetSize(&Center.x, &Center.y); Center.x /= 2; Center.y /= 2; for(int i = 0; i < m_lQuads.size(); i++) { CQuad *q = &m_lQuads[i]; for(int p = 0; p < 5; p++) { vec2 Pos(fx2f(q->m_aPoints[p].x), fx2f(q->m_aPoints[p].y)); Rotate(&Center, &Pos, Amount); q->m_aPoints[p].x = f2fx(Pos.x); q->m_aPoints[p].y = f2fx(Pos.y); } } } void CLayerQuads::GetSize(float *w, float *h) { *w = 0; *h = 0; for(int i = 0; i < m_lQuads.size(); i++) { for(int p = 0; p < 5; p++) { *w = max(*w, fx2f(m_lQuads[i].m_aPoints[p].x)); *h = max(*h, fx2f(m_lQuads[i].m_aPoints[p].y)); } } } extern int gs_SelectedPoints; int CLayerQuads::RenderProperties(CUIRect *pToolBox) { // layer props enum { PROP_IMAGE=0, NUM_PROPS, }; CProperty aProps[] = { {"Image", m_Image, PROPTYPE_IMAGE, -1, 0}, {0}, }; static int s_aIds[NUM_PROPS] = {0}; int NewVal = 0; int Prop = m_pEditor->DoProperties(pToolBox, aProps, s_aIds, &NewVal); if(Prop != -1) m_pEditor->m_Map.m_Modified = true; if(Prop == PROP_IMAGE) { if(NewVal >= 0) m_Image = NewVal%m_pEditor->m_Map.m_lImages.size(); else m_Image = -1; } return 0; } void CLayerQuads::ModifyImageIndex(INDEX_MODIFY_FUNC Func) { Func(&m_Image); } void CLayerQuads::ModifyEnvelopeIndex(INDEX_MODIFY_FUNC Func) { for(int i = 0; i < m_lQuads.size(); i++) { Func(&m_lQuads[i].m_PosEnv); Func(&m_lQuads[i].m_ColorEnv); } } ================================================ FILE: src/game/editor/layer_tiles.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <base/math.h> #include <engine/client.h> #include <engine/graphics.h> #include <engine/textrender.h> #include <game/generated/client_data.h> #include <game/client/localization.h> #include <game/client/render.h> #include "editor.h" CLayerTiles::CLayerTiles(int w, int h) { m_Type = LAYERTYPE_TILES; str_copy(m_aName, "Tiles", sizeof(m_aName)); m_Width = w; m_Height = h; m_Image = -1; m_Game = 0; m_Color.r = 255; m_Color.g = 255; m_Color.b = 255; m_Color.a = 255; m_ColorEnv = -1; m_ColorEnvOffset = 0; m_pTiles = new CTile[m_Width*m_Height]; mem_zero(m_pTiles, m_Width*m_Height*sizeof(CTile)); m_SelectedRuleSet = 0; m_SelectedAmount = 50; } CLayerTiles::~CLayerTiles() { delete [] m_pTiles; } void CLayerTiles::PrepareForSave() { for(int y = 0; y < m_Height; y++) for(int x = 0; x < m_Width; x++) m_pTiles[y*m_Width+x].m_Flags &= TILEFLAG_VFLIP|TILEFLAG_HFLIP|TILEFLAG_ROTATE; if(m_Image != -1 && m_Color.a == 255) { for(int y = 0; y < m_Height; y++) for(int x = 0; x < m_Width; x++) m_pTiles[y*m_Width+x].m_Flags |= m_pEditor->m_Map.m_lImages[m_Image]->m_aTileFlags[m_pTiles[y*m_Width+x].m_Index]; } } void CLayerTiles::MakePalette() { for(int y = 0; y < m_Height; y++) for(int x = 0; x < m_Width; x++) m_pTiles[y*m_Width+x].m_Index = y*16+x; } void CLayerTiles::Render() { if(m_Image >= 0 && m_Image < m_pEditor->m_Map.m_lImages.size()) m_Texture = m_pEditor->m_Map.m_lImages[m_Image]->m_Texture; Graphics()->TextureSet(m_Texture); vec4 Color = vec4(m_Color.r/255.0f, m_Color.g/255.0f, m_Color.b/255.0f, m_Color.a/255.0f); Graphics()->BlendNone(); m_pEditor->RenderTools()->RenderTilemap(m_pTiles, m_Width, m_Height, 32.0f, Color, LAYERRENDERFLAG_OPAQUE, m_pEditor->EnvelopeEval, m_pEditor, m_ColorEnv, m_ColorEnvOffset); Graphics()->BlendNormal(); m_pEditor->RenderTools()->RenderTilemap(m_pTiles, m_Width, m_Height, 32.0f, Color, LAYERRENDERFLAG_TRANSPARENT, m_pEditor->EnvelopeEval, m_pEditor, m_ColorEnv, m_ColorEnvOffset); } int CLayerTiles::ConvertX(float x) const { return (int)(x/32.0f); } int CLayerTiles::ConvertY(float y) const { return (int)(y/32.0f); } void CLayerTiles::Convert(CUIRect Rect, RECTi *pOut) { pOut->x = ConvertX(Rect.x); pOut->y = ConvertY(Rect.y); pOut->w = ConvertX(Rect.x+Rect.w+31) - pOut->x; pOut->h = ConvertY(Rect.y+Rect.h+31) - pOut->y; } void CLayerTiles::Snap(CUIRect *pRect) { RECTi Out; Convert(*pRect, &Out); pRect->x = Out.x*32.0f; pRect->y = Out.y*32.0f; pRect->w = Out.w*32.0f; pRect->h = Out.h*32.0f; } void CLayerTiles::Clamp(RECTi *pRect) { if(pRect->x < 0) { pRect->w += pRect->x; pRect->x = 0; } if(pRect->y < 0) { pRect->h += pRect->y; pRect->y = 0; } if(pRect->x+pRect->w > m_Width) pRect->w = m_Width - pRect->x; if(pRect->y+pRect->h > m_Height) pRect->h = m_Height - pRect->y; if(pRect->h < 0) pRect->h = 0; if(pRect->w < 0) pRect->w = 0; } void CLayerTiles::BrushSelecting(CUIRect Rect) { Graphics()->TextureClear(); m_pEditor->Graphics()->QuadsBegin(); m_pEditor->Graphics()->SetColor(1.0f, 1.0f, 1.0f, 0.4f); Snap(&Rect); IGraphics::CQuadItem QuadItem(Rect.x, Rect.y, Rect.w, Rect.h); m_pEditor->Graphics()->QuadsDrawTL(&QuadItem, 1); m_pEditor->Graphics()->QuadsEnd(); char aBuf[16]; str_format(aBuf, sizeof(aBuf), "%d,%d", ConvertX(Rect.w), ConvertY(Rect.h)); TextRender()->Text(0, Rect.x+3.0f, Rect.y+3.0f, m_pEditor->m_ShowPicker?15.0f:15.0f*m_pEditor->m_WorldZoom, aBuf, -1); } int CLayerTiles::BrushGrab(CLayerGroup *pBrush, CUIRect Rect) { RECTi r; Convert(Rect, &r); Clamp(&r); if(!r.w || !r.h) return 0; // create new layers CLayerTiles *pGrabbed = new CLayerTiles(r.w, r.h); pGrabbed->m_pEditor = m_pEditor; pGrabbed->m_Texture = m_Texture; pGrabbed->m_Image = m_Image; pGrabbed->m_Game = m_Game; pBrush->AddLayer(pGrabbed); // copy the tiles for(int y = 0; y < r.h; y++) for(int x = 0; x < r.w; x++) pGrabbed->m_pTiles[y*pGrabbed->m_Width+x] = m_pTiles[(r.y+y)*m_Width+(r.x+x)]; return 1; } void CLayerTiles::FillSelection(bool Empty, CLayer *pBrush, CUIRect Rect) { if(m_Readonly) return; Snap(&Rect); int sx = ConvertX(Rect.x); int sy = ConvertY(Rect.y); int w = ConvertX(Rect.w); int h = ConvertY(Rect.h); CLayerTiles *pLt = static_cast<CLayerTiles*>(pBrush); for(int y = 0; y < h; y++) { for(int x = 0; x < w; x++) { int fx = x+sx; int fy = y+sy; if(fx < 0 || fx >= m_Width || fy < 0 || fy >= m_Height) continue; if(Empty) m_pTiles[fy*m_Width+fx].m_Index = 1; else m_pTiles[fy*m_Width+fx] = pLt->m_pTiles[(y*pLt->m_Width + x%pLt->m_Width) % (pLt->m_Width*pLt->m_Height)]; } } m_pEditor->m_Map.m_Modified = true; } void CLayerTiles::BrushDraw(CLayer *pBrush, float wx, float wy) { if(m_Readonly) return; // CLayerTiles *l = (CLayerTiles *)pBrush; int sx = ConvertX(wx); int sy = ConvertY(wy); for(int y = 0; y < l->m_Height; y++) for(int x = 0; x < l->m_Width; x++) { int fx = x+sx; int fy = y+sy; if(fx<0 || fx >= m_Width || fy < 0 || fy >= m_Height) continue; m_pTiles[fy*m_Width+fx] = l->m_pTiles[y*l->m_Width+x]; } m_pEditor->m_Map.m_Modified = true; } void CLayerTiles::BrushFlipX() { for(int y = 0; y < m_Height; y++) for(int x = 0; x < m_Width/2; x++) { CTile Tmp = m_pTiles[y*m_Width+x]; m_pTiles[y*m_Width+x] = m_pTiles[y*m_Width+m_Width-1-x]; m_pTiles[y*m_Width+m_Width-1-x] = Tmp; } if(!m_Game) for(int y = 0; y < m_Height; y++) for(int x = 0; x < m_Width; x++) m_pTiles[y*m_Width+x].m_Flags ^= m_pTiles[y*m_Width+x].m_Flags&TILEFLAG_ROTATE ? TILEFLAG_HFLIP : TILEFLAG_VFLIP; } void CLayerTiles::BrushFlipY() { for(int y = 0; y < m_Height/2; y++) for(int x = 0; x < m_Width; x++) { CTile Tmp = m_pTiles[y*m_Width+x]; m_pTiles[y*m_Width+x] = m_pTiles[(m_Height-1-y)*m_Width+x]; m_pTiles[(m_Height-1-y)*m_Width+x] = Tmp; } if(!m_Game) for(int y = 0; y < m_Height; y++) for(int x = 0; x < m_Width; x++) m_pTiles[y*m_Width+x].m_Flags ^= m_pTiles[y*m_Width+x].m_Flags&TILEFLAG_ROTATE ? TILEFLAG_VFLIP : TILEFLAG_HFLIP; } void CLayerTiles::BrushRotate(float Amount) { int Rotation = (round(360.0f*Amount/(pi*2))/90)%4; // 0=0, 1=90, 2=180, 3=270 if(Rotation < 0) Rotation +=4; if(Rotation == 1 || Rotation == 3) { // 90 rotation CTile *pTempData = new CTile[m_Width*m_Height]; mem_copy(pTempData, m_pTiles, m_Width*m_Height*sizeof(CTile)); CTile *pDst = m_pTiles; for(int x = 0; x < m_Width; ++x) for(int y = m_Height-1; y >= 0; --y, ++pDst) { *pDst = pTempData[y*m_Width+x]; if(!m_Game) { if(pDst->m_Flags&TILEFLAG_ROTATE) pDst->m_Flags ^= (TILEFLAG_HFLIP|TILEFLAG_VFLIP); pDst->m_Flags ^= TILEFLAG_ROTATE; } } int Temp = m_Width; m_Width = m_Height; m_Height = Temp; delete[] pTempData; } if(Rotation == 2 || Rotation == 3) { BrushFlipX(); BrushFlipY(); } } void CLayerTiles::Resize(int NewW, int NewH) { CTile *pNewData = new CTile[NewW*NewH]; mem_zero(pNewData, NewW*NewH*sizeof(CTile)); // copy old data for(int y = 0; y < min(NewH, m_Height); y++) mem_copy(&pNewData[y*NewW], &m_pTiles[y*m_Width], min(m_Width, NewW)*sizeof(CTile)); // replace old delete [] m_pTiles; m_pTiles = pNewData; m_Width = NewW; m_Height = NewH; } void CLayerTiles::Shift(int Direction) { switch(Direction) { case 1: { // left for(int y = 0; y < m_Height; ++y) mem_move(&m_pTiles[y*m_Width], &m_pTiles[y*m_Width+1], (m_Width-1)*sizeof(CTile)); } break; case 2: { // right for(int y = 0; y < m_Height; ++y) mem_move(&m_pTiles[y*m_Width+1], &m_pTiles[y*m_Width], (m_Width-1)*sizeof(CTile)); } break; case 4: { // up for(int y = 0; y < m_Height-1; ++y) mem_copy(&m_pTiles[y*m_Width], &m_pTiles[(y+1)*m_Width], m_Width*sizeof(CTile)); } break; case 8: { // down for(int y = m_Height-1; y > 0; --y) mem_copy(&m_pTiles[y*m_Width], &m_pTiles[(y-1)*m_Width], m_Width*sizeof(CTile)); } } } void CLayerTiles::ShowInfo() { float ScreenX0, ScreenY0, ScreenX1, ScreenY1; Graphics()->GetScreen(&ScreenX0, &ScreenY0, &ScreenX1, &ScreenY1); Graphics()->TextureSet(m_pEditor->Client()->GetDebugFont()); Graphics()->QuadsBegin(); int StartY = max(0, (int)(ScreenY0/32.0f)-1); int StartX = max(0, (int)(ScreenX0/32.0f)-1); int EndY = min((int)(ScreenY1/32.0f)+1, m_Height); int EndX = min((int)(ScreenX1/32.0f)+1, m_Width); for(int y = StartY; y < EndY; y++) for(int x = StartX; x < EndX; x++) { int c = x + y*m_Width; if(m_pTiles[c].m_Index) { char aBuf[64]; str_format(aBuf, sizeof(aBuf), "%i", m_pTiles[c].m_Index); m_pEditor->Graphics()->QuadsText(x*32, y*32, 16.0f, aBuf); char aFlags[4] = { m_pTiles[c].m_Flags&TILEFLAG_VFLIP ? 'V' : ' ', m_pTiles[c].m_Flags&TILEFLAG_HFLIP ? 'H' : ' ', m_pTiles[c].m_Flags&TILEFLAG_ROTATE? 'R' : ' ', 0}; m_pEditor->Graphics()->QuadsText(x*32, y*32+16, 16.0f, aFlags); } x += m_pTiles[c].m_Skip; } Graphics()->QuadsEnd(); Graphics()->MapScreen(ScreenX0, ScreenY0, ScreenX1, ScreenY1); } int CLayerTiles::RenderProperties(CUIRect *pToolBox) { CUIRect Button; bool InGameGroup = !find_linear(m_pEditor->m_Map.m_pGameGroup->m_lLayers.all(), this).empty(); if(m_pEditor->m_Map.m_pGameLayer != this) { if(m_Image >= 0 && m_Image < m_pEditor->m_Map.m_lImages.size() && m_pEditor->m_Map.m_lImages[m_Image]->m_pAutoMapper) { static int s_AutoMapperButton = 0; pToolBox->HSplitBottom(12.0f, pToolBox, &Button); if(m_pEditor->DoButton_Editor(&s_AutoMapperButton, "Auto map", 0, &Button, 0, "")) m_pEditor->PopupSelectConfigAutoMapInvoke(m_pEditor->UI()->MouseX(), m_pEditor->UI()->MouseY()); bool Proceed = m_pEditor->PopupAutoMapProceedOrder(); if(Proceed) { if(m_pEditor->m_Map.m_lImages[m_Image]->m_pAutoMapper->GetType() == IAutoMapper::TYPE_TILESET) { m_pEditor->m_Map.m_lImages[m_Image]->m_pAutoMapper->Proceed(this, m_SelectedRuleSet); return 1; // only close the popup when it's a tileset } else if(m_pEditor->m_Map.m_lImages[m_Image]->m_pAutoMapper->GetType() == IAutoMapper::TYPE_DOODADS) m_pEditor->m_Map.m_lImages[m_Image]->m_pAutoMapper->Proceed(this, m_SelectedRuleSet, m_SelectedAmount); } } } else InGameGroup = false; if(InGameGroup) { pToolBox->HSplitBottom(2.0f, pToolBox, 0); pToolBox->HSplitBottom(12.0f, pToolBox, &Button); static int s_ColclButton = 0; if(m_pEditor->DoButton_Editor(&s_ColclButton, "Game tiles", 0, &Button, 0, "Constructs game tiles from this layer")) m_pEditor->PopupSelectGametileOpInvoke(m_pEditor->UI()->MouseX(), m_pEditor->UI()->MouseY()); int Result = m_pEditor->PopupSelectGameTileOpResult(); if(Result > -1) { CLayerTiles *gl = m_pEditor->m_Map.m_pGameLayer; int w = min(gl->m_Width, m_Width); int h = min(gl->m_Height, m_Height); for(int y = 0; y < h; y++) for(int x = 0; x < w; x++) if(m_pTiles[y*m_Width+x].m_Index) gl->m_pTiles[y*gl->m_Width+x].m_Index = TILE_AIR+Result; return 1; } } enum { PROP_WIDTH=0, PROP_HEIGHT, PROP_SHIFT, PROP_IMAGE, PROP_COLOR, PROP_COLOR_ENV, PROP_COLOR_ENV_OFFSET, NUM_PROPS, }; int Color = 0; Color |= m_Color.r<<24; Color |= m_Color.g<<16; Color |= m_Color.b<<8; Color |= m_Color.a; CProperty aProps[] = { {"Width", m_Width, PROPTYPE_INT_SCROLL, 1, 1000000000}, {"Height", m_Height, PROPTYPE_INT_SCROLL, 1, 1000000000}, {"Shift", 0, PROPTYPE_SHIFT, 0, 0}, {"Image", m_Image, PROPTYPE_IMAGE, 0, 0}, {"Color", Color, PROPTYPE_COLOR, 0, 0}, {"Color Env", m_ColorEnv+1, PROPTYPE_INT_STEP, 0, m_pEditor->m_Map.m_lEnvelopes.size()+1}, {"Color TO", m_ColorEnvOffset, PROPTYPE_INT_SCROLL, -1000000, 1000000}, {0}, }; if(m_pEditor->m_Map.m_pGameLayer == this) // remove the image and color properties if this is the game layer { aProps[3].m_pName = 0; aProps[4].m_pName = 0; } static int s_aIds[NUM_PROPS] = {0}; int NewVal = 0; int Prop = m_pEditor->DoProperties(pToolBox, aProps, s_aIds, &NewVal); if(Prop != -1) m_pEditor->m_Map.m_Modified = true; if(Prop == PROP_WIDTH && NewVal > 1) Resize(NewVal, m_Height); else if(Prop == PROP_HEIGHT && NewVal > 1) Resize(m_Width, NewVal); else if(Prop == PROP_SHIFT) Shift(NewVal); else if(Prop == PROP_IMAGE) { if (NewVal == -1) { m_Texture = IGraphics::CTextureHandle(); m_Image = -1; } else m_Image = NewVal%m_pEditor->m_Map.m_lImages.size(); } else if(Prop == PROP_COLOR) { m_Color.r = (NewVal>>24)&0xff; m_Color.g = (NewVal>>16)&0xff; m_Color.b = (NewVal>>8)&0xff; m_Color.a = NewVal&0xff; } if(Prop == PROP_COLOR_ENV) { int Index = clamp(NewVal-1, -1, m_pEditor->m_Map.m_lEnvelopes.size()-1); int Step = (Index-m_ColorEnv)%2; if(Step != 0) { for(; Index >= -1 && Index < m_pEditor->m_Map.m_lEnvelopes.size(); Index += Step) if(Index == -1 || m_pEditor->m_Map.m_lEnvelopes[Index]->m_Channels == 4) { m_ColorEnv = Index; break; } } } if(Prop == PROP_COLOR_ENV_OFFSET) m_ColorEnvOffset = NewVal; return 0; } void CLayerTiles::ModifyImageIndex(INDEX_MODIFY_FUNC Func) { Func(&m_Image); } void CLayerTiles::ModifyEnvelopeIndex(INDEX_MODIFY_FUNC Func) { } ================================================ FILE: src/game/editor/popups.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <base/tl/array.h> #include <engine/console.h> #include <engine/graphics.h> #include <engine/input.h> #include <engine/keys.h> #include <engine/storage.h> #include "editor.h" // popup menu handling static struct { CUIRect m_Rect; void *m_pId; int (*m_pfnFunc)(CEditor *pEditor, CUIRect Rect); int m_IsMenu; void *m_pExtra; } s_UiPopups[8]; static int g_UiNumPopups = 0; void CEditor::UiInvokePopupMenu(void *pID, int Flags, float x, float y, float Width, float Height, int (*pfnFunc)(CEditor *pEditor, CUIRect Rect), void *pExtra) { Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "editor", "invoked"); if(x + Width > UI()->Screen()->w) x -= Width; if(y + Height > UI()->Screen()->h) y -= Height; s_UiPopups[g_UiNumPopups].m_pId = pID; s_UiPopups[g_UiNumPopups].m_IsMenu = Flags; s_UiPopups[g_UiNumPopups].m_Rect.x = x; s_UiPopups[g_UiNumPopups].m_Rect.y = y; s_UiPopups[g_UiNumPopups].m_Rect.w = Width; s_UiPopups[g_UiNumPopups].m_Rect.h = Height; s_UiPopups[g_UiNumPopups].m_pfnFunc = pfnFunc; s_UiPopups[g_UiNumPopups].m_pExtra = pExtra; g_UiNumPopups++; } void CEditor::UiDoPopupMenu() { for(int i = 0; i < g_UiNumPopups; i++) { bool Inside = UI()->MouseInside(&s_UiPopups[i].m_Rect); UI()->SetHotItem(&s_UiPopups[i].m_pId); if(UI()->ActiveItem() == &s_UiPopups[i].m_pId) { if(!UI()->MouseButton(0)) { if(!Inside) g_UiNumPopups--; UI()->SetActiveItem(0); } } else if(UI()->HotItem() == &s_UiPopups[i].m_pId) { if(UI()->MouseButton(0)) UI()->SetActiveItem(&s_UiPopups[i].m_pId); } int Corners = CUI::CORNER_ALL; if(s_UiPopups[i].m_IsMenu) Corners = CUI::CORNER_R|CUI::CORNER_B; CUIRect r = s_UiPopups[i].m_Rect; RenderTools()->DrawUIRect(&r, vec4(0.5f,0.5f,0.5f,0.75f), Corners, 3.0f); r.Margin(1.0f, &r); RenderTools()->DrawUIRect(&r, vec4(0,0,0,0.75f), Corners, 3.0f); r.Margin(4.0f, &r); if(s_UiPopups[i].m_pfnFunc(this, r)) g_UiNumPopups--; if(Input()->KeyDown(KEY_ESCAPE)) g_UiNumPopups--; } } int CEditor::PopupGroup(CEditor *pEditor, CUIRect View) { // remove group button CUIRect Button; View.HSplitBottom(12.0f, &View, &Button); static int s_DeleteButton = 0; // don't allow deletion of game group if(pEditor->m_Map.m_pGameGroup != pEditor->GetSelectedGroup()) { if(pEditor->DoButton_Editor(&s_DeleteButton, "Delete group", 0, &Button, 0, "Delete group")) { pEditor->m_Map.DeleteGroup(pEditor->m_SelectedGroup); pEditor->m_SelectedGroup = max(0, pEditor->m_SelectedGroup-1); return 1; } } else { if(pEditor->DoButton_Editor(&s_DeleteButton, "Clean-up game tiles", 0, &Button, 0, "Removes game tiles that aren't based on a layer")) { // gather all tile layers array<CLayerTiles*> Layers; for(int i = 0; i < pEditor->m_Map.m_pGameGroup->m_lLayers.size(); ++i) { if(pEditor->m_Map.m_pGameGroup->m_lLayers[i] != pEditor->m_Map.m_pGameLayer && pEditor->m_Map.m_pGameGroup->m_lLayers[i]->m_Type == LAYERTYPE_TILES) Layers.add(static_cast<CLayerTiles *>(pEditor->m_Map.m_pGameGroup->m_lLayers[i])); } // search for unneeded game tiles CLayerTiles *gl = pEditor->m_Map.m_pGameLayer; for(int y = 0; y < gl->m_Height; ++y) for(int x = 0; x < gl->m_Width; ++x) { if(gl->m_pTiles[y*gl->m_Width+x].m_Index > static_cast<unsigned char>(TILE_NOHOOK)) continue; bool Found = false; for(int i = 0; i < Layers.size(); ++i) { if(x < Layers[i]->m_Width && y < Layers[i]->m_Height && Layers[i]->m_pTiles[y*Layers[i]->m_Width+x].m_Index) { Found = true; break; } } if(!Found) { gl->m_pTiles[y*gl->m_Width+x].m_Index = TILE_AIR; pEditor->m_Map.m_Modified = true; } } return 1; } } // new tile layer View.HSplitBottom(10.0f, &View, &Button); View.HSplitBottom(12.0f, &View, &Button); static int s_NewQuadLayerButton = 0; if(pEditor->DoButton_Editor(&s_NewQuadLayerButton, "Add quads layer", 0, &Button, 0, "Creates a new quad layer")) { CLayer *l = new CLayerQuads; l->m_pEditor = pEditor; pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->AddLayer(l); pEditor->m_SelectedLayer = pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_lLayers.size()-1; pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_Collapse = false; return 1; } // new quad layer View.HSplitBottom(5.0f, &View, &Button); View.HSplitBottom(12.0f, &View, &Button); static int s_NewTileLayerButton = 0; if(pEditor->DoButton_Editor(&s_NewTileLayerButton, "Add tile layer", 0, &Button, 0, "Creates a new tile layer")) { CLayer *l = new CLayerTiles(50, 50); l->m_pEditor = pEditor; pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->AddLayer(l); pEditor->m_SelectedLayer = pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_lLayers.size()-1; pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_Collapse = false; return 1; } // group name if(!pEditor->GetSelectedGroup()->m_GameGroup) { View.HSplitBottom(5.0f, &View, &Button); View.HSplitBottom(12.0f, &View, &Button); static float s_Name = 0; pEditor->UI()->DoLabel(&Button, "Name:", 10.0f, -1, -1); Button.VSplitLeft(40.0f, 0, &Button); if(pEditor->DoEditBox(&s_Name, &Button, pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_aName, sizeof(pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_aName), 10.0f, &s_Name)) pEditor->m_Map.m_Modified = true; } enum { PROP_ORDER=0, PROP_POS_X, PROP_POS_Y, PROP_PARA_X, PROP_PARA_Y, PROP_USE_CLIPPING, PROP_CLIP_X, PROP_CLIP_Y, PROP_CLIP_W, PROP_CLIP_H, NUM_PROPS, }; CProperty aProps[] = { {"Order", pEditor->m_SelectedGroup, PROPTYPE_INT_STEP, 0, pEditor->m_Map.m_lGroups.size()-1}, {"Pos X", -pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_OffsetX, PROPTYPE_INT_SCROLL, -1000000, 1000000}, {"Pos Y", -pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_OffsetY, PROPTYPE_INT_SCROLL, -1000000, 1000000}, {"Para X", pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_ParallaxX, PROPTYPE_INT_SCROLL, -1000000, 1000000}, {"Para Y", pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_ParallaxY, PROPTYPE_INT_SCROLL, -1000000, 1000000}, {"Use Clipping", pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_UseClipping, PROPTYPE_BOOL, 0, 1}, {"Clip X", pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_ClipX, PROPTYPE_INT_SCROLL, -1000000, 1000000}, {"Clip Y", pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_ClipY, PROPTYPE_INT_SCROLL, -1000000, 1000000}, {"Clip W", pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_ClipW, PROPTYPE_INT_SCROLL, -1000000, 1000000}, {"Clip H", pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_ClipH, PROPTYPE_INT_SCROLL, -1000000, 1000000}, {0}, }; static int s_aIds[NUM_PROPS] = {0}; int NewVal = 0; // cut the properties that isn't needed if(pEditor->GetSelectedGroup()->m_GameGroup) aProps[PROP_POS_X].m_pName = 0; int Prop = pEditor->DoProperties(&View, aProps, s_aIds, &NewVal); if(Prop != -1) pEditor->m_Map.m_Modified = true; if(Prop == PROP_ORDER) pEditor->m_SelectedGroup = pEditor->m_Map.SwapGroups(pEditor->m_SelectedGroup, NewVal); // these can not be changed on the game group if(!pEditor->GetSelectedGroup()->m_GameGroup) { if(Prop == PROP_PARA_X) pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_ParallaxX = NewVal; else if(Prop == PROP_PARA_Y) pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_ParallaxY = NewVal; else if(Prop == PROP_POS_X) pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_OffsetX = -NewVal; else if(Prop == PROP_POS_Y) pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_OffsetY = -NewVal; else if(Prop == PROP_USE_CLIPPING) pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_UseClipping = NewVal; else if(Prop == PROP_CLIP_X) pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_ClipX = NewVal; else if(Prop == PROP_CLIP_Y) pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_ClipY = NewVal; else if(Prop == PROP_CLIP_W) pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_ClipW = NewVal; else if(Prop == PROP_CLIP_H) pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->m_ClipH = NewVal; } return 0; } int CEditor::PopupLayer(CEditor *pEditor, CUIRect View) { // remove layer button CUIRect Button; View.HSplitBottom(12.0f, &View, &Button); static int s_DeleteButton = 0; // don't allow deletion of game layer if(pEditor->m_Map.m_pGameLayer != pEditor->GetSelectedLayer(0) && pEditor->DoButton_Editor(&s_DeleteButton, "Delete layer", 0, &Button, 0, "Deletes the layer")) { pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]->DeleteLayer(pEditor->m_SelectedLayer); return 1; } // layer name if(pEditor->m_Map.m_pGameLayer != pEditor->GetSelectedLayer(0)) { View.HSplitBottom(5.0f, &View, &Button); View.HSplitBottom(12.0f, &View, &Button); static float s_Name = 0; pEditor->UI()->DoLabel(&Button, "Name:", 10.0f, -1, -1); Button.VSplitLeft(40.0f, 0, &Button); if(pEditor->DoEditBox(&s_Name, &Button, pEditor->GetSelectedLayer(0)->m_aName, sizeof(pEditor->GetSelectedLayer(0)->m_aName), 10.0f, &s_Name)) pEditor->m_Map.m_Modified = true; } View.HSplitBottom(10.0f, &View, 0); CLayerGroup *pCurrentGroup = pEditor->m_Map.m_lGroups[pEditor->m_SelectedGroup]; CLayer *pCurrentLayer = pEditor->GetSelectedLayer(0); enum { PROP_GROUP=0, PROP_ORDER, PROP_HQ, NUM_PROPS, }; CProperty aProps[] = { {"Group", pEditor->m_SelectedGroup, PROPTYPE_INT_STEP, 0, pEditor->m_Map.m_lGroups.size()-1}, {"Order", pEditor->m_SelectedLayer, PROPTYPE_INT_STEP, 0, pCurrentGroup->m_lLayers.size()}, {"Detail", pCurrentLayer->m_Flags&LAYERFLAG_DETAIL, PROPTYPE_BOOL, 0, 1}, {0}, }; if(pEditor->m_Map.m_pGameLayer == pEditor->GetSelectedLayer(0)) // dont use Group and Detail from the selection if this is the game layer { aProps[0].m_Type = PROPTYPE_NULL; aProps[2].m_Type = PROPTYPE_NULL; } static int s_aIds[NUM_PROPS] = {0}; int NewVal = 0; int Prop = pEditor->DoProperties(&View, aProps, s_aIds, &NewVal); if(Prop != -1) pEditor->m_Map.m_Modified = true; if(Prop == PROP_ORDER) pEditor->m_SelectedLayer = pCurrentGroup->SwapLayers(pEditor->m_SelectedLayer, NewVal); else if(Prop == PROP_GROUP && pCurrentLayer->m_Type != LAYERTYPE_GAME) { if(NewVal >= 0 && NewVal < pEditor->m_Map.m_lGroups.size()) { pCurrentGroup->m_lLayers.remove(pCurrentLayer); pEditor->m_Map.m_lGroups[NewVal]->m_lLayers.add(pCurrentLayer); pEditor->m_SelectedGroup = NewVal; pEditor->m_SelectedLayer = pEditor->m_Map.m_lGroups[NewVal]->m_lLayers.size()-1; } } else if(Prop == PROP_HQ) { pCurrentLayer->m_Flags &= ~LAYERFLAG_DETAIL; if(NewVal) pCurrentLayer->m_Flags |= LAYERFLAG_DETAIL; } return pCurrentLayer->RenderProperties(&View); } int CEditor::PopupQuad(CEditor *pEditor, CUIRect View) { CQuad *pQuad = pEditor->GetSelectedQuad(); CUIRect Button; // delete button View.HSplitBottom(12.0f, &View, &Button); static int s_DeleteButton = 0; if(pEditor->DoButton_Editor(&s_DeleteButton, "Delete", 0, &Button, 0, "Deletes the current quad")) { CLayerQuads *pLayer = (CLayerQuads *)pEditor->GetSelectedLayerType(0, LAYERTYPE_QUADS); if(pLayer) { pEditor->m_Map.m_Modified = true; pLayer->m_lQuads.remove_index(pEditor->m_SelectedQuad); pEditor->m_SelectedQuad--; } return 1; } // aspect ratio button View.HSplitBottom(10.0f, &View, &Button); View.HSplitBottom(12.0f, &View, &Button); CLayerQuads *pLayer = (CLayerQuads *)pEditor->GetSelectedLayerType(0, LAYERTYPE_QUADS); if(pLayer && pLayer->m_Image >= 0 && pLayer->m_Image < pEditor->m_Map.m_lImages.size()) { static int s_AspectRatioButton = 0; if(pEditor->DoButton_Editor(&s_AspectRatioButton, "Aspect ratio", 0, &Button, 0, "Resizes the current Quad based on the aspect ratio of the image")) { int Top = pQuad->m_aPoints[0].y; int Left = pQuad->m_aPoints[0].x; int Right = pQuad->m_aPoints[0].x; for(int k = 1; k < 4; k++) { if(pQuad->m_aPoints[k].y < Top) Top = pQuad->m_aPoints[k].y; if(pQuad->m_aPoints[k].x < Left) Left = pQuad->m_aPoints[k].x; if(pQuad->m_aPoints[k].x > Right) Right = pQuad->m_aPoints[k].x; } int Height = (Right-Left)*pEditor->m_Map.m_lImages[pLayer->m_Image]->m_Height/pEditor->m_Map.m_lImages[pLayer->m_Image]->m_Width; pQuad->m_aPoints[0].x = Left; pQuad->m_aPoints[0].y = Top; pQuad->m_aPoints[1].x = Right; pQuad->m_aPoints[1].y = Top; pQuad->m_aPoints[2].x = Left; pQuad->m_aPoints[2].y = Top+Height; pQuad->m_aPoints[3].x = Right; pQuad->m_aPoints[3].y = Top+Height; pEditor->m_Map.m_Modified = true; return 1; } } // align button View.HSplitBottom(6.0f, &View, &Button); View.HSplitBottom(12.0f, &View, &Button); static int s_AlignButton = 0; if(pEditor->DoButton_Editor(&s_AlignButton, "Align", 0, &Button, 0, "Aligns coordinates of the quad points")) { for(int k = 1; k < 4; k++) { pQuad->m_aPoints[k].x = 1000.0f * (int(pQuad->m_aPoints[k].x) / 1000); pQuad->m_aPoints[k].y = 1000.0f * (int(pQuad->m_aPoints[k].y) / 1000); } pEditor->m_Map.m_Modified = true; return 1; } // square button View.HSplitBottom(6.0f, &View, &Button); View.HSplitBottom(12.0f, &View, &Button); static int s_SquareButton = 0; if(pEditor->DoButton_Editor(&s_SquareButton, "Square", 0, &Button, 0, "Squares the current quad")) { int Top = pQuad->m_aPoints[0].y; int Left = pQuad->m_aPoints[0].x; int Bottom = pQuad->m_aPoints[0].y; int Right = pQuad->m_aPoints[0].x; for(int k = 1; k < 4; k++) { if(pQuad->m_aPoints[k].y < Top) Top = pQuad->m_aPoints[k].y; if(pQuad->m_aPoints[k].x < Left) Left = pQuad->m_aPoints[k].x; if(pQuad->m_aPoints[k].y > Bottom) Bottom = pQuad->m_aPoints[k].y; if(pQuad->m_aPoints[k].x > Right) Right = pQuad->m_aPoints[k].x; } pQuad->m_aPoints[0].x = Left; pQuad->m_aPoints[0].y = Top; pQuad->m_aPoints[1].x = Right; pQuad->m_aPoints[1].y = Top; pQuad->m_aPoints[2].x = Left; pQuad->m_aPoints[2].y = Bottom; pQuad->m_aPoints[3].x = Right; pQuad->m_aPoints[3].y = Bottom; pEditor->m_Map.m_Modified = true; return 1; } // center pivot button View.HSplitBottom(6.0f, &View, &Button); View.HSplitBottom(12.0f, &View, &Button); static int s_CenterButton = 0; if(pEditor->DoButton_Editor(&s_CenterButton, "Center pivot", 0, &Button, 0, "Centers the pivot of the current quad")) { int Top = pQuad->m_aPoints[0].y; int Left = pQuad->m_aPoints[0].x; int Bottom = pQuad->m_aPoints[0].y; int Right = pQuad->m_aPoints[0].x; for(int k = 1; k < 4; k++) { if(pQuad->m_aPoints[k].y < Top) Top = pQuad->m_aPoints[k].y; if(pQuad->m_aPoints[k].x < Left) Left = pQuad->m_aPoints[k].x; if(pQuad->m_aPoints[k].y > Bottom) Bottom = pQuad->m_aPoints[k].y; if(pQuad->m_aPoints[k].x > Right) Right = pQuad->m_aPoints[k].x; } pQuad->m_aPoints[4].x = Left+int((Right-Left)/2); pQuad->m_aPoints[4].y = Top+int((Bottom-Top)/2); pEditor->m_Map.m_Modified = true; return 1; } enum { PROP_POS_X=0, PROP_POS_Y, PROP_POS_ENV, PROP_POS_ENV_OFFSET, PROP_COLOR_ENV, PROP_COLOR_ENV_OFFSET, NUM_PROPS, }; CProperty aProps[] = { {"Pos X", pQuad->m_aPoints[4].x/1000, PROPTYPE_INT_SCROLL, -1000000, 1000000}, {"Pos Y", pQuad->m_aPoints[4].y/1000, PROPTYPE_INT_SCROLL, -1000000, 1000000}, {"Pos. Env", pQuad->m_PosEnv+1, PROPTYPE_INT_STEP, 0, pEditor->m_Map.m_lEnvelopes.size()+1}, {"Pos. TO", pQuad->m_PosEnvOffset, PROPTYPE_INT_SCROLL, -1000000, 1000000}, {"Color Env", pQuad->m_ColorEnv+1, PROPTYPE_INT_STEP, 0, pEditor->m_Map.m_lEnvelopes.size()+1}, {"Color TO", pQuad->m_ColorEnvOffset, PROPTYPE_INT_SCROLL, -1000000, 1000000}, {0}, }; static int s_aIds[NUM_PROPS] = {0}; int NewVal = 0; int Prop = pEditor->DoProperties(&View, aProps, s_aIds, &NewVal); if(Prop != -1) pEditor->m_Map.m_Modified = true; if(Prop == PROP_POS_X) { float Offset = NewVal*1000-pQuad->m_aPoints[4].x; for(int k = 0; k < 5; ++k) pQuad->m_aPoints[k].x += Offset; } if(Prop == PROP_POS_Y) { float Offset = NewVal*1000-pQuad->m_aPoints[4].y; for(int k = 0; k < 5; ++k) pQuad->m_aPoints[k].y += Offset; } if(Prop == PROP_POS_ENV) { int Index = clamp(NewVal-1, -1, pEditor->m_Map.m_lEnvelopes.size()-1); int Step = (Index-pQuad->m_PosEnv)%2; if(Step != 0) { for(; Index >= -1 && Index < pEditor->m_Map.m_lEnvelopes.size(); Index += Step) if(Index == -1 || pEditor->m_Map.m_lEnvelopes[Index]->m_Channels == 3) { pQuad->m_PosEnv = Index; break; } } } if(Prop == PROP_POS_ENV_OFFSET) pQuad->m_PosEnvOffset = NewVal; if(Prop == PROP_COLOR_ENV) { int Index = clamp(NewVal-1, -1, pEditor->m_Map.m_lEnvelopes.size()-1); int Step = (Index-pQuad->m_ColorEnv)%2; if(Step != 0) { for(; Index >= -1 && Index < pEditor->m_Map.m_lEnvelopes.size(); Index += Step) if(Index == -1 || pEditor->m_Map.m_lEnvelopes[Index]->m_Channels == 4) { pQuad->m_ColorEnv = Index; break; } } } if(Prop == PROP_COLOR_ENV_OFFSET) pQuad->m_ColorEnvOffset = NewVal; return 0; } int CEditor::PopupPoint(CEditor *pEditor, CUIRect View) { CQuad *pQuad = pEditor->GetSelectedQuad(); enum { PROP_POS_X=0, PROP_POS_Y, PROP_COLOR, NUM_PROPS, }; int Color = 0; int x = 0, y = 0; for(int v = 0; v < 4; v++) { if(pEditor->m_SelectedPoints&(1<<v)) { Color = 0; Color |= pQuad->m_aColors[v].r<<24; Color |= pQuad->m_aColors[v].g<<16; Color |= pQuad->m_aColors[v].b<<8; Color |= pQuad->m_aColors[v].a; x = pQuad->m_aPoints[v].x/1000; y = pQuad->m_aPoints[v].y/1000; } } CProperty aProps[] = { {"Pos X", x, PROPTYPE_INT_SCROLL, -1000000, 1000000}, {"Pos Y", y, PROPTYPE_INT_SCROLL, -1000000, 1000000}, {"Color", Color, PROPTYPE_COLOR, -1, pEditor->m_Map.m_lEnvelopes.size()}, {0}, }; static int s_aIds[NUM_PROPS] = {0}; int NewVal = 0; int Prop = pEditor->DoProperties(&View, aProps, s_aIds, &NewVal); if(Prop != -1) pEditor->m_Map.m_Modified = true; if(Prop == PROP_POS_X) { for(int v = 0; v < 4; v++) if(pEditor->m_SelectedPoints&(1<<v)) pQuad->m_aPoints[v].x = NewVal*1000; } if(Prop == PROP_POS_Y) { for(int v = 0; v < 4; v++) if(pEditor->m_SelectedPoints&(1<<v)) pQuad->m_aPoints[v].y = NewVal*1000; } if(Prop == PROP_COLOR) { for(int v = 0; v < 4; v++) { if(pEditor->m_SelectedPoints&(1<<v)) { pQuad->m_aColors[v].r = (NewVal>>24)&0xff; pQuad->m_aColors[v].g = (NewVal>>16)&0xff; pQuad->m_aColors[v].b = (NewVal>>8)&0xff; pQuad->m_aColors[v].a = NewVal&0xff; } } } return 0; } int CEditor::PopupNewFolder(CEditor *pEditor, CUIRect View) { CUIRect Label, ButtonBar; // title View.HSplitTop(10.0f, 0, &View); View.HSplitTop(30.0f, &Label, &View); pEditor->UI()->DoLabel(&Label, "Create new folder", 20.0f, 0); View.HSplitBottom(10.0f, &View, 0); View.HSplitBottom(20.0f, &View, &ButtonBar); if(pEditor->m_FileDialogErrString[0] == 0) { // interaction box View.HSplitBottom(40.0f, &View, 0); View.VMargin(40.0f, &View); View.HSplitBottom(20.0f, &View, &Label); static float s_FolderBox = 0; pEditor->DoEditBox(&s_FolderBox, &Label, pEditor->m_FileDialogNewFolderName, sizeof(pEditor->m_FileDialogNewFolderName), 15.0f, &s_FolderBox); View.HSplitBottom(20.0f, &View, &Label); pEditor->UI()->DoLabel(&Label, "Name:", 10.0f, -1); // button bar ButtonBar.VSplitLeft(30.0f, 0, &ButtonBar); ButtonBar.VSplitLeft(110.0f, &Label, &ButtonBar); static int s_CreateButton = 0; if(pEditor->DoButton_Editor(&s_CreateButton, "Create", 0, &Label, 0, 0)) { // create the folder if(*pEditor->m_FileDialogNewFolderName) { char aBuf[512]; str_format(aBuf, sizeof(aBuf), "%s/%s", pEditor->m_pFileDialogPath, pEditor->m_FileDialogNewFolderName); if(pEditor->Storage()->CreateFolder(aBuf, IStorage::TYPE_SAVE)) { pEditor->FilelistPopulate(IStorage::TYPE_SAVE); return 1; } else str_copy(pEditor->m_FileDialogErrString, "Unable to create the folder", sizeof(pEditor->m_FileDialogErrString)); } } ButtonBar.VSplitRight(30.0f, &ButtonBar, 0); ButtonBar.VSplitRight(110.0f, &ButtonBar, &Label); static int s_AbortButton = 0; if(pEditor->DoButton_Editor(&s_AbortButton, "Abort", 0, &Label, 0, 0)) return 1; } else { // error text View.HSplitTop(30.0f, 0, &View); View.VMargin(40.0f, &View); View.HSplitTop(20.0f, &Label, &View); pEditor->UI()->DoLabel(&Label, "Error:", 10.0f, -1); View.HSplitTop(20.0f, &Label, &View); pEditor->UI()->DoLabel(&Label, "Unable to create the folder", 10.0f, -1, View.w); // button ButtonBar.VMargin(ButtonBar.w/2.0f-55.0f, &ButtonBar); static int s_CreateButton = 0; if(pEditor->DoButton_Editor(&s_CreateButton, "Ok", 0, &ButtonBar, 0, 0)) return 1; } return 0; } int CEditor::PopupMapInfo(CEditor *pEditor, CUIRect View) { CUIRect Label, ButtonBar, Button; // title View.HSplitTop(10.0f, 0, &View); View.HSplitTop(30.0f, &Label, &View); pEditor->UI()->DoLabel(&Label, "Map details", 20.0f, 0); View.HSplitBottom(10.0f, &View, 0); View.HSplitBottom(20.0f, &View, &ButtonBar); View.VMargin(40.0f, &View); // author box View.HSplitTop(20.0f, &Label, &View); pEditor->UI()->DoLabel(&Label, "Author:", 10.0f, -1); Label.VSplitLeft(40.0f, 0, &Button); Button.HSplitTop(12.0f, &Button, 0); static float s_AuthorBox = 0; pEditor->DoEditBox(&s_AuthorBox, &Button, pEditor->m_Map.m_MapInfo.m_aAuthorTmp, sizeof(pEditor->m_Map.m_MapInfo.m_aAuthorTmp), 10.0f, &s_AuthorBox); // version box View.HSplitTop(20.0f, &Label, &View); pEditor->UI()->DoLabel(&Label, "Version:", 10.0f, -1); Label.VSplitLeft(40.0f, 0, &Button); Button.HSplitTop(12.0f, &Button, 0); static float s_VersionBox = 0; pEditor->DoEditBox(&s_VersionBox, &Button, pEditor->m_Map.m_MapInfo.m_aVersionTmp, sizeof(pEditor->m_Map.m_MapInfo.m_aVersionTmp), 10.0f, &s_VersionBox); // credits box View.HSplitTop(20.0f, &Label, &View); pEditor->UI()->DoLabel(&Label, "Credits:", 10.0f, -1); Label.VSplitLeft(40.0f, 0, &Button); Button.HSplitTop(12.0f, &Button, 0); static float s_CreditsBox = 0; pEditor->DoEditBox(&s_CreditsBox, &Button, pEditor->m_Map.m_MapInfo.m_aCreditsTmp, sizeof(pEditor->m_Map.m_MapInfo.m_aCreditsTmp), 10.0f, &s_CreditsBox); // license box View.HSplitTop(20.0f, &Label, &View); pEditor->UI()->DoLabel(&Label, "License:", 10.0f, -1); Label.VSplitLeft(40.0f, 0, &Button); Button.HSplitTop(12.0f, &Button, 0); static float s_LicenseBox = 0; pEditor->DoEditBox(&s_LicenseBox, &Button, pEditor->m_Map.m_MapInfo.m_aLicenseTmp, sizeof(pEditor->m_Map.m_MapInfo.m_aLicenseTmp), 10.0f, &s_LicenseBox); // button bar ButtonBar.VSplitLeft(30.0f, 0, &ButtonBar); ButtonBar.VSplitLeft(110.0f, &Label, &ButtonBar); static int s_CreateButton = 0; if(pEditor->DoButton_Editor(&s_CreateButton, "Save", 0, &Label, 0, 0)) { str_copy(pEditor->m_Map.m_MapInfo.m_aAuthor, pEditor->m_Map.m_MapInfo.m_aAuthorTmp, sizeof(pEditor->m_Map.m_MapInfo.m_aAuthor)); str_copy(pEditor->m_Map.m_MapInfo.m_aVersion, pEditor->m_Map.m_MapInfo.m_aVersionTmp, sizeof(pEditor->m_Map.m_MapInfo.m_aVersion)); str_copy(pEditor->m_Map.m_MapInfo.m_aCredits, pEditor->m_Map.m_MapInfo.m_aCreditsTmp, sizeof(pEditor->m_Map.m_MapInfo.m_aCredits)); str_copy(pEditor->m_Map.m_MapInfo.m_aLicense, pEditor->m_Map.m_MapInfo.m_aLicenseTmp, sizeof(pEditor->m_Map.m_MapInfo.m_aLicense)); return 1; } ButtonBar.VSplitRight(30.0f, &ButtonBar, 0); ButtonBar.VSplitRight(110.0f, &ButtonBar, &Label); static int s_AbortButton = 0; if(pEditor->DoButton_Editor(&s_AbortButton, "Abort", 0, &Label, 0, 0)) return 1; return 0; } int CEditor::PopupEvent(CEditor *pEditor, CUIRect View) { CUIRect Label, ButtonBar; // title View.HSplitTop(10.0f, 0, &View); View.HSplitTop(30.0f, &Label, &View); if(pEditor->m_PopupEventType == POPEVENT_EXIT) pEditor->UI()->DoLabel(&Label, "Exit the editor", 20.0f, 0); else if(pEditor->m_PopupEventType == POPEVENT_LOAD) pEditor->UI()->DoLabel(&Label, "Load map", 20.0f, 0); else if(pEditor->m_PopupEventType == POPEVENT_NEW) pEditor->UI()->DoLabel(&Label, "New map", 20.0f, 0); else if(pEditor->m_PopupEventType == POPEVENT_SAVE) pEditor->UI()->DoLabel(&Label, "Save map", 20.0f, 0); View.HSplitBottom(10.0f, &View, 0); View.HSplitBottom(20.0f, &View, &ButtonBar); // notification text View.HSplitTop(30.0f, 0, &View); View.VMargin(40.0f, &View); View.HSplitTop(20.0f, &Label, &View); if(pEditor->m_PopupEventType == POPEVENT_EXIT) pEditor->UI()->DoLabel(&Label, "The map contains unsaved data, you might want to save it before you exit the editor.\nContinue anyway?", 10.0f, -1, Label.w-10.0f); else if(pEditor->m_PopupEventType == POPEVENT_LOAD) pEditor->UI()->DoLabel(&Label, "The map contains unsaved data, you might want to save it before you load a new map.\nContinue anyway?", 10.0f, -1, Label.w-10.0f); else if(pEditor->m_PopupEventType == POPEVENT_NEW) pEditor->UI()->DoLabel(&Label, "The map contains unsaved data, you might want to save it before you create a new map.\nContinue anyway?", 10.0f, -1, Label.w-10.0f); else if(pEditor->m_PopupEventType == POPEVENT_SAVE) pEditor->UI()->DoLabel(&Label, "The file already exists.\nDo you want to overwrite the map?", 10.0f, -1); // button bar ButtonBar.VSplitLeft(30.0f, 0, &ButtonBar); ButtonBar.VSplitLeft(110.0f, &Label, &ButtonBar); static int s_OkButton = 0; if(pEditor->DoButton_Editor(&s_OkButton, "Ok", 0, &Label, 0, 0)) { if(pEditor->m_PopupEventType == POPEVENT_EXIT) g_Config.m_ClEditor = 0; else if(pEditor->m_PopupEventType == POPEVENT_LOAD) pEditor->InvokeFileDialog(IStorage::TYPE_ALL, FILETYPE_MAP, "Load map", "Load", "maps", "", pEditor->CallbackOpenMap, pEditor); else if(pEditor->m_PopupEventType == POPEVENT_NEW) { pEditor->Reset(); pEditor->m_aFileName[0] = 0; } else if(pEditor->m_PopupEventType == POPEVENT_SAVE) pEditor->CallbackSaveMap(pEditor->m_aFileSaveName, IStorage::TYPE_SAVE, pEditor); pEditor->m_PopupEventWasActivated = false; return 1; } ButtonBar.VSplitRight(30.0f, &ButtonBar, 0); ButtonBar.VSplitRight(110.0f, &ButtonBar, &Label); static int s_AbortButton = 0; if(pEditor->DoButton_Editor(&s_AbortButton, "Abort", 0, &Label, 0, 0)) { pEditor->m_PopupEventWasActivated = false; return 1; } return 0; } static int g_SelectImageSelected = -100; static int g_SelectImageCurrent = -100; int CEditor::PopupSelectImage(CEditor *pEditor, CUIRect View) { CUIRect ButtonBar, ImageView; View.VSplitLeft(80.0f, &ButtonBar, &View); View.Margin(10.0f, &ImageView); int ShowImage = g_SelectImageCurrent; for(int i = -1; i < pEditor->m_Map.m_lImages.size(); i++) { CUIRect Button; ButtonBar.HSplitTop(12.0f, &Button, &ButtonBar); ButtonBar.HSplitTop(2.0f, 0, &ButtonBar); if(pEditor->UI()->MouseInside(&Button)) ShowImage = i; if(i == -1) { if(pEditor->DoButton_MenuItem(&pEditor->m_Map.m_lImages[i], "None", i==g_SelectImageCurrent, &Button)) g_SelectImageSelected = -1; } else { if(pEditor->DoButton_MenuItem(&pEditor->m_Map.m_lImages[i], pEditor->m_Map.m_lImages[i]->m_aName, i==g_SelectImageCurrent, &Button)) g_SelectImageSelected = i; } } if(ShowImage >= 0 && ShowImage < pEditor->m_Map.m_lImages.size()) { if(ImageView.h < ImageView.w) ImageView.w = ImageView.h; else ImageView.h = ImageView.w; float Max = (float)(max(pEditor->m_Map.m_lImages[ShowImage]->m_Width, pEditor->m_Map.m_lImages[ShowImage]->m_Height)); ImageView.w *= pEditor->m_Map.m_lImages[ShowImage]->m_Width/Max; ImageView.h *= pEditor->m_Map.m_lImages[ShowImage]->m_Height/Max; pEditor->Graphics()->TextureSet(pEditor->m_Map.m_lImages[ShowImage]->m_Texture); pEditor->Graphics()->BlendNormal(); pEditor->Graphics()->WrapClamp(); pEditor->Graphics()->QuadsBegin(); IGraphics::CQuadItem QuadItem(ImageView.x, ImageView.y, ImageView.w, ImageView.h); pEditor->Graphics()->QuadsDrawTL(&QuadItem, 1); pEditor->Graphics()->QuadsEnd(); pEditor->Graphics()->WrapNormal(); } return 0; } void CEditor::PopupSelectImageInvoke(int Current, float x, float y) { static int s_SelectImagePopupId = 0; g_SelectImageSelected = -100; g_SelectImageCurrent = Current; UiInvokePopupMenu(&s_SelectImagePopupId, 0, x, y, 400, 300, PopupSelectImage); } int CEditor::PopupSelectImageResult() { if(g_SelectImageSelected == -100) return -100; g_SelectImageCurrent = g_SelectImageSelected; g_SelectImageSelected = -100; return g_SelectImageCurrent; } static int s_GametileOpSelected = -1; int CEditor::PopupSelectGametileOp(CEditor *pEditor, CUIRect View) { static const char *s_pButtonNames[] = { "Clear", "Collision", "Death", "Unhookable" }; static unsigned s_NumButtons = sizeof(s_pButtonNames) / sizeof(char*); CUIRect Button; for(unsigned i = 0; i < s_NumButtons; ++i) { View.HSplitTop(2.0f, 0, &View); View.HSplitTop(12.0f, &Button, &View); if(pEditor->DoButton_Editor(&s_pButtonNames[i], s_pButtonNames[i], 0, &Button, 0, 0)) s_GametileOpSelected = i; } return 0; } void CEditor::PopupSelectGametileOpInvoke(float x, float y) { static int s_SelectGametileOpPopupId = 0; s_GametileOpSelected = -1; UiInvokePopupMenu(&s_SelectGametileOpPopupId, 0, x, y, 120.0f, 70.0f, PopupSelectGametileOp); } int CEditor::PopupSelectGameTileOpResult() { if(s_GametileOpSelected < 0) return -1; int Result = s_GametileOpSelected; s_GametileOpSelected = -1; return Result; } static bool s_AutoMapProceedOrder = false; int CEditor::PopupDoodadAutoMap(CEditor *pEditor, CUIRect View) { CLayerTiles *pLayer = static_cast<CLayerTiles*>(pEditor->GetSelectedLayer(0)); IAutoMapper *pMapper = pEditor->m_Map.m_lImages[pLayer->m_Image]->m_pAutoMapper; CUIRect Rect; View.HSplitTop(15.0f, &Rect, &View); // ruleset selection static int s_ChooseDoodadRuleset = 0; if(pEditor->DoButton_Editor(&s_ChooseDoodadRuleset, pMapper->GetRuleSetName(pLayer->m_SelectedRuleSet), 0, &Rect, 0, 0)) pEditor->UiInvokePopupMenu(&s_ChooseDoodadRuleset, 0, pEditor->UI()->MouseX(), pEditor->UI()->MouseY(), 120.0f, 12.0f+14.0f*pMapper->RuleSetNum(), PopupSelectDoodadRuleSet); View.HMargin(3.f, &View); View.HSplitTop(15.0f, &Rect, &View); // Amount int s_DoodadSelectAmountButton = 0; int NewValue = pEditor->UiDoValueSelector(&s_DoodadSelectAmountButton, &Rect, "", pLayer->m_SelectedAmount, 1, 100, 1, 1.0f, "Use left mouse button to drag and change the value. Hold shift to be more precise."); if(NewValue != pLayer->m_SelectedAmount) { pLayer->m_SelectedAmount = NewValue; } View.HMargin(3.f, &View); View.HSplitTop(15.0f, &Rect, &View); // Generate button static int s_ButtonDoodadGenerate = 0; if(pEditor->DoButton_Editor(&s_ButtonDoodadGenerate, "Generate", 0, &Rect, 0, 0)) s_AutoMapProceedOrder = true; return 0; } int CEditor::PopupSelectDoodadRuleSet(CEditor *pEditor, CUIRect View) { CLayerTiles *pLayer = static_cast<CLayerTiles*>(pEditor->GetSelectedLayer(0)); CUIRect Button; static int s_AutoMapperDoodadButtons[IAutoMapper::MAX_RULES]; IAutoMapper *pMapper = pEditor->m_Map.m_lImages[pLayer->m_Image]->m_pAutoMapper; for(int i = 0; i < pMapper->RuleSetNum(); ++i) { View.HSplitTop(2.0f, 0, &View); View.HSplitTop(12.0f, &Button, &View); if(pEditor->DoButton_Editor(&s_AutoMapperDoodadButtons[i], pMapper->GetRuleSetName(i), 0, &Button, 0, 0)) { pLayer->m_SelectedRuleSet = i; return 1; // close the popup } } return 0; } int CEditor::PopupSelectConfigAutoMap(CEditor *pEditor, CUIRect View) { CLayerTiles *pLayer = static_cast<CLayerTiles*>(pEditor->GetSelectedLayer(0)); CUIRect Button; static int s_AutoMapperConfigButtons[IAutoMapper::MAX_RULES]; for(int i = 0; i < pEditor->m_Map.m_lImages[pLayer->m_Image]->m_pAutoMapper->RuleSetNum(); ++i) { View.HSplitTop(2.0f, 0, &View); View.HSplitTop(12.0f, &Button, &View); if(pEditor->DoButton_Editor(&s_AutoMapperConfigButtons[i], pEditor->m_Map.m_lImages[pLayer->m_Image]->m_pAutoMapper->GetRuleSetName(i), 0, &Button, 0, 0)) { pLayer->m_SelectedRuleSet = i; s_AutoMapProceedOrder = true; break; } } return 0; } void CEditor::PopupSelectConfigAutoMapInvoke(float x, float y) { static int s_AutoMapConfigSelectID = 0; CLayerTiles *pLayer = static_cast<CLayerTiles*>(GetSelectedLayer(0)); if(pLayer && pLayer->m_Image >= 0 && pLayer->m_Image < m_Map.m_lImages.size() && m_Map.m_lImages[pLayer->m_Image]->m_pAutoMapper->RuleSetNum()) { if(m_Map.m_lImages[pLayer->m_Image]->m_pAutoMapper->GetType() == IAutoMapper::TYPE_TILESET) UiInvokePopupMenu(&s_AutoMapConfigSelectID, 0, x, y, 120.0f, 12.0f+14.0f*m_Map.m_lImages[pLayer->m_Image]->m_pAutoMapper->RuleSetNum(), PopupSelectConfigAutoMap); else if(m_Map.m_lImages[pLayer->m_Image]->m_pAutoMapper->GetType() == IAutoMapper::TYPE_DOODADS) UiInvokePopupMenu(&s_AutoMapConfigSelectID, 0, x, y, 120.0f, 60.0f, PopupDoodadAutoMap); } } bool CEditor::PopupAutoMapProceedOrder() { if(s_AutoMapProceedOrder) { // reset s_AutoMapProceedOrder = false; return true; } return false; } ================================================ FILE: src/game/gamecore.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include "gamecore.h" const char *CTuningParams::m_apNames[] = { #define MACRO_TUNING_PARAM(Name,ScriptName,Value) #ScriptName, #include "tuning.h" #undef MACRO_TUNING_PARAM }; bool CTuningParams::Set(int Index, float Value) { if(Index < 0 || Index >= Num()) return false; ((CTuneParam *)this)[Index] = Value; return true; } bool CTuningParams::Get(int Index, float *pValue) { if(Index < 0 || Index >= Num()) return false; *pValue = (float)((CTuneParam *)this)[Index]; return true; } bool CTuningParams::Set(const char *pName, float Value) { for(int i = 0; i < Num(); i++) if(str_comp_nocase(pName, m_apNames[i]) == 0) return Set(i, Value); return false; } bool CTuningParams::Get(const char *pName, float *pValue) { for(int i = 0; i < Num(); i++) if(str_comp_nocase(pName, m_apNames[i]) == 0) return Get(i, pValue); return false; } float HermiteBasis1(float v) { return 2*v*v*v - 3*v*v+1; } float VelocityRamp(float Value, float Start, float Range, float Curvature) { if(Value < Start) return 1.0f; return 1.0f/powf(Curvature, (Value-Start)/Range); } void CCharacterCore::Init(CWorldCore *pWorld, CCollision *pCollision) { m_pWorld = pWorld; m_pCollision = pCollision; } void CCharacterCore::Reset() { m_Pos = vec2(0,0); m_Vel = vec2(0,0); m_HookPos = vec2(0,0); m_HookDir = vec2(0,0); m_HookTick = 0; m_HookState = HOOK_IDLE; m_HookedPlayer = -1; m_Jumped = 0; m_TriggeredEvents = 0; } void CCharacterCore::Tick(bool UseInput) { float PhysSize = 28.0f; m_TriggeredEvents = 0; // get ground state bool Grounded = false; if(m_pCollision->CheckPoint(m_Pos.x+PhysSize/2, m_Pos.y+PhysSize/2+5)) Grounded = true; if(m_pCollision->CheckPoint(m_Pos.x-PhysSize/2, m_Pos.y+PhysSize/2+5)) Grounded = true; vec2 TargetDirection = normalize(vec2(m_Input.m_TargetX, m_Input.m_TargetY)); m_Vel.y += m_pWorld->m_Tuning.m_Gravity; float MaxSpeed = Grounded ? m_pWorld->m_Tuning.m_GroundControlSpeed : m_pWorld->m_Tuning.m_AirControlSpeed; float Accel = Grounded ? m_pWorld->m_Tuning.m_GroundControlAccel : m_pWorld->m_Tuning.m_AirControlAccel; float Friction = Grounded ? m_pWorld->m_Tuning.m_GroundFriction : m_pWorld->m_Tuning.m_AirFriction; // handle input if(UseInput) { m_Direction = m_Input.m_Direction; // setup angle float a = 0; if(m_Input.m_TargetX == 0) a = atanf((float)m_Input.m_TargetY); else a = atanf((float)m_Input.m_TargetY/(float)m_Input.m_TargetX); if(m_Input.m_TargetX < 0) a = a+pi; m_Angle = (int)(a*256.0f); // handle jump if(m_Input.m_Jump) { if(!(m_Jumped&1)) { if(Grounded) { m_TriggeredEvents |= COREEVENTFLAG_GROUND_JUMP; m_Vel.y = -m_pWorld->m_Tuning.m_GroundJumpImpulse; m_Jumped |= 1; } else if(!(m_Jumped&2)) { m_TriggeredEvents |= COREEVENTFLAG_AIR_JUMP; m_Vel.y = -m_pWorld->m_Tuning.m_AirJumpImpulse; m_Jumped |= 3; } } } else m_Jumped &= ~1; // handle hook if(m_Input.m_Hook) { if(m_HookState == HOOK_IDLE) { m_HookState = HOOK_FLYING; m_HookPos = m_Pos+TargetDirection*PhysSize*1.5f; m_HookDir = TargetDirection; m_HookedPlayer = -1; m_HookTick = 0; //m_TriggeredEvents |= COREEVENTFLAG_HOOK_LAUNCH; } } else { m_HookedPlayer = -1; m_HookState = HOOK_IDLE; m_HookPos = vec2(0,0); m_HookDir = vec2(0,0); m_HookTick = 0; } } // add the speed modification according to players wanted direction if(m_Direction < 0) m_Vel.x = SaturatedAdd(-MaxSpeed, MaxSpeed, m_Vel.x, -Accel); if(m_Direction > 0) m_Vel.x = SaturatedAdd(-MaxSpeed, MaxSpeed, m_Vel.x, Accel); if(m_Direction == 0) m_Vel.x *= Friction; // handle jumping // 1 bit = to keep track if a jump has been made on this input // 2 bit = to keep track if a air-jump has been made if(Grounded) m_Jumped &= ~2; // do hook if(m_HookState == HOOK_IDLE) { m_HookedPlayer = -1; m_HookState = HOOK_IDLE; m_HookPos = m_Pos; } else if(m_HookState >= HOOK_RETRACT_START && m_HookState < HOOK_RETRACT_END) { m_HookState++; } else if(m_HookState == HOOK_RETRACT_END) { m_HookState = HOOK_RETRACTED; //m_TriggeredEvents |= COREEVENTFLAG_HOOK_RETRACT; m_HookState = HOOK_RETRACTED; } else if(m_HookState == HOOK_FLYING) { vec2 NewPos = m_HookPos+m_HookDir*m_pWorld->m_Tuning.m_HookFireSpeed; if(distance(m_Pos, NewPos) > m_pWorld->m_Tuning.m_HookLength) { m_HookState = HOOK_RETRACT_START; NewPos = m_Pos + normalize(NewPos-m_Pos) * m_pWorld->m_Tuning.m_HookLength; } // make sure that the hook doesn't go though the ground bool GoingToHitGround = false; bool GoingToRetract = false; int Hit = m_pCollision->IntersectLine(m_HookPos, NewPos, &NewPos, 0); if(Hit) { if(Hit&CCollision::COLFLAG_NOHOOK) GoingToRetract = true; else GoingToHitGround = true; } // Check against other players first if(m_pWorld && m_pWorld->m_Tuning.m_PlayerHooking) { float Distance = 0.0f; for(int i = 0; i < MAX_CLIENTS; i++) { CCharacterCore *pCharCore = m_pWorld->m_apCharacters[i]; if(!pCharCore || pCharCore == this) continue; vec2 ClosestPoint = closest_point_on_line(m_HookPos, NewPos, pCharCore->m_Pos); if(distance(pCharCore->m_Pos, ClosestPoint) < PhysSize+2.0f) { if (m_HookedPlayer == -1 || distance(m_HookPos, pCharCore->m_Pos) < Distance) { m_TriggeredEvents |= COREEVENTFLAG_HOOK_ATTACH_PLAYER; m_HookState = HOOK_GRABBED; m_HookedPlayer = i; Distance = distance(m_HookPos, pCharCore->m_Pos); } } } } if(m_HookState == HOOK_FLYING) { // check against ground if(GoingToHitGround) { m_TriggeredEvents |= COREEVENTFLAG_HOOK_ATTACH_GROUND; m_HookState = HOOK_GRABBED; } else if(GoingToRetract) { m_TriggeredEvents |= COREEVENTFLAG_HOOK_HIT_NOHOOK; m_HookState = HOOK_RETRACT_START; } m_HookPos = NewPos; } } if(m_HookState == HOOK_GRABBED) { if(m_HookedPlayer != -1) { CCharacterCore *pCharCore = m_pWorld->m_apCharacters[m_HookedPlayer]; if(pCharCore) m_HookPos = pCharCore->m_Pos; else { // release hook m_HookedPlayer = -1; m_HookState = HOOK_RETRACTED; m_HookPos = m_Pos; } // keep players hooked for a max of 1.5sec //if(Server()->Tick() > hook_tick+(Server()->TickSpeed()*3)/2) //release_hooked(); } // don't do this hook rutine when we are hook to a player if(m_HookedPlayer == -1 && distance(m_HookPos, m_Pos) > 46.0f) { vec2 HookVel = normalize(m_HookPos-m_Pos)*m_pWorld->m_Tuning.m_HookDragAccel; // the hook as more power to drag you up then down. // this makes it easier to get on top of an platform if(HookVel.y > 0) HookVel.y *= 0.3f; // the hook will boost it's power if the player wants to move // in that direction. otherwise it will dampen everything abit if((HookVel.x < 0 && m_Direction < 0) || (HookVel.x > 0 && m_Direction > 0)) HookVel.x *= 0.95f; else HookVel.x *= 0.75f; vec2 NewVel = m_Vel+HookVel; // check if we are under the legal limit for the hook if(length(NewVel) < m_pWorld->m_Tuning.m_HookDragSpeed || length(NewVel) < length(m_Vel)) m_Vel = NewVel; // no problem. apply } // release hook (max hook time is 1.25 m_HookTick++; if(m_HookedPlayer != -1 && (m_HookTick > SERVER_TICK_SPEED+SERVER_TICK_SPEED/5 || !m_pWorld->m_apCharacters[m_HookedPlayer])) { m_HookedPlayer = -1; m_HookState = HOOK_RETRACTED; m_HookPos = m_Pos; } } if(m_pWorld) { for(int i = 0; i < MAX_CLIENTS; i++) { CCharacterCore *pCharCore = m_pWorld->m_apCharacters[i]; if(!pCharCore) continue; //player *p = (player*)ent; if(pCharCore == this) // || !(p->flags&FLAG_ALIVE) continue; // make sure that we don't nudge our self // handle player <-> player collision float Distance = distance(m_Pos, pCharCore->m_Pos); vec2 Dir = normalize(m_Pos - pCharCore->m_Pos); if(m_pWorld->m_Tuning.m_PlayerCollision && Distance < PhysSize*1.25f && Distance > 0.0f) { float a = (PhysSize*1.45f - Distance); float Velocity = 0.5f; // make sure that we don't add excess force by checking the // direction against the current velocity. if not zero. if (length(m_Vel) > 0.0001) Velocity = 1-(dot(normalize(m_Vel), Dir)+1)/2; m_Vel += Dir*a*(Velocity*0.75f); m_Vel *= 0.85f; } // handle hook influence if(m_HookedPlayer == i && m_pWorld->m_Tuning.m_PlayerHooking) { if(Distance > PhysSize*1.50f) // TODO: fix tweakable variable { float Accel = m_pWorld->m_Tuning.m_HookDragAccel * (Distance/m_pWorld->m_Tuning.m_HookLength); float DragSpeed = m_pWorld->m_Tuning.m_HookDragSpeed; // add force to the hooked player pCharCore->m_Vel.x = SaturatedAdd(-DragSpeed, DragSpeed, pCharCore->m_Vel.x, Accel*Dir.x*1.5f); pCharCore->m_Vel.y = SaturatedAdd(-DragSpeed, DragSpeed, pCharCore->m_Vel.y, Accel*Dir.y*1.5f); // add a little bit force to the guy who has the grip m_Vel.x = SaturatedAdd(-DragSpeed, DragSpeed, m_Vel.x, -Accel*Dir.x*0.25f); m_Vel.y = SaturatedAdd(-DragSpeed, DragSpeed, m_Vel.y, -Accel*Dir.y*0.25f); } } } } // clamp the velocity to something sane if(length(m_Vel) > 6000) m_Vel = normalize(m_Vel) * 6000; } void CCharacterCore::Move() { float RampValue = VelocityRamp(length(m_Vel)*50, m_pWorld->m_Tuning.m_VelrampStart, m_pWorld->m_Tuning.m_VelrampRange, m_pWorld->m_Tuning.m_VelrampCurvature); m_Vel.x = m_Vel.x*RampValue; vec2 NewPos = m_Pos; m_pCollision->MoveBox(&NewPos, &m_Vel, vec2(28.0f, 28.0f), 0); m_Vel.x = m_Vel.x*(1.0f/RampValue); if(m_pWorld && m_pWorld->m_Tuning.m_PlayerCollision) { // check player collision float Distance = distance(m_Pos, NewPos); int End = Distance+1; vec2 LastPos = m_Pos; for(int i = 0; i < End; i++) { float a = i/Distance; vec2 Pos = mix(m_Pos, NewPos, a); for(int p = 0; p < MAX_CLIENTS; p++) { CCharacterCore *pCharCore = m_pWorld->m_apCharacters[p]; if(!pCharCore || pCharCore == this) continue; float D = distance(Pos, pCharCore->m_Pos); if(D < 28.0f && D > 0.0f) { if(a > 0.0f) m_Pos = LastPos; else if(distance(NewPos, pCharCore->m_Pos) > D) m_Pos = NewPos; return; } } LastPos = Pos; } } m_Pos = NewPos; } void CCharacterCore::Write(CNetObj_CharacterCore *pObjCore) { pObjCore->m_X = round(m_Pos.x); pObjCore->m_Y = round(m_Pos.y); pObjCore->m_VelX = round(m_Vel.x*256.0f); pObjCore->m_VelY = round(m_Vel.y*256.0f); pObjCore->m_HookState = m_HookState; pObjCore->m_HookTick = m_HookTick; pObjCore->m_HookX = round(m_HookPos.x); pObjCore->m_HookY = round(m_HookPos.y); pObjCore->m_HookedPlayer = m_HookedPlayer; pObjCore->m_Jumped = m_Jumped; pObjCore->m_Direction = m_Direction; pObjCore->m_Angle = m_Angle; } void CCharacterCore::Read(const CNetObj_CharacterCore *pObjCore) { m_Pos.x = pObjCore->m_X; m_Pos.y = pObjCore->m_Y; m_Vel.x = pObjCore->m_VelX/256.0f; m_Vel.y = pObjCore->m_VelY/256.0f; m_HookState = pObjCore->m_HookState; m_HookTick = pObjCore->m_HookTick; m_HookPos.x = pObjCore->m_HookX; m_HookPos.y = pObjCore->m_HookY; m_HookDir = normalize(m_HookPos-m_Pos); m_HookedPlayer = pObjCore->m_HookedPlayer; m_Jumped = pObjCore->m_Jumped; m_Direction = pObjCore->m_Direction; m_Angle = pObjCore->m_Angle; } void CCharacterCore::Quantize() { CNetObj_CharacterCore Core; Write(&Core); Read(&Core); } ================================================ FILE: src/game/gamecore.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_GAMECORE_H #define GAME_GAMECORE_H #include <base/system.h> #include <base/math.h> #include <math.h> #include "collision.h" #include <engine/shared/protocol.h> #include <game/generated/protocol.h> class CTuneParam { int m_Value; public: void Set(int v) { m_Value = v; } int Get() const { return m_Value; } CTuneParam &operator = (int v) { m_Value = (int)(v*100.0f); return *this; } CTuneParam &operator = (float v) { m_Value = (int)(v*100.0f); return *this; } operator float() const { return m_Value/100.0f; } }; class CTuningParams { public: CTuningParams() { const float TicksPerSecond = 50.0f; #define MACRO_TUNING_PARAM(Name,ScriptName,Value) m_##Name.Set((int)(Value*100.0f)); #include "tuning.h" #undef MACRO_TUNING_PARAM } static const char *m_apNames[]; #define MACRO_TUNING_PARAM(Name,ScriptName,Value) CTuneParam m_##Name; #include "tuning.h" #undef MACRO_TUNING_PARAM static int Num() { return sizeof(CTuningParams)/sizeof(int); } bool Set(int Index, float Value); bool Set(const char *pName, float Value); bool Get(int Index, float *pValue); bool Get(const char *pName, float *pValue); }; inline vec2 GetDirection(int Angle) { float a = Angle/256.0f; return vec2(cosf(a), sinf(a)); } inline vec2 GetDir(float Angle) { return vec2(cosf(Angle), sinf(Angle)); } inline float GetAngle(vec2 Dir) { if(Dir.x == 0 && Dir.y == 0) return 0.0f; float a = atanf(Dir.y/Dir.x); if(Dir.x < 0) a = a+pi; return a; } inline void StrToInts(int *pInts, int Num, const char *pStr) { int Index = 0; while(Num) { char aBuf[4] = {0,0,0,0}; for(int c = 0; c < 4 && pStr[Index]; c++, Index++) aBuf[c] = pStr[Index]; *pInts = ((aBuf[0]+128)<<24)|((aBuf[1]+128)<<16)|((aBuf[2]+128)<<8)|(aBuf[3]+128); pInts++; Num--; } // null terminate pInts[-1] &= 0xffffff00; } inline void IntsToStr(const int *pInts, int Num, char *pStr) { while(Num) { pStr[0] = (((*pInts)>>24)&0xff)-128; pStr[1] = (((*pInts)>>16)&0xff)-128; pStr[2] = (((*pInts)>>8)&0xff)-128; pStr[3] = ((*pInts)&0xff)-128; pStr += 4; pInts++; Num--; } // null terminate pStr[-1] = 0; } inline vec2 CalcPos(vec2 Pos, vec2 Velocity, float Curvature, float Speed, float Time) { vec2 n; Time *= Speed; n.x = Pos.x + Velocity.x*Time; n.y = Pos.y + Velocity.y*Time + Curvature/10000*(Time*Time); return n; } template<typename T> inline T SaturatedAdd(T Min, T Max, T Current, T Modifier) { if(Modifier < 0) { if(Current < Min) return Current; Current += Modifier; if(Current < Min) Current = Min; return Current; } else { if(Current > Max) return Current; Current += Modifier; if(Current > Max) Current = Max; return Current; } } float VelocityRamp(float Value, float Start, float Range, float Curvature); // hooking stuff enum { HOOK_RETRACTED=-1, HOOK_IDLE=0, HOOK_RETRACT_START=1, HOOK_RETRACT_END=3, HOOK_FLYING, HOOK_GRABBED, }; class CWorldCore { public: CWorldCore() { mem_zero(m_apCharacters, sizeof(m_apCharacters)); } CTuningParams m_Tuning; class CCharacterCore *m_apCharacters[MAX_CLIENTS]; }; class CCharacterCore { CWorldCore *m_pWorld; CCollision *m_pCollision; public: vec2 m_Pos; vec2 m_Vel; vec2 m_HookPos; vec2 m_HookDir; int m_HookTick; int m_HookState; int m_HookedPlayer; int m_Jumped; int m_Direction; int m_Angle; CNetObj_PlayerInput m_Input; int m_TriggeredEvents; void Init(CWorldCore *pWorld, CCollision *pCollision); void Reset(); void Tick(bool UseInput); void Move(); void Read(const CNetObj_CharacterCore *pObjCore); void Write(CNetObj_CharacterCore *pObjCore); void Quantize(); }; #endif ================================================ FILE: src/game/layers.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include "layers.h" CLayers::CLayers() { m_GroupsNum = 0; m_GroupsStart = 0; m_LayersNum = 0; m_LayersStart = 0; m_pGameGroup = 0; m_pGameLayer = 0; m_pMap = 0; } void CLayers::Init(class IKernel *pKernel, IMap *pMap) { m_pMap = pMap ? pMap : pKernel->RequestInterface<IMap>(); m_pMap->GetType(MAPITEMTYPE_GROUP, &m_GroupsStart, &m_GroupsNum); m_pMap->GetType(MAPITEMTYPE_LAYER, &m_LayersStart, &m_LayersNum); for(int g = 0; g < NumGroups(); g++) { CMapItemGroup *pGroup = GetGroup(g); for(int l = 0; l < pGroup->m_NumLayers; l++) { CMapItemLayer *pLayer = GetLayer(pGroup->m_StartLayer+l); if(pLayer->m_Type == LAYERTYPE_TILES) { CMapItemLayerTilemap *pTilemap = reinterpret_cast<CMapItemLayerTilemap *>(pLayer); if(pTilemap->m_Flags&TILESLAYERFLAG_GAME) { m_pGameLayer = pTilemap; m_pGameGroup = pGroup; // make sure the game group has standard settings m_pGameGroup->m_OffsetX = 0; m_pGameGroup->m_OffsetY = 0; m_pGameGroup->m_ParallaxX = 100; m_pGameGroup->m_ParallaxY = 100; if(m_pGameGroup->m_Version >= 2) { m_pGameGroup->m_UseClipping = 0; m_pGameGroup->m_ClipX = 0; m_pGameGroup->m_ClipY = 0; m_pGameGroup->m_ClipW = 0; m_pGameGroup->m_ClipH = 0; } break; } } } } } CMapItemGroup *CLayers::GetGroup(int Index) const { return static_cast<CMapItemGroup *>(m_pMap->GetItem(m_GroupsStart+Index, 0, 0)); } CMapItemLayer *CLayers::GetLayer(int Index) const { return static_cast<CMapItemLayer *>(m_pMap->GetItem(m_LayersStart+Index, 0, 0)); } ================================================ FILE: src/game/layers.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_LAYERS_H #define GAME_LAYERS_H #include <engine/map.h> #include <game/mapitems.h> class CLayers { int m_GroupsNum; int m_GroupsStart; int m_LayersNum; int m_LayersStart; CMapItemGroup *m_pGameGroup; CMapItemLayerTilemap *m_pGameLayer; class IMap *m_pMap; public: CLayers(); void Init(class IKernel *pKernel, class IMap *pMap=0); int NumGroups() const { return m_GroupsNum; }; class IMap *Map() const { return m_pMap; }; CMapItemGroup *GameGroup() const { return m_pGameGroup; }; CMapItemLayerTilemap *GameLayer() const { return m_pGameLayer; }; CMapItemGroup *GetGroup(int Index) const; CMapItemLayer *GetLayer(int Index) const; }; #endif ================================================ FILE: src/game/mapitems.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_MAPITEMS_H #define GAME_MAPITEMS_H // layer types enum { LAYERTYPE_INVALID=0, LAYERTYPE_GAME, LAYERTYPE_TILES, LAYERTYPE_QUADS, MAPITEMTYPE_VERSION=0, MAPITEMTYPE_INFO, MAPITEMTYPE_IMAGE, MAPITEMTYPE_ENVELOPE, MAPITEMTYPE_GROUP, MAPITEMTYPE_LAYER, MAPITEMTYPE_ENVPOINTS, CURVETYPE_STEP=0, CURVETYPE_LINEAR, CURVETYPE_SLOW, CURVETYPE_FAST, CURVETYPE_SMOOTH, NUM_CURVETYPES, // game layer tiles ENTITY_NULL=0, ENTITY_SPAWN, ENTITY_SPAWN_RED, ENTITY_SPAWN_BLUE, ENTITY_FLAGSTAND_RED, ENTITY_FLAGSTAND_BLUE, ENTITY_ARMOR_1, ENTITY_HEALTH_1, ENTITY_WEAPON_SHOTGUN, ENTITY_WEAPON_GRENADE, ENTITY_POWERUP_NINJA, ENTITY_WEAPON_LASER, NUM_ENTITIES, TILE_AIR=0, TILE_SOLID, TILE_DEATH, TILE_NOHOOK, TILEFLAG_VFLIP=1, TILEFLAG_HFLIP=2, TILEFLAG_OPAQUE=4, TILEFLAG_ROTATE=8, LAYERFLAG_DETAIL=1, TILESLAYERFLAG_GAME=1, ENTITY_OFFSET=255-16*4, }; struct CPoint { int x, y; // 22.10 fixed point }; struct CColor { int r, g, b, a; }; struct CQuad { CPoint m_aPoints[5]; CColor m_aColors[4]; CPoint m_aTexcoords[4]; int m_PosEnv; int m_PosEnvOffset; int m_ColorEnv; int m_ColorEnvOffset; }; class CTile { public: unsigned char m_Index; unsigned char m_Flags; unsigned char m_Skip; unsigned char m_Reserved; }; struct CMapItemInfo { int m_Version; int m_Author; int m_MapVersion; int m_Credits; int m_License; } ; struct CMapItemImage_v1 { int m_Version; int m_Width; int m_Height; int m_External; int m_ImageName; int m_ImageData; } ; struct CMapItemImage : public CMapItemImage_v1 { enum { CURRENT_VERSION=2 }; int m_Format; }; struct CMapItemGroup_v1 { int m_Version; int m_OffsetX; int m_OffsetY; int m_ParallaxX; int m_ParallaxY; int m_StartLayer; int m_NumLayers; } ; struct CMapItemGroup : public CMapItemGroup_v1 { enum { CURRENT_VERSION=3 }; int m_UseClipping; int m_ClipX; int m_ClipY; int m_ClipW; int m_ClipH; int m_aName[3]; } ; struct CMapItemLayer { int m_Version; int m_Type; int m_Flags; } ; struct CMapItemLayerTilemap { CMapItemLayer m_Layer; int m_Version; int m_Width; int m_Height; int m_Flags; CColor m_Color; int m_ColorEnv; int m_ColorEnvOffset; int m_Image; int m_Data; int m_aName[3]; } ; struct CMapItemLayerQuads { CMapItemLayer m_Layer; int m_Version; int m_NumQuads; int m_Data; int m_Image; int m_aName[3]; } ; struct CMapItemVersion { enum { CURRENT_VERSION=1 }; int m_Version; } ; struct CEnvPoint { int m_Time; // in ms int m_Curvetype; int m_aValues[4]; // 1-4 depending on envelope (22.10 fixed point) bool operator<(const CEnvPoint &Other) { return m_Time < Other.m_Time; } } ; struct CMapItemEnvelope_v1 { int m_Version; int m_Channels; int m_StartPoint; int m_NumPoints; int m_aName[8]; } ; struct CMapItemEnvelope : public CMapItemEnvelope_v1 { enum { CURRENT_VERSION=2 }; int m_Synchronized; }; #endif ================================================ FILE: src/game/server/alloc.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_SERVER_ALLOC_H #define GAME_SERVER_ALLOC_H #include <new> #define MACRO_ALLOC_HEAP() \ public: \ void *operator new(size_t Size) \ { \ void *p = mem_alloc(Size, 1); \ /*dbg_msg("", "++ %p %d", p, size);*/ \ mem_zero(p, Size); \ return p; \ } \ void operator delete(void *pPtr) \ { \ /*dbg_msg("", "-- %p", p);*/ \ mem_free(pPtr); \ } \ private: #define MACRO_ALLOC_POOL_ID() \ public: \ void *operator new(size_t Size, int id); \ void operator delete(void *p); \ private: #define MACRO_ALLOC_POOL_ID_IMPL(POOLTYPE, PoolSize) \ static char ms_PoolData##POOLTYPE[PoolSize][sizeof(POOLTYPE)] = {{0}}; \ static int ms_PoolUsed##POOLTYPE[PoolSize] = {0}; \ void *POOLTYPE::operator new(size_t Size, int id) \ { \ dbg_assert(sizeof(POOLTYPE) == Size, "size error"); \ dbg_assert(!ms_PoolUsed##POOLTYPE[id], "already used"); \ /*dbg_msg("pool", "++ %s %d", #POOLTYPE, id);*/ \ ms_PoolUsed##POOLTYPE[id] = 1; \ mem_zero(ms_PoolData##POOLTYPE[id], Size); \ return ms_PoolData##POOLTYPE[id]; \ } \ void POOLTYPE::operator delete(void *p) \ { \ int id = (POOLTYPE*)p - (POOLTYPE*)ms_PoolData##POOLTYPE; \ dbg_assert(ms_PoolUsed##POOLTYPE[id], "not used"); \ /*dbg_msg("pool", "-- %s %d", #POOLTYPE, id);*/ \ ms_PoolUsed##POOLTYPE[id] = 0; \ mem_zero(ms_PoolData##POOLTYPE[id], sizeof(POOLTYPE)); \ } #endif ================================================ FILE: src/game/server/entities/character.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <engine/shared/config.h> #include <game/generated/server_data.h> #include <game/server/gamecontext.h> #include <game/server/gamecontroller.h> #include <game/server/player.h> #include "character.h" #include "laser.h" #include "projectile.h" //input count struct CInputCount { int m_Presses; int m_Releases; }; CInputCount CountInput(int Prev, int Cur) { CInputCount c = {0, 0}; Prev &= INPUT_STATE_MASK; Cur &= INPUT_STATE_MASK; int i = Prev; while(i != Cur) { i = (i+1)&INPUT_STATE_MASK; if(i&1) c.m_Presses++; else c.m_Releases++; } return c; } MACRO_ALLOC_POOL_ID_IMPL(CCharacter, MAX_CLIENTS) // Character, "physical" player's part CCharacter::CCharacter(CGameWorld *pWorld) : CEntity(pWorld, CGameWorld::ENTTYPE_CHARACTER) { m_ProximityRadius = ms_PhysSize; m_Health = 0; m_Armor = 0; m_TriggeredEvents = 0; } void CCharacter::Reset() { Destroy(); } bool CCharacter::Spawn(CPlayer *pPlayer, vec2 Pos) { m_EmoteStop = -1; m_LastAction = -1; m_LastNoAmmoSound = -1; m_ActiveWeapon = WEAPON_GUN; m_LastWeapon = WEAPON_HAMMER; m_QueuedWeapon = -1; m_pPlayer = pPlayer; m_Pos = Pos; m_Core.Reset(); m_Core.Init(&GameServer()->m_World.m_Core, GameServer()->Collision()); m_Core.m_Pos = m_Pos; GameServer()->m_World.m_Core.m_apCharacters[m_pPlayer->GetCID()] = &m_Core; m_ReckoningTick = 0; mem_zero(&m_SendCore, sizeof(m_SendCore)); mem_zero(&m_ReckoningCore, sizeof(m_ReckoningCore)); GameServer()->m_World.InsertEntity(this); m_Alive = true; GameServer()->m_pController->OnCharacterSpawn(this); return true; } void CCharacter::Destroy() { GameServer()->m_World.m_Core.m_apCharacters[m_pPlayer->GetCID()] = 0; m_Alive = false; } void CCharacter::SetWeapon(int W) { if(W == m_ActiveWeapon) return; m_LastWeapon = m_ActiveWeapon; m_QueuedWeapon = -1; m_ActiveWeapon = W; GameServer()->CreateSound(m_Pos, SOUND_WEAPON_SWITCH); if(m_ActiveWeapon < 0 || m_ActiveWeapon >= NUM_WEAPONS) m_ActiveWeapon = 0; } bool CCharacter::IsGrounded() { if(GameServer()->Collision()->CheckPoint(m_Pos.x+m_ProximityRadius/2, m_Pos.y+m_ProximityRadius/2+5)) return true; if(GameServer()->Collision()->CheckPoint(m_Pos.x-m_ProximityRadius/2, m_Pos.y+m_ProximityRadius/2+5)) return true; return false; } void CCharacter::HandleNinja() { if(m_ActiveWeapon != WEAPON_NINJA) return; if ((Server()->Tick() - m_Ninja.m_ActivationTick) > (g_pData->m_Weapons.m_Ninja.m_Duration * Server()->TickSpeed() / 1000)) { // time's up, return m_aWeapons[WEAPON_NINJA].m_Got = false; m_ActiveWeapon = m_LastWeapon; SetWeapon(m_ActiveWeapon); return; } // force ninja Weapon SetWeapon(WEAPON_NINJA); m_Ninja.m_CurrentMoveTime--; if (m_Ninja.m_CurrentMoveTime == 0) { // reset velocity m_Core.m_Vel = m_Ninja.m_ActivationDir*m_Ninja.m_OldVelAmount; } if (m_Ninja.m_CurrentMoveTime > 0) { // Set velocity m_Core.m_Vel = m_Ninja.m_ActivationDir * g_pData->m_Weapons.m_Ninja.m_Velocity; vec2 OldPos = m_Pos; GameServer()->Collision()->MoveBox(&m_Core.m_Pos, &m_Core.m_Vel, vec2(m_ProximityRadius, m_ProximityRadius), 0.f); // reset velocity so the client doesn't predict stuff m_Core.m_Vel = vec2(0.f, 0.f); // check if we Hit anything along the way { CCharacter *aEnts[MAX_CLIENTS]; vec2 Dir = m_Pos - OldPos; float Radius = m_ProximityRadius * 2.0f; vec2 Center = OldPos + Dir * 0.5f; int Num = GameServer()->m_World.FindEntities(Center, Radius, (CEntity**)aEnts, MAX_CLIENTS, CGameWorld::ENTTYPE_CHARACTER); for (int i = 0; i < Num; ++i) { if (aEnts[i] == this) continue; // make sure we haven't Hit this object before bool bAlreadyHit = false; for (int j = 0; j < m_NumObjectsHit; j++) { if (m_apHitObjects[j] == aEnts[i]) bAlreadyHit = true; } if (bAlreadyHit) continue; // check so we are sufficiently close if (distance(aEnts[i]->m_Pos, m_Pos) > (m_ProximityRadius * 2.0f)) continue; // Hit a player, give him damage and stuffs... GameServer()->CreateSound(aEnts[i]->m_Pos, SOUND_NINJA_HIT); // set his velocity to fast upward (for now) if(m_NumObjectsHit < 10) m_apHitObjects[m_NumObjectsHit++] = aEnts[i]; aEnts[i]->TakeDamage(vec2(0, -10.0f), g_pData->m_Weapons.m_Ninja.m_pBase->m_Damage, m_pPlayer->GetCID(), WEAPON_NINJA); } } return; } return; } void CCharacter::DoWeaponSwitch() { // make sure we can switch if(m_ReloadTimer != 0 || m_QueuedWeapon == -1 || m_aWeapons[WEAPON_NINJA].m_Got) return; // switch Weapon SetWeapon(m_QueuedWeapon); } void CCharacter::HandleWeaponSwitch() { int WantedWeapon = m_ActiveWeapon; if(m_QueuedWeapon != -1) WantedWeapon = m_QueuedWeapon; // select Weapon int Next = CountInput(m_LatestPrevInput.m_NextWeapon, m_LatestInput.m_NextWeapon).m_Presses; int Prev = CountInput(m_LatestPrevInput.m_PrevWeapon, m_LatestInput.m_PrevWeapon).m_Presses; if(Next < 128) // make sure we only try sane stuff { while(Next) // Next Weapon selection { WantedWeapon = (WantedWeapon+1)%NUM_WEAPONS; if(m_aWeapons[WantedWeapon].m_Got) Next--; } } if(Prev < 128) // make sure we only try sane stuff { while(Prev) // Prev Weapon selection { WantedWeapon = (WantedWeapon-1)<0?NUM_WEAPONS-1:WantedWeapon-1; if(m_aWeapons[WantedWeapon].m_Got) Prev--; } } // Direct Weapon selection if(m_LatestInput.m_WantedWeapon) WantedWeapon = m_Input.m_WantedWeapon-1; // check for insane values if(WantedWeapon >= 0 && WantedWeapon < NUM_WEAPONS && WantedWeapon != m_ActiveWeapon && m_aWeapons[WantedWeapon].m_Got) m_QueuedWeapon = WantedWeapon; DoWeaponSwitch(); } void CCharacter::FireWeapon() { if(m_ReloadTimer != 0) return; DoWeaponSwitch(); vec2 Direction = normalize(vec2(m_LatestInput.m_TargetX, m_LatestInput.m_TargetY)); bool FullAuto = false; if(m_ActiveWeapon == WEAPON_GRENADE || m_ActiveWeapon == WEAPON_SHOTGUN || m_ActiveWeapon == WEAPON_LASER) FullAuto = true; // check if we gonna fire bool WillFire = false; if(CountInput(m_LatestPrevInput.m_Fire, m_LatestInput.m_Fire).m_Presses) WillFire = true; if(FullAuto && (m_LatestInput.m_Fire&1) && m_aWeapons[m_ActiveWeapon].m_Ammo) WillFire = true; if(!WillFire) return; // check for ammo if(!m_aWeapons[m_ActiveWeapon].m_Ammo) { // 125ms is a magical limit of how fast a human can click m_ReloadTimer = 125 * Server()->TickSpeed() / 1000; if(m_LastNoAmmoSound+Server()->TickSpeed() <= Server()->Tick()) { GameServer()->CreateSound(m_Pos, SOUND_WEAPON_NOAMMO); m_LastNoAmmoSound = Server()->Tick(); } return; } vec2 ProjStartPos = m_Pos+Direction*m_ProximityRadius*0.75f; switch(m_ActiveWeapon) { case WEAPON_HAMMER: { // reset objects Hit m_NumObjectsHit = 0; GameServer()->CreateSound(m_Pos, SOUND_HAMMER_FIRE); CCharacter *apEnts[MAX_CLIENTS]; int Hits = 0; int Num = GameServer()->m_World.FindEntities(ProjStartPos, m_ProximityRadius*0.5f, (CEntity**)apEnts, MAX_CLIENTS, CGameWorld::ENTTYPE_CHARACTER); for (int i = 0; i < Num; ++i) { CCharacter *pTarget = apEnts[i]; if ((pTarget == this) || GameServer()->Collision()->IntersectLine(ProjStartPos, pTarget->m_Pos, NULL, NULL)) continue; // set his velocity to fast upward (for now) if(length(pTarget->m_Pos-ProjStartPos) > 0.0f) GameServer()->CreateHammerHit(pTarget->m_Pos-normalize(pTarget->m_Pos-ProjStartPos)*m_ProximityRadius*0.5f); else GameServer()->CreateHammerHit(ProjStartPos); vec2 Dir; if (length(pTarget->m_Pos - m_Pos) > 0.0f) Dir = normalize(pTarget->m_Pos - m_Pos); else Dir = vec2(0.f, -1.f); pTarget->TakeDamage(vec2(0.f, -1.f) + normalize(Dir + vec2(0.f, -1.1f)) * 10.0f, g_pData->m_Weapons.m_Hammer.m_pBase->m_Damage, m_pPlayer->GetCID(), m_ActiveWeapon); Hits++; } // if we Hit anything, we have to wait for the reload if(Hits) m_ReloadTimer = Server()->TickSpeed()/3; } break; case WEAPON_GUN: { CProjectile *pProj = new CProjectile(GameWorld(), WEAPON_GUN, m_pPlayer->GetCID(), ProjStartPos, Direction, (int)(Server()->TickSpeed()*GameServer()->Tuning()->m_GunLifetime), 1, 0, 0, -1, WEAPON_GUN); // pack the Projectile and send it to the client Directly CNetObj_Projectile p; pProj->FillInfo(&p); CMsgPacker Msg(NETMSGTYPE_SV_EXTRAPROJECTILE); Msg.AddInt(1); for(unsigned i = 0; i < sizeof(CNetObj_Projectile)/sizeof(int); i++) Msg.AddInt(((int *)&p)[i]); Server()->SendMsg(&Msg, 0, m_pPlayer->GetCID()); GameServer()->CreateSound(m_Pos, SOUND_GUN_FIRE); } break; case WEAPON_SHOTGUN: { int ShotSpread = 2; CMsgPacker Msg(NETMSGTYPE_SV_EXTRAPROJECTILE); Msg.AddInt(ShotSpread*2+1); for(int i = -ShotSpread; i <= ShotSpread; ++i) { float Spreading[] = {-0.185f, -0.070f, 0, 0.070f, 0.185f}; float a = GetAngle(Direction); a += Spreading[i+2]; float v = 1-(absolute(i)/(float)ShotSpread); float Speed = mix((float)GameServer()->Tuning()->m_ShotgunSpeeddiff, 1.0f, v); CProjectile *pProj = new CProjectile(GameWorld(), WEAPON_SHOTGUN, m_pPlayer->GetCID(), ProjStartPos, vec2(cosf(a), sinf(a))*Speed, (int)(Server()->TickSpeed()*GameServer()->Tuning()->m_ShotgunLifetime), 1, 0, 0, -1, WEAPON_SHOTGUN); // pack the Projectile and send it to the client Directly CNetObj_Projectile p; pProj->FillInfo(&p); for(unsigned i = 0; i < sizeof(CNetObj_Projectile)/sizeof(int); i++) Msg.AddInt(((int *)&p)[i]); } Server()->SendMsg(&Msg, 0,m_pPlayer->GetCID()); GameServer()->CreateSound(m_Pos, SOUND_SHOTGUN_FIRE); } break; case WEAPON_GRENADE: { CProjectile *pProj = new CProjectile(GameWorld(), WEAPON_GRENADE, m_pPlayer->GetCID(), ProjStartPos, Direction, (int)(Server()->TickSpeed()*GameServer()->Tuning()->m_GrenadeLifetime), 1, true, 0, SOUND_GRENADE_EXPLODE, WEAPON_GRENADE); // pack the Projectile and send it to the client Directly CNetObj_Projectile p; pProj->FillInfo(&p); CMsgPacker Msg(NETMSGTYPE_SV_EXTRAPROJECTILE); Msg.AddInt(1); for(unsigned i = 0; i < sizeof(CNetObj_Projectile)/sizeof(int); i++) Msg.AddInt(((int *)&p)[i]); Server()->SendMsg(&Msg, 0, m_pPlayer->GetCID()); GameServer()->CreateSound(m_Pos, SOUND_GRENADE_FIRE); } break; case WEAPON_LASER: { new CLaser(GameWorld(), m_Pos, Direction, GameServer()->Tuning()->m_LaserReach, m_pPlayer->GetCID()); GameServer()->CreateSound(m_Pos, SOUND_LASER_FIRE); } break; case WEAPON_NINJA: { // reset Hit objects m_NumObjectsHit = 0; m_Ninja.m_ActivationDir = Direction; m_Ninja.m_CurrentMoveTime = g_pData->m_Weapons.m_Ninja.m_Movetime * Server()->TickSpeed() / 1000; m_Ninja.m_OldVelAmount = length(m_Core.m_Vel); GameServer()->CreateSound(m_Pos, SOUND_NINJA_FIRE); } break; } m_AttackTick = Server()->Tick(); if(m_aWeapons[m_ActiveWeapon].m_Ammo > 0) // -1 == unlimited m_aWeapons[m_ActiveWeapon].m_Ammo--; if(!m_ReloadTimer) m_ReloadTimer = g_pData->m_Weapons.m_aId[m_ActiveWeapon].m_Firedelay * Server()->TickSpeed() / 1000; } void CCharacter::HandleWeapons() { //ninja HandleNinja(); // check reload timer if(m_ReloadTimer) { m_ReloadTimer--; return; } // fire Weapon, if wanted FireWeapon(); // ammo regen int AmmoRegenTime = g_pData->m_Weapons.m_aId[m_ActiveWeapon].m_Ammoregentime; if(AmmoRegenTime) { // If equipped and not active, regen ammo? if (m_ReloadTimer <= 0) { if (m_aWeapons[m_ActiveWeapon].m_AmmoRegenStart < 0) m_aWeapons[m_ActiveWeapon].m_AmmoRegenStart = Server()->Tick(); if ((Server()->Tick() - m_aWeapons[m_ActiveWeapon].m_AmmoRegenStart) >= AmmoRegenTime * Server()->TickSpeed() / 1000) { // Add some ammo m_aWeapons[m_ActiveWeapon].m_Ammo = min(m_aWeapons[m_ActiveWeapon].m_Ammo + 1, 10); m_aWeapons[m_ActiveWeapon].m_AmmoRegenStart = -1; } } else { m_aWeapons[m_ActiveWeapon].m_AmmoRegenStart = -1; } } return; } bool CCharacter::GiveWeapon(int Weapon, int Ammo) { if(m_aWeapons[Weapon].m_Ammo < g_pData->m_Weapons.m_aId[Weapon].m_Maxammo || !m_aWeapons[Weapon].m_Got) { m_aWeapons[Weapon].m_Got = true; m_aWeapons[Weapon].m_Ammo = min(g_pData->m_Weapons.m_aId[Weapon].m_Maxammo, Ammo); return true; } return false; } void CCharacter::GiveNinja() { m_Ninja.m_ActivationTick = Server()->Tick(); m_aWeapons[WEAPON_NINJA].m_Got = true; m_aWeapons[WEAPON_NINJA].m_Ammo = -1; if (m_ActiveWeapon != WEAPON_NINJA) m_LastWeapon = m_ActiveWeapon; m_ActiveWeapon = WEAPON_NINJA; GameServer()->CreateSound(m_Pos, SOUND_PICKUP_NINJA); } void CCharacter::SetEmote(int Emote, int Tick) { m_EmoteType = Emote; m_EmoteStop = Tick; } void CCharacter::OnPredictedInput(CNetObj_PlayerInput *pNewInput) { // check for changes if(mem_comp(&m_Input, pNewInput, sizeof(CNetObj_PlayerInput)) != 0) m_LastAction = Server()->Tick(); // copy new input mem_copy(&m_Input, pNewInput, sizeof(m_Input)); m_NumInputs++; // it is not allowed to aim in the center if(m_Input.m_TargetX == 0 && m_Input.m_TargetY == 0) m_Input.m_TargetY = -1; } void CCharacter::OnDirectInput(CNetObj_PlayerInput *pNewInput) { mem_copy(&m_LatestPrevInput, &m_LatestInput, sizeof(m_LatestInput)); mem_copy(&m_LatestInput, pNewInput, sizeof(m_LatestInput)); // it is not allowed to aim in the center if(m_LatestInput.m_TargetX == 0 && m_LatestInput.m_TargetY == 0) m_LatestInput.m_TargetY = -1; if(m_NumInputs > 2 && m_pPlayer->GetTeam() != TEAM_SPECTATORS) { HandleWeaponSwitch(); FireWeapon(); } mem_copy(&m_LatestPrevInput, &m_LatestInput, sizeof(m_LatestInput)); } void CCharacter::ResetInput() { m_Input.m_Direction = 0; m_Input.m_Hook = 0; // simulate releasing the fire button if((m_Input.m_Fire&1) != 0) m_Input.m_Fire++; m_Input.m_Fire &= INPUT_STATE_MASK; m_Input.m_Jump = 0; m_LatestPrevInput = m_LatestInput = m_Input; } void CCharacter::Tick() { m_Core.m_Input = m_Input; m_Core.Tick(true); // handle death-tiles and leaving gamelayer if(GameServer()->Collision()->GetCollisionAt(m_Pos.x+m_ProximityRadius/3.f, m_Pos.y-m_ProximityRadius/3.f)&CCollision::COLFLAG_DEATH || GameServer()->Collision()->GetCollisionAt(m_Pos.x+m_ProximityRadius/3.f, m_Pos.y+m_ProximityRadius/3.f)&CCollision::COLFLAG_DEATH || GameServer()->Collision()->GetCollisionAt(m_Pos.x-m_ProximityRadius/3.f, m_Pos.y-m_ProximityRadius/3.f)&CCollision::COLFLAG_DEATH || GameServer()->Collision()->GetCollisionAt(m_Pos.x-m_ProximityRadius/3.f, m_Pos.y+m_ProximityRadius/3.f)&CCollision::COLFLAG_DEATH || GameLayerClipped(m_Pos)) { Die(m_pPlayer->GetCID(), WEAPON_WORLD); } // handle Weapons HandleWeapons(); // Previnput m_PrevInput = m_Input; return; } void CCharacter::TickDefered() { // advance the dummy { CWorldCore TempWorld; m_ReckoningCore.Init(&TempWorld, GameServer()->Collision()); m_ReckoningCore.Tick(false); m_ReckoningCore.Move(); m_ReckoningCore.Quantize(); } //lastsentcore vec2 StartPos = m_Core.m_Pos; vec2 StartVel = m_Core.m_Vel; bool StuckBefore = GameServer()->Collision()->TestBox(m_Core.m_Pos, vec2(28.0f, 28.0f)); m_Core.Move(); bool StuckAfterMove = GameServer()->Collision()->TestBox(m_Core.m_Pos, vec2(28.0f, 28.0f)); m_Core.Quantize(); bool StuckAfterQuant = GameServer()->Collision()->TestBox(m_Core.m_Pos, vec2(28.0f, 28.0f)); m_Pos = m_Core.m_Pos; if(!StuckBefore && (StuckAfterMove || StuckAfterQuant)) { // Hackish solution to get rid of strict-aliasing warning union { float f; unsigned u; }StartPosX, StartPosY, StartVelX, StartVelY; StartPosX.f = StartPos.x; StartPosY.f = StartPos.y; StartVelX.f = StartVel.x; StartVelY.f = StartVel.y; char aBuf[256]; str_format(aBuf, sizeof(aBuf), "STUCK!!! %d %d %d %f %f %f %f %x %x %x %x", StuckBefore, StuckAfterMove, StuckAfterQuant, StartPos.x, StartPos.y, StartVel.x, StartVel.y, StartPosX.u, StartPosY.u, StartVelX.u, StartVelY.u); GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", aBuf); } m_TriggeredEvents |= m_Core.m_TriggeredEvents; if(m_pPlayer->GetTeam() == TEAM_SPECTATORS) { m_Pos.x = m_Input.m_TargetX; m_Pos.y = m_Input.m_TargetY; } // update the m_SendCore if needed { CNetObj_Character Predicted; CNetObj_Character Current; mem_zero(&Predicted, sizeof(Predicted)); mem_zero(&Current, sizeof(Current)); m_ReckoningCore.Write(&Predicted); m_Core.Write(&Current); // only allow dead reackoning for a top of 3 seconds if(m_ReckoningTick+Server()->TickSpeed()*3 < Server()->Tick() || mem_comp(&Predicted, &Current, sizeof(CNetObj_Character)) != 0) { m_ReckoningTick = Server()->Tick(); m_SendCore = m_Core; m_ReckoningCore = m_Core; } } } void CCharacter::TickPaused() { ++m_AttackTick; ++m_DamageTakenTick; ++m_Ninja.m_ActivationTick; ++m_ReckoningTick; if(m_LastAction != -1) ++m_LastAction; if(m_aWeapons[m_ActiveWeapon].m_AmmoRegenStart > -1) ++m_aWeapons[m_ActiveWeapon].m_AmmoRegenStart; if(m_EmoteStop > -1) ++m_EmoteStop; } bool CCharacter::IncreaseHealth(int Amount) { if(m_Health >= 10) return false; m_Health = clamp(m_Health+Amount, 0, 10); return true; } bool CCharacter::IncreaseArmor(int Amount) { if(m_Armor >= 10) return false; m_Armor = clamp(m_Armor+Amount, 0, 10); return true; } void CCharacter::Die(int Killer, int Weapon) { // we got to wait 0.5 secs before respawning m_Alive = false; m_pPlayer->m_RespawnTick = Server()->Tick()+Server()->TickSpeed()/2; int ModeSpecial = GameServer()->m_pController->OnCharacterDeath(this, GameServer()->m_apPlayers[Killer], Weapon); char aBuf[256]; str_format(aBuf, sizeof(aBuf), "kill killer='%d:%s' victim='%d:%s' weapon=%d special=%d", Killer, Server()->ClientName(Killer), m_pPlayer->GetCID(), Server()->ClientName(m_pPlayer->GetCID()), Weapon, ModeSpecial); GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", aBuf); // send the kill message CNetMsg_Sv_KillMsg Msg; Msg.m_Killer = Killer; Msg.m_Victim = m_pPlayer->GetCID(); Msg.m_Weapon = Weapon; Msg.m_ModeSpecial = ModeSpecial; Server()->SendPackMsg(&Msg, MSGFLAG_VITAL, -1); // a nice sound GameServer()->CreateSound(m_Pos, SOUND_PLAYER_DIE); // this is for auto respawn after 3 secs m_pPlayer->m_DieTick = Server()->Tick(); GameServer()->m_World.RemoveEntity(this); GameServer()->m_World.m_Core.m_apCharacters[m_pPlayer->GetCID()] = 0; GameServer()->CreateDeath(m_Pos, m_pPlayer->GetCID()); } bool CCharacter::TakeDamage(vec2 Force, int Dmg, int From, int Weapon) { m_Core.m_Vel += Force; if(GameServer()->m_pController->IsFriendlyFire(m_pPlayer->GetCID(), From)) return false; // m_pPlayer only inflicts half damage on self if(From == m_pPlayer->GetCID()) Dmg = max(1, Dmg/2); m_DamageTaken++; // create healthmod indicator if(Server()->Tick() < m_DamageTakenTick+25) { // make sure that the damage indicators doesn't group together GameServer()->CreateDamageInd(m_Pos, m_DamageTaken*0.25f, Dmg); } else { m_DamageTaken = 0; GameServer()->CreateDamageInd(m_Pos, 0, Dmg); } if(Dmg) { if(m_Armor) { if(Dmg > 1) { m_Health--; Dmg--; } if(Dmg > m_Armor) { Dmg -= m_Armor; m_Armor = 0; } else { m_Armor -= Dmg; Dmg = 0; } } m_Health -= Dmg; } m_DamageTakenTick = Server()->Tick(); // do damage Hit sound if(From >= 0 && From != m_pPlayer->GetCID() && GameServer()->m_apPlayers[From]) { int Mask = CmaskOne(From); for(int i = 0; i < MAX_CLIENTS; i++) { if(GameServer()->m_apPlayers[i] && (GameServer()->m_apPlayers[i]->GetTeam() == TEAM_SPECTATORS || GameServer()->m_apPlayers[i]->m_DeadSpecMode) && GameServer()->m_apPlayers[i]->GetSpectatorID() == From) Mask |= CmaskOne(i); } GameServer()->CreateSound(GameServer()->m_apPlayers[From]->m_ViewPos, SOUND_HIT, Mask); } // check for death if(m_Health <= 0) { Die(From, Weapon); // set attacker's face to happy (taunt!) if (From >= 0 && From != m_pPlayer->GetCID() && GameServer()->m_apPlayers[From]) { CCharacter *pChr = GameServer()->m_apPlayers[From]->GetCharacter(); if (pChr) { pChr->m_EmoteType = EMOTE_HAPPY; pChr->m_EmoteStop = Server()->Tick() + Server()->TickSpeed(); } } return false; } if (Dmg > 2) GameServer()->CreateSound(m_Pos, SOUND_PLAYER_PAIN_LONG); else GameServer()->CreateSound(m_Pos, SOUND_PLAYER_PAIN_SHORT); m_EmoteType = EMOTE_PAIN; m_EmoteStop = Server()->Tick() + 500 * Server()->TickSpeed() / 1000; return true; } void CCharacter::Snap(int SnappingClient) { if(NetworkClipped(SnappingClient)) return; CNetObj_Character *pCharacter = static_cast<CNetObj_Character *>(Server()->SnapNewItem(NETOBJTYPE_CHARACTER, m_pPlayer->GetCID(), sizeof(CNetObj_Character))); if(!pCharacter) return; // write down the m_Core if(!m_ReckoningTick || GameServer()->m_World.m_Paused) { // no dead reckoning when paused because the client doesn't know // how far to perform the reckoning pCharacter->m_Tick = 0; m_Core.Write(pCharacter); } else { pCharacter->m_Tick = m_ReckoningTick; m_SendCore.Write(pCharacter); } // set emote if (m_EmoteStop < Server()->Tick()) { m_EmoteType = EMOTE_NORMAL; m_EmoteStop = -1; } pCharacter->m_Emote = m_EmoteType; pCharacter->m_AmmoCount = 0; pCharacter->m_Health = 0; pCharacter->m_Armor = 0; pCharacter->m_TriggeredEvents = m_TriggeredEvents; pCharacter->m_Weapon = m_ActiveWeapon; pCharacter->m_AttackTick = m_AttackTick; pCharacter->m_Direction = m_Input.m_Direction; if(m_pPlayer->GetCID() == SnappingClient || SnappingClient == -1 || (!g_Config.m_SvStrictSpectateMode && m_pPlayer->GetCID() == GameServer()->m_apPlayers[SnappingClient]->GetSpectatorID())) { pCharacter->m_Health = m_Health; pCharacter->m_Armor = m_Armor; if(m_ActiveWeapon == WEAPON_NINJA) pCharacter->m_AmmoCount = m_Ninja.m_ActivationTick + g_pData->m_Weapons.m_Ninja.m_Duration * Server()->TickSpeed() / 1000; else if(m_aWeapons[m_ActiveWeapon].m_Ammo > 0) pCharacter->m_AmmoCount = m_aWeapons[m_ActiveWeapon].m_Ammo; } if(pCharacter->m_Emote == EMOTE_NORMAL) { if(250 - ((Server()->Tick() - m_LastAction)%(250)) < 5) pCharacter->m_Emote = EMOTE_BLINK; } } void CCharacter::PostSnap() { m_TriggeredEvents = 0; } ================================================ FILE: src/game/server/entities/character.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_SERVER_ENTITIES_CHARACTER_H #define GAME_SERVER_ENTITIES_CHARACTER_H #include <game/server/entity.h> class CCharacter : public CEntity { MACRO_ALLOC_POOL_ID() public: //character's size static const int ms_PhysSize = 28; CCharacter(CGameWorld *pWorld); virtual void Reset(); virtual void Destroy(); virtual void Tick(); virtual void TickDefered(); virtual void TickPaused(); virtual void Snap(int SnappingClient); virtual void PostSnap(); bool IsGrounded(); void SetWeapon(int W); void HandleWeaponSwitch(); void DoWeaponSwitch(); void HandleWeapons(); void HandleNinja(); void OnPredictedInput(CNetObj_PlayerInput *pNewInput); void OnDirectInput(CNetObj_PlayerInput *pNewInput); void ResetInput(); void FireWeapon(); void Die(int Killer, int Weapon); bool TakeDamage(vec2 Force, int Dmg, int From, int Weapon); bool Spawn(class CPlayer *pPlayer, vec2 Pos); bool Remove(); bool IncreaseHealth(int Amount); bool IncreaseArmor(int Amount); bool GiveWeapon(int Weapon, int Ammo); void GiveNinja(); void SetEmote(int Emote, int Tick); bool IsAlive() const { return m_Alive; } class CPlayer *GetPlayer() { return m_pPlayer; } private: // player controlling this character class CPlayer *m_pPlayer; bool m_Alive; // weapon info CEntity *m_apHitObjects[10]; int m_NumObjectsHit; struct WeaponStat { int m_AmmoRegenStart; int m_Ammo; int m_Ammocost; bool m_Got; } m_aWeapons[NUM_WEAPONS]; int m_ActiveWeapon; int m_LastWeapon; int m_QueuedWeapon; int m_ReloadTimer; int m_AttackTick; int m_DamageTaken; int m_EmoteType; int m_EmoteStop; // last tick that the player took any action ie some input int m_LastAction; int m_LastNoAmmoSound; // these are non-heldback inputs CNetObj_PlayerInput m_LatestPrevInput; CNetObj_PlayerInput m_LatestInput; // input CNetObj_PlayerInput m_PrevInput; CNetObj_PlayerInput m_Input; int m_NumInputs; int m_Jumped; int m_DamageTakenTick; int m_Health; int m_Armor; int m_TriggeredEvents; // ninja struct { vec2 m_ActivationDir; int m_ActivationTick; int m_CurrentMoveTime; int m_OldVelAmount; } m_Ninja; // the player core for the physics CCharacterCore m_Core; // info for dead reckoning int m_ReckoningTick; // tick that we are performing dead reckoning From CCharacterCore m_SendCore; // core that we should send CCharacterCore m_ReckoningCore; // the dead reckoning core }; #endif ================================================ FILE: src/game/server/entities/flag.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <game/server/gamecontext.h> #include "character.h" #include "flag.h" CFlag::CFlag(CGameWorld *pGameWorld, int Team) : CEntity(pGameWorld, CGameWorld::ENTTYPE_FLAG) { m_Team = Team; m_ProximityRadius = ms_PhysSize; m_pCarryingCharacter = NULL; m_GrabTick = 0; Reset(); } void CFlag::Reset() { m_pCarryingCharacter = NULL; m_AtStand = 1; m_Pos = m_StandPos; m_Vel = vec2(0,0); m_GrabTick = 0; } void CFlag::TickPaused() { ++m_DropTick; if(m_GrabTick) ++m_GrabTick; } void CFlag::Snap(int SnappingClient) { if(NetworkClipped(SnappingClient)) return; CNetObj_Flag *pFlag = (CNetObj_Flag *)Server()->SnapNewItem(NETOBJTYPE_FLAG, m_Team, sizeof(CNetObj_Flag)); if(!pFlag) return; pFlag->m_X = (int)m_Pos.x; pFlag->m_Y = (int)m_Pos.y; pFlag->m_Team = m_Team; } ================================================ FILE: src/game/server/entities/flag.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_SERVER_ENTITIES_FLAG_H #define GAME_SERVER_ENTITIES_FLAG_H #include <game/server/entity.h> class CFlag : public CEntity { public: static const int ms_PhysSize = 14; CCharacter *m_pCarryingCharacter; vec2 m_Vel; vec2 m_StandPos; int m_Team; int m_AtStand; int m_DropTick; int m_GrabTick; CFlag(CGameWorld *pGameWorld, int Team); virtual void Reset(); virtual void TickPaused(); virtual void Snap(int SnappingClient); }; #endif ================================================ FILE: src/game/server/entities/laser.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <game/server/gamecontext.h> #include "character.h" #include "laser.h" CLaser::CLaser(CGameWorld *pGameWorld, vec2 Pos, vec2 Direction, float StartEnergy, int Owner) : CEntity(pGameWorld, CGameWorld::ENTTYPE_LASER) { m_Pos = Pos; m_Owner = Owner; m_Energy = StartEnergy; m_Dir = Direction; m_Bounces = 0; m_EvalTick = 0; GameWorld()->InsertEntity(this); DoBounce(); } bool CLaser::HitCharacter(vec2 From, vec2 To) { vec2 At; CCharacter *pOwnerChar = GameServer()->GetPlayerChar(m_Owner); CCharacter *pHit = GameServer()->m_World.IntersectCharacter(m_Pos, To, 0.f, At, pOwnerChar); if(!pHit) return false; m_From = From; m_Pos = At; m_Energy = -1; pHit->TakeDamage(vec2(0.f, 0.f), GameServer()->Tuning()->m_LaserDamage, m_Owner, WEAPON_LASER); return true; } void CLaser::DoBounce() { m_EvalTick = Server()->Tick(); if(m_Energy < 0) { GameServer()->m_World.DestroyEntity(this); return; } vec2 To = m_Pos + m_Dir * m_Energy; if(GameServer()->Collision()->IntersectLine(m_Pos, To, 0x0, &To)) { if(!HitCharacter(m_Pos, To)) { // intersected m_From = m_Pos; m_Pos = To; vec2 TempPos = m_Pos; vec2 TempDir = m_Dir * 4.0f; GameServer()->Collision()->MovePoint(&TempPos, &TempDir, 1.0f, 0); m_Pos = TempPos; m_Dir = normalize(TempDir); m_Energy -= distance(m_From, m_Pos) + GameServer()->Tuning()->m_LaserBounceCost; m_Bounces++; if(m_Bounces > GameServer()->Tuning()->m_LaserBounceNum) m_Energy = -1; GameServer()->CreateSound(m_Pos, SOUND_LASER_BOUNCE); } } else { if(!HitCharacter(m_Pos, To)) { m_From = m_Pos; m_Pos = To; m_Energy = -1; } } } void CLaser::Reset() { GameServer()->m_World.DestroyEntity(this); } void CLaser::Tick() { if(Server()->Tick() > m_EvalTick+(Server()->TickSpeed()*GameServer()->Tuning()->m_LaserBounceDelay)/1000.0f) DoBounce(); } void CLaser::TickPaused() { ++m_EvalTick; } void CLaser::Snap(int SnappingClient) { if(NetworkClipped(SnappingClient)) return; CNetObj_Laser *pObj = static_cast<CNetObj_Laser *>(Server()->SnapNewItem(NETOBJTYPE_LASER, m_ID, sizeof(CNetObj_Laser))); if(!pObj) return; pObj->m_X = (int)m_Pos.x; pObj->m_Y = (int)m_Pos.y; pObj->m_FromX = (int)m_From.x; pObj->m_FromY = (int)m_From.y; pObj->m_StartTick = m_EvalTick; } ================================================ FILE: src/game/server/entities/laser.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_SERVER_ENTITIES_LASER_H #define GAME_SERVER_ENTITIES_LASER_H #include <game/server/entity.h> class CLaser : public CEntity { public: CLaser(CGameWorld *pGameWorld, vec2 Pos, vec2 Direction, float StartEnergy, int Owner); virtual void Reset(); virtual void Tick(); virtual void TickPaused(); virtual void Snap(int SnappingClient); protected: bool HitCharacter(vec2 From, vec2 To); void DoBounce(); private: vec2 m_From; vec2 m_Dir; float m_Energy; int m_Bounces; int m_EvalTick; int m_Owner; }; #endif ================================================ FILE: src/game/server/entities/pickup.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <game/generated/server_data.h> #include <game/server/gamecontext.h> #include <game/server/player.h> #include "character.h" #include "pickup.h" CPickup::CPickup(CGameWorld *pGameWorld, int Type) : CEntity(pGameWorld, CGameWorld::ENTTYPE_PICKUP) { m_Type = Type; m_ProximityRadius = PickupPhysSize; Reset(); GameWorld()->InsertEntity(this); } void CPickup::Reset() { if (g_pData->m_aPickups[m_Type].m_Spawndelay > 0) m_SpawnTick = Server()->Tick() + Server()->TickSpeed() * g_pData->m_aPickups[m_Type].m_Spawndelay; else m_SpawnTick = -1; } void CPickup::Tick() { // wait for respawn if(m_SpawnTick > 0) { if(Server()->Tick() > m_SpawnTick) { // respawn m_SpawnTick = -1; if(m_Type == PICKUP_GRENADE || m_Type == PICKUP_SHOTGUN || m_Type == PICKUP_LASER) GameServer()->CreateSound(m_Pos, SOUND_WEAPON_SPAWN); } else return; } // Check if a player intersected us CCharacter *pChr = GameServer()->m_World.ClosestCharacter(m_Pos, 20.0f, 0); if(pChr && pChr->IsAlive()) { // player picked us up, is someone was hooking us, let them go int RespawnTime = -1; switch (m_Type) { case PICKUP_HEALTH: if(pChr->IncreaseHealth(1)) { GameServer()->CreateSound(m_Pos, SOUND_PICKUP_HEALTH); RespawnTime = g_pData->m_aPickups[m_Type].m_Respawntime; } break; case PICKUP_ARMOR: if(pChr->IncreaseArmor(1)) { GameServer()->CreateSound(m_Pos, SOUND_PICKUP_ARMOR); RespawnTime = g_pData->m_aPickups[m_Type].m_Respawntime; } break; case PICKUP_GRENADE: if(pChr->GiveWeapon(WEAPON_GRENADE, 10)) { RespawnTime = g_pData->m_aPickups[m_Type].m_Respawntime; GameServer()->CreateSound(m_Pos, SOUND_PICKUP_GRENADE); if(pChr->GetPlayer()) GameServer()->SendWeaponPickup(pChr->GetPlayer()->GetCID(), WEAPON_GRENADE); } break; case PICKUP_SHOTGUN: if(pChr->GiveWeapon(WEAPON_SHOTGUN, 10)) { RespawnTime = g_pData->m_aPickups[m_Type].m_Respawntime; GameServer()->CreateSound(m_Pos, SOUND_PICKUP_SHOTGUN); if(pChr->GetPlayer()) GameServer()->SendWeaponPickup(pChr->GetPlayer()->GetCID(), WEAPON_SHOTGUN); } break; case PICKUP_LASER: if(pChr->GiveWeapon(WEAPON_LASER, 10)) { RespawnTime = g_pData->m_aPickups[m_Type].m_Respawntime; GameServer()->CreateSound(m_Pos, SOUND_PICKUP_SHOTGUN); if(pChr->GetPlayer()) GameServer()->SendWeaponPickup(pChr->GetPlayer()->GetCID(), WEAPON_LASER); } break; case PICKUP_NINJA: { // activate ninja on target player pChr->GiveNinja(); RespawnTime = g_pData->m_aPickups[m_Type].m_Respawntime; // loop through all players, setting their emotes CCharacter *pC = static_cast<CCharacter *>(GameServer()->m_World.FindFirst(CGameWorld::ENTTYPE_CHARACTER)); for(; pC; pC = (CCharacter *)pC->TypeNext()) { if (pC != pChr) pC->SetEmote(EMOTE_SURPRISE, Server()->Tick() + Server()->TickSpeed()); } pChr->SetEmote(EMOTE_ANGRY, Server()->Tick() + 1200 * Server()->TickSpeed() / 1000); break; } default: break; }; if(RespawnTime >= 0) { char aBuf[256]; str_format(aBuf, sizeof(aBuf), "pickup player='%d:%s' item=%d/%d", pChr->GetPlayer()->GetCID(), Server()->ClientName(pChr->GetPlayer()->GetCID()), m_Type); GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", aBuf); m_SpawnTick = Server()->Tick() + Server()->TickSpeed() * RespawnTime; } } } void CPickup::TickPaused() { if(m_SpawnTick != -1) ++m_SpawnTick; } void CPickup::Snap(int SnappingClient) { if(m_SpawnTick != -1 || NetworkClipped(SnappingClient)) return; CNetObj_Pickup *pP = static_cast<CNetObj_Pickup *>(Server()->SnapNewItem(NETOBJTYPE_PICKUP, m_ID, sizeof(CNetObj_Pickup))); if(!pP) return; pP->m_X = (int)m_Pos.x; pP->m_Y = (int)m_Pos.y; pP->m_Type = m_Type; } ================================================ FILE: src/game/server/entities/pickup.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_SERVER_ENTITIES_PICKUP_H #define GAME_SERVER_ENTITIES_PICKUP_H #include <game/server/entity.h> const int PickupPhysSize = 14; class CPickup : public CEntity { public: CPickup(CGameWorld *pGameWorld, int Type); virtual void Reset(); virtual void Tick(); virtual void TickPaused(); virtual void Snap(int SnappingClient); private: int m_Type; int m_SpawnTick; }; #endif ================================================ FILE: src/game/server/entities/projectile.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <game/server/gamecontext.h> #include "character.h" #include "projectile.h" CProjectile::CProjectile(CGameWorld *pGameWorld, int Type, int Owner, vec2 Pos, vec2 Dir, int Span, int Damage, bool Explosive, float Force, int SoundImpact, int Weapon) : CEntity(pGameWorld, CGameWorld::ENTTYPE_PROJECTILE) { m_Type = Type; m_Pos = Pos; m_Direction = Dir; m_LifeSpan = Span; m_Owner = Owner; m_Force = Force; m_Damage = Damage; m_SoundImpact = SoundImpact; m_Weapon = Weapon; m_StartTick = Server()->Tick(); m_Explosive = Explosive; GameWorld()->InsertEntity(this); } void CProjectile::Reset() { GameServer()->m_World.DestroyEntity(this); } vec2 CProjectile::GetPos(float Time) { float Curvature = 0; float Speed = 0; switch(m_Type) { case WEAPON_GRENADE: Curvature = GameServer()->Tuning()->m_GrenadeCurvature; Speed = GameServer()->Tuning()->m_GrenadeSpeed; break; case WEAPON_SHOTGUN: Curvature = GameServer()->Tuning()->m_ShotgunCurvature; Speed = GameServer()->Tuning()->m_ShotgunSpeed; break; case WEAPON_GUN: Curvature = GameServer()->Tuning()->m_GunCurvature; Speed = GameServer()->Tuning()->m_GunSpeed; break; } return CalcPos(m_Pos, m_Direction, Curvature, Speed, Time); } void CProjectile::Tick() { float Pt = (Server()->Tick()-m_StartTick-1)/(float)Server()->TickSpeed(); float Ct = (Server()->Tick()-m_StartTick)/(float)Server()->TickSpeed(); vec2 PrevPos = GetPos(Pt); vec2 CurPos = GetPos(Ct); int Collide = GameServer()->Collision()->IntersectLine(PrevPos, CurPos, &CurPos, 0); CCharacter *OwnerChar = GameServer()->GetPlayerChar(m_Owner); CCharacter *TargetChr = GameServer()->m_World.IntersectCharacter(PrevPos, CurPos, 6.0f, CurPos, OwnerChar); m_LifeSpan--; if(TargetChr || Collide || m_LifeSpan < 0 || GameLayerClipped(CurPos)) { if(m_LifeSpan >= 0 || m_Weapon == WEAPON_GRENADE) GameServer()->CreateSound(CurPos, m_SoundImpact); if(m_Explosive) GameServer()->CreateExplosion(CurPos, m_Owner, m_Weapon, false); else if(TargetChr) TargetChr->TakeDamage(m_Direction * max(0.001f, m_Force), m_Damage, m_Owner, m_Weapon); GameServer()->m_World.DestroyEntity(this); } } void CProjectile::TickPaused() { ++m_StartTick; } void CProjectile::FillInfo(CNetObj_Projectile *pProj) { pProj->m_X = (int)m_Pos.x; pProj->m_Y = (int)m_Pos.y; pProj->m_VelX = (int)(m_Direction.x*100.0f); pProj->m_VelY = (int)(m_Direction.y*100.0f); pProj->m_StartTick = m_StartTick; pProj->m_Type = m_Type; } void CProjectile::Snap(int SnappingClient) { float Ct = (Server()->Tick()-m_StartTick)/(float)Server()->TickSpeed(); if(NetworkClipped(SnappingClient, GetPos(Ct))) return; CNetObj_Projectile *pProj = static_cast<CNetObj_Projectile *>(Server()->SnapNewItem(NETOBJTYPE_PROJECTILE, m_ID, sizeof(CNetObj_Projectile))); if(pProj) FillInfo(pProj); } ================================================ FILE: src/game/server/entities/projectile.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_SERVER_ENTITIES_PROJECTILE_H #define GAME_SERVER_ENTITIES_PROJECTILE_H class CProjectile : public CEntity { public: CProjectile(CGameWorld *pGameWorld, int Type, int Owner, vec2 Pos, vec2 Dir, int Span, int Damage, bool Explosive, float Force, int SoundImpact, int Weapon); vec2 GetPos(float Time); void FillInfo(CNetObj_Projectile *pProj); virtual void Reset(); virtual void Tick(); virtual void TickPaused(); virtual void Snap(int SnappingClient); private: vec2 m_Direction; int m_LifeSpan; int m_Owner; int m_Type; int m_Damage; int m_SoundImpact; int m_Weapon; float m_Force; int m_StartTick; bool m_Explosive; }; #endif ================================================ FILE: src/game/server/entity.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include "entity.h" #include "gamecontext.h" #include "player.h" ////////////////////////////////////////////////// // Entity ////////////////////////////////////////////////// CEntity::CEntity(CGameWorld *pGameWorld, int ObjType) { m_pGameWorld = pGameWorld; m_ObjType = ObjType; m_Pos = vec2(0,0); m_ProximityRadius = 0; m_MarkedForDestroy = false; m_ID = Server()->SnapNewID(); m_pPrevTypeEntity = 0; m_pNextTypeEntity = 0; } CEntity::~CEntity() { GameWorld()->RemoveEntity(this); Server()->SnapFreeID(m_ID); } int CEntity::NetworkClipped(int SnappingClient) { return NetworkClipped(SnappingClient, m_Pos); } int CEntity::NetworkClipped(int SnappingClient, vec2 CheckPos) { if(SnappingClient == -1) return 0; float dx = GameServer()->m_apPlayers[SnappingClient]->m_ViewPos.x-CheckPos.x; float dy = GameServer()->m_apPlayers[SnappingClient]->m_ViewPos.y-CheckPos.y; if(absolute(dx) > 1000.0f || absolute(dy) > 800.0f) return 1; if(distance(GameServer()->m_apPlayers[SnappingClient]->m_ViewPos, CheckPos) > 1100.0f) return 1; return 0; } bool CEntity::GameLayerClipped(vec2 CheckPos) { return round(CheckPos.x)/32 < -200 || round(CheckPos.x)/32 > GameServer()->Collision()->GetWidth()+200 || round(CheckPos.y)/32 < -200 || round(CheckPos.y)/32 > GameServer()->Collision()->GetHeight()+200 ? true : false; } ================================================ FILE: src/game/server/entity.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_SERVER_ENTITY_H #define GAME_SERVER_ENTITY_H #include <base/vmath.h> #include <game/server/gameworld.h> #include "alloc.h" /* Class: Entity Basic entity class. */ class CEntity { MACRO_ALLOC_HEAP() friend class CGameWorld; // entity list handling CEntity *m_pPrevTypeEntity; CEntity *m_pNextTypeEntity; class CGameWorld *m_pGameWorld; protected: bool m_MarkedForDestroy; int m_ID; int m_ObjType; public: CEntity(CGameWorld *pGameWorld, int Objtype); virtual ~CEntity(); class CGameWorld *GameWorld() { return m_pGameWorld; } class CGameContext *GameServer() { return GameWorld()->GameServer(); } class IServer *Server() { return GameWorld()->Server(); } CEntity *TypeNext() { return m_pNextTypeEntity; } CEntity *TypePrev() { return m_pPrevTypeEntity; } /* Function: destroy Destorys the entity. */ virtual void Destroy() { delete this; } /* Function: reset Called when the game resets the map. Puts the entity back to it's starting state or perhaps destroys it. */ virtual void Reset() {} /* Function: tick Called progress the entity to the next tick. Updates and moves the entity to it's new state and position. */ virtual void Tick() {} /* Function: tick_defered Called after all entities tick() function has been called. */ virtual void TickDefered() {} /* Function: TickPaused Called when the game is paused, to freeze the state and position of the entity. */ virtual void TickPaused() {} /* Function: snap Called when a new snapshot is being generated for a specific client. Arguments: snapping_client - ID of the client which snapshot is being generated. Could be -1 to create a complete snapshot of everything in the game for demo recording. */ virtual void Snap(int SnappingClient) {} virtual void PostSnap() {} /* Function: networkclipped(int snapping_client) Performs a series of test to see if a client can see the entity. Arguments: snapping_client - ID of the client which snapshot is being generated. Could be -1 to create a complete snapshot of everything in the game for demo recording. Returns: Non-zero if the entity doesn't have to be in the snapshot. */ int NetworkClipped(int SnappingClient); int NetworkClipped(int SnappingClient, vec2 CheckPos); bool GameLayerClipped(vec2 CheckPos); /* Variable: proximity_radius Contains the physical size of the entity. */ float m_ProximityRadius; /* Variable: pos Contains the current posititon of the entity. */ vec2 m_Pos; }; #endif ================================================ FILE: src/game/server/eventhandler.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include "eventhandler.h" #include "gamecontext.h" #include "player.h" ////////////////////////////////////////////////// // Event handler ////////////////////////////////////////////////// CEventHandler::CEventHandler() { m_pGameServer = 0; Clear(); } void CEventHandler::SetGameServer(CGameContext *pGameServer) { m_pGameServer = pGameServer; } void *CEventHandler::Create(int Type, int Size, int Mask) { if(m_NumEvents == MAX_EVENTS) return 0; if(m_CurrentOffset+Size >= MAX_DATASIZE) return 0; void *p = &m_aData[m_CurrentOffset]; m_aOffsets[m_NumEvents] = m_CurrentOffset; m_aTypes[m_NumEvents] = Type; m_aSizes[m_NumEvents] = Size; m_aClientMasks[m_NumEvents] = Mask; m_CurrentOffset += Size; m_NumEvents++; return p; } void CEventHandler::Clear() { m_NumEvents = 0; m_CurrentOffset = 0; } void CEventHandler::Snap(int SnappingClient) { for(int i = 0; i < m_NumEvents; i++) { if(SnappingClient == -1 || CmaskIsSet(m_aClientMasks[i], SnappingClient)) { CNetEvent_Common *ev = (CNetEvent_Common *)&m_aData[m_aOffsets[i]]; if(SnappingClient == -1 || distance(GameServer()->m_apPlayers[SnappingClient]->m_ViewPos, vec2(ev->m_X, ev->m_Y)) < 1500.0f) { void *d = GameServer()->Server()->SnapNewItem(m_aTypes[i], i, m_aSizes[i]); if(d) mem_copy(d, &m_aData[m_aOffsets[i]], m_aSizes[i]); } } } } ================================================ FILE: src/game/server/eventhandler.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_SERVER_EVENTHANDLER_H #define GAME_SERVER_EVENTHANDLER_H // class CEventHandler { static const int MAX_EVENTS = 128; static const int MAX_DATASIZE = 128*64; int m_aTypes[MAX_EVENTS]; // TODO: remove some of these arrays int m_aOffsets[MAX_EVENTS]; int m_aSizes[MAX_EVENTS]; int m_aClientMasks[MAX_EVENTS]; char m_aData[MAX_DATASIZE]; class CGameContext *m_pGameServer; int m_CurrentOffset; int m_NumEvents; public: CGameContext *GameServer() const { return m_pGameServer; } void SetGameServer(CGameContext *pGameServer); CEventHandler(); void *Create(int Type, int Size, int Mask = -1); void Clear(); void Snap(int SnappingClient); }; #endif ================================================ FILE: src/game/server/gamecontext.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <base/math.h> #include <engine/shared/config.h> #include <engine/shared/memheap.h> #include <engine/map.h> #include <game/collision.h> #include <game/gamecore.h> #include <game/version.h> #include "entities/character.h" #include "gamemodes/ctf.h" #include "gamemodes/dm.h" #include "gamemodes/lms.h" #include "gamemodes/mod.h" #include "gamemodes/sur.h" #include "gamemodes/tdm.h" #include "gamecontext.h" #include "player.h" enum { RESET, NO_RESET }; void CGameContext::Construct(int Resetting) { m_Resetting = 0; m_pServer = 0; for(int i = 0; i < MAX_CLIENTS; i++) m_apPlayers[i] = 0; m_pController = 0; m_VoteCloseTime = 0; m_pVoteOptionFirst = 0; m_pVoteOptionLast = 0; m_NumVoteOptions = 0; m_LockTeams = 0; if(Resetting==NO_RESET) m_pVoteOptionHeap = new CHeap(); } CGameContext::CGameContext(int Resetting) { Construct(Resetting); } CGameContext::CGameContext() { Construct(NO_RESET); } CGameContext::~CGameContext() { for(int i = 0; i < MAX_CLIENTS; i++) delete m_apPlayers[i]; if(!m_Resetting) delete m_pVoteOptionHeap; } void CGameContext::Clear() { CHeap *pVoteOptionHeap = m_pVoteOptionHeap; CVoteOptionServer *pVoteOptionFirst = m_pVoteOptionFirst; CVoteOptionServer *pVoteOptionLast = m_pVoteOptionLast; int NumVoteOptions = m_NumVoteOptions; CTuningParams Tuning = m_Tuning; m_Resetting = true; this->~CGameContext(); mem_zero(this, sizeof(*this)); new (this) CGameContext(RESET); m_pVoteOptionHeap = pVoteOptionHeap; m_pVoteOptionFirst = pVoteOptionFirst; m_pVoteOptionLast = pVoteOptionLast; m_NumVoteOptions = NumVoteOptions; m_Tuning = Tuning; } class CCharacter *CGameContext::GetPlayerChar(int ClientID) { if(ClientID < 0 || ClientID >= MAX_CLIENTS || !m_apPlayers[ClientID]) return 0; return m_apPlayers[ClientID]->GetCharacter(); } void CGameContext::CreateDamageInd(vec2 Pos, float Angle, int Amount) { float a = 3 * 3.14159f / 2 + Angle; //float a = get_angle(dir); float s = a-pi/3; float e = a+pi/3; for(int i = 0; i < Amount; i++) { float f = mix(s, e, float(i+1)/float(Amount+2)); CNetEvent_DamageInd *pEvent = (CNetEvent_DamageInd *)m_Events.Create(NETEVENTTYPE_DAMAGEIND, sizeof(CNetEvent_DamageInd)); if(pEvent) { pEvent->m_X = (int)Pos.x; pEvent->m_Y = (int)Pos.y; pEvent->m_Angle = (int)(f*256.0f); } } } void CGameContext::CreateHammerHit(vec2 Pos) { // create the event CNetEvent_HammerHit *pEvent = (CNetEvent_HammerHit *)m_Events.Create(NETEVENTTYPE_HAMMERHIT, sizeof(CNetEvent_HammerHit)); if(pEvent) { pEvent->m_X = (int)Pos.x; pEvent->m_Y = (int)Pos.y; } } void CGameContext::CreateExplosion(vec2 Pos, int Owner, int Weapon, bool NoDamage) { // create the event CNetEvent_Explosion *pEvent = (CNetEvent_Explosion *)m_Events.Create(NETEVENTTYPE_EXPLOSION, sizeof(CNetEvent_Explosion)); if(pEvent) { pEvent->m_X = (int)Pos.x; pEvent->m_Y = (int)Pos.y; } if (!NoDamage) { // deal damage CCharacter *apEnts[MAX_CLIENTS]; float Radius = 135.0f; float InnerRadius = 48.0f; int Num = m_World.FindEntities(Pos, Radius, (CEntity**)apEnts, MAX_CLIENTS, CGameWorld::ENTTYPE_CHARACTER); for(int i = 0; i < Num; i++) { vec2 Diff = apEnts[i]->m_Pos - Pos; vec2 ForceDir(0,1); float l = length(Diff); if(l) ForceDir = normalize(Diff); l = 1-clamp((l-InnerRadius)/(Radius-InnerRadius), 0.0f, 1.0f); float Dmg = 6 * l; if((int)Dmg) apEnts[i]->TakeDamage(ForceDir*Dmg*2, (int)Dmg, Owner, Weapon); } } } void CGameContext::CreatePlayerSpawn(vec2 Pos) { // create the event CNetEvent_Spawn *ev = (CNetEvent_Spawn *)m_Events.Create(NETEVENTTYPE_SPAWN, sizeof(CNetEvent_Spawn)); if(ev) { ev->m_X = (int)Pos.x; ev->m_Y = (int)Pos.y; } } void CGameContext::CreateDeath(vec2 Pos, int ClientID) { // create the event CNetEvent_Death *pEvent = (CNetEvent_Death *)m_Events.Create(NETEVENTTYPE_DEATH, sizeof(CNetEvent_Death)); if(pEvent) { pEvent->m_X = (int)Pos.x; pEvent->m_Y = (int)Pos.y; pEvent->m_ClientID = ClientID; } } void CGameContext::CreateSound(vec2 Pos, int Sound, int Mask) { if (Sound < 0) return; // create a sound CNetEvent_SoundWorld *pEvent = (CNetEvent_SoundWorld *)m_Events.Create(NETEVENTTYPE_SOUNDWORLD, sizeof(CNetEvent_SoundWorld), Mask); if(pEvent) { pEvent->m_X = (int)Pos.x; pEvent->m_Y = (int)Pos.y; pEvent->m_SoundID = Sound; } } void CGameContext::SendChatTarget(int To, const char *pText) { CNetMsg_Sv_Chat Msg; Msg.m_Team = 0; Msg.m_ClientID = -1; Msg.m_pMessage = pText; Server()->SendPackMsg(&Msg, MSGFLAG_VITAL, To); } void CGameContext::SendChat(int ChatterClientID, int Team, const char *pText) { char aBuf[256]; if(ChatterClientID >= 0 && ChatterClientID < MAX_CLIENTS) str_format(aBuf, sizeof(aBuf), "%d:%d:%s: %s", ChatterClientID, Team, Server()->ClientName(ChatterClientID), pText); else str_format(aBuf, sizeof(aBuf), "*** %s", pText); Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, Team!=CHAT_ALL?"teamchat":"chat", aBuf); if(Team == CHAT_ALL) { CNetMsg_Sv_Chat Msg; Msg.m_Team = 0; Msg.m_ClientID = ChatterClientID; Msg.m_pMessage = pText; Server()->SendPackMsg(&Msg, MSGFLAG_VITAL, -1); } else { CNetMsg_Sv_Chat Msg; Msg.m_Team = 1; Msg.m_ClientID = ChatterClientID; Msg.m_pMessage = pText; // pack one for the recording only Server()->SendPackMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_NOSEND, -1); // send to the clients for(int i = 0; i < MAX_CLIENTS; i++) { if(m_apPlayers[i] && m_apPlayers[i]->GetTeam() == Team) Server()->SendPackMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_NORECORD, i); } } } void CGameContext::SendEmoticon(int ClientID, int Emoticon) { CNetMsg_Sv_Emoticon Msg; Msg.m_ClientID = ClientID; Msg.m_Emoticon = Emoticon; Server()->SendPackMsg(&Msg, MSGFLAG_VITAL, -1); } void CGameContext::SendWeaponPickup(int ClientID, int Weapon) { CNetMsg_Sv_WeaponPickup Msg; Msg.m_Weapon = Weapon; Server()->SendPackMsg(&Msg, MSGFLAG_VITAL, ClientID); } void CGameContext::SendMotd(int ClientID) { CNetMsg_Sv_Motd Msg; Msg.m_pMessage = g_Config.m_SvMotd; Server()->SendPackMsg(&Msg, MSGFLAG_VITAL, ClientID); } void CGameContext::SendSettings(int ClientID) { CNetMsg_Sv_ServerSettings Msg; Msg.m_KickVote = g_Config.m_SvVoteKick; Msg.m_KickMin = g_Config.m_SvVoteKickMin; Msg.m_SpecVote = g_Config.m_SvVoteSpectate; Msg.m_TeamLock = m_LockTeams != 0; Msg.m_TeamBalance = g_Config.m_SvTeambalanceTime != 0; Msg.m_PlayerSlots = Server()->MaxClients()-g_Config.m_SvSpectatorSlots; Server()->SendPackMsg(&Msg, MSGFLAG_VITAL, ClientID); } void CGameContext::SendGameMsg(int GameMsgID, int ClientID) { CMsgPacker Msg(NETMSGTYPE_SV_GAMEMSG); Msg.AddInt(GameMsgID); Server()->SendMsg(&Msg, MSGFLAG_VITAL, ClientID); } void CGameContext::SendGameMsg(int GameMsgID, int ParaI1, int ClientID) { CMsgPacker Msg(NETMSGTYPE_SV_GAMEMSG); Msg.AddInt(GameMsgID); Msg.AddInt(ParaI1); Server()->SendMsg(&Msg, MSGFLAG_VITAL, ClientID); } void CGameContext::SendGameMsg(int GameMsgID, int ParaI1, int ParaI2, int ParaI3, int ClientID) { CMsgPacker Msg(NETMSGTYPE_SV_GAMEMSG); Msg.AddInt(GameMsgID); Msg.AddInt(ParaI1); Msg.AddInt(ParaI2); Msg.AddInt(ParaI3); Server()->SendMsg(&Msg, MSGFLAG_VITAL, ClientID); } // void CGameContext::StartVote(int Type, const char *pDesc, const char *pCommand, const char *pReason) { // check if a vote is already running if(m_VoteCloseTime) return; // reset votes m_VoteEnforce = VOTE_ENFORCE_UNKNOWN; for(int i = 0; i < MAX_CLIENTS; i++) { if(m_apPlayers[i]) { m_apPlayers[i]->m_Vote = 0; m_apPlayers[i]->m_VotePos = 0; } } // start vote m_VoteCloseTime = time_get() + time_freq()*VOTE_TIME; str_copy(m_aVoteDescription, pDesc, sizeof(m_aVoteDescription)); str_copy(m_aVoteCommand, pCommand, sizeof(m_aVoteCommand)); str_copy(m_aVoteReason, pReason, sizeof(m_aVoteReason)); SendVoteSet(Type, -1); m_VoteUpdate = true; } void CGameContext::EndVote(int Type, bool Force) { m_VoteCloseTime = 0; if(Force) m_VoteCreator = -1; SendVoteSet(Type, -1); } void CGameContext::ForceVote(int Type, const char *pDescription, const char *pReason) { CNetMsg_Sv_VoteSet Msg; Msg.m_Type = Type; Msg.m_Timeout = 0; Msg.m_ClientID = -1; Msg.m_pDescription = pDescription; Msg.m_pReason = pReason; Server()->SendPackMsg(&Msg, MSGFLAG_VITAL, -1); } void CGameContext::SendVoteSet(int Type, int ToClientID) { CNetMsg_Sv_VoteSet Msg; if(m_VoteCloseTime) { Msg.m_ClientID = m_VoteCreator; Msg.m_Type = Type; Msg.m_Timeout = (m_VoteCloseTime-time_get())/time_freq(); Msg.m_pDescription = m_aVoteDescription; Msg.m_pReason = m_aVoteReason; } else { Msg.m_Type = Type; Msg.m_Timeout = 0; Msg.m_ClientID = m_VoteCreator; Msg.m_pDescription = ""; Msg.m_pReason = ""; } Server()->SendPackMsg(&Msg, MSGFLAG_VITAL, ToClientID); } void CGameContext::SendVoteStatus(int ClientID, int Total, int Yes, int No) { CNetMsg_Sv_VoteStatus Msg = {0}; Msg.m_Total = Total; Msg.m_Yes = Yes; Msg.m_No = No; Msg.m_Pass = Total - (Yes+No); Server()->SendPackMsg(&Msg, MSGFLAG_VITAL, ClientID); } void CGameContext::AbortVoteOnDisconnect(int ClientID) { if(m_VoteCloseTime && ClientID == m_VoteClientID && (!str_comp_num(m_aVoteCommand, "kick ", 5) || !str_comp_num(m_aVoteCommand, "set_team ", 9) || (!str_comp_num(m_aVoteCommand, "ban ", 4) && Server()->IsBanned(ClientID)))) m_VoteCloseTime = -1; } void CGameContext::AbortVoteOnTeamChange(int ClientID) { if(m_VoteCloseTime && ClientID == m_VoteClientID && !str_comp_num(m_aVoteCommand, "set_team ", 9)) m_VoteCloseTime = -1; } void CGameContext::CheckPureTuning() { // might not be created yet during start up if(!m_pController) return; if( str_comp(m_pController->GetGameType(), "DM")==0 || str_comp(m_pController->GetGameType(), "TDM")==0 || str_comp(m_pController->GetGameType(), "CTF")==0 || str_comp(m_pController->GetGameType(), "LMS")==0 || str_comp(m_pController->GetGameType(), "SUR")==0) { CTuningParams p; if(mem_comp(&p, &m_Tuning, sizeof(p)) != 0) { Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", "resetting tuning due to pure server"); m_Tuning = p; } } } void CGameContext::SendTuningParams(int ClientID) { CheckPureTuning(); CMsgPacker Msg(NETMSGTYPE_SV_TUNEPARAMS); int *pParams = (int *)&m_Tuning; for(unsigned i = 0; i < sizeof(m_Tuning)/sizeof(int); i++) Msg.AddInt(pParams[i]); Server()->SendMsg(&Msg, MSGFLAG_VITAL, ClientID); } void CGameContext::SwapTeams() { if(!m_pController->IsTeamplay()) return; SendGameMsg(GAMEMSG_TEAM_SWAP, -1); for(int i = 0; i < MAX_CLIENTS; ++i) { if(m_apPlayers[i] && m_apPlayers[i]->GetTeam() != TEAM_SPECTATORS) m_pController->DoTeamChange(m_apPlayers[i], m_apPlayers[i]->GetTeam()^1, false); } } void CGameContext::OnTick() { // check tuning CheckPureTuning(); // copy tuning m_World.m_Core.m_Tuning = m_Tuning; m_World.Tick(); //if(world.paused) // make sure that the game object always updates m_pController->Tick(); for(int i = 0; i < MAX_CLIENTS; i++) { if(m_apPlayers[i]) { m_apPlayers[i]->Tick(); m_apPlayers[i]->PostTick(); } } // update voting if(m_VoteCloseTime) { // abort the kick-vote on player-leave if(m_VoteCloseTime == -1) EndVote(VOTE_END_ABORT, false); else { int Total = 0, Yes = 0, No = 0; if(m_VoteUpdate) { // count votes char aaBuf[MAX_CLIENTS][NETADDR_MAXSTRSIZE] = {{0}}; for(int i = 0; i < MAX_CLIENTS; i++) if(m_apPlayers[i]) Server()->GetClientAddr(i, aaBuf[i], NETADDR_MAXSTRSIZE); bool aVoteChecked[MAX_CLIENTS] = {0}; for(int i = 0; i < MAX_CLIENTS; i++) { if(!m_apPlayers[i] || m_apPlayers[i]->GetTeam() == TEAM_SPECTATORS || aVoteChecked[i]) // don't count in votes by spectators continue; int ActVote = m_apPlayers[i]->m_Vote; int ActVotePos = m_apPlayers[i]->m_VotePos; // check for more players with the same ip (only use the vote of the one who voted first) for(int j = i+1; j < MAX_CLIENTS; ++j) { if(!m_apPlayers[j] || aVoteChecked[j] || str_comp(aaBuf[j], aaBuf[i])) continue; aVoteChecked[j] = true; if(m_apPlayers[j]->m_Vote && (!ActVote || ActVotePos > m_apPlayers[j]->m_VotePos)) { ActVote = m_apPlayers[j]->m_Vote; ActVotePos = m_apPlayers[j]->m_VotePos; } } Total++; if(ActVote > 0) Yes++; else if(ActVote < 0) No++; } } if(m_VoteEnforce == VOTE_ENFORCE_YES || (m_VoteUpdate && Yes >= Total/2+1)) { Server()->SetRconCID(IServer::RCON_CID_VOTE); Console()->ExecuteLine(m_aVoteCommand); Server()->SetRconCID(IServer::RCON_CID_SERV); if(m_VoteCreator != -1 && m_apPlayers[m_VoteCreator]) m_apPlayers[m_VoteCreator]->m_LastVoteCall = 0; EndVote(VOTE_END_PASS, m_VoteEnforce==VOTE_ENFORCE_YES); } else if(m_VoteEnforce == VOTE_ENFORCE_NO || (m_VoteUpdate && No >= (Total+1)/2) || time_get() > m_VoteCloseTime) EndVote(VOTE_END_FAIL, m_VoteEnforce==VOTE_ENFORCE_NO); else if(m_VoteUpdate) { m_VoteUpdate = false; SendVoteStatus(-1, Total, Yes, No); } } } #ifdef CONF_DEBUG for(int i = 0; i < MAX_CLIENTS; i++) { if(m_apPlayers[i] && m_apPlayers[i]->IsDummy()) { CNetObj_PlayerInput Input = {0}; Input.m_Direction = (i&1)?-1:1; m_apPlayers[i]->OnPredictedInput(&Input); } } #endif } // Server hooks void CGameContext::OnClientDirectInput(int ClientID, void *pInput) { int NumCorrections = m_NetObjHandler.NumObjCorrections(); if(m_NetObjHandler.ValidateObj(NETOBJTYPE_PLAYERINPUT, pInput, sizeof(CNetObj_PlayerInput)) == 0) { if(g_Config.m_Debug && NumCorrections != m_NetObjHandler.NumObjCorrections()) { char aBuf[128]; str_format(aBuf, sizeof(aBuf), "NETOBJTYPE_PLAYERINPUT corrected on '%s'", m_NetObjHandler.CorrectedObjOn()); Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "server", aBuf); } m_apPlayers[ClientID]->OnDirectInput((CNetObj_PlayerInput *)pInput); } } void CGameContext::OnClientPredictedInput(int ClientID, void *pInput) { if(!m_World.m_Paused) { int NumCorrections = m_NetObjHandler.NumObjCorrections(); if(m_NetObjHandler.ValidateObj(NETOBJTYPE_PLAYERINPUT, pInput, sizeof(CNetObj_PlayerInput)) == 0) { if(g_Config.m_Debug && NumCorrections != m_NetObjHandler.NumObjCorrections()) { char aBuf[128]; str_format(aBuf, sizeof(aBuf), "NETOBJTYPE_PLAYERINPUT corrected on '%s'", m_NetObjHandler.CorrectedObjOn()); Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "server", aBuf); } m_apPlayers[ClientID]->OnPredictedInput((CNetObj_PlayerInput *)pInput); } } } void CGameContext::OnClientEnter(int ClientID) { m_pController->OnPlayerConnect(m_apPlayers[ClientID]); m_VoteUpdate = true; // update client infos (others before local) CNetMsg_Sv_ClientInfo NewClientInfoMsg; NewClientInfoMsg.m_ClientID = ClientID; NewClientInfoMsg.m_Local = 0; NewClientInfoMsg.m_Team = m_apPlayers[ClientID]->GetTeam(); NewClientInfoMsg.m_pName = Server()->ClientName(ClientID); NewClientInfoMsg.m_pClan = Server()->ClientClan(ClientID); NewClientInfoMsg.m_Country = Server()->ClientCountry(ClientID); for(int p = 0; p < 6; p++) { NewClientInfoMsg.m_apSkinPartNames[p] = m_apPlayers[ClientID]->m_TeeInfos.m_aaSkinPartNames[p]; NewClientInfoMsg.m_aUseCustomColors[p] = m_apPlayers[ClientID]->m_TeeInfos.m_aUseCustomColors[p]; NewClientInfoMsg.m_aSkinPartColors[p] = m_apPlayers[ClientID]->m_TeeInfos.m_aSkinPartColors[p]; } for(int i = 0; i < MAX_CLIENTS; ++i) { if(i == ClientID || !m_apPlayers[i] || (!Server()->ClientIngame(i) && !m_apPlayers[i]->IsDummy())) continue; // new info for others if(Server()->ClientIngame(i)) Server()->SendPackMsg(&NewClientInfoMsg, MSGFLAG_VITAL|MSGFLAG_NORECORD, i); // existing infos for new player CNetMsg_Sv_ClientInfo ClientInfoMsg; ClientInfoMsg.m_ClientID = i; ClientInfoMsg.m_Local = 0; ClientInfoMsg.m_Team = m_apPlayers[i]->GetTeam(); ClientInfoMsg.m_pName = Server()->ClientName(i); ClientInfoMsg.m_pClan = Server()->ClientClan(i); ClientInfoMsg.m_Country = Server()->ClientCountry(i); for(int p = 0; p < 6; p++) { ClientInfoMsg.m_apSkinPartNames[p] = m_apPlayers[i]->m_TeeInfos.m_aaSkinPartNames[p]; ClientInfoMsg.m_aUseCustomColors[p] = m_apPlayers[i]->m_TeeInfos.m_aUseCustomColors[p]; ClientInfoMsg.m_aSkinPartColors[p] = m_apPlayers[i]->m_TeeInfos.m_aSkinPartColors[p]; } Server()->SendPackMsg(&ClientInfoMsg, MSGFLAG_VITAL|MSGFLAG_NORECORD, ClientID); } // local info NewClientInfoMsg.m_Local = 1; Server()->SendPackMsg(&NewClientInfoMsg, MSGFLAG_VITAL|MSGFLAG_NORECORD, ClientID); if(Server()->DemoRecorder_IsRecording()) { CNetMsg_De_ClientEnter Msg; Msg.m_pName = NewClientInfoMsg.m_pName; Msg.m_Team = NewClientInfoMsg.m_Team; Server()->SendPackMsg(&Msg, MSGFLAG_NOSEND, -1); } } void CGameContext::OnClientConnected(int ClientID, bool Dummy) { m_apPlayers[ClientID] = new(ClientID) CPlayer(this, ClientID, Dummy); if(Dummy) return; // send active vote if(m_VoteCloseTime) SendVoteSet(VOTE_UNKNOWN, ClientID); // send motd SendMotd(ClientID); // send settings SendSettings(ClientID); } void CGameContext::OnClientTeamChange(int ClientID) { if(m_apPlayers[ClientID]->GetTeam() == TEAM_SPECTATORS) AbortVoteOnTeamChange(ClientID); } void CGameContext::OnClientDrop(int ClientID, const char *pReason) { // update clients on drop if(Server()->ClientIngame(ClientID)) { if(Server()->DemoRecorder_IsRecording()) { CNetMsg_De_ClientLeave Msg; Msg.m_pName = Server()->ClientName(ClientID); Msg.m_pReason = pReason; Server()->SendPackMsg(&Msg, MSGFLAG_NOSEND, -1); } CNetMsg_Sv_ClientDrop Msg; Msg.m_ClientID = ClientID; Msg.m_pReason = pReason; Server()->SendPackMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_NORECORD, -1); } AbortVoteOnDisconnect(ClientID); m_pController->OnPlayerDisconnect(m_apPlayers[ClientID]); delete m_apPlayers[ClientID]; m_apPlayers[ClientID] = 0; m_VoteUpdate = true; } void CGameContext::OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID) { void *pRawMsg = m_NetObjHandler.SecureUnpackMsg(MsgID, pUnpacker); CPlayer *pPlayer = m_apPlayers[ClientID]; if(!pRawMsg) { if(g_Config.m_Debug) { char aBuf[256]; str_format(aBuf, sizeof(aBuf), "dropped weird message '%s' (%d), failed on '%s'", m_NetObjHandler.GetMsgName(MsgID), MsgID, m_NetObjHandler.FailedMsgOn()); Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "server", aBuf); } return; } if(Server()->ClientIngame(ClientID)) { if(MsgID == NETMSGTYPE_CL_SAY) { CNetMsg_Cl_Say *pMsg = (CNetMsg_Cl_Say *)pRawMsg; int Team = pMsg->m_Team; if(Team) Team = pPlayer->GetTeam(); else Team = CGameContext::CHAT_ALL; if(g_Config.m_SvSpamprotection && pPlayer->m_LastChat && pPlayer->m_LastChat+Server()->TickSpeed() > Server()->Tick()) return; pPlayer->m_LastChat = Server()->Tick(); // check for invalid chars unsigned char *pMessage = (unsigned char *)pMsg->m_pMessage; while (*pMessage) { if(*pMessage < 32) *pMessage = ' '; pMessage++; } SendChat(ClientID, Team, pMsg->m_pMessage); } else if(MsgID == NETMSGTYPE_CL_CALLVOTE) { CNetMsg_Cl_CallVote *pMsg = (CNetMsg_Cl_CallVote *)pRawMsg; int64 Now = Server()->Tick(); if(pMsg->m_Force) { if(!Server()->IsAuthed(ClientID)) return; } else { if((g_Config.m_SvSpamprotection && ((pPlayer->m_LastVoteTry && pPlayer->m_LastVoteTry+Server()->TickSpeed()*3 > Now) || (pPlayer->m_LastVoteCall && pPlayer->m_LastVoteCall+Server()->TickSpeed()*VOTE_COOLDOWN > Now))) || pPlayer->GetTeam() == TEAM_SPECTATORS || m_VoteCloseTime) return; pPlayer->m_LastVoteTry = Now; } int Type = VOTE_UNKNOWN; char aDesc[VOTE_DESC_LENGTH] = {0}; char aCmd[VOTE_CMD_LENGTH] = {0}; const char *pReason = pMsg->m_Reason[0] ? pMsg->m_Reason : "No reason given"; if(str_comp_nocase(pMsg->m_Type, "option") == 0) { CVoteOptionServer *pOption = m_pVoteOptionFirst; while(pOption) { if(str_comp_nocase(pMsg->m_Value, pOption->m_aDescription) == 0) { str_format(aDesc, sizeof(aDesc), "%s", pOption->m_aDescription); str_format(aCmd, sizeof(aCmd), "%s", pOption->m_aCommand); if(pMsg->m_Force) { Server()->SetRconCID(ClientID); Console()->ExecuteLine(aCmd); Server()->SetRconCID(IServer::RCON_CID_SERV); ForceVote(VOTE_START_OP, aDesc, pReason); return; } Type = VOTE_START_OP; break; } pOption = pOption->m_pNext; } if(!pOption) return; } else if(str_comp_nocase(pMsg->m_Type, "kick") == 0) { if(!g_Config.m_SvVoteKick || m_pController->GetRealPlayerNum() < g_Config.m_SvVoteKickMin) return; int KickID = str_toint(pMsg->m_Value); if(KickID < 0 || KickID >= MAX_CLIENTS || !m_apPlayers[KickID] || KickID == ClientID || Server()->IsAuthed(KickID)) return; str_format(aDesc, sizeof(aDesc), "Kick '%s'", Server()->ClientName(KickID)); if (!g_Config.m_SvVoteKickBantime) str_format(aCmd, sizeof(aCmd), "kick %d Kicked by vote", KickID); else { char aAddrStr[NETADDR_MAXSTRSIZE] = {0}; Server()->GetClientAddr(KickID, aAddrStr, sizeof(aAddrStr)); str_format(aCmd, sizeof(aCmd), "ban %s %d Banned by vote", aAddrStr, g_Config.m_SvVoteKickBantime); } if(pMsg->m_Force) { Server()->SetRconCID(ClientID); Console()->ExecuteLine(aCmd); Server()->SetRconCID(IServer::RCON_CID_SERV); return; } Type = VOTE_START_KICK; m_VoteClientID = KickID; } else if(str_comp_nocase(pMsg->m_Type, "spectate") == 0) { if(!g_Config.m_SvVoteSpectate) return; int SpectateID = str_toint(pMsg->m_Value); if(SpectateID < 0 || SpectateID >= MAX_CLIENTS || !m_apPlayers[SpectateID] || m_apPlayers[SpectateID]->GetTeam() == TEAM_SPECTATORS || SpectateID == ClientID) return; str_format(aDesc, sizeof(aDesc), "move '%s' to spectators", Server()->ClientName(SpectateID)); str_format(aCmd, sizeof(aCmd), "set_team %d -1 %d", SpectateID, g_Config.m_SvVoteSpectateRejoindelay); if(pMsg->m_Force) { Server()->SetRconCID(ClientID); Console()->ExecuteLine(aCmd); Server()->SetRconCID(IServer::RCON_CID_SERV); ForceVote(VOTE_START_SPEC, aDesc, pReason); return; } Type = VOTE_START_SPEC; m_VoteClientID = SpectateID; } if(Type != VOTE_UNKNOWN) { m_VoteCreator = ClientID; StartVote(Type, aDesc, aCmd, pReason); pPlayer->m_Vote = 1; pPlayer->m_VotePos = m_VotePos = 1; pPlayer->m_LastVoteCall = Now; } } else if(MsgID == NETMSGTYPE_CL_VOTE) { if(!m_VoteCloseTime) return; if(pPlayer->m_Vote == 0) { CNetMsg_Cl_Vote *pMsg = (CNetMsg_Cl_Vote *)pRawMsg; if(!pMsg->m_Vote) return; pPlayer->m_Vote = pMsg->m_Vote; pPlayer->m_VotePos = ++m_VotePos; m_VoteUpdate = true; } } else if(MsgID == NETMSGTYPE_CL_SETTEAM && m_pController->IsTeamChangeAllowed()) { CNetMsg_Cl_SetTeam *pMsg = (CNetMsg_Cl_SetTeam *)pRawMsg; if(pPlayer->GetTeam() == pMsg->m_Team || (g_Config.m_SvSpamprotection && pPlayer->m_LastSetTeam && pPlayer->m_LastSetTeam+Server()->TickSpeed()*3 > Server()->Tick()) || (pMsg->m_Team != TEAM_SPECTATORS && m_LockTeams) || pPlayer->m_TeamChangeTick > Server()->Tick()) return; pPlayer->m_LastSetTeam = Server()->Tick(); // Switch team on given client and kill/respawn him if(m_pController->CanJoinTeam(pMsg->m_Team, ClientID) && m_pController->CanChangeTeam(pPlayer, pMsg->m_Team)) { if(pPlayer->GetTeam() == TEAM_SPECTATORS || pMsg->m_Team == TEAM_SPECTATORS) m_VoteUpdate = true; pPlayer->m_TeamChangeTick = Server()->Tick()+Server()->TickSpeed()*3; m_pController->DoTeamChange(pPlayer, pMsg->m_Team); } } else if (MsgID == NETMSGTYPE_CL_SETSPECTATORMODE && !m_World.m_Paused) { CNetMsg_Cl_SetSpectatorMode *pMsg = (CNetMsg_Cl_SetSpectatorMode *)pRawMsg; if(g_Config.m_SvSpamprotection && pPlayer->m_LastSetSpectatorMode && pPlayer->m_LastSetSpectatorMode+Server()->TickSpeed()*3 > Server()->Tick()) return; pPlayer->m_LastSetSpectatorMode = Server()->Tick(); if(!pPlayer->SetSpectatorID(pMsg->m_SpectatorID)) SendGameMsg(GAMEMSG_SPEC_INVALIDID, ClientID); } else if (MsgID == NETMSGTYPE_CL_EMOTICON && !m_World.m_Paused) { CNetMsg_Cl_Emoticon *pMsg = (CNetMsg_Cl_Emoticon *)pRawMsg; if(g_Config.m_SvSpamprotection && pPlayer->m_LastEmote && pPlayer->m_LastEmote+Server()->TickSpeed()*3 > Server()->Tick()) return; pPlayer->m_LastEmote = Server()->Tick(); SendEmoticon(ClientID, pMsg->m_Emoticon); } else if (MsgID == NETMSGTYPE_CL_KILL && !m_World.m_Paused) { if(pPlayer->m_LastKill && pPlayer->m_LastKill+Server()->TickSpeed()*3 > Server()->Tick()) return; pPlayer->m_LastKill = Server()->Tick(); pPlayer->KillCharacter(WEAPON_SELF); } else if (MsgID == NETMSGTYPE_CL_READYCHANGE) { if(pPlayer->m_LastReadyChange && pPlayer->m_LastReadyChange+Server()->TickSpeed()*1 > Server()->Tick()) return; pPlayer->m_LastReadyChange = Server()->Tick(); m_pController->OnPlayerReadyChange(pPlayer); } } else { if (MsgID == NETMSGTYPE_CL_STARTINFO) { if(pPlayer->m_IsReadyToEnter) return; CNetMsg_Cl_StartInfo *pMsg = (CNetMsg_Cl_StartInfo *)pRawMsg; pPlayer->m_LastChangeInfo = Server()->Tick(); // set start infos Server()->SetClientName(ClientID, pMsg->m_pName); Server()->SetClientClan(ClientID, pMsg->m_pClan); Server()->SetClientCountry(ClientID, pMsg->m_Country); for(int p = 0; p < 6; p++) { str_copy(pPlayer->m_TeeInfos.m_aaSkinPartNames[p], pMsg->m_apSkinPartNames[p], 24); pPlayer->m_TeeInfos.m_aUseCustomColors[p] = pMsg->m_aUseCustomColors[p]; pPlayer->m_TeeInfos.m_aSkinPartColors[p] = pMsg->m_aSkinPartColors[p]; } m_pController->OnPlayerInfoChange(pPlayer); // send vote options CNetMsg_Sv_VoteClearOptions ClearMsg; Server()->SendPackMsg(&ClearMsg, MSGFLAG_VITAL, ClientID); CVoteOptionServer *pCurrent = m_pVoteOptionFirst; while(pCurrent) { // count options for actual packet int NumOptions = 0; for(CVoteOptionServer *p = pCurrent; p && NumOptions < MAX_VOTE_OPTION_ADD; p = p->m_pNext, ++NumOptions); // pack and send vote list packet CMsgPacker Msg(NETMSGTYPE_SV_VOTEOPTIONLISTADD); Msg.AddInt(NumOptions); while(pCurrent && NumOptions--) { Msg.AddString(pCurrent->m_aDescription, VOTE_DESC_LENGTH); pCurrent = pCurrent->m_pNext; } Server()->SendMsg(&Msg, MSGFLAG_VITAL, ClientID); } // send tuning parameters to client SendTuningParams(ClientID); // client is ready to enter pPlayer->m_IsReadyToEnter = true; CNetMsg_Sv_ReadyToEnter m; Server()->SendPackMsg(&m, MSGFLAG_VITAL|MSGFLAG_FLUSH, ClientID); } } } void CGameContext::ConTuneParam(IConsole::IResult *pResult, void *pUserData) { CGameContext *pSelf = (CGameContext *)pUserData; const char *pParamName = pResult->GetString(0); float NewValue = pResult->GetFloat(1); if(pSelf->Tuning()->Set(pParamName, NewValue)) { char aBuf[256]; str_format(aBuf, sizeof(aBuf), "%s changed to %.2f", pParamName, NewValue); pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "tuning", aBuf); pSelf->SendTuningParams(-1); } else pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "tuning", "No such tuning parameter"); } void CGameContext::ConTuneReset(IConsole::IResult *pResult, void *pUserData) { CGameContext *pSelf = (CGameContext *)pUserData; CTuningParams TuningParams; *pSelf->Tuning() = TuningParams; pSelf->SendTuningParams(-1); pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "tuning", "Tuning reset"); } void CGameContext::ConTuneDump(IConsole::IResult *pResult, void *pUserData) { CGameContext *pSelf = (CGameContext *)pUserData; char aBuf[256]; for(int i = 0; i < pSelf->Tuning()->Num(); i++) { float v; pSelf->Tuning()->Get(i, &v); str_format(aBuf, sizeof(aBuf), "%s %.2f", pSelf->Tuning()->m_apNames[i], v); pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "tuning", aBuf); } } void CGameContext::ConPause(IConsole::IResult *pResult, void *pUserData) { CGameContext *pSelf = (CGameContext *)pUserData; if(pResult->NumArguments()) pSelf->m_pController->DoPause(clamp(pResult->GetInteger(0), -1, 1000)); else pSelf->m_pController->DoPause(pSelf->m_pController->IsGamePaused() ? 0 : IGameController::TIMER_INFINITE); } void CGameContext::ConChangeMap(IConsole::IResult *pResult, void *pUserData) { CGameContext *pSelf = (CGameContext *)pUserData; pSelf->m_pController->ChangeMap(pResult->NumArguments() ? pResult->GetString(0) : ""); } void CGameContext::ConRestart(IConsole::IResult *pResult, void *pUserData) { CGameContext *pSelf = (CGameContext *)pUserData; if(pResult->NumArguments()) pSelf->m_pController->DoWarmup(clamp(pResult->GetInteger(0), -1, 1000)); else pSelf->m_pController->DoWarmup(0); } void CGameContext::ConSay(IConsole::IResult *pResult, void *pUserData) { CGameContext *pSelf = (CGameContext *)pUserData; pSelf->SendChat(-1, CGameContext::CHAT_ALL, pResult->GetString(0)); } void CGameContext::ConSetTeam(IConsole::IResult *pResult, void *pUserData) { CGameContext *pSelf = (CGameContext *)pUserData; int ClientID = clamp(pResult->GetInteger(0), 0, (int)MAX_CLIENTS-1); int Team = clamp(pResult->GetInteger(1), -1, 1); int Delay = pResult->NumArguments()>2 ? pResult->GetInteger(2) : 0; if(!pSelf->m_apPlayers[ClientID]) return; char aBuf[256]; str_format(aBuf, sizeof(aBuf), "moved client %d to team %d", ClientID, Team); pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); pSelf->m_apPlayers[ClientID]->m_TeamChangeTick = pSelf->Server()->Tick()+pSelf->Server()->TickSpeed()*Delay*60; pSelf->m_pController->DoTeamChange(pSelf->m_apPlayers[ClientID], Team); } void CGameContext::ConSetTeamAll(IConsole::IResult *pResult, void *pUserData) { CGameContext *pSelf = (CGameContext *)pUserData; int Team = clamp(pResult->GetInteger(0), -1, 1); pSelf->SendGameMsg(GAMEMSG_TEAM_ALL, Team, -1); for(int i = 0; i < MAX_CLIENTS; ++i) if(pSelf->m_apPlayers[i]) pSelf->m_pController->DoTeamChange(pSelf->m_apPlayers[i], Team, false); } void CGameContext::ConSwapTeams(IConsole::IResult *pResult, void *pUserData) { CGameContext *pSelf = (CGameContext *)pUserData; pSelf->SwapTeams(); } void CGameContext::ConShuffleTeams(IConsole::IResult *pResult, void *pUserData) { CGameContext *pSelf = (CGameContext *)pUserData; if(!pSelf->m_pController->IsTeamplay()) return; int rnd = 0; int PlayerTeam = 0; int aPlayer[MAX_CLIENTS]; for(int i = 0; i < MAX_CLIENTS; i++) if(pSelf->m_apPlayers[i] && pSelf->m_apPlayers[i]->GetTeam() != TEAM_SPECTATORS) aPlayer[PlayerTeam++]=i; pSelf->SendGameMsg(GAMEMSG_TEAM_SHUFFLE, -1); //creating random permutation for(int i = PlayerTeam; i > 1; i--) { rnd = rand() % i; int tmp = aPlayer[rnd]; aPlayer[rnd] = aPlayer[i-1]; aPlayer[i-1] = tmp; } //uneven Number of Players? rnd = PlayerTeam % 2 ? rand() % 2 : 0; for(int i = 0; i < PlayerTeam; i++) pSelf->m_pController->DoTeamChange(pSelf->m_apPlayers[aPlayer[i]], i < (PlayerTeam+rnd)/2 ? TEAM_RED : TEAM_BLUE, false); } void CGameContext::ConLockTeams(IConsole::IResult *pResult, void *pUserData) { CGameContext *pSelf = (CGameContext *)pUserData; pSelf->m_LockTeams ^= 1; pSelf->SendSettings(-1); } void CGameContext::ConForceTeamBalance(IConsole::IResult *pResult, void *pUserData) { CGameContext *pSelf = (CGameContext *)pUserData; pSelf->m_pController->ForceTeamBalance(); } void CGameContext::ConAddVote(IConsole::IResult *pResult, void *pUserData) { CGameContext *pSelf = (CGameContext *)pUserData; const char *pDescription = pResult->GetString(0); const char *pCommand = pResult->GetString(1); if(pSelf->m_NumVoteOptions == MAX_VOTE_OPTIONS) { pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", "maximum number of vote options reached"); return; } // check for valid option if(!pSelf->Console()->LineIsValid(pCommand) || str_length(pCommand) >= VOTE_CMD_LENGTH) { char aBuf[256]; str_format(aBuf, sizeof(aBuf), "skipped invalid command '%s'", pCommand); pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); return; } while(*pDescription && *pDescription == ' ') pDescription++; if(str_length(pDescription) >= VOTE_DESC_LENGTH || *pDescription == 0) { char aBuf[256]; str_format(aBuf, sizeof(aBuf), "skipped invalid option '%s'", pDescription); pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); return; } // check for duplicate entry CVoteOptionServer *pOption = pSelf->m_pVoteOptionFirst; while(pOption) { if(str_comp_nocase(pDescription, pOption->m_aDescription) == 0) { char aBuf[256]; str_format(aBuf, sizeof(aBuf), "option '%s' already exists", pDescription); pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); return; } pOption = pOption->m_pNext; } // add the option ++pSelf->m_NumVoteOptions; int Len = str_length(pCommand); pOption = (CVoteOptionServer *)pSelf->m_pVoteOptionHeap->Allocate(sizeof(CVoteOptionServer) + Len); pOption->m_pNext = 0; pOption->m_pPrev = pSelf->m_pVoteOptionLast; if(pOption->m_pPrev) pOption->m_pPrev->m_pNext = pOption; pSelf->m_pVoteOptionLast = pOption; if(!pSelf->m_pVoteOptionFirst) pSelf->m_pVoteOptionFirst = pOption; str_copy(pOption->m_aDescription, pDescription, sizeof(pOption->m_aDescription)); mem_copy(pOption->m_aCommand, pCommand, Len+1); char aBuf[256]; str_format(aBuf, sizeof(aBuf), "added option '%s' '%s'", pOption->m_aDescription, pOption->m_aCommand); pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); // inform clients about added option CNetMsg_Sv_VoteOptionAdd OptionMsg; OptionMsg.m_pDescription = pOption->m_aDescription; pSelf->Server()->SendPackMsg(&OptionMsg, MSGFLAG_VITAL, -1); } void CGameContext::ConRemoveVote(IConsole::IResult *pResult, void *pUserData) { CGameContext *pSelf = (CGameContext *)pUserData; const char *pDescription = pResult->GetString(0); // check for valid option CVoteOptionServer *pOption = pSelf->m_pVoteOptionFirst; while(pOption) { if(str_comp_nocase(pDescription, pOption->m_aDescription) == 0) break; pOption = pOption->m_pNext; } if(!pOption) { char aBuf[256]; str_format(aBuf, sizeof(aBuf), "option '%s' does not exist", pDescription); pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); return; } // inform clients about removed option CNetMsg_Sv_VoteOptionRemove OptionMsg; OptionMsg.m_pDescription = pOption->m_aDescription; pSelf->Server()->SendPackMsg(&OptionMsg, MSGFLAG_VITAL, -1); // TODO: improve this // remove the option --pSelf->m_NumVoteOptions; char aBuf[256]; str_format(aBuf, sizeof(aBuf), "removed option '%s' '%s'", pOption->m_aDescription, pOption->m_aCommand); pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); CHeap *pVoteOptionHeap = new CHeap(); CVoteOptionServer *pVoteOptionFirst = 0; CVoteOptionServer *pVoteOptionLast = 0; int NumVoteOptions = pSelf->m_NumVoteOptions; for(CVoteOptionServer *pSrc = pSelf->m_pVoteOptionFirst; pSrc; pSrc = pSrc->m_pNext) { if(pSrc == pOption) continue; // copy option int Len = str_length(pSrc->m_aCommand); CVoteOptionServer *pDst = (CVoteOptionServer *)pVoteOptionHeap->Allocate(sizeof(CVoteOptionServer) + Len); pDst->m_pNext = 0; pDst->m_pPrev = pVoteOptionLast; if(pDst->m_pPrev) pDst->m_pPrev->m_pNext = pDst; pVoteOptionLast = pDst; if(!pVoteOptionFirst) pVoteOptionFirst = pDst; str_copy(pDst->m_aDescription, pSrc->m_aDescription, sizeof(pDst->m_aDescription)); mem_copy(pDst->m_aCommand, pSrc->m_aCommand, Len+1); } // clean up delete pSelf->m_pVoteOptionHeap; pSelf->m_pVoteOptionHeap = pVoteOptionHeap; pSelf->m_pVoteOptionFirst = pVoteOptionFirst; pSelf->m_pVoteOptionLast = pVoteOptionLast; pSelf->m_NumVoteOptions = NumVoteOptions; } void CGameContext::ConClearVotes(IConsole::IResult *pResult, void *pUserData) { CGameContext *pSelf = (CGameContext *)pUserData; pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", "cleared votes"); CNetMsg_Sv_VoteClearOptions VoteClearOptionsMsg; pSelf->Server()->SendPackMsg(&VoteClearOptionsMsg, MSGFLAG_VITAL, -1); pSelf->m_pVoteOptionHeap->Reset(); pSelf->m_pVoteOptionFirst = 0; pSelf->m_pVoteOptionLast = 0; pSelf->m_NumVoteOptions = 0; } void CGameContext::ConVote(IConsole::IResult *pResult, void *pUserData) { CGameContext *pSelf = (CGameContext *)pUserData; // check if there is a vote running if(!pSelf->m_VoteCloseTime) return; if(str_comp_nocase(pResult->GetString(0), "yes") == 0) pSelf->m_VoteEnforce = CGameContext::VOTE_ENFORCE_YES; else if(str_comp_nocase(pResult->GetString(0), "no") == 0) pSelf->m_VoteEnforce = CGameContext::VOTE_ENFORCE_NO; char aBuf[256]; str_format(aBuf, sizeof(aBuf), "forcing vote %s", pResult->GetString(0)); pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf); } void CGameContext::ConchainSpecialMotdupdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData) { pfnCallback(pResult, pCallbackUserData); if(pResult->NumArguments()) { CGameContext *pSelf = (CGameContext *)pUserData; pSelf->SendMotd(-1); } } void CGameContext::ConchainSettingUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData) { pfnCallback(pResult, pCallbackUserData); if(pResult->NumArguments()) { CGameContext *pSelf = (CGameContext *)pUserData; pSelf->SendSettings(-1); } } void CGameContext::OnConsoleInit() { m_pServer = Kernel()->RequestInterface<IServer>(); m_pConsole = Kernel()->RequestInterface<IConsole>(); Console()->Register("tune", "si", CFGFLAG_SERVER, ConTuneParam, this, "Tune variable to value"); Console()->Register("tune_reset", "", CFGFLAG_SERVER, ConTuneReset, this, "Reset tuning"); Console()->Register("tune_dump", "", CFGFLAG_SERVER, ConTuneDump, this, "Dump tuning"); Console()->Register("pause", "?i", CFGFLAG_SERVER|CFGFLAG_STORE, ConPause, this, "Pause/unpause game"); Console()->Register("change_map", "?r", CFGFLAG_SERVER|CFGFLAG_STORE, ConChangeMap, this, "Change map"); Console()->Register("restart", "?i", CFGFLAG_SERVER|CFGFLAG_STORE, ConRestart, this, "Restart in x seconds (0 = abort)"); Console()->Register("say", "r", CFGFLAG_SERVER, ConSay, this, "Say in chat"); Console()->Register("set_team", "ii?i", CFGFLAG_SERVER, ConSetTeam, this, "Set team of player to team"); Console()->Register("set_team_all", "i", CFGFLAG_SERVER, ConSetTeamAll, this, "Set team of all players to team"); Console()->Register("swap_teams", "", CFGFLAG_SERVER, ConSwapTeams, this, "Swap the current teams"); Console()->Register("shuffle_teams", "", CFGFLAG_SERVER, ConShuffleTeams, this, "Shuffle the current teams"); Console()->Register("lock_teams", "", CFGFLAG_SERVER, ConLockTeams, this, "Lock/unlock teams"); Console()->Register("force_teambalance", "", CFGFLAG_SERVER, ConForceTeamBalance, this, "Force team balance"); Console()->Register("add_vote", "sr", CFGFLAG_SERVER, ConAddVote, this, "Add a voting option"); Console()->Register("remove_vote", "s", CFGFLAG_SERVER, ConRemoveVote, this, "remove a voting option"); Console()->Register("clear_votes", "", CFGFLAG_SERVER, ConClearVotes, this, "Clears the voting options"); Console()->Register("vote", "r", CFGFLAG_SERVER, ConVote, this, "Force a vote to yes/no"); Console()->Chain("sv_motd", ConchainSpecialMotdupdate, this); Console()->Chain("sv_vote_kick", ConchainSettingUpdate, this); Console()->Chain("sv_vote_kick_min", ConchainSettingUpdate, this); Console()->Chain("sv_vote_spectate", ConchainSettingUpdate, this); Console()->Chain("sv_teambalance_time", ConchainSettingUpdate, this); Console()->Chain("sv_spectator_slots", ConchainSettingUpdate, this); } void CGameContext::OnInit() { // init everything m_pServer = Kernel()->RequestInterface<IServer>(); m_pConsole = Kernel()->RequestInterface<IConsole>(); m_World.SetGameServer(this); m_Events.SetGameServer(this); for(int i = 0; i < NUM_NETOBJTYPES; i++) Server()->SnapSetStaticsize(i, m_NetObjHandler.GetObjSize(i)); m_Layers.Init(Kernel()); m_Collision.Init(&m_Layers); // select gametype if(str_comp_nocase(g_Config.m_SvGametype, "mod") == 0) m_pController = new CGameControllerMOD(this); else if(str_comp_nocase(g_Config.m_SvGametype, "ctf") == 0) m_pController = new CGameControllerCTF(this); else if(str_comp_nocase(g_Config.m_SvGametype, "lms") == 0) m_pController = new CGameControllerLMS(this); else if(str_comp_nocase(g_Config.m_SvGametype, "sur") == 0) m_pController = new CGameControllerSUR(this); else if(str_comp_nocase(g_Config.m_SvGametype, "tdm") == 0) m_pController = new CGameControllerTDM(this); else m_pController = new CGameControllerDM(this); // create all entities from the game layer CMapItemLayerTilemap *pTileMap = m_Layers.GameLayer(); CTile *pTiles = (CTile *)Kernel()->RequestInterface<IMap>()->GetData(pTileMap->m_Data); for(int y = 0; y < pTileMap->m_Height; y++) { for(int x = 0; x < pTileMap->m_Width; x++) { int Index = pTiles[y*pTileMap->m_Width+x].m_Index; if(Index >= ENTITY_OFFSET) { vec2 Pos(x*32.0f+16.0f, y*32.0f+16.0f); m_pController->OnEntity(Index-ENTITY_OFFSET, Pos); } } } #ifdef CONF_DEBUG if(g_Config.m_DbgDummies) { for(int i = 0; i < g_Config.m_DbgDummies ; i++) OnClientConnected(MAX_CLIENTS-i-1, true); } #endif } void CGameContext::OnShutdown() { delete m_pController; m_pController = 0; Clear(); } void CGameContext::OnSnap(int ClientID) { // add tuning to demo CTuningParams StandardTuning; if(ClientID == -1 && Server()->DemoRecorder_IsRecording() && mem_comp(&StandardTuning, &m_Tuning, sizeof(CTuningParams)) != 0) { CNetObj_De_TuneParams *pTuneParams = static_cast<CNetObj_De_TuneParams *>(Server()->SnapNewItem(NETOBJTYPE_DE_TUNEPARAMS, 0, sizeof(CNetObj_De_TuneParams))); if(!pTuneParams) return; mem_copy(pTuneParams->m_aTuneParams, &m_Tuning, sizeof(pTuneParams->m_aTuneParams)); } m_World.Snap(ClientID); m_pController->Snap(ClientID); m_Events.Snap(ClientID); for(int i = 0; i < MAX_CLIENTS; i++) { if(m_apPlayers[i]) m_apPlayers[i]->Snap(ClientID); } } void CGameContext::OnPreSnap() {} void CGameContext::OnPostSnap() { m_World.PostSnap(); m_Events.Clear(); } bool CGameContext::IsClientReady(int ClientID) { return m_apPlayers[ClientID] && m_apPlayers[ClientID]->m_IsReadyToEnter ? true : false; } bool CGameContext::IsClientPlayer(int ClientID) { return m_apPlayers[ClientID] && m_apPlayers[ClientID]->GetTeam() == TEAM_SPECTATORS ? false : true; } const char *CGameContext::GameType() { return m_pController && m_pController->GetGameType() ? m_pController->GetGameType() : ""; } const char *CGameContext::Version() { return GAME_VERSION; } const char *CGameContext::NetVersion() { return GAME_NETVERSION; } IGameServer *CreateGameServer() { return new CGameContext; } ================================================ FILE: src/game/server/gamecontext.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_SERVER_GAMECONTEXT_H #define GAME_SERVER_GAMECONTEXT_H #include <engine/console.h> #include <engine/server.h> #include <game/layers.h> #include <game/voting.h> #include "eventhandler.h" #include "gameworld.h" /* Tick Game Context (CGameContext::tick) Game World (GAMEWORLD::tick) Reset world if requested (GAMEWORLD::reset) All entities in the world (ENTITY::tick) All entities in the world (ENTITY::tick_defered) Remove entities marked for deletion (GAMEWORLD::remove_entities) Game Controller (GAMECONTROLLER::tick) All players (CPlayer::tick) Snap Game Context (CGameContext::snap) Game World (GAMEWORLD::snap) All entities in the world (ENTITY::snap) Game Controller (GAMECONTROLLER::snap) Events handler (EVENT_HANDLER::snap) All players (CPlayer::snap) */ class CGameContext : public IGameServer { IServer *m_pServer; class IConsole *m_pConsole; CLayers m_Layers; CCollision m_Collision; CNetObjHandler m_NetObjHandler; CTuningParams m_Tuning; static void ConTuneParam(IConsole::IResult *pResult, void *pUserData); static void ConTuneReset(IConsole::IResult *pResult, void *pUserData); static void ConTuneDump(IConsole::IResult *pResult, void *pUserData); static void ConPause(IConsole::IResult *pResult, void *pUserData); static void ConChangeMap(IConsole::IResult *pResult, void *pUserData); static void ConRestart(IConsole::IResult *pResult, void *pUserData); static void ConBroadcast(IConsole::IResult *pResult, void *pUserData); static void ConSay(IConsole::IResult *pResult, void *pUserData); static void ConSetTeam(IConsole::IResult *pResult, void *pUserData); static void ConSetTeamAll(IConsole::IResult *pResult, void *pUserData); static void ConSwapTeams(IConsole::IResult *pResult, void *pUserData); static void ConShuffleTeams(IConsole::IResult *pResult, void *pUserData); static void ConLockTeams(IConsole::IResult *pResult, void *pUserData); static void ConForceTeamBalance(IConsole::IResult *pResult, void *pUserData); static void ConAddVote(IConsole::IResult *pResult, void *pUserData); static void ConRemoveVote(IConsole::IResult *pResult, void *pUserData); static void ConClearVotes(IConsole::IResult *pResult, void *pUserData); static void ConVote(IConsole::IResult *pResult, void *pUserData); static void ConchainSpecialMotdupdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData); static void ConchainSettingUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData); CGameContext(int Resetting); void Construct(int Resetting); bool m_Resetting; public: IServer *Server() const { return m_pServer; } class IConsole *Console() { return m_pConsole; } CCollision *Collision() { return &m_Collision; } CTuningParams *Tuning() { return &m_Tuning; } CGameContext(); ~CGameContext(); void Clear(); CEventHandler m_Events; class CPlayer *m_apPlayers[MAX_CLIENTS]; class IGameController *m_pController; CGameWorld m_World; // helper functions class CCharacter *GetPlayerChar(int ClientID); int m_LockTeams; // voting void StartVote(int Type, const char *pDesc, const char *pCommand, const char *pReason); void EndVote(int Type, bool Force); void ForceVote(int Type, const char *pDescription, const char *pReason); void SendVoteSet(int Type, int ToClientID); void SendVoteStatus(int ClientID, int Total, int Yes, int No); void AbortVoteOnDisconnect(int ClientID); void AbortVoteOnTeamChange(int ClientID); int m_VoteCreator; int64 m_VoteCloseTime; bool m_VoteUpdate; int m_VotePos; char m_aVoteDescription[VOTE_DESC_LENGTH]; char m_aVoteCommand[VOTE_CMD_LENGTH]; char m_aVoteReason[VOTE_REASON_LENGTH]; int m_VoteClientID; int m_NumVoteOptions; int m_VoteEnforce; enum { VOTE_ENFORCE_UNKNOWN=0, VOTE_ENFORCE_NO, VOTE_ENFORCE_YES, VOTE_TIME=25, }; class CHeap *m_pVoteOptionHeap; CVoteOptionServer *m_pVoteOptionFirst; CVoteOptionServer *m_pVoteOptionLast; // helper functions void CreateDamageInd(vec2 Pos, float AngleMod, int Amount); void CreateExplosion(vec2 Pos, int Owner, int Weapon, bool NoDamage); void CreateHammerHit(vec2 Pos); void CreatePlayerSpawn(vec2 Pos); void CreateDeath(vec2 Pos, int Who); void CreateSound(vec2 Pos, int Sound, int Mask=-1); enum { CHAT_ALL=-2, CHAT_SPEC=-1, CHAT_RED=0, CHAT_BLUE=1 }; // network void SendChatTarget(int To, const char *pText); void SendChat(int ClientID, int Team, const char *pText); void SendEmoticon(int ClientID, int Emoticon); void SendWeaponPickup(int ClientID, int Weapon); void SendMotd(int ClientID); void SendSettings(int ClientID); void SendGameMsg(int GameMsgID, int ClientID); void SendGameMsg(int GameMsgID, int ParaI1, int ClientID); void SendGameMsg(int GameMsgID, int ParaI1, int ParaI2, int ParaI3, int ClientID); // void CheckPureTuning(); void SendTuningParams(int ClientID); // void SwapTeams(); // engine events virtual void OnInit(); virtual void OnConsoleInit(); virtual void OnShutdown(); virtual void OnTick(); virtual void OnPreSnap(); virtual void OnSnap(int ClientID); virtual void OnPostSnap(); virtual void OnMessage(int MsgID, CUnpacker *pUnpacker, int ClientID); virtual void OnClientConnected(int ClientID) { OnClientConnected(ClientID, false); } void OnClientConnected(int ClientID, bool Dummy); void OnClientTeamChange(int ClientID); virtual void OnClientEnter(int ClientID); virtual void OnClientDrop(int ClientID, const char *pReason); virtual void OnClientDirectInput(int ClientID, void *pInput); virtual void OnClientPredictedInput(int ClientID, void *pInput); virtual bool IsClientReady(int ClientID); virtual bool IsClientPlayer(int ClientID); virtual const char *GameType(); virtual const char *Version(); virtual const char *NetVersion(); }; inline int CmaskAll() { return -1; } inline int CmaskOne(int ClientID) { return 1<<ClientID; } inline int CmaskAllExceptOne(int ClientID) { return 0x7fffffff^CmaskOne(ClientID); } inline bool CmaskIsSet(int Mask, int ClientID) { return (Mask&CmaskOne(ClientID)) != 0; } #endif ================================================ FILE: src/game/server/gamecontroller.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <engine/shared/config.h> #include <game/mapitems.h> #include "entities/character.h" #include "entities/pickup.h" #include "gamecontext.h" #include "gamecontroller.h" #include "player.h" IGameController::IGameController(CGameContext *pGameServer) { m_pGameServer = pGameServer; m_pServer = m_pGameServer->Server(); // balancing m_aTeamSize[TEAM_RED] = 0; m_aTeamSize[TEAM_BLUE] = 0; m_UnbalancedTick = TBALANCE_OK; // game m_GameState = IGS_GAME_RUNNING; m_GameStateTimer = TIMER_INFINITE; m_GameStartTick = Server()->Tick(); m_MatchCount = 0; m_RoundCount = 0; m_SuddenDeath = 0; m_aTeamscore[TEAM_RED] = 0; m_aTeamscore[TEAM_BLUE] = 0; if(g_Config.m_SvWarmup) SetGameState(IGS_WARMUP_USER, g_Config.m_SvWarmup); else SetGameState(IGS_WARMUP_GAME, TIMER_INFINITE); // info m_GameFlags = 0; m_pGameType = "unknown"; m_GameInfo.m_MatchCurrent = m_MatchCount+1; m_GameInfo.m_MatchNum = (str_length(g_Config.m_SvMaprotation) && g_Config.m_SvMatchesPerMap) ? g_Config.m_SvMatchesPerMap : 0; m_GameInfo.m_ScoreLimit = g_Config.m_SvScorelimit; m_GameInfo.m_TimeLimit = g_Config.m_SvTimelimit; // map m_aMapWish[0] = 0; // spawn m_aNumSpawnPoints[0] = 0; m_aNumSpawnPoints[1] = 0; m_aNumSpawnPoints[2] = 0; } //activity void IGameController::DoActivityCheck() { if(g_Config.m_SvInactiveKickTime == 0) return; for(int i = 0; i < MAX_CLIENTS; ++i) { if(GameServer()->m_apPlayers[i] && !GameServer()->m_apPlayers[i]->IsDummy() && GameServer()->m_apPlayers[i]->GetTeam() != TEAM_SPECTATORS && !Server()->IsAuthed(i) && (GameServer()->m_apPlayers[i]->m_InactivityTickCounter > g_Config.m_SvInactiveKickTime*Server()->TickSpeed()*60)) { switch(g_Config.m_SvInactiveKick) { case 0: { // move player to spectator DoTeamChange(GameServer()->m_apPlayers[i], TEAM_SPECTATORS); } break; case 1: { // move player to spectator if the reserved slots aren't filled yet, kick him otherwise int Spectators = 0; for(int j = 0; j < MAX_CLIENTS; ++j) if(GameServer()->m_apPlayers[j] && GameServer()->m_apPlayers[j]->GetTeam() == TEAM_SPECTATORS) ++Spectators; if(Spectators >= g_Config.m_SvSpectatorSlots) Server()->Kick(i, "Kicked for inactivity"); else DoTeamChange(GameServer()->m_apPlayers[i], TEAM_SPECTATORS); } break; case 2: { // kick the player Server()->Kick(i, "Kicked for inactivity"); } } } } } bool IGameController::GetPlayersReadyState() { for(int i = 0; i < MAX_CLIENTS; ++i) { if(GameServer()->m_apPlayers[i] && GameServer()->m_apPlayers[i]->GetTeam() != TEAM_SPECTATORS && !GameServer()->m_apPlayers[i]->m_IsReadyToPlay) return false; } return true; } void IGameController::SetPlayersReadyState(bool ReadyState) { for(int i = 0; i < MAX_CLIENTS; ++i) { if(GameServer()->m_apPlayers[i] && GameServer()->m_apPlayers[i]->GetTeam() != TEAM_SPECTATORS && (ReadyState || !GameServer()->m_apPlayers[i]->m_DeadSpecMode)) GameServer()->m_apPlayers[i]->m_IsReadyToPlay = ReadyState; } } // balancing bool IGameController::CanBeMovedOnBalance(int ClientID) const { return true; } void IGameController::CheckTeamBalance() { if(!IsTeamplay() || !g_Config.m_SvTeambalanceTime) { m_UnbalancedTick = TBALANCE_OK; return; } // check if teams are unbalanced char aBuf[256]; if(absolute(m_aTeamSize[TEAM_RED]-m_aTeamSize[TEAM_BLUE]) >= NUM_TEAMS) { str_format(aBuf, sizeof(aBuf), "Teams are NOT balanced (red=%d blue=%d)", m_aTeamSize[TEAM_RED], m_aTeamSize[TEAM_BLUE]); if(m_UnbalancedTick <= TBALANCE_OK) m_UnbalancedTick = Server()->Tick(); } else { str_format(aBuf, sizeof(aBuf), "Teams are balanced (red=%d blue=%d)", m_aTeamSize[TEAM_RED], m_aTeamSize[TEAM_BLUE]); m_UnbalancedTick = TBALANCE_OK; } GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", aBuf); } void IGameController::DoTeamBalance() { if(!IsTeamplay() || !g_Config.m_SvTeambalanceTime || absolute(m_aTeamSize[TEAM_RED]-m_aTeamSize[TEAM_BLUE]) < NUM_TEAMS) return; GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", "Balancing teams"); float aTeamScore[NUM_TEAMS] = {0}; float aPlayerScore[MAX_CLIENTS] = {0.0f}; // gather stats for(int i = 0; i < MAX_CLIENTS; i++) { if(GameServer()->m_apPlayers[i] && GameServer()->m_apPlayers[i]->GetTeam() != TEAM_SPECTATORS) { aPlayerScore[i] = GameServer()->m_apPlayers[i]->m_Score*Server()->TickSpeed()*60.0f/ (Server()->Tick()-GameServer()->m_apPlayers[i]->m_ScoreStartTick); aTeamScore[GameServer()->m_apPlayers[i]->GetTeam()] += aPlayerScore[i]; } } int BiggerTeam = (m_aTeamSize[TEAM_RED] > m_aTeamSize[TEAM_BLUE]) ? TEAM_RED : TEAM_BLUE; int NumBalance = absolute(m_aTeamSize[TEAM_RED]-m_aTeamSize[TEAM_BLUE]) / NUM_TEAMS; // balance teams do { CPlayer *pPlayer = 0; float ScoreDiff = aTeamScore[BiggerTeam]; for(int i = 0; i < MAX_CLIENTS; i++) { if(!GameServer()->m_apPlayers[i] || !CanBeMovedOnBalance(i)) continue; // remember the player whom would cause lowest score-difference if(GameServer()->m_apPlayers[i]->GetTeam() == BiggerTeam && (!pPlayer || absolute((aTeamScore[BiggerTeam^1]+aPlayerScore[i]) - (aTeamScore[BiggerTeam]-aPlayerScore[i])) < ScoreDiff)) { pPlayer = GameServer()->m_apPlayers[i]; ScoreDiff = absolute((aTeamScore[BiggerTeam^1]+aPlayerScore[i]) - (aTeamScore[BiggerTeam]-aPlayerScore[i])); } } // move the player to the other team int Temp = pPlayer->m_LastActionTick; DoTeamChange(pPlayer, BiggerTeam^1); pPlayer->m_LastActionTick = Temp; pPlayer->Respawn(); GameServer()->SendGameMsg(GAMEMSG_TEAM_BALANCE_VICTIM, pPlayer->GetTeam(), pPlayer->GetCID()); } while(--NumBalance); m_UnbalancedTick = TBALANCE_OK; GameServer()->SendGameMsg(GAMEMSG_TEAM_BALANCE, -1); } // event int IGameController::OnCharacterDeath(CCharacter *pVictim, CPlayer *pKiller, int Weapon) { // do scoreing if(!pKiller || Weapon == WEAPON_GAME) return 0; if(pKiller == pVictim->GetPlayer()) pVictim->GetPlayer()->m_Score--; // suicide else { if(IsTeamplay() && pVictim->GetPlayer()->GetTeam() == pKiller->GetTeam()) pKiller->m_Score--; // teamkill else pKiller->m_Score++; // normal kill } if(Weapon == WEAPON_SELF) pVictim->GetPlayer()->m_RespawnTick = Server()->Tick()+Server()->TickSpeed()*3.0f; // update spectator modes for dead players in survival if(m_GameFlags&GAMEFLAG_SURVIVAL) { for(int i = 0; i < MAX_CLIENTS; ++i) if(GameServer()->m_apPlayers[i] && GameServer()->m_apPlayers[i]->m_DeadSpecMode) GameServer()->m_apPlayers[i]->UpdateDeadSpecMode(); } return 0; } void IGameController::OnCharacterSpawn(CCharacter *pChr) { if(m_GameFlags&GAMEFLAG_SURVIVAL) { // give start equipment pChr->IncreaseHealth(10); pChr->IncreaseArmor(5); pChr->GiveWeapon(WEAPON_HAMMER, -1); pChr->GiveWeapon(WEAPON_GUN, 10); pChr->GiveWeapon(WEAPON_SHOTGUN, 10); pChr->GiveWeapon(WEAPON_GRENADE, 10); pChr->GiveWeapon(WEAPON_LASER, 5); // prevent respawn pChr->GetPlayer()->m_RespawnDisabled = GetStartRespawnState(); } else { // default health pChr->IncreaseHealth(10); // give default weapons pChr->GiveWeapon(WEAPON_HAMMER, -1); pChr->GiveWeapon(WEAPON_GUN, 10); } } bool IGameController::OnEntity(int Index, vec2 Pos) { // don't add pickups in survival if(m_GameFlags&GAMEFLAG_SURVIVAL) { if(Index < ENTITY_SPAWN || Index > ENTITY_SPAWN_BLUE) return false; } int Type = -1; switch(Index) { case ENTITY_SPAWN: m_aaSpawnPoints[0][m_aNumSpawnPoints[0]++] = Pos; break; case ENTITY_SPAWN_RED: m_aaSpawnPoints[1][m_aNumSpawnPoints[1]++] = Pos; break; case ENTITY_SPAWN_BLUE: m_aaSpawnPoints[2][m_aNumSpawnPoints[2]++] = Pos; break; case ENTITY_ARMOR_1: Type = PICKUP_ARMOR; break; case ENTITY_HEALTH_1: Type = PICKUP_HEALTH; break; case ENTITY_WEAPON_SHOTGUN: Type = PICKUP_SHOTGUN; break; case ENTITY_WEAPON_GRENADE: Type = PICKUP_GRENADE; break; case ENTITY_WEAPON_LASER: Type = PICKUP_LASER; break; case ENTITY_POWERUP_NINJA: if(g_Config.m_SvPowerups) Type = PICKUP_NINJA; } if(Type != -1) { CPickup *pPickup = new CPickup(&GameServer()->m_World, Type); pPickup->m_Pos = Pos; return true; } return false; } void IGameController::OnPlayerConnect(CPlayer *pPlayer) { int ClientID = pPlayer->GetCID(); pPlayer->Respawn(); char aBuf[128]; str_format(aBuf, sizeof(aBuf), "team_join player='%d:%s' team=%d", ClientID, Server()->ClientName(ClientID), pPlayer->GetTeam()); GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", aBuf); // update game info UpdateGameInfo(ClientID); } void IGameController::OnPlayerDisconnect(CPlayer *pPlayer) { pPlayer->OnDisconnect(); int ClientID = pPlayer->GetCID(); if(Server()->ClientIngame(ClientID)) { char aBuf[128]; str_format(aBuf, sizeof(aBuf), "leave player='%d:%s'", ClientID, Server()->ClientName(ClientID)); GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "game", aBuf); } if(pPlayer->GetTeam() != TEAM_SPECTATORS) { --m_aTeamSize[pPlayer->GetTeam()]; m_UnbalancedTick = TBALANCE_CHECK; } } void IGameController::OnPlayerInfoChange(CPlayer *pPlayer) { } void IGameController::OnPlayerReadyChange(CPlayer *pPlayer) { if(g_Config.m_SvPlayerReadyMode && pPlayer->GetTeam() != TEAM_SPECTATORS && !pPlayer->m_DeadSpecMode) { // change players ready state pPlayer->m_IsReadyToPlay ^= 1; // check if it effects current game state switch(m_GameState) { case IGS_GAME_RUNNING: // one player isn't ready -> pause the game if(!pPlayer->m_IsReadyToPlay) SetGameState(IGS_GAME_PAUSED, TIMER_INFINITE); break; case IGS_WARMUP_USER: // all players are ready -> end warmup if(GetPlayersReadyState()) SetGameState(IGS_WARMUP_USER, 0); break; case IGS_GAME_PAUSED: // all players are ready -> unpause the game if(GetPlayersReadyState()) SetGameState(IGS_GAME_PAUSED, 0); break; case IGS_WARMUP_GAME: case IGS_START_COUNTDOWN: case IGS_END_MATCH: case IGS_END_ROUND: // not effected break; } } } void IGameController::OnReset() { for(int i = 0; i < MAX_CLIENTS; i++) { if(GameServer()->m_apPlayers[i]) { GameServer()->m_apPlayers[i]->m_RespawnDisabled = false; GameServer()->m_apPlayers[i]->Respawn(); GameServer()->m_apPlayers[i]->m_RespawnTick = Server()->Tick()+Server()->TickSpeed()/2; if(m_RoundCount == 0) { GameServer()->m_apPlayers[i]->m_Score = 0; GameServer()->m_apPlayers[i]->m_ScoreStartTick = Server()->Tick(); } GameServer()->m_apPlayers[i]->m_IsReadyToPlay = true; } } } // game void IGameController::DoWincheckMatch() { if(IsTeamplay()) { // check score win condition if((m_GameInfo.m_ScoreLimit > 0 && (m_aTeamscore[TEAM_RED] >= m_GameInfo.m_ScoreLimit || m_aTeamscore[TEAM_BLUE] >= m_GameInfo.m_ScoreLimit)) || (m_GameInfo.m_TimeLimit > 0 && (Server()->Tick()-m_GameStartTick) >= m_GameInfo.m_TimeLimit*Server()->TickSpeed()*60)) { if(m_aTeamscore[TEAM_RED] != m_aTeamscore[TEAM_BLUE] || m_GameFlags&GAMEFLAG_SURVIVAL) EndMatch(); else m_SuddenDeath = 1; } } else { // gather some stats int Topscore = 0; int TopscoreCount = 0; for(int i = 0; i < MAX_CLIENTS; i++) { if(GameServer()->m_apPlayers[i]) { if(GameServer()->m_apPlayers[i]->m_Score > Topscore) { Topscore = GameServer()->m_apPlayers[i]->m_Score; TopscoreCount = 1; } else if(GameServer()->m_apPlayers[i]->m_Score == Topscore) TopscoreCount++; } } // check score win condition if((m_GameInfo.m_ScoreLimit > 0 && Topscore >= m_GameInfo.m_ScoreLimit) || (m_GameInfo.m_TimeLimit > 0 && (Server()->Tick()-m_GameStartTick) >= m_GameInfo.m_TimeLimit*Server()->TickSpeed()*60)) { if(TopscoreCount == 1) EndMatch(); else m_SuddenDeath = 1; } } } void IGameController::ResetGame() { // reset the game GameServer()->m_World.m_ResetRequested = true; SetGameState(IGS_GAME_RUNNING); m_GameStartTick = Server()->Tick(); m_SuddenDeath = 0; int MatchNum = (str_length(g_Config.m_SvMaprotation) && g_Config.m_SvMatchesPerMap) ? g_Config.m_SvMatchesPerMap : 0; if(MatchNum == 0) m_MatchCount = 0; bool GameInfoChanged = (m_GameInfo.m_MatchCurrent != m_MatchCount+1) || (m_GameInfo.m_MatchNum != MatchNum) || (m_GameInfo.m_ScoreLimit != g_Config.m_SvScorelimit) || (m_GameInfo.m_TimeLimit != g_Config.m_SvTimelimit); m_GameInfo.m_MatchCurrent = m_MatchCount+1; m_GameInfo.m_MatchNum = MatchNum; m_GameInfo.m_ScoreLimit = g_Config.m_SvScorelimit; m_GameInfo.m_TimeLimit = g_Config.m_SvTimelimit; if(GameInfoChanged) UpdateGameInfo(-1); // do team-balancing DoTeamBalance(); } void IGameController::SetGameState(EGameState GameState, int Timer) { // change game state switch(GameState) { case IGS_WARMUP_GAME: // game based warmup is only possible when game or any warmup is running if(m_GameState == IGS_GAME_RUNNING || m_GameState == IGS_WARMUP_GAME || m_GameState == IGS_WARMUP_USER) { if(Timer == TIMER_INFINITE) { // run warmup till there're enough players m_GameState = GameState; m_GameStateTimer = TIMER_INFINITE; // enable respawning in survival when activating warmup if(m_GameFlags&GAMEFLAG_SURVIVAL) { for(int i = 0; i < MAX_CLIENTS; ++i) if(GameServer()->m_apPlayers[i]) GameServer()->m_apPlayers[i]->m_RespawnDisabled = false; } } else if(Timer == 0) { // start new match StartMatch(); } } break; case IGS_WARMUP_USER: // user based warmup is only possible when the game or a user based warmup is running if(m_GameState == IGS_GAME_RUNNING || m_GameState == IGS_WARMUP_USER) { if(Timer != 0) { // start warmup if(Timer < 0 && g_Config.m_SvPlayerReadyMode) { // run warmup till all players are ready m_GameState = GameState; m_GameStateTimer = TIMER_INFINITE; SetPlayersReadyState(false); } else if(Timer > 0) { // run warmup for a specific time intervall m_GameState = GameState; m_GameStateTimer = Timer*Server()->TickSpeed(); } // enable respawning in survival when activating warmup if(m_GameFlags&GAMEFLAG_SURVIVAL) { for(int i = 0; i < MAX_CLIENTS; ++i) if(GameServer()->m_apPlayers[i]) GameServer()->m_apPlayers[i]->m_RespawnDisabled = false; } } else { // start new match StartMatch(); } } break; case IGS_START_COUNTDOWN: // only possible when game, pause or start countdown is running if(m_GameState == IGS_GAME_RUNNING || m_GameState == IGS_GAME_PAUSED || m_GameState == IGS_START_COUNTDOWN) { m_GameState = GameState; m_GameStateTimer = 3*Server()->TickSpeed(); GameServer()->m_World.m_Paused = true; } break; case IGS_GAME_RUNNING: // always possible { m_GameState = GameState; m_GameStateTimer = TIMER_INFINITE; SetPlayersReadyState(true); GameServer()->m_World.m_Paused = false; } break; case IGS_GAME_PAUSED: // only possible when game is running or paused if(m_GameState == IGS_GAME_RUNNING || m_GameState == IGS_GAME_PAUSED) { if(Timer != 0) { // start pause if(Timer < 0) { // pauses infinitely till all players are ready or disabled via rcon command m_GameStateTimer = TIMER_INFINITE; SetPlayersReadyState(false); } else { // pauses for a specific time intervall m_GameStateTimer = Timer*Server()->TickSpeed(); } m_GameState = GameState; GameServer()->m_World.m_Paused = true; } else { // start a countdown to end pause SetGameState(IGS_START_COUNTDOWN); } } break; case IGS_END_ROUND: case IGS_END_MATCH: // only possible when game is running or over if(m_GameState == IGS_GAME_RUNNING || m_GameState == IGS_END_MATCH || m_GameState == IGS_END_ROUND || m_GameState == IGS_GAME_PAUSED) { m_GameState = GameState; m_GameStateTimer = Timer*Server()->TickSpeed(); m_SuddenDeath = 0; GameServer()->m_World.m_Paused = true; } } } void IGameController::StartMatch() { ResetGame(); m_RoundCount = 0; m_aTeamscore[TEAM_RED] = 0; m_aTeamscore[TEAM_BLUE] = 0; // start countdown if there're enough players, otherwise do warmup till there're if(HasEnoughPlayers()) SetGameState(IGS_START_COUNTDOWN); else SetGameState(IGS_WARMUP_GAME, TIMER_INFINITE); Server()->DemoRecorder_HandleAutoStart(); char aBuf[256]; str_format(aBuf, sizeof(aBuf), "start match type='%s' teamplay='%d'", m_pGameType, m_GameFlags&GAMEFLAG_TEAMS); GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", aBuf); } void IGameController::StartRound() { ResetGame(); ++m_RoundCount; // start countdown if there're enough players, otherwise abort to warmup if(HasEnoughPlayers()) SetGameState(IGS_START_COUNTDOWN); else SetGameState(IGS_WARMUP_GAME, TIMER_INFINITE); } // general void IGameController::Snap(int SnappingClient) { CNetObj_GameData *pGameData = static_cast<CNetObj_GameData *>(Server()->SnapNewItem(NETOBJTYPE_GAMEDATA, 0, sizeof(CNetObj_GameData))); if(!pGameData) return; pGameData->m_GameStartTick = m_GameStartTick; pGameData->m_GameStateFlags = 0; pGameData->m_GameStateEndTick = 0; // no timer/infinite = 0, on end = GameEndTick, otherwise = GameStateEndTick switch(m_GameState) { case IGS_WARMUP_GAME: case IGS_WARMUP_USER: pGameData->m_GameStateFlags |= GAMESTATEFLAG_WARMUP; if(m_GameStateTimer != TIMER_INFINITE) pGameData->m_GameStateEndTick = Server()->Tick()+m_GameStateTimer; break; case IGS_START_COUNTDOWN: pGameData->m_GameStateFlags |= GAMESTATEFLAG_STARTCOUNTDOWN|GAMESTATEFLAG_PAUSED; if(m_GameStateTimer != TIMER_INFINITE) pGameData->m_GameStateEndTick = Server()->Tick()+m_GameStateTimer; break; case IGS_GAME_PAUSED: pGameData->m_GameStateFlags |= GAMESTATEFLAG_PAUSED; if(m_GameStateTimer != TIMER_INFINITE) pGameData->m_GameStateEndTick = Server()->Tick()+m_GameStateTimer; break; case IGS_END_ROUND: pGameData->m_GameStateFlags |= GAMESTATEFLAG_ROUNDOVER; pGameData->m_GameStateEndTick = Server()->Tick()-m_GameStartTick-TIMER_END*Server()->TickSpeed()+m_GameStateTimer; break; case IGS_END_MATCH: pGameData->m_GameStateFlags |= GAMESTATEFLAG_GAMEOVER; pGameData->m_GameStateEndTick = Server()->Tick()-m_GameStartTick-TIMER_END*Server()->TickSpeed()+m_GameStateTimer; break; case IGS_GAME_RUNNING: // not effected break; } if(m_SuddenDeath) pGameData->m_GameStateFlags |= GAMESTATEFLAG_SUDDENDEATH; if(IsTeamplay()) { CNetObj_GameDataTeam *pGameDataTeam = static_cast<CNetObj_GameDataTeam *>(Server()->SnapNewItem(NETOBJTYPE_GAMEDATATEAM, 0, sizeof(CNetObj_GameDataTeam))); if(!pGameDataTeam) return; pGameDataTeam->m_TeamscoreRed = m_aTeamscore[TEAM_RED]; pGameDataTeam->m_TeamscoreBlue = m_aTeamscore[TEAM_BLUE]; } // demo recording if(SnappingClient == -1) { CNetObj_De_GameInfo *pGameInfo = static_cast<CNetObj_De_GameInfo *>(Server()->SnapNewItem(NETOBJTYPE_DE_GAMEINFO, 0, sizeof(CNetObj_De_GameInfo))); if(!pGameInfo) return; pGameInfo->m_GameFlags = m_GameFlags; pGameInfo->m_ScoreLimit = m_GameInfo.m_ScoreLimit; pGameInfo->m_TimeLimit = m_GameInfo.m_TimeLimit; pGameInfo->m_MatchNum = m_GameInfo.m_MatchNum; pGameInfo->m_MatchCurrent = m_GameInfo.m_MatchCurrent; } } void IGameController::Tick() { // handle game states if(m_GameState != IGS_GAME_RUNNING) { if(m_GameStateTimer > 0) --m_GameStateTimer; if(m_GameStateTimer == 0) { // timer fires switch(m_GameState) { case IGS_WARMUP_USER: // end warmup SetGameState(IGS_WARMUP_USER, 0); break; case IGS_START_COUNTDOWN: // unpause the game SetGameState(IGS_GAME_RUNNING); break; case IGS_GAME_PAUSED: // end pause SetGameState(IGS_GAME_PAUSED, 0); break; case IGS_END_ROUND: // check if the match is over otherwise start next round DoWincheckMatch(); if(m_GameState != IGS_END_MATCH) StartRound(); break; case IGS_END_MATCH: // start next match CycleMap(); m_MatchCount++; StartMatch(); break; case IGS_WARMUP_GAME: case IGS_GAME_RUNNING: // not effected break; } } else { // timer still running switch(m_GameState) { case IGS_WARMUP_USER: // check if player ready mode was disabled and it waits that all players are ready -> end warmup if(!g_Config.m_SvPlayerReadyMode && m_GameStateTimer == TIMER_INFINITE) SetGameState(IGS_WARMUP_USER, 0); break; case IGS_START_COUNTDOWN: case IGS_GAME_PAUSED: // freeze the game ++m_GameStartTick; break; case IGS_WARMUP_GAME: case IGS_GAME_RUNNING: case IGS_END_MATCH: case IGS_END_ROUND: // not effected break; } } } // do team-balancing (skip this in survival, done there when a round starts) if(IsTeamplay() && !(m_GameFlags&GAMEFLAG_SURVIVAL)) { switch(m_UnbalancedTick) { case TBALANCE_CHECK: CheckTeamBalance(); break; case TBALANCE_OK: break; default: if(Server()->Tick() > m_UnbalancedTick+g_Config.m_SvTeambalanceTime*Server()->TickSpeed()*60) DoTeamBalance(); } } // check for inactive players DoActivityCheck(); // win check if((m_GameState == IGS_GAME_RUNNING || m_GameState == IGS_GAME_PAUSED) && !GameServer()->m_World.m_ResetRequested) { if(m_GameFlags&GAMEFLAG_SURVIVAL) DoWincheckRound(); else DoWincheckMatch(); } } // info bool IGameController::IsFriendlyFire(int ClientID1, int ClientID2) const { if(ClientID1 == ClientID2) return false; if(IsTeamplay()) { if(!GameServer()->m_apPlayers[ClientID1] || !GameServer()->m_apPlayers[ClientID2]) return false; if(!g_Config.m_SvTeamdamage && GameServer()->m_apPlayers[ClientID1]->GetTeam() == GameServer()->m_apPlayers[ClientID2]->GetTeam()) return true; } return false; } bool IGameController::IsPlayerReadyMode() const { return g_Config.m_SvPlayerReadyMode != 0 && (m_GameStateTimer == TIMER_INFINITE && (m_GameState == IGS_WARMUP_USER || m_GameState == IGS_GAME_PAUSED)); } bool IGameController::IsTeamChangeAllowed() const { return !GameServer()->m_World.m_Paused || (m_GameState == IGS_START_COUNTDOWN && m_GameStartTick == Server()->Tick()); } void IGameController::UpdateGameInfo(int ClientID) { CNetMsg_Sv_GameInfo GameInfoMsg; GameInfoMsg.m_GameFlags = m_GameFlags; GameInfoMsg.m_ScoreLimit = m_GameInfo.m_ScoreLimit; GameInfoMsg.m_TimeLimit = m_GameInfo.m_TimeLimit; GameInfoMsg.m_MatchNum = m_GameInfo.m_MatchNum; GameInfoMsg.m_MatchCurrent = m_GameInfo.m_MatchCurrent; if(ClientID == -1) { for(int i = 0; i < MAX_CLIENTS; ++i) { if(!GameServer()->m_apPlayers[i] || !Server()->ClientIngame(i)) continue; Server()->SendPackMsg(&GameInfoMsg, MSGFLAG_VITAL|MSGFLAG_NORECORD, i); } } else Server()->SendPackMsg(&GameInfoMsg, MSGFLAG_VITAL|MSGFLAG_NORECORD, ClientID); } // map static bool IsSeparator(char c) { return c == ';' || c == ' ' || c == ',' || c == '\t'; } void IGameController::ChangeMap(const char *pToMap) { str_copy(m_aMapWish, pToMap, sizeof(m_aMapWish)); EndMatch(); } void IGameController::CycleMap() { if(m_aMapWish[0] != 0) { char aBuf[256]; str_format(aBuf, sizeof(aBuf), "rotating map to %s", m_aMapWish); GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", aBuf); str_copy(g_Config.m_SvMap, m_aMapWish, sizeof(g_Config.m_SvMap)); m_aMapWish[0] = 0; m_MatchCount = 0; return; } if(!str_length(g_Config.m_SvMaprotation)) return; if(m_MatchCount < m_GameInfo.m_MatchNum-1) { if(g_Config.m_SvMatchSwap) GameServer()->SwapTeams(); return; } // handle maprotation const char *pMapRotation = g_Config.m_SvMaprotation; const char *pCurrentMap = g_Config.m_SvMap; int CurrentMapLen = str_length(pCurrentMap); const char *pNextMap = pMapRotation; while(*pNextMap) { int WordLen = 0; while(pNextMap[WordLen] && !IsSeparator(pNextMap[WordLen])) WordLen++; if(WordLen == CurrentMapLen && str_comp_num(pNextMap, pCurrentMap, CurrentMapLen) == 0) { // map found pNextMap += CurrentMapLen; while(*pNextMap && IsSeparator(*pNextMap)) pNextMap++; break; } pNextMap++; } // restart rotation if(pNextMap[0] == 0) pNextMap = pMapRotation; // cut out the next map char aBuf[512] = {0}; for(int i = 0; i < 511; i++) { aBuf[i] = pNextMap[i]; if(IsSeparator(pNextMap[i]) || pNextMap[i] == 0) { aBuf[i] = 0; break; } } // skip spaces int i = 0; while(IsSeparator(aBuf[i])) i++; m_MatchCount = 0; char aBufMsg[256]; str_format(aBufMsg, sizeof(aBufMsg), "rotating map to %s", &aBuf[i]); GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", aBuf); str_copy(g_Config.m_SvMap, &aBuf[i], sizeof(g_Config.m_SvMap)); } // spawn bool IGameController::CanSpawn(int Team, vec2 *pOutPos) const { // spectators can't spawn if(Team == TEAM_SPECTATORS || GameServer()->m_World.m_Paused || GameServer()->m_World.m_ResetRequested) return false; CSpawnEval Eval; if(IsTeamplay()) { Eval.m_FriendlyTeam = Team; // first try own team spawn, then normal spawn and then enemy EvaluateSpawnType(&Eval, 1+(Team&1)); if(!Eval.m_Got) { EvaluateSpawnType(&Eval, 0); if(!Eval.m_Got) EvaluateSpawnType(&Eval, 1+((Team+1)&1)); } } else { EvaluateSpawnType(&Eval, 0); EvaluateSpawnType(&Eval, 1); EvaluateSpawnType(&Eval, 2); } *pOutPos = Eval.m_Pos; return Eval.m_Got; } float IGameController::EvaluateSpawnPos(CSpawnEval *pEval, vec2 Pos) const { float Score = 0.0f; CCharacter *pC = static_cast<CCharacter *>(GameServer()->m_World.FindFirst(CGameWorld::ENTTYPE_CHARACTER)); for(; pC; pC = (CCharacter *)pC->TypeNext()) { // team mates are not as dangerous as enemies float Scoremod = 1.0f; if(pEval->m_FriendlyTeam != -1 && pC->GetPlayer()->GetTeam() == pEval->m_FriendlyTeam) Scoremod = 0.5f; float d = distance(Pos, pC->m_Pos); Score += Scoremod * (d == 0 ? 1000000000.0f : 1.0f/d); } return Score; } void IGameController::EvaluateSpawnType(CSpawnEval *pEval, int Type) const { // get spawn point for(int i = 0; i < m_aNumSpawnPoints[Type]; i++) { // check if the position is occupado CCharacter *aEnts[MAX_CLIENTS]; int Num = GameServer()->m_World.FindEntities(m_aaSpawnPoints[Type][i], 64, (CEntity**)aEnts, MAX_CLIENTS, CGameWorld::ENTTYPE_CHARACTER); vec2 Positions[5] = { vec2(0.0f, 0.0f), vec2(-32.0f, 0.0f), vec2(0.0f, -32.0f), vec2(32.0f, 0.0f), vec2(0.0f, 32.0f) }; // start, left, up, right, down int Result = -1; for(int Index = 0; Index < 5 && Result == -1; ++Index) { Result = Index; for(int c = 0; c < Num; ++c) if(GameServer()->Collision()->CheckPoint(m_aaSpawnPoints[Type][i]+Positions[Index]) || distance(aEnts[c]->m_Pos, m_aaSpawnPoints[Type][i]+Positions[Index]) <= aEnts[c]->m_ProximityRadius) { Result = -1; break; } } if(Result == -1) continue; // try next spawn point vec2 P = m_aaSpawnPoints[Type][i]+Positions[Result]; float S = EvaluateSpawnPos(pEval, P); if(!pEval->m_Got || pEval->m_Score > S) { pEval->m_Got = true; pEval->m_Score = S; pEval->m_Pos = P; } } } bool IGameController::GetStartRespawnState() const { if(m_GameFlags&GAMEFLAG_SURVIVAL) { // players can always respawn during warmup or match/round start countdown if(m_GameState == IGS_WARMUP_GAME || m_GameState == IGS_WARMUP_USER || (m_GameState == IGS_START_COUNTDOWN && m_GameStartTick == Server()->Tick())) return false; else return true; } else return false; } // team bool IGameController::CanChangeTeam(CPlayer *pPlayer, int JoinTeam) const { if(!IsTeamplay() || JoinTeam == TEAM_SPECTATORS || !g_Config.m_SvTeambalanceTime) return true; // simulate what would happen if the player changes team int aPlayerCount[NUM_TEAMS] = { m_aTeamSize[TEAM_RED], m_aTeamSize[TEAM_BLUE] }; aPlayerCount[JoinTeam]++; if(pPlayer->GetTeam() != TEAM_SPECTATORS) aPlayerCount[JoinTeam^1]--; // check if the player-difference decreases or is smaller than 2 return aPlayerCount[JoinTeam]-aPlayerCount[JoinTeam^1] < NUM_TEAMS; } bool IGameController::CanJoinTeam(int Team, int NotThisID) const { if(Team == TEAM_SPECTATORS) return true; // check if there're enough player slots left int TeamMod = GameServer()->m_apPlayers[NotThisID] && GameServer()->m_apPlayers[NotThisID]->GetTeam() != TEAM_SPECTATORS ? -1 : 0; return TeamMod+m_aTeamSize[TEAM_RED]+m_aTeamSize[TEAM_BLUE] < Server()->MaxClients()-g_Config.m_SvSpectatorSlots; } int IGameController::ClampTeam(int Team) const { if(Team < TEAM_RED) return TEAM_SPECTATORS; if(IsTeamplay()) return Team&1; return TEAM_RED; } void IGameController::DoTeamChange(CPlayer *pPlayer, int Team, bool DoChatMsg) { Team = ClampTeam(Team); if(Team == pPlayer->GetTeam()) return; int OldTeam = pPlayer->GetTeam(); pPlayer->SetTeam(Team); int ClientID = pPlayer->GetCID(); // notify clients CNetMsg_Sv_Team Msg; Msg.m_ClientID = ClientID; Msg.m_Team = Team; Msg.m_Silent = DoChatMsg ? 0 : 1; Msg.m_CooldownTick = pPlayer->m_TeamChangeTick; Server()->SendPackMsg(&Msg, MSGFLAG_VITAL, -1); char aBuf[128]; str_format(aBuf, sizeof(aBuf), "team_join player='%d:%s' m_Team=%d", ClientID, Server()->ClientName(ClientID), Team); GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", aBuf); // update effected game settings if(OldTeam != TEAM_SPECTATORS) { --m_aTeamSize[OldTeam]; m_UnbalancedTick = TBALANCE_CHECK; } if(Team != TEAM_SPECTATORS) { ++m_aTeamSize[Team]; m_UnbalancedTick = TBALANCE_CHECK; if(m_GameState == IGS_WARMUP_GAME && HasEnoughPlayers()) SetGameState(IGS_WARMUP_GAME, 0); pPlayer->m_IsReadyToPlay = !IsPlayerReadyMode(); if(m_GameFlags&GAMEFLAG_SURVIVAL) pPlayer->m_RespawnDisabled = GetStartRespawnState(); } OnPlayerInfoChange(pPlayer); GameServer()->OnClientTeamChange(ClientID); } int IGameController::GetStartTeam() { // this will force the auto balancer to work overtime aswell if(g_Config.m_DbgStress) return TEAM_RED; if(g_Config.m_SvTournamentMode) return TEAM_SPECTATORS; // determine new team int Team = TEAM_RED; if(IsTeamplay()) Team = m_aTeamSize[TEAM_RED] > m_aTeamSize[TEAM_BLUE] ? TEAM_BLUE : TEAM_RED; // check if there're enough player slots left if(m_aTeamSize[TEAM_RED]+m_aTeamSize[TEAM_BLUE] < Server()->MaxClients()-g_Config.m_SvSpectatorSlots) { ++m_aTeamSize[Team]; m_UnbalancedTick = TBALANCE_CHECK; if(m_GameState == IGS_WARMUP_GAME && HasEnoughPlayers()) SetGameState(IGS_WARMUP_GAME, 0); return Team; } return TEAM_SPECTATORS; } ================================================ FILE: src/game/server/gamecontroller.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_SERVER_GAMECONTROLLER_H #define GAME_SERVER_GAMECONTROLLER_H #include <base/vmath.h> #include <game/generated/protocol.h> /* Class: Game Controller Controls the main game logic. Keeping track of team and player score, winning conditions and specific game logic. */ class IGameController { class CGameContext *m_pGameServer; class IServer *m_pServer; // activity void DoActivityCheck(); bool GetPlayersReadyState(); void SetPlayersReadyState(bool ReadyState); // balancing enum { TBALANCE_CHECK=-2, TBALANCE_OK, }; int m_aTeamSize[NUM_TEAMS]; int m_UnbalancedTick; virtual bool CanBeMovedOnBalance(int ClientID) const; void CheckTeamBalance(); void DoTeamBalance(); // game enum EGameState { // internal game states IGS_WARMUP_GAME, // warmup started by game because there're not enough players (infinite) IGS_WARMUP_USER, // warmup started by user action via rcon or new match (infinite or timer) IGS_START_COUNTDOWN, // start countown to unpause the game or start match/round (tick timer) IGS_GAME_PAUSED, // game paused (infinite or tick timer) IGS_GAME_RUNNING, // game running (infinite) IGS_END_MATCH, // match is over (tick timer) IGS_END_ROUND, // round is over (tick timer) }; EGameState m_GameState; int m_GameStateTimer; virtual void DoWincheckMatch(); virtual void DoWincheckRound() {}; bool HasEnoughPlayers() const { return (IsTeamplay() && m_aTeamSize[TEAM_RED] > 0 && m_aTeamSize[TEAM_BLUE] > 0) || (!IsTeamplay() && m_aTeamSize[TEAM_RED] > 1); } void ResetGame(); void SetGameState(EGameState GameState, int Timer=0); void StartMatch(); void StartRound(); // map char m_aMapWish[128]; void CycleMap(); // spawn struct CSpawnEval { CSpawnEval() { m_Got = false; m_FriendlyTeam = -1; m_Pos = vec2(100,100); } vec2 m_Pos; bool m_Got; int m_FriendlyTeam; float m_Score; }; vec2 m_aaSpawnPoints[3][64]; int m_aNumSpawnPoints[3]; float EvaluateSpawnPos(CSpawnEval *pEval, vec2 Pos) const; void EvaluateSpawnType(CSpawnEval *pEval, int Type) const; // team int ClampTeam(int Team) const; protected: CGameContext *GameServer() const { return m_pGameServer; } IServer *Server() const { return m_pServer; } // game int m_GameStartTick; int m_MatchCount; int m_RoundCount; int m_SuddenDeath; int m_aTeamscore[NUM_TEAMS]; void EndMatch() { SetGameState(IGS_END_MATCH, TIMER_END); } void EndRound() { SetGameState(IGS_END_ROUND, TIMER_END); } // info int m_GameFlags; const char *m_pGameType; struct CGameInfo { int m_MatchCurrent; int m_MatchNum; int m_ScoreLimit; int m_TimeLimit; } m_GameInfo; void UpdateGameInfo(int ClientID); public: IGameController(class CGameContext *pGameServer); virtual ~IGameController() {}; // event /* Function: on_CCharacter_death Called when a CCharacter in the world dies. Arguments: victim - The CCharacter that died. killer - The player that killed it. weapon - What weapon that killed it. Can be -1 for undefined weapon when switching team or player suicides. */ virtual int OnCharacterDeath(class CCharacter *pVictim, class CPlayer *pKiller, int Weapon); /* Function: on_CCharacter_spawn Called when a CCharacter spawns into the game world. Arguments: chr - The CCharacter that was spawned. */ virtual void OnCharacterSpawn(class CCharacter *pChr); /* Function: on_entity Called when the map is loaded to process an entity in the map. Arguments: index - Entity index. pos - Where the entity is located in the world. Returns: bool? */ virtual bool OnEntity(int Index, vec2 Pos); void OnPlayerConnect(class CPlayer *pPlayer); void OnPlayerDisconnect(class CPlayer *pPlayer); void OnPlayerInfoChange(class CPlayer *pPlayer); void OnPlayerReadyChange(class CPlayer *pPlayer); void OnReset(); // game enum { TIMER_INFINITE = -1, TIMER_END = 10, }; void DoPause(int Seconds) { SetGameState(IGS_GAME_PAUSED, Seconds); } void DoWarmup(int Seconds) { if(m_GameState==IGS_WARMUP_GAME) SetGameState(IGS_WARMUP_GAME, 0); else SetGameState(IGS_WARMUP_USER, Seconds); } // general virtual void Snap(int SnappingClient); virtual void Tick(); // info bool IsFriendlyFire(int ClientID1, int ClientID2) const; bool IsGamePaused() const { return m_GameState == IGS_GAME_PAUSED || m_GameState == IGS_START_COUNTDOWN; } bool IsPlayerReadyMode() const; bool IsTeamChangeAllowed() const; bool IsTeamplay() const { return m_GameFlags&GAMEFLAG_TEAMS; } const char *GetGameType() const { return m_pGameType; } // map void ChangeMap(const char *pToMap); //spawn bool CanSpawn(int Team, vec2 *pPos) const; bool GetStartRespawnState() const; // team bool CanJoinTeam(int Team, int NotThisID) const; bool CanChangeTeam(CPlayer *pPplayer, int JoinTeam) const; void DoTeamChange(class CPlayer *pPlayer, int Team, bool DoChatMsg=true); void ForceTeamBalance() { if(!(m_GameFlags&GAMEFLAG_SURVIVAL)) DoTeamBalance(); } int GetRealPlayerNum() const { return m_aTeamSize[TEAM_RED]+m_aTeamSize[TEAM_BLUE]; } int GetStartTeam(); }; #endif ================================================ FILE: src/game/server/gamemodes/ctf.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <engine/shared/config.h> #include <game/mapitems.h> #include <game/server/entities/character.h> #include <game/server/entities/flag.h> #include <game/server/gamecontext.h> #include <game/server/player.h> #include "ctf.h" CGameControllerCTF::CGameControllerCTF(CGameContext *pGameServer) : IGameController(pGameServer) { // game m_apFlags[0] = 0; m_apFlags[1] = 0; m_pGameType = "CTF"; m_GameFlags = GAMEFLAG_TEAMS|GAMEFLAG_FLAGS; } // balancing bool CGameControllerCTF::CanBeMovedOnBalance(int ClientID) const { CCharacter* Character = GameServer()->m_apPlayers[ClientID]->GetCharacter(); if(Character) { for(int fi = 0; fi < 2; fi++) { CFlag *F = m_apFlags[fi]; if(F && F->m_pCarryingCharacter == Character) return false; } } return true; } // event int CGameControllerCTF::OnCharacterDeath(CCharacter *pVictim, CPlayer *pKiller, int WeaponID) { IGameController::OnCharacterDeath(pVictim, pKiller, WeaponID); int HadFlag = 0; // drop flags for(int i = 0; i < 2; i++) { CFlag *F = m_apFlags[i]; if(F && pKiller && pKiller->GetCharacter() && F->m_pCarryingCharacter == pKiller->GetCharacter()) HadFlag |= 2; if(F && F->m_pCarryingCharacter == pVictim) { GameServer()->SendGameMsg(GAMEMSG_CTF_DROP, -1); F->m_DropTick = Server()->Tick(); F->m_pCarryingCharacter = 0; F->m_Vel = vec2(0,0); if(pKiller && pKiller->GetTeam() != pVictim->GetPlayer()->GetTeam()) pKiller->m_Score++; HadFlag |= 1; } } return HadFlag; } bool CGameControllerCTF::OnEntity(int Index, vec2 Pos) { if(IGameController::OnEntity(Index, Pos)) return true; int Team = -1; if(Index == ENTITY_FLAGSTAND_RED) Team = TEAM_RED; if(Index == ENTITY_FLAGSTAND_BLUE) Team = TEAM_BLUE; if(Team == -1 || m_apFlags[Team]) return false; CFlag *F = new CFlag(&GameServer()->m_World, Team); F->m_StandPos = Pos; F->m_Pos = Pos; m_apFlags[Team] = F; GameServer()->m_World.InsertEntity(F); return true; } // game void CGameControllerCTF::DoWincheckMatch() { // check score win condition if((m_GameInfo.m_ScoreLimit > 0 && (m_aTeamscore[TEAM_RED] >= m_GameInfo.m_ScoreLimit || m_aTeamscore[TEAM_BLUE] >= m_GameInfo.m_ScoreLimit)) || (m_GameInfo.m_TimeLimit > 0 && (Server()->Tick()-m_GameStartTick) >= m_GameInfo.m_TimeLimit*Server()->TickSpeed()*60)) { if(m_SuddenDeath) { if(m_aTeamscore[TEAM_RED]/100 != m_aTeamscore[TEAM_BLUE]/100) EndMatch(); } else { if(m_aTeamscore[TEAM_RED] != m_aTeamscore[TEAM_BLUE]) EndMatch(); else m_SuddenDeath = 1; } } } // general void CGameControllerCTF::Snap(int SnappingClient) { IGameController::Snap(SnappingClient); CNetObj_GameDataFlag *pGameDataFlag = static_cast<CNetObj_GameDataFlag *>(Server()->SnapNewItem(NETOBJTYPE_GAMEDATAFLAG, 0, sizeof(CNetObj_GameDataFlag))); if(!pGameDataFlag) return; pGameDataFlag->m_FlagDropTickRed = 0; if(m_apFlags[TEAM_RED]) { if(m_apFlags[TEAM_RED]->m_AtStand) pGameDataFlag->m_FlagCarrierRed = FLAG_ATSTAND; else if(m_apFlags[TEAM_RED]->m_pCarryingCharacter && m_apFlags[TEAM_RED]->m_pCarryingCharacter->GetPlayer()) pGameDataFlag->m_FlagCarrierRed = m_apFlags[TEAM_RED]->m_pCarryingCharacter->GetPlayer()->GetCID(); else { pGameDataFlag->m_FlagCarrierRed = FLAG_TAKEN; pGameDataFlag->m_FlagDropTickRed = m_apFlags[TEAM_RED]->m_DropTick; } } else pGameDataFlag->m_FlagCarrierRed = FLAG_MISSING; pGameDataFlag->m_FlagDropTickBlue = 0; if(m_apFlags[TEAM_BLUE]) { if(m_apFlags[TEAM_BLUE]->m_AtStand) pGameDataFlag->m_FlagCarrierBlue = FLAG_ATSTAND; else if(m_apFlags[TEAM_BLUE]->m_pCarryingCharacter && m_apFlags[TEAM_BLUE]->m_pCarryingCharacter->GetPlayer()) pGameDataFlag->m_FlagCarrierBlue = m_apFlags[TEAM_BLUE]->m_pCarryingCharacter->GetPlayer()->GetCID(); else { pGameDataFlag->m_FlagCarrierBlue = FLAG_TAKEN; pGameDataFlag->m_FlagDropTickBlue = m_apFlags[TEAM_BLUE]->m_DropTick; } } else pGameDataFlag->m_FlagCarrierBlue = FLAG_MISSING; } void CGameControllerCTF::Tick() { IGameController::Tick(); if(GameServer()->m_World.m_ResetRequested || GameServer()->m_World.m_Paused) return; for(int fi = 0; fi < 2; fi++) { CFlag *F = m_apFlags[fi]; if(!F) continue; // flag hits death-tile or left the game layer, reset it if(GameServer()->Collision()->GetCollisionAt(F->m_Pos.x, F->m_Pos.y)&CCollision::COLFLAG_DEATH || F->GameLayerClipped(F->m_Pos)) { GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", "flag_return"); GameServer()->SendGameMsg(GAMEMSG_CTF_RETURN, -1); F->Reset(); continue; } // if(F->m_pCarryingCharacter) { // update flag position F->m_Pos = F->m_pCarryingCharacter->m_Pos; if(m_apFlags[fi^1] && m_apFlags[fi^1]->m_AtStand) { if(distance(F->m_Pos, m_apFlags[fi^1]->m_Pos) < CFlag::ms_PhysSize + CCharacter::ms_PhysSize) { // CAPTURE! \o/ m_aTeamscore[fi^1] += 100; F->m_pCarryingCharacter->GetPlayer()->m_Score += 5; char aBuf[64]; str_format(aBuf, sizeof(aBuf), "flag_capture player='%d:%s'", F->m_pCarryingCharacter->GetPlayer()->GetCID(), Server()->ClientName(F->m_pCarryingCharacter->GetPlayer()->GetCID())); GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", aBuf); GameServer()->SendGameMsg(GAMEMSG_CTF_CAPTURE, fi, F->m_pCarryingCharacter->GetPlayer()->GetCID(), Server()->Tick()-F->m_GrabTick, -1); for(int i = 0; i < 2; i++) m_apFlags[i]->Reset(); } } } else { CCharacter *apCloseCCharacters[MAX_CLIENTS]; int Num = GameServer()->m_World.FindEntities(F->m_Pos, CFlag::ms_PhysSize, (CEntity**)apCloseCCharacters, MAX_CLIENTS, CGameWorld::ENTTYPE_CHARACTER); for(int i = 0; i < Num; i++) { if(!apCloseCCharacters[i]->IsAlive() || apCloseCCharacters[i]->GetPlayer()->GetTeam() == TEAM_SPECTATORS || GameServer()->Collision()->IntersectLine(F->m_Pos, apCloseCCharacters[i]->m_Pos, NULL, NULL)) continue; if(apCloseCCharacters[i]->GetPlayer()->GetTeam() == F->m_Team) { // return the flag if(!F->m_AtStand) { CCharacter *pChr = apCloseCCharacters[i]; pChr->GetPlayer()->m_Score += 1; char aBuf[256]; str_format(aBuf, sizeof(aBuf), "flag_return player='%d:%s'", pChr->GetPlayer()->GetCID(), Server()->ClientName(pChr->GetPlayer()->GetCID())); GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", aBuf); GameServer()->SendGameMsg(GAMEMSG_CTF_RETURN, -1); F->Reset(); } } else { // take the flag if(F->m_AtStand) { m_aTeamscore[fi^1]++; F->m_GrabTick = Server()->Tick(); } F->m_AtStand = 0; F->m_pCarryingCharacter = apCloseCCharacters[i]; F->m_pCarryingCharacter->GetPlayer()->m_Score += 1; char aBuf[256]; str_format(aBuf, sizeof(aBuf), "flag_grab player='%d:%s'", F->m_pCarryingCharacter->GetPlayer()->GetCID(), Server()->ClientName(F->m_pCarryingCharacter->GetPlayer()->GetCID())); GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", aBuf); GameServer()->SendGameMsg(GAMEMSG_CTF_GRAB, fi, -1); break; } } if(!F->m_pCarryingCharacter && !F->m_AtStand) { if(Server()->Tick() > F->m_DropTick + Server()->TickSpeed()*30) { GameServer()->SendGameMsg(GAMEMSG_CTF_RETURN, -1); F->Reset(); } else { F->m_Vel.y += GameServer()->m_World.m_Core.m_Tuning.m_Gravity; GameServer()->Collision()->MoveBox(&F->m_Pos, &F->m_Vel, vec2(F->ms_PhysSize, F->ms_PhysSize), 0.5f); } } } } } ================================================ FILE: src/game/server/gamemodes/ctf.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_SERVER_GAMEMODES_CTF_H #define GAME_SERVER_GAMEMODES_CTF_H #include <game/server/gamecontroller.h> #include <game/server/entity.h> class CGameControllerCTF : public IGameController { // balancing virtual bool CanBeMovedOnBalance(int ClientID) const; // game class CFlag *m_apFlags[2]; virtual void DoWincheckMatch(); public: CGameControllerCTF(class CGameContext *pGameServer); // event virtual int OnCharacterDeath(class CCharacter *pVictim, class CPlayer *pKiller, int Weapon); virtual bool OnEntity(int Index, vec2 Pos); // general virtual void Snap(int SnappingClient); virtual void Tick(); }; #endif ================================================ FILE: src/game/server/gamemodes/dm.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include "dm.h" CGameControllerDM::CGameControllerDM(CGameContext *pGameServer) : IGameController(pGameServer) { m_pGameType = "DM"; } ================================================ FILE: src/game/server/gamemodes/dm.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_SERVER_GAMEMODES_DM_H #define GAME_SERVER_GAMEMODES_DM_H #include <game/server/gamecontroller.h> class CGameControllerDM : public IGameController { public: CGameControllerDM(class CGameContext *pGameServer); }; #endif ================================================ FILE: src/game/server/gamemodes/lms.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <engine/shared/config.h> #include <game/server/entities/character.h> #include <game/server/gamecontext.h> #include <game/server/player.h> #include "lms.h" CGameControllerLMS::CGameControllerLMS(CGameContext *pGameServer) : IGameController(pGameServer) { m_pGameType = "LMS"; m_GameFlags = GAMEFLAG_SURVIVAL; } // event int CGameControllerLMS::OnCharacterDeath(CCharacter *pVictim, CPlayer *pKiller, int Weapon) { // update spectator modes for dead players in survival if(m_GameFlags&GAMEFLAG_SURVIVAL) { for(int i = 0; i < MAX_CLIENTS; ++i) if(GameServer()->m_apPlayers[i] && GameServer()->m_apPlayers[i]->m_DeadSpecMode) GameServer()->m_apPlayers[i]->UpdateDeadSpecMode(); } return 0; } // game void CGameControllerLMS::DoWincheckRound() { // check for time based win if(m_GameInfo.m_TimeLimit > 0 && (Server()->Tick()-m_GameStartTick) >= m_GameInfo.m_TimeLimit*Server()->TickSpeed()*60) { for(int i = 0; i < MAX_CLIENTS; ++i) { if(GameServer()->m_apPlayers[i] && GameServer()->m_apPlayers[i]->GetTeam() != TEAM_SPECTATORS && (!GameServer()->m_apPlayers[i]->m_RespawnDisabled || (GameServer()->m_apPlayers[i]->GetCharacter() && GameServer()->m_apPlayers[i]->GetCharacter()->IsAlive()))) GameServer()->m_apPlayers[i]->m_Score++; } EndRound(); } else { // check for survival win CPlayer *pAlivePlayer = 0; int AlivePlayerCount = 0; for(int i = 0; i < MAX_CLIENTS; ++i) { if(GameServer()->m_apPlayers[i] && GameServer()->m_apPlayers[i]->GetTeam() != TEAM_SPECTATORS && (!GameServer()->m_apPlayers[i]->m_RespawnDisabled || (GameServer()->m_apPlayers[i]->GetCharacter() && GameServer()->m_apPlayers[i]->GetCharacter()->IsAlive()))) { ++AlivePlayerCount; pAlivePlayer = GameServer()->m_apPlayers[i]; } } if(AlivePlayerCount == 0) // no winner EndRound(); else if(AlivePlayerCount == 1) // 1 winner { pAlivePlayer->m_Score++; EndRound(); } } } ================================================ FILE: src/game/server/gamemodes/lms.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_SERVER_GAMEMODES_LMS_H #define GAME_SERVER_GAMEMODES_LMS_H #include <game/server/gamecontroller.h> class CGameControllerLMS : public IGameController { public: CGameControllerLMS(class CGameContext *pGameServer); // event virtual int OnCharacterDeath(class CCharacter *pVictim, class CPlayer *pKiller, int Weapon); // game virtual void DoWincheckRound(); }; #endif ================================================ FILE: src/game/server/gamemodes/mod.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include "mod.h" CGameControllerMOD::CGameControllerMOD(class CGameContext *pGameServer) : IGameController(pGameServer) { // Exchange this to a string that identifies your game mode. // DM, TDM and CTF are reserved for teeworlds original modes. m_pGameType = "MOD"; //m_GameFlags = GAMEFLAG_TEAMS; // GAMEFLAG_TEAMS makes it a two-team gamemode } void CGameControllerMOD::Tick() { // this is the main part of the gamemode, this function is run every tick IGameController::Tick(); } ================================================ FILE: src/game/server/gamemodes/mod.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_SERVER_GAMEMODES_MOD_H #define GAME_SERVER_GAMEMODES_MOD_H #include <game/server/gamecontroller.h> // you can subclass GAMECONTROLLER_CTF, GAMECONTROLLER_TDM etc if you want // todo a modification with their base as well. class CGameControllerMOD : public IGameController { public: CGameControllerMOD(class CGameContext *pGameServer); virtual void Tick(); // add more virtual functions here if you wish }; #endif ================================================ FILE: src/game/server/gamemodes/sur.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <engine/shared/config.h> #include <game/server/entities/character.h> #include <game/server/gamecontext.h> #include <game/server/player.h> #include "sur.h" CGameControllerSUR::CGameControllerSUR(CGameContext *pGameServer) : IGameController(pGameServer) { m_pGameType = "SUR"; m_GameFlags = GAMEFLAG_TEAMS|GAMEFLAG_SURVIVAL; } // game void CGameControllerSUR::DoWincheckRound() { int Count[2] = {0}; for(int i = 0; i < MAX_CLIENTS; ++i) { if(GameServer()->m_apPlayers[i] && GameServer()->m_apPlayers[i]->GetTeam() != TEAM_SPECTATORS && (!GameServer()->m_apPlayers[i]->m_RespawnDisabled || (GameServer()->m_apPlayers[i]->GetCharacter() && GameServer()->m_apPlayers[i]->GetCharacter()->IsAlive()))) ++Count[GameServer()->m_apPlayers[i]->GetTeam()]; } if(Count[TEAM_RED]+Count[TEAM_BLUE] == 0 || (m_GameInfo.m_TimeLimit > 0 && (Server()->Tick()-m_GameStartTick) >= m_GameInfo.m_TimeLimit*Server()->TickSpeed()*60)) { ++m_aTeamscore[TEAM_BLUE]; ++m_aTeamscore[TEAM_RED]; EndRound(); } else if(Count[TEAM_RED] == 0) { ++m_aTeamscore[TEAM_BLUE]; EndRound(); } else if(Count[TEAM_BLUE] == 0) { ++m_aTeamscore[TEAM_RED]; EndRound(); } } ================================================ FILE: src/game/server/gamemodes/sur.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_SERVER_GAMEMODES_SUR_H #define GAME_SERVER_GAMEMODES_SUR_H #include <game/server/gamecontroller.h> class CGameControllerSUR : public IGameController { public: CGameControllerSUR(class CGameContext *pGameServer); // game virtual void DoWincheckRound(); }; #endif ================================================ FILE: src/game/server/gamemodes/tdm.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <engine/shared/config.h> #include <game/server/entities/character.h> #include <game/server/gamecontext.h> #include <game/server/player.h> #include "tdm.h" CGameControllerTDM::CGameControllerTDM(class CGameContext *pGameServer) : IGameController(pGameServer) { m_pGameType = "TDM"; m_GameFlags = GAMEFLAG_TEAMS; } // event int CGameControllerTDM::OnCharacterDeath(class CCharacter *pVictim, class CPlayer *pKiller, int Weapon) { IGameController::OnCharacterDeath(pVictim, pKiller, Weapon); if(pKiller && Weapon != WEAPON_GAME) { // do team scoring if(pKiller == pVictim->GetPlayer() || pKiller->GetTeam() == pVictim->GetPlayer()->GetTeam()) m_aTeamscore[pKiller->GetTeam()&1]--; // klant arschel else m_aTeamscore[pKiller->GetTeam()&1]++; // good shit } pVictim->GetPlayer()->m_RespawnTick = max(pVictim->GetPlayer()->m_RespawnTick, Server()->Tick()+Server()->TickSpeed()*g_Config.m_SvRespawnDelayTDM); return 0; } ================================================ FILE: src/game/server/gamemodes/tdm.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_SERVER_GAMEMODES_TDM_H #define GAME_SERVER_GAMEMODES_TDM_H #include <game/server/gamecontroller.h> class CGameControllerTDM : public IGameController { public: CGameControllerTDM(class CGameContext *pGameServer); // event virtual int OnCharacterDeath(class CCharacter *pVictim, class CPlayer *pKiller, int Weapon); }; #endif ================================================ FILE: src/game/server/gameworld.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include "entities/character.h" #include "entity.h" #include "gamecontext.h" #include "gamecontroller.h" #include "gameworld.h" ////////////////////////////////////////////////// // game world ////////////////////////////////////////////////// CGameWorld::CGameWorld() { m_pGameServer = 0x0; m_pServer = 0x0; m_Paused = false; m_ResetRequested = false; for(int i = 0; i < NUM_ENTTYPES; i++) m_apFirstEntityTypes[i] = 0; } CGameWorld::~CGameWorld() { // delete all entities for(int i = 0; i < NUM_ENTTYPES; i++) while(m_apFirstEntityTypes[i]) delete m_apFirstEntityTypes[i]; } void CGameWorld::SetGameServer(CGameContext *pGameServer) { m_pGameServer = pGameServer; m_pServer = m_pGameServer->Server(); } CEntity *CGameWorld::FindFirst(int Type) { return Type < 0 || Type >= NUM_ENTTYPES ? 0 : m_apFirstEntityTypes[Type]; } int CGameWorld::FindEntities(vec2 Pos, float Radius, CEntity **ppEnts, int Max, int Type) { if(Type < 0 || Type >= NUM_ENTTYPES) return 0; int Num = 0; for(CEntity *pEnt = m_apFirstEntityTypes[Type]; pEnt; pEnt = pEnt->m_pNextTypeEntity) { if(distance(pEnt->m_Pos, Pos) < Radius+pEnt->m_ProximityRadius) { if(ppEnts) ppEnts[Num] = pEnt; Num++; if(Num == Max) break; } } return Num; } void CGameWorld::InsertEntity(CEntity *pEnt) { #ifdef CONF_DEBUG for(CEntity *pCur = m_apFirstEntityTypes[pEnt->m_ObjType]; pCur; pCur = pCur->m_pNextTypeEntity) dbg_assert(pCur != pEnt, "err"); #endif // insert it if(m_apFirstEntityTypes[pEnt->m_ObjType]) m_apFirstEntityTypes[pEnt->m_ObjType]->m_pPrevTypeEntity = pEnt; pEnt->m_pNextTypeEntity = m_apFirstEntityTypes[pEnt->m_ObjType]; pEnt->m_pPrevTypeEntity = 0x0; m_apFirstEntityTypes[pEnt->m_ObjType] = pEnt; } void CGameWorld::DestroyEntity(CEntity *pEnt) { pEnt->m_MarkedForDestroy = true; } void CGameWorld::RemoveEntity(CEntity *pEnt) { // not in the list if(!pEnt->m_pNextTypeEntity && !pEnt->m_pPrevTypeEntity && m_apFirstEntityTypes[pEnt->m_ObjType] != pEnt) return; // remove if(pEnt->m_pPrevTypeEntity) pEnt->m_pPrevTypeEntity->m_pNextTypeEntity = pEnt->m_pNextTypeEntity; else m_apFirstEntityTypes[pEnt->m_ObjType] = pEnt->m_pNextTypeEntity; if(pEnt->m_pNextTypeEntity) pEnt->m_pNextTypeEntity->m_pPrevTypeEntity = pEnt->m_pPrevTypeEntity; // keep list traversing valid if(m_pNextTraverseEntity == pEnt) m_pNextTraverseEntity = pEnt->m_pNextTypeEntity; pEnt->m_pNextTypeEntity = 0; pEnt->m_pPrevTypeEntity = 0; } // void CGameWorld::Snap(int SnappingClient) { for(int i = 0; i < NUM_ENTTYPES; i++) for(CEntity *pEnt = m_apFirstEntityTypes[i]; pEnt; ) { m_pNextTraverseEntity = pEnt->m_pNextTypeEntity; pEnt->Snap(SnappingClient); pEnt = m_pNextTraverseEntity; } } void CGameWorld::PostSnap() { for(int i = 0; i < NUM_ENTTYPES; i++) for(CEntity *pEnt = m_apFirstEntityTypes[i]; pEnt; ) { m_pNextTraverseEntity = pEnt->m_pNextTypeEntity; pEnt->PostSnap(); pEnt = m_pNextTraverseEntity; } } void CGameWorld::Reset() { // reset all entities for(int i = 0; i < NUM_ENTTYPES; i++) for(CEntity *pEnt = m_apFirstEntityTypes[i]; pEnt; ) { m_pNextTraverseEntity = pEnt->m_pNextTypeEntity; pEnt->Reset(); pEnt = m_pNextTraverseEntity; } RemoveEntities(); GameServer()->m_pController->OnReset(); RemoveEntities(); m_ResetRequested = false; } void CGameWorld::RemoveEntities() { // destroy objects marked for destruction for(int i = 0; i < NUM_ENTTYPES; i++) for(CEntity *pEnt = m_apFirstEntityTypes[i]; pEnt; ) { m_pNextTraverseEntity = pEnt->m_pNextTypeEntity; if(pEnt->m_MarkedForDestroy) { RemoveEntity(pEnt); pEnt->Destroy(); } pEnt = m_pNextTraverseEntity; } } void CGameWorld::Tick() { if(m_ResetRequested) Reset(); if(!m_Paused) { // update all objects for(int i = 0; i < NUM_ENTTYPES; i++) for(CEntity *pEnt = m_apFirstEntityTypes[i]; pEnt; ) { m_pNextTraverseEntity = pEnt->m_pNextTypeEntity; pEnt->Tick(); pEnt = m_pNextTraverseEntity; } for(int i = 0; i < NUM_ENTTYPES; i++) for(CEntity *pEnt = m_apFirstEntityTypes[i]; pEnt; ) { m_pNextTraverseEntity = pEnt->m_pNextTypeEntity; pEnt->TickDefered(); pEnt = m_pNextTraverseEntity; } } else if(GameServer()->m_pController->IsGamePaused()) { // update all objects for(int i = 0; i < NUM_ENTTYPES; i++) for(CEntity *pEnt = m_apFirstEntityTypes[i]; pEnt; ) { m_pNextTraverseEntity = pEnt->m_pNextTypeEntity; pEnt->TickPaused(); pEnt = m_pNextTraverseEntity; } } RemoveEntities(); } // TODO: should be more general CCharacter *CGameWorld::IntersectCharacter(vec2 Pos0, vec2 Pos1, float Radius, vec2& NewPos, CEntity *pNotThis) { // Find other players float ClosestLen = distance(Pos0, Pos1) * 100.0f; CCharacter *pClosest = 0; CCharacter *p = (CCharacter *)FindFirst(ENTTYPE_CHARACTER); for(; p; p = (CCharacter *)p->TypeNext()) { if(p == pNotThis) continue; vec2 IntersectPos = closest_point_on_line(Pos0, Pos1, p->m_Pos); float Len = distance(p->m_Pos, IntersectPos); if(Len < p->m_ProximityRadius+Radius) { Len = distance(Pos0, IntersectPos); if(Len < ClosestLen) { NewPos = IntersectPos; ClosestLen = Len; pClosest = p; } } } return pClosest; } CCharacter *CGameWorld::ClosestCharacter(vec2 Pos, float Radius, CEntity *pNotThis) { // Find other players float ClosestRange = Radius*2; CCharacter *pClosest = 0; CCharacter *p = (CCharacter *)GameServer()->m_World.FindFirst(ENTTYPE_CHARACTER); for(; p; p = (CCharacter *)p->TypeNext()) { if(p == pNotThis) continue; float Len = distance(Pos, p->m_Pos); if(Len < p->m_ProximityRadius+Radius) { if(Len < ClosestRange) { ClosestRange = Len; pClosest = p; } } } return pClosest; } ================================================ FILE: src/game/server/gameworld.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_SERVER_GAMEWORLD_H #define GAME_SERVER_GAMEWORLD_H #include <game/gamecore.h> class CEntity; class CCharacter; /* Class: Game World Tracks all entities in the game. Propagates tick and snap calls to all entities. */ class CGameWorld { public: enum { ENTTYPE_PROJECTILE = 0, ENTTYPE_LASER, ENTTYPE_PICKUP, ENTTYPE_FLAG, ENTTYPE_CHARACTER, NUM_ENTTYPES }; private: void Reset(); void RemoveEntities(); CEntity *m_pNextTraverseEntity; CEntity *m_apFirstEntityTypes[NUM_ENTTYPES]; class CGameContext *m_pGameServer; class IServer *m_pServer; public: class CGameContext *GameServer() { return m_pGameServer; } class IServer *Server() { return m_pServer; } bool m_ResetRequested; bool m_Paused; CWorldCore m_Core; CGameWorld(); ~CGameWorld(); void SetGameServer(CGameContext *pGameServer); CEntity *FindFirst(int Type); /* Function: find_entities Finds entities close to a position and returns them in a list. Arguments: pos - Position. radius - How close the entities have to be. ents - Pointer to a list that should be filled with the pointers to the entities. max - Number of entities that fits into the ents array. type - Type of the entities to find. Returns: Number of entities found and added to the ents array. */ int FindEntities(vec2 Pos, float Radius, CEntity **ppEnts, int Max, int Type); /* Function: interserct_CCharacter Finds the closest CCharacter that intersects the line. Arguments: pos0 - Start position pos2 - End position radius - How for from the line the CCharacter is allowed to be. new_pos - Intersection position notthis - Entity to ignore intersecting with Returns: Returns a pointer to the closest hit or NULL of there is no intersection. */ class CCharacter *IntersectCharacter(vec2 Pos0, vec2 Pos1, float Radius, vec2 &NewPos, class CEntity *pNotThis = 0); /* Function: closest_CCharacter Finds the closest CCharacter to a specific point. Arguments: pos - The center position. radius - How far off the CCharacter is allowed to be notthis - Entity to ignore Returns: Returns a pointer to the closest CCharacter or NULL if no CCharacter is close enough. */ class CCharacter *ClosestCharacter(vec2 Pos, float Radius, CEntity *ppNotThis); /* Function: insert_entity Adds an entity to the world. Arguments: entity - Entity to add */ void InsertEntity(CEntity *pEntity); /* Function: remove_entity Removes an entity from the world. Arguments: entity - Entity to remove */ void RemoveEntity(CEntity *pEntity); /* Function: destroy_entity Destroys an entity in the world. Arguments: entity - Entity to destroy */ void DestroyEntity(CEntity *pEntity); /* Function: snap Calls snap on all the entities in the world to create the snapshot. Arguments: snapping_client - ID of the client which snapshot is being created. */ void Snap(int SnappingClient); void PostSnap(); /* Function: tick Calls tick on all the entities in the world to progress the world to the next tick. */ void Tick(); }; #endif ================================================ FILE: src/game/server/player.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include "entities/character.h" #include "gamecontext.h" #include "gamecontroller.h" #include "player.h" MACRO_ALLOC_POOL_ID_IMPL(CPlayer, MAX_CLIENTS) IServer *CPlayer::Server() const { return m_pGameServer->Server(); } CPlayer::CPlayer(CGameContext *pGameServer, int ClientID, bool Dummy) { m_pGameServer = pGameServer; m_RespawnTick = Server()->Tick(); m_DieTick = Server()->Tick(); m_ScoreStartTick = Server()->Tick(); m_pCharacter = 0; m_ClientID = ClientID; m_Team = GameServer()->m_pController->GetStartTeam(); m_SpectatorID = SPEC_FREEVIEW; m_LastActionTick = Server()->Tick(); m_TeamChangeTick = Server()->Tick(); m_InactivityTickCounter = 0; m_Dummy = Dummy; m_IsReadyToPlay = !GameServer()->m_pController->IsPlayerReadyMode(); m_RespawnDisabled = GameServer()->m_pController->GetStartRespawnState(); m_DeadSpecMode = false; m_Spawning = 0; } CPlayer::~CPlayer() { delete m_pCharacter; m_pCharacter = 0; } void CPlayer::Tick() { if(!IsDummy() && !Server()->ClientIngame(m_ClientID)) return; Server()->SetClientScore(m_ClientID, m_Score); // do latency stuff { IServer::CClientInfo Info; if(Server()->GetClientInfo(m_ClientID, &Info)) { m_Latency.m_Accum += Info.m_Latency; m_Latency.m_AccumMax = max(m_Latency.m_AccumMax, Info.m_Latency); m_Latency.m_AccumMin = min(m_Latency.m_AccumMin, Info.m_Latency); } // each second if(Server()->Tick()%Server()->TickSpeed() == 0) { m_Latency.m_Avg = m_Latency.m_Accum/Server()->TickSpeed(); m_Latency.m_Max = m_Latency.m_AccumMax; m_Latency.m_Min = m_Latency.m_AccumMin; m_Latency.m_Accum = 0; m_Latency.m_AccumMin = 1000; m_Latency.m_AccumMax = 0; } } if(m_pCharacter && !m_pCharacter->IsAlive()) { delete m_pCharacter; m_pCharacter = 0; } if(!GameServer()->m_pController->IsGamePaused()) { if(!m_pCharacter && m_Team == TEAM_SPECTATORS && m_SpectatorID == SPEC_FREEVIEW) m_ViewPos -= vec2(clamp(m_ViewPos.x-m_LatestActivity.m_TargetX, -500.0f, 500.0f), clamp(m_ViewPos.y-m_LatestActivity.m_TargetY, -400.0f, 400.0f)); if(!m_pCharacter && m_DieTick+Server()->TickSpeed()*3 <= Server()->Tick() && !m_DeadSpecMode) Respawn(); if(m_pCharacter) { if(m_pCharacter->IsAlive()) m_ViewPos = m_pCharacter->m_Pos; } else if(m_Spawning && m_RespawnTick <= Server()->Tick()) TryRespawn(); if(!m_DeadSpecMode && m_LastActionTick != Server()->Tick()) ++m_InactivityTickCounter; } else { ++m_RespawnTick; ++m_DieTick; ++m_ScoreStartTick; ++m_LastActionTick; ++m_TeamChangeTick; } } void CPlayer::PostTick() { // update latency value if(m_PlayerFlags&PLAYERFLAG_SCOREBOARD) { for(int i = 0; i < MAX_CLIENTS; ++i) { if(GameServer()->m_apPlayers[i] && GameServer()->m_apPlayers[i]->GetTeam() != TEAM_SPECTATORS) m_aActLatency[i] = GameServer()->m_apPlayers[i]->m_Latency.m_Min; } } // update view pos for spectators and dead players if((m_Team == TEAM_SPECTATORS || m_DeadSpecMode) && m_SpectatorID != SPEC_FREEVIEW && GameServer()->m_apPlayers[m_SpectatorID]) m_ViewPos = GameServer()->m_apPlayers[m_SpectatorID]->m_ViewPos; } void CPlayer::Snap(int SnappingClient) { if(!IsDummy() && !Server()->ClientIngame(m_ClientID)) return; CNetObj_PlayerInfo *pPlayerInfo = static_cast<CNetObj_PlayerInfo *>(Server()->SnapNewItem(NETOBJTYPE_PLAYERINFO, m_ClientID, sizeof(CNetObj_PlayerInfo))); if(!pPlayerInfo) return; pPlayerInfo->m_PlayerFlags = m_PlayerFlags&PLAYERFLAG_CHATTING; if(Server()->IsAuthed(m_ClientID)) pPlayerInfo->m_PlayerFlags |= PLAYERFLAG_ADMIN; if(!GameServer()->m_pController->IsPlayerReadyMode() || m_IsReadyToPlay) pPlayerInfo->m_PlayerFlags |= PLAYERFLAG_READY; if(m_RespawnDisabled && (!GetCharacter() || !GetCharacter()->IsAlive())) pPlayerInfo->m_PlayerFlags |= PLAYERFLAG_DEAD; if(SnappingClient != -1 && (m_Team == TEAM_SPECTATORS || m_DeadSpecMode) && SnappingClient == m_SpectatorID) pPlayerInfo->m_PlayerFlags |= PLAYERFLAG_WATCHING; pPlayerInfo->m_Latency = SnappingClient == -1 ? m_Latency.m_Min : GameServer()->m_apPlayers[SnappingClient]->m_aActLatency[m_ClientID]; pPlayerInfo->m_Score = m_Score; if(m_ClientID == SnappingClient && (m_Team == TEAM_SPECTATORS || m_DeadSpecMode)) { CNetObj_SpectatorInfo *pSpectatorInfo = static_cast<CNetObj_SpectatorInfo *>(Server()->SnapNewItem(NETOBJTYPE_SPECTATORINFO, m_ClientID, sizeof(CNetObj_SpectatorInfo))); if(!pSpectatorInfo) return; pSpectatorInfo->m_SpectatorID = m_SpectatorID; pSpectatorInfo->m_X = m_ViewPos.x; pSpectatorInfo->m_Y = m_ViewPos.y; } // demo recording if(SnappingClient == -1) { CNetObj_De_ClientInfo *pClientInfo = static_cast<CNetObj_De_ClientInfo *>(Server()->SnapNewItem(NETOBJTYPE_DE_CLIENTINFO, m_ClientID, sizeof(CNetObj_De_ClientInfo))); if(!pClientInfo) return; pClientInfo->m_Local = 0; pClientInfo->m_Team = m_Team; StrToInts(pClientInfo->m_aName, 4, Server()->ClientName(m_ClientID)); StrToInts(pClientInfo->m_aClan, 3, Server()->ClientClan(m_ClientID)); pClientInfo->m_Country = Server()->ClientCountry(m_ClientID); for(int p = 0; p < 6; p++) { StrToInts(pClientInfo->m_aaSkinPartNames[p], 6, m_TeeInfos.m_aaSkinPartNames[p]); pClientInfo->m_aUseCustomColors[p] = m_TeeInfos.m_aUseCustomColors[p]; pClientInfo->m_aSkinPartColors[p] = m_TeeInfos.m_aSkinPartColors[p]; } } } void CPlayer::OnDisconnect() { KillCharacter(); if(m_Team != TEAM_SPECTATORS) { // update spectator modes for(int i = 0; i < MAX_CLIENTS; ++i) { if(GameServer()->m_apPlayers[i] && GameServer()->m_apPlayers[i]->m_SpectatorID == m_ClientID) { if(GameServer()->m_apPlayers[i]->m_DeadSpecMode) GameServer()->m_apPlayers[i]->UpdateDeadSpecMode(); else GameServer()->m_apPlayers[i]->m_SpectatorID = SPEC_FREEVIEW; } } } } void CPlayer::OnPredictedInput(CNetObj_PlayerInput *NewInput) { // skip the input if chat is active if((m_PlayerFlags&PLAYERFLAG_CHATTING) && (NewInput->m_PlayerFlags&PLAYERFLAG_CHATTING)) return; if(m_pCharacter) m_pCharacter->OnPredictedInput(NewInput); } void CPlayer::OnDirectInput(CNetObj_PlayerInput *NewInput) { if(GameServer()->m_World.m_Paused) { m_PlayerFlags = NewInput->m_PlayerFlags; return; } if(NewInput->m_PlayerFlags&PLAYERFLAG_CHATTING) { // skip the input if chat is active if(m_PlayerFlags&PLAYERFLAG_CHATTING) return; // reset input if(m_pCharacter) m_pCharacter->ResetInput(); m_PlayerFlags = NewInput->m_PlayerFlags; return; } m_PlayerFlags = NewInput->m_PlayerFlags; if(m_pCharacter) m_pCharacter->OnDirectInput(NewInput); if(!m_pCharacter && m_Team != TEAM_SPECTATORS && (NewInput->m_Fire&1)) Respawn(); // check for activity if(NewInput->m_Direction || m_LatestActivity.m_TargetX != NewInput->m_TargetX || m_LatestActivity.m_TargetY != NewInput->m_TargetY || NewInput->m_Jump || NewInput->m_Fire&1 || NewInput->m_Hook) { m_LatestActivity.m_TargetX = NewInput->m_TargetX; m_LatestActivity.m_TargetY = NewInput->m_TargetY; m_LastActionTick = Server()->Tick(); m_InactivityTickCounter = 0; } } CCharacter *CPlayer::GetCharacter() { if(m_pCharacter && m_pCharacter->IsAlive()) return m_pCharacter; return 0; } void CPlayer::KillCharacter(int Weapon) { if(m_pCharacter) { m_pCharacter->Die(m_ClientID, Weapon); delete m_pCharacter; m_pCharacter = 0; } } void CPlayer::Respawn() { if(m_RespawnDisabled) { // enable spectate mode for dead players m_DeadSpecMode = true; m_IsReadyToPlay = true; UpdateDeadSpecMode(); return; } m_DeadSpecMode = false; if(m_Team != TEAM_SPECTATORS) m_Spawning = true; } bool CPlayer::SetSpectatorID(int SpectatorID) { if(m_SpectatorID == SpectatorID || m_ClientID == SpectatorID) return false; if(m_Team == TEAM_SPECTATORS) { // check for freeview or if wanted player is playing if(SpectatorID == SPEC_FREEVIEW || (GameServer()->m_apPlayers[SpectatorID] && GameServer()->m_apPlayers[SpectatorID]->GetTeam() != TEAM_SPECTATORS)) { m_SpectatorID = SpectatorID; return true; } } else if(m_DeadSpecMode) { // check if wanted player can be followed if(GameServer()->m_apPlayers[SpectatorID] && DeadCanFollow(GameServer()->m_apPlayers[SpectatorID])) { m_SpectatorID = SpectatorID; return true; } } return false; } bool CPlayer::DeadCanFollow(CPlayer *pPlayer) const { // check if wanted player is in the same team and alive return (!pPlayer->m_RespawnDisabled || (pPlayer->GetCharacter() && pPlayer->GetCharacter()->IsAlive())) && pPlayer->GetTeam() == m_Team; } void CPlayer::UpdateDeadSpecMode() { // check if actual spectator id is valid if(m_SpectatorID != SPEC_FREEVIEW && GameServer()->m_apPlayers[m_SpectatorID] && DeadCanFollow(GameServer()->m_apPlayers[m_SpectatorID])) return; // find player to follow for(int i = 0; i < MAX_CLIENTS; ++i) { if(GameServer()->m_apPlayers[i] && DeadCanFollow(GameServer()->m_apPlayers[i])) { m_SpectatorID = i; return; } } // no one available to follow -> turn spectator mode off m_DeadSpecMode = false; } void CPlayer::SetTeam(int Team, bool DoChatMsg) { KillCharacter(); m_Team = Team; m_LastActionTick = Server()->Tick(); m_SpectatorID = SPEC_FREEVIEW; m_DeadSpecMode = false; // we got to wait 0.5 secs before respawning m_RespawnTick = Server()->Tick()+Server()->TickSpeed()/2; if(Team == TEAM_SPECTATORS) { // update spectator modes for(int i = 0; i < MAX_CLIENTS; ++i) { if(GameServer()->m_apPlayers[i] && GameServer()->m_apPlayers[i]->m_SpectatorID == m_ClientID) { if(GameServer()->m_apPlayers[i]->m_DeadSpecMode) GameServer()->m_apPlayers[i]->UpdateDeadSpecMode(); else GameServer()->m_apPlayers[i]->m_SpectatorID = SPEC_FREEVIEW; } } } } void CPlayer::TryRespawn() { vec2 SpawnPos; if(!GameServer()->m_pController->CanSpawn(m_Team, &SpawnPos)) return; m_Spawning = false; m_pCharacter = new(m_ClientID) CCharacter(&GameServer()->m_World); m_pCharacter->Spawn(this, SpawnPos); GameServer()->CreatePlayerSpawn(SpawnPos); } ================================================ FILE: src/game/server/player.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_SERVER_PLAYER_H #define GAME_SERVER_PLAYER_H #include "alloc.h" enum { WEAPON_GAME = -3, // team switching etc WEAPON_SELF = -2, // console kill command WEAPON_WORLD = -1, // death tiles etc }; // player object class CPlayer { MACRO_ALLOC_POOL_ID() public: CPlayer(CGameContext *pGameServer, int ClientID, bool Dummy); ~CPlayer(); void Init(int CID); void TryRespawn(); void Respawn(); void SetTeam(int Team, bool DoChatMsg=true); int GetTeam() const { return m_Team; }; int GetCID() const { return m_ClientID; }; bool IsDummy() const { return m_Dummy; } void Tick(); void PostTick(); void Snap(int SnappingClient); void OnDirectInput(CNetObj_PlayerInput *NewInput); void OnPredictedInput(CNetObj_PlayerInput *NewInput); void OnDisconnect(); void KillCharacter(int Weapon = WEAPON_GAME); CCharacter *GetCharacter(); //--------------------------------------------------------- // this is used for snapping so we know how we can clip the view for the player vec2 m_ViewPos; // states if the client is chatting, accessing a menu etc. int m_PlayerFlags; // used for snapping to just update latency if the scoreboard is active int m_aActLatency[MAX_CLIENTS]; // used for spectator mode int GetSpectatorID() const { return m_SpectatorID; } bool SetSpectatorID(int SpectatorID); bool m_DeadSpecMode; bool DeadCanFollow(CPlayer *pPlayer) const; void UpdateDeadSpecMode(); bool m_IsReadyToEnter; bool m_IsReadyToPlay; bool m_RespawnDisabled; // int m_Vote; int m_VotePos; // int m_LastVoteCall; int m_LastVoteTry; int m_LastChat; int m_LastSetTeam; int m_LastSetSpectatorMode; int m_LastChangeInfo; int m_LastEmote; int m_LastKill; int m_LastReadyChange; // TODO: clean this up struct { char m_aaSkinPartNames[6][24]; int m_aUseCustomColors[6]; int m_aSkinPartColors[6]; } m_TeeInfos; int m_RespawnTick; int m_DieTick; int m_Score; int m_ScoreStartTick; int m_LastActionTick; int m_TeamChangeTick; int m_InactivityTickCounter; struct { int m_TargetX; int m_TargetY; } m_LatestActivity; // network latency calculations struct { int m_Accum; int m_AccumMin; int m_AccumMax; int m_Avg; int m_Min; int m_Max; } m_Latency; private: CCharacter *m_pCharacter; CGameContext *m_pGameServer; CGameContext *GameServer() const { return m_pGameServer; } IServer *Server() const; // bool m_Spawning; int m_ClientID; int m_Team; bool m_Dummy; // used for spectator mode int m_SpectatorID; }; #endif ================================================ FILE: src/game/tuning.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_TUNING_H #define GAME_TUNING_H #undef GAME_TUNING_H // this file will be included several times // physics tuning MACRO_TUNING_PARAM(GroundControlSpeed, ground_control_speed, 10.0f) MACRO_TUNING_PARAM(GroundControlAccel, ground_control_accel, 100.0f / TicksPerSecond) MACRO_TUNING_PARAM(GroundFriction, ground_friction, 0.5f) MACRO_TUNING_PARAM(GroundJumpImpulse, ground_jump_impulse, 13.2f) MACRO_TUNING_PARAM(AirJumpImpulse, air_jump_impulse, 12.0f) MACRO_TUNING_PARAM(AirControlSpeed, air_control_speed, 250.0f / TicksPerSecond) MACRO_TUNING_PARAM(AirControlAccel, air_control_accel, 1.5f) MACRO_TUNING_PARAM(AirFriction, air_friction, 0.95f) MACRO_TUNING_PARAM(HookLength, hook_length, 380.0f) MACRO_TUNING_PARAM(HookFireSpeed, hook_fire_speed, 80.0f) MACRO_TUNING_PARAM(HookDragAccel, hook_drag_accel, 3.0f) MACRO_TUNING_PARAM(HookDragSpeed, hook_drag_speed, 15.0f) MACRO_TUNING_PARAM(Gravity, gravity, 0.5f) MACRO_TUNING_PARAM(VelrampStart, velramp_start, 550) MACRO_TUNING_PARAM(VelrampRange, velramp_range, 2000) MACRO_TUNING_PARAM(VelrampCurvature, velramp_curvature, 1.4f) // weapon tuning MACRO_TUNING_PARAM(GunCurvature, gun_curvature, 1.25f) MACRO_TUNING_PARAM(GunSpeed, gun_speed, 2200.0f) MACRO_TUNING_PARAM(GunLifetime, gun_lifetime, 2.0f) MACRO_TUNING_PARAM(ShotgunCurvature, shotgun_curvature, 1.25f) MACRO_TUNING_PARAM(ShotgunSpeed, shotgun_speed, 2750.0f) MACRO_TUNING_PARAM(ShotgunSpeeddiff, shotgun_speeddiff, 0.8f) MACRO_TUNING_PARAM(ShotgunLifetime, shotgun_lifetime, 0.20f) MACRO_TUNING_PARAM(GrenadeCurvature, grenade_curvature, 7.0f) MACRO_TUNING_PARAM(GrenadeSpeed, grenade_speed, 1000.0f) MACRO_TUNING_PARAM(GrenadeLifetime, grenade_lifetime, 2.0f) MACRO_TUNING_PARAM(LaserReach, laser_reach, 800.0f) MACRO_TUNING_PARAM(LaserBounceDelay, laser_bounce_delay, 150) MACRO_TUNING_PARAM(LaserBounceNum, laser_bounce_num, 1) MACRO_TUNING_PARAM(LaserBounceCost, laser_bounce_cost, 0) MACRO_TUNING_PARAM(LaserDamage, laser_damage, 5) MACRO_TUNING_PARAM(PlayerCollision, player_collision, 1) MACRO_TUNING_PARAM(PlayerHooking, player_hooking, 1) #endif ================================================ FILE: src/game/variables.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_VARIABLES_H #define GAME_VARIABLES_H #undef GAME_VARIABLES_H // this file will be included several times // client MACRO_CONFIG_INT(ClPredict, cl_predict, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Predict client movements") MACRO_CONFIG_INT(ClNameplates, cl_nameplates, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show name plates") MACRO_CONFIG_INT(ClNameplatesAlways, cl_nameplates_always, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Always show name plates disregarding of distance") MACRO_CONFIG_INT(ClNameplatesTeamcolors, cl_nameplates_teamcolors, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Use team colors for name plates") MACRO_CONFIG_INT(ClNameplatesSize, cl_nameplates_size, 50, 0, 100, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Size of the name plates from 0 to 100%") MACRO_CONFIG_INT(ClAutoswitchWeapons, cl_autoswitch_weapons, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Auto switch weapon on pickup") MACRO_CONFIG_INT(ClShowhud, cl_showhud, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show ingame HUD") MACRO_CONFIG_INT(ClShowChatFriends, cl_show_chat_friends, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show only chat messages from friends") MACRO_CONFIG_INT(ClShowfps, cl_showfps, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show ingame FPS counter") MACRO_CONFIG_INT(ClAirjumpindicator, cl_airjumpindicator, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "") MACRO_CONFIG_INT(ClThreadsoundloading, cl_threadsoundloading, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Load sound files threaded") MACRO_CONFIG_INT(ClWarningTeambalance, cl_warning_teambalance, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Warn about team balance") MACRO_CONFIG_INT(ClMouseDeadzone, cl_mouse_deadzone, 300, 0, 0, CFGFLAG_CLIENT|CFGFLAG_SAVE, "") MACRO_CONFIG_INT(ClMouseFollowfactor, cl_mouse_followfactor, 60, 0, 200, CFGFLAG_CLIENT|CFGFLAG_SAVE, "") MACRO_CONFIG_INT(ClMouseMaxDistance, cl_mouse_max_distance, 800, 0, 0, CFGFLAG_CLIENT|CFGFLAG_SAVE, "") MACRO_CONFIG_INT(ClCustomizeSkin, cl_customize_skin, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "") MACRO_CONFIG_INT(EdShowkeys, ed_showkeys, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "") //MACRO_CONFIG_INT(ClFlow, cl_flow, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "") MACRO_CONFIG_INT(ClShowWelcome, cl_show_welcome, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "") MACRO_CONFIG_INT(ClMotdTime, cl_motd_time, 10, 0, 100, CFGFLAG_CLIENT|CFGFLAG_SAVE, "How long to show the server message of the day") MACRO_CONFIG_STR(ClVersionServer, cl_version_server, 100, "version.teeworlds.com", CFGFLAG_CLIENT|CFGFLAG_SAVE, "Server to use to check for new versions") MACRO_CONFIG_STR(ClFontfile, cl_fontfile, 255, "DejaVuSans.ttf", CFGFLAG_CLIENT|CFGFLAG_SAVE, "What font file to use") MACRO_CONFIG_STR(ClLanguagefile, cl_languagefile, 255, "", CFGFLAG_CLIENT|CFGFLAG_SAVE, "What language file to use") MACRO_CONFIG_INT(PlayerColorBody, player_color_body, 0x1B6F74, 0, 0xFFFFFF, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Player body color") MACRO_CONFIG_INT(PlayerColorTattoo, player_color_tattoo, 0xFF0000FF, 0, 0, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Player tattoo color") MACRO_CONFIG_INT(PlayerColorDecoration, player_color_decoration, 0x1B6F74, 0, 0xFFFFFF, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Player decoration color") MACRO_CONFIG_INT(PlayerColorHands, player_color_hands, 0x1B759E, 0, 0xFFFFFF, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Player hands color") MACRO_CONFIG_INT(PlayerColorFeet, player_color_feet, 0x1C873E, 0, 0xFFFFFF, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Player feet color") MACRO_CONFIG_INT(PlayerColorEyes, player_color_eyes, 0x0000FF, 0, 0xFFFFFF, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Player eyes color") MACRO_CONFIG_INT(PlayerUseCustomColorBody, player_use_custom_color_body, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Toggles usage of custom colors for body") MACRO_CONFIG_INT(PlayerUseCustomColorTattoo, player_use_custom_color_tattoo, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Toggles usage of custom colors for tattoo") MACRO_CONFIG_INT(PlayerUseCustomColorDecoration, player_use_custom_color_decoration, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Toggles usage of custom colors for decoration") MACRO_CONFIG_INT(PlayerUseCustomColorHands, player_use_custom_color_hands, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Toggles usage of custom colors for hands") MACRO_CONFIG_INT(PlayerUseCustomColorFeet, player_use_custom_color_feet, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Toggles usage of custom colors for feet") MACRO_CONFIG_INT(PlayerUseCustomColorEyes, player_use_custom_color_eyes, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Toggles usage of custom colors for eyes") MACRO_CONFIG_STR(PlayerSkin, player_skin, 24, "default", CFGFLAG_CLIENT|CFGFLAG_SAVE, "Player skin") MACRO_CONFIG_STR(PlayerSkinBody, player_skin_body, 24, "standard", CFGFLAG_CLIENT|CFGFLAG_SAVE, "Player skin body") MACRO_CONFIG_STR(PlayerSkinTattoo, player_skin_tattoo, 24, "", CFGFLAG_CLIENT|CFGFLAG_SAVE, "Player skin tattoo") MACRO_CONFIG_STR(PlayerSkinDecoration, player_skin_decoration, 24, "", CFGFLAG_CLIENT|CFGFLAG_SAVE, "Player skin decoration") MACRO_CONFIG_STR(PlayerSkinHands, player_skin_hands, 24, "standard", CFGFLAG_CLIENT|CFGFLAG_SAVE, "Player skin hands") MACRO_CONFIG_STR(PlayerSkinFeet, player_skin_feet, 24, "standard", CFGFLAG_CLIENT|CFGFLAG_SAVE, "Player skin feet") MACRO_CONFIG_STR(PlayerSkinEyes, player_skin_eyes, 24, "standard", CFGFLAG_CLIENT|CFGFLAG_SAVE, "Player skin eyes") //MACRO_CONFIG_INT(UiPage, ui_page, 6, 0, 10, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Interface page") MACRO_CONFIG_INT(UiBrowserPage, ui_browser_page, 5, 5, 8, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Interface serverbrowser page") MACRO_CONFIG_INT(UiSettingsPage, ui_settings_page, 0, 0, 5, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Interface settings page") //MACRO_CONFIG_INT(UiToolboxPage, ui_toolbox_page, 0, 0, 2, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Toolbox page") MACRO_CONFIG_STR(UiServerAddress, ui_server_address, 64, "localhost:8303", CFGFLAG_CLIENT|CFGFLAG_SAVE, "Interface server address") MACRO_CONFIG_INT(UiMousesens, ui_mousesens, 100, 5, 100000, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Mouse sensitivity for menus/editor") MACRO_CONFIG_INT(GfxNoclip, gfx_noclip, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Disable clipping") MACRO_CONFIG_STR(ClBackgroundMap, cl_background_map, 64, "menu_night", CFGFLAG_CLIENT|CFGFLAG_SAVE, "Background map") MACRO_CONFIG_INT(ClRotationRadius, cl_rotation_radius, 30, 1, 500, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Camera rotation radius") MACRO_CONFIG_INT(ClRotationSpeed, cl_rotation_speed, 40, 1, 120, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Camera rotations in seconds") MACRO_CONFIG_INT(ClShowStartMenuImages, cl_show_start_menu_images, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show start menu images") // server MACRO_CONFIG_INT(SvWarmup, sv_warmup, 0, -1, 1000, CFGFLAG_SERVER, "Number of seconds to do warmup before match starts (0 disables, -1 all players ready)") MACRO_CONFIG_STR(SvMotd, sv_motd, 900, "", CFGFLAG_SERVER, "Message of the day to display for the clients") MACRO_CONFIG_INT(SvTeamdamage, sv_teamdamage, 0, 0, 1, CFGFLAG_SERVER, "Team damage") MACRO_CONFIG_STR(SvMaprotation, sv_maprotation, 768, "", CFGFLAG_SERVER, "Maps to rotate between") MACRO_CONFIG_INT(SvMatchesPerMap, sv_matches_per_map, 1, 1, 100, CFGFLAG_SERVER, "Number of matches on each map before rotating") MACRO_CONFIG_INT(SvMatchSwap, sv_match_swap, 1, 0, 1, CFGFLAG_SERVER, "Swap teams between matches") MACRO_CONFIG_INT(SvPowerups, sv_powerups, 1, 0, 1, CFGFLAG_SERVER, "Allow powerups like ninja") MACRO_CONFIG_INT(SvScorelimit, sv_scorelimit, 20, 0, 1000, CFGFLAG_SERVER, "Score limit (0 disables)") MACRO_CONFIG_INT(SvTimelimit, sv_timelimit, 0, 0, 1000, CFGFLAG_SERVER, "Time limit in minutes (0 disables)") MACRO_CONFIG_STR(SvGametype, sv_gametype, 32, "dm", CFGFLAG_SERVER, "Game type (dm, tdm, ctf, lms, sur)") MACRO_CONFIG_INT(SvTournamentMode, sv_tournament_mode, 0, 0, 1, CFGFLAG_SERVER, "Tournament mode. When enabled, players joins the server as spectator") MACRO_CONFIG_INT(SvPlayerReadyMode, sv_player_ready_mode, 0, 0, 1, CFGFLAG_SERVER, "When enabled, players can pause/unpause the game and start the game on warmup via their ready state") MACRO_CONFIG_INT(SvSpamprotection, sv_spamprotection, 1, 0, 1, CFGFLAG_SERVER, "Spam protection") MACRO_CONFIG_INT(SvRespawnDelayTDM, sv_respawn_delay_tdm, 3, 0, 10, CFGFLAG_SERVER, "Time needed to respawn after death in tdm gametype") MACRO_CONFIG_INT(SvSpectatorSlots, sv_spectator_slots, 0, 0, MAX_CLIENTS, CFGFLAG_SERVER, "Number of slots to reserve for spectators") MACRO_CONFIG_INT(SvSkillLevel, sv_skill_level, 1, SERVERINFO_LEVEL_MIN, SERVERINFO_LEVEL_MAX, CFGFLAG_SERVER, "Supposed player skill level") MACRO_CONFIG_INT(SvTeambalanceTime, sv_teambalance_time, 1, 0, 1000, CFGFLAG_SERVER, "How many minutes to wait before autobalancing teams") MACRO_CONFIG_INT(SvInactiveKickTime, sv_inactivekick_time, 3, 0, 1000, CFGFLAG_SERVER, "How many minutes to wait before taking care of inactive players") MACRO_CONFIG_INT(SvInactiveKick, sv_inactivekick, 1, 0, 2, CFGFLAG_SERVER, "How to deal with inactive players (0=move to spectator, 1=move to free spectator slot/kick, 2=kick)") MACRO_CONFIG_INT(SvStrictSpectateMode, sv_strict_spectate_mode, 0, 0, 1, CFGFLAG_SERVER, "Restricts information in spectator mode") MACRO_CONFIG_INT(SvVoteSpectate, sv_vote_spectate, 1, 0, 1, CFGFLAG_SERVER, "Allow voting to move players to spectators") MACRO_CONFIG_INT(SvVoteSpectateRejoindelay, sv_vote_spectate_rejoindelay, 3, 0, 1000, CFGFLAG_SERVER, "How many minutes to wait before a player can rejoin after being moved to spectators by vote") MACRO_CONFIG_INT(SvVoteKick, sv_vote_kick, 1, 0, 1, CFGFLAG_SERVER, "Allow voting to kick players") MACRO_CONFIG_INT(SvVoteKickMin, sv_vote_kick_min, 0, 0, MAX_CLIENTS, CFGFLAG_SERVER, "Minimum number of players required to start a kick vote") MACRO_CONFIG_INT(SvVoteKickBantime, sv_vote_kick_bantime, 5, 0, 1440, CFGFLAG_SERVER, "The time to ban a player if kicked by vote. 0 makes it just use kick") // debug #ifdef CONF_DEBUG // this one can crash the server if not used correctly MACRO_CONFIG_INT(DbgDummies, dbg_dummies, 0, 0, 15, CFGFLAG_SERVER, "") #endif MACRO_CONFIG_INT(DbgFocus, dbg_focus, 0, 0, 1, CFGFLAG_CLIENT, "") MACRO_CONFIG_INT(DbgTuning, dbg_tuning, 0, 0, 1, CFGFLAG_CLIENT, "") #endif ================================================ FILE: src/game/version.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_VERSION_H #define GAME_VERSION_H #include "generated/nethash.cpp" #define GAME_VERSION "0.7 trunk" #define GAME_NETVERSION "0.7 " GAME_NETVERSION_HASH static const char GAME_RELEASE_VERSION[8] = {'0', '.', '6', '1', 0}; #endif ================================================ FILE: src/game/voting.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_VOTING_H #define GAME_VOTING_H enum { VOTE_DESC_LENGTH=64, VOTE_CMD_LENGTH=512, VOTE_REASON_LENGTH=16, MAX_VOTE_OPTIONS=128, MAX_VOTE_OPTION_ADD=21, VOTE_COOLDOWN=60, }; struct CVoteOptionClient { CVoteOptionClient *m_pNext; CVoteOptionClient *m_pPrev; char m_aDescription[VOTE_DESC_LENGTH]; }; struct CVoteOptionServer { CVoteOptionServer *m_pNext; CVoteOptionServer *m_pPrev; char m_aDescription[VOTE_DESC_LENGTH]; char m_aCommand[1]; }; #endif ================================================ FILE: src/mastersrv/mastersrv.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <base/system.h> #include <engine/config.h> #include <engine/console.h> #include <engine/kernel.h> #include <engine/storage.h> #include <engine/shared/config.h> #include <engine/shared/netban.h> #include <engine/shared/network.h> #include "mastersrv.h" enum { MTU = 1400, MAX_SERVERS_PER_PACKET=75, MAX_PACKETS=16, MAX_SERVERS=MAX_SERVERS_PER_PACKET*MAX_PACKETS, EXPIRE_TIME = 90 }; struct CCheckServer { enum ServerType m_Type; NETADDR m_Address; NETADDR m_AltAddress; int m_TryCount; int64 m_TryTime; }; static CCheckServer m_aCheckServers[MAX_SERVERS]; static int m_NumCheckServers = 0; struct CServerEntry { enum ServerType m_Type; NETADDR m_Address; int64 m_Expire; }; static CServerEntry m_aServers[MAX_SERVERS]; static int m_NumServers = 0; struct CPacketData { int m_Size; struct { unsigned char m_aHeader[sizeof(SERVERBROWSE_LIST)]; CMastersrvAddr m_aServers[MAX_SERVERS_PER_PACKET]; } m_Data; }; CPacketData m_aPackets[MAX_PACKETS]; static int m_NumPackets = 0; // legacy code struct CPacketDataLegacy { int m_Size; struct { unsigned char m_aHeader[sizeof(SERVERBROWSE_LIST_LEGACY)]; CMastersrvAddrLegacy m_aServers[MAX_SERVERS_PER_PACKET]; } m_Data; }; CPacketDataLegacy m_aPacketsLegacy[MAX_PACKETS]; static int m_NumPacketsLegacy = 0; struct CCountPacketData { unsigned char m_Header[sizeof(SERVERBROWSE_COUNT)]; unsigned char m_High; unsigned char m_Low; }; static CCountPacketData m_CountData; static CCountPacketData m_CountDataLegacy; CNetBan m_NetBan; static CNetClient m_NetChecker; // NAT/FW checker static CNetClient m_NetOp; // main IConsole *m_pConsole; void BuildPackets() { CServerEntry *pCurrent = &m_aServers[0]; int ServersLeft = m_NumServers; m_NumPackets = 0; m_NumPacketsLegacy = 0; int PacketIndex = 0; int PacketIndexLegacy = 0; while(ServersLeft-- && (m_NumPackets + m_NumPacketsLegacy) < MAX_PACKETS) { if(pCurrent->m_Type == SERVERTYPE_NORMAL) { if(PacketIndex % MAX_SERVERS_PER_PACKET == 0) { PacketIndex = 0; m_NumPackets++; } // copy header mem_copy(m_aPackets[m_NumPackets-1].m_Data.m_aHeader, SERVERBROWSE_LIST, sizeof(SERVERBROWSE_LIST)); // copy server addresses if(pCurrent->m_Address.type == NETTYPE_IPV6) { mem_copy(m_aPackets[m_NumPackets-1].m_Data.m_aServers[PacketIndex].m_aIp, pCurrent->m_Address.ip, sizeof(m_aPackets[m_NumPackets-1].m_Data.m_aServers[PacketIndex].m_aIp)); } else { static unsigned char s_aIPV4Mapping[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF}; mem_copy(m_aPackets[m_NumPackets-1].m_Data.m_aServers[PacketIndex].m_aIp, s_aIPV4Mapping, sizeof(s_aIPV4Mapping)); m_aPackets[m_NumPackets-1].m_Data.m_aServers[PacketIndex].m_aIp[12] = pCurrent->m_Address.ip[0]; m_aPackets[m_NumPackets-1].m_Data.m_aServers[PacketIndex].m_aIp[13] = pCurrent->m_Address.ip[1]; m_aPackets[m_NumPackets-1].m_Data.m_aServers[PacketIndex].m_aIp[14] = pCurrent->m_Address.ip[2]; m_aPackets[m_NumPackets-1].m_Data.m_aServers[PacketIndex].m_aIp[15] = pCurrent->m_Address.ip[3]; } m_aPackets[m_NumPackets-1].m_Data.m_aServers[PacketIndex].m_aPort[0] = (pCurrent->m_Address.port>>8)&0xff; m_aPackets[m_NumPackets-1].m_Data.m_aServers[PacketIndex].m_aPort[1] = pCurrent->m_Address.port&0xff; PacketIndex++; m_aPackets[m_NumPackets-1].m_Size = sizeof(SERVERBROWSE_LIST) + sizeof(CMastersrvAddr)*PacketIndex; pCurrent++; } else if(pCurrent->m_Type == SERVERTYPE_LEGACY) { if(PacketIndexLegacy % MAX_SERVERS_PER_PACKET == 0) { PacketIndexLegacy = 0; m_NumPacketsLegacy++; } // copy header mem_copy(m_aPacketsLegacy[m_NumPacketsLegacy-1].m_Data.m_aHeader, SERVERBROWSE_LIST_LEGACY, sizeof(SERVERBROWSE_LIST_LEGACY)); // copy server addresses mem_copy(m_aPacketsLegacy[m_NumPacketsLegacy-1].m_Data.m_aServers[PacketIndexLegacy].m_aIp, pCurrent->m_Address.ip, sizeof(m_aPacketsLegacy[m_NumPacketsLegacy-1].m_Data.m_aServers[PacketIndexLegacy].m_aIp)); // 0.5 has the port in little endian on the network m_aPacketsLegacy[m_NumPacketsLegacy-1].m_Data.m_aServers[PacketIndexLegacy].m_aPort[0] = pCurrent->m_Address.port&0xff; m_aPacketsLegacy[m_NumPacketsLegacy-1].m_Data.m_aServers[PacketIndexLegacy].m_aPort[1] = (pCurrent->m_Address.port>>8)&0xff; PacketIndexLegacy++; m_aPacketsLegacy[m_NumPacketsLegacy-1].m_Size = sizeof(SERVERBROWSE_LIST_LEGACY) + sizeof(CMastersrvAddrLegacy)*PacketIndexLegacy; pCurrent++; } else { *pCurrent = m_aServers[m_NumServers-1]; m_NumServers--; dbg_msg("mastersrv", "error: server of invalid type, dropping it"); } } } void SendOk(NETADDR *pAddr) { CNetChunk p; p.m_ClientID = -1; p.m_Address = *pAddr; p.m_Flags = NETSENDFLAG_CONNLESS; p.m_DataSize = sizeof(SERVERBROWSE_FWOK); p.m_pData = SERVERBROWSE_FWOK; // send on both to be sure m_NetChecker.Send(&p); m_NetOp.Send(&p); } void SendError(NETADDR *pAddr) { CNetChunk p; p.m_ClientID = -1; p.m_Address = *pAddr; p.m_Flags = NETSENDFLAG_CONNLESS; p.m_DataSize = sizeof(SERVERBROWSE_FWERROR); p.m_pData = SERVERBROWSE_FWERROR; m_NetOp.Send(&p); } void SendCheck(NETADDR *pAddr) { CNetChunk p; p.m_ClientID = -1; p.m_Address = *pAddr; p.m_Flags = NETSENDFLAG_CONNLESS; p.m_DataSize = sizeof(SERVERBROWSE_FWCHECK); p.m_pData = SERVERBROWSE_FWCHECK; m_NetChecker.Send(&p); } void AddCheckserver(NETADDR *pInfo, NETADDR *pAlt, ServerType Type) { // add server if(m_NumCheckServers == MAX_SERVERS) { dbg_msg("mastersrv", "error: mastersrv is full"); return; } char aAddrStr[NETADDR_MAXSTRSIZE]; net_addr_str(pInfo, aAddrStr, sizeof(aAddrStr), true); char aAltAddrStr[NETADDR_MAXSTRSIZE]; net_addr_str(pAlt, aAltAddrStr, sizeof(aAltAddrStr), true); dbg_msg("mastersrv", "checking: %s (%s)", aAddrStr, aAltAddrStr); m_aCheckServers[m_NumCheckServers].m_Address = *pInfo; m_aCheckServers[m_NumCheckServers].m_AltAddress = *pAlt; m_aCheckServers[m_NumCheckServers].m_TryCount = 0; m_aCheckServers[m_NumCheckServers].m_TryTime = 0; m_aCheckServers[m_NumCheckServers].m_Type = Type; m_NumCheckServers++; } void AddServer(NETADDR *pInfo, ServerType Type) { // see if server already exists in list for(int i = 0; i < m_NumServers; i++) { if(net_addr_comp(&m_aServers[i].m_Address, pInfo) == 0) { char aAddrStr[NETADDR_MAXSTRSIZE]; net_addr_str(pInfo, aAddrStr, sizeof(aAddrStr), true); dbg_msg("mastersrv", "updated: %s", aAddrStr); m_aServers[i].m_Expire = time_get()+time_freq()*EXPIRE_TIME; return; } } // add server if(m_NumServers == MAX_SERVERS) { dbg_msg("mastersrv", "error: mastersrv is full"); return; } char aAddrStr[NETADDR_MAXSTRSIZE]; net_addr_str(pInfo, aAddrStr, sizeof(aAddrStr), true); dbg_msg("mastersrv", "added: %s", aAddrStr); m_aServers[m_NumServers].m_Address = *pInfo; m_aServers[m_NumServers].m_Expire = time_get()+time_freq()*EXPIRE_TIME; m_aServers[m_NumServers].m_Type = Type; m_NumServers++; } void UpdateServers() { int64 Now = time_get(); int64 Freq = time_freq(); for(int i = 0; i < m_NumCheckServers; i++) { if(Now > m_aCheckServers[i].m_TryTime+Freq) { if(m_aCheckServers[i].m_TryCount == 10) { char aAddrStr[NETADDR_MAXSTRSIZE]; net_addr_str(&m_aCheckServers[i].m_Address, aAddrStr, sizeof(aAddrStr), true); char aAltAddrStr[NETADDR_MAXSTRSIZE]; net_addr_str(&m_aCheckServers[i].m_AltAddress, aAltAddrStr, sizeof(aAltAddrStr), true); dbg_msg("mastersrv", "check failed: %s (%s)", aAddrStr, aAltAddrStr); // FAIL!! SendError(&m_aCheckServers[i].m_Address); m_aCheckServers[i] = m_aCheckServers[m_NumCheckServers-1]; m_NumCheckServers--; i--; } else { m_aCheckServers[i].m_TryCount++; m_aCheckServers[i].m_TryTime = Now; if(m_aCheckServers[i].m_TryCount&1) SendCheck(&m_aCheckServers[i].m_Address); else SendCheck(&m_aCheckServers[i].m_AltAddress); } } } } void PurgeServers() { int64 Now = time_get(); int i = 0; while(i < m_NumServers) { if(m_aServers[i].m_Expire < Now) { // remove server char aAddrStr[NETADDR_MAXSTRSIZE]; net_addr_str(&m_aServers[i].m_Address, aAddrStr, sizeof(aAddrStr), true); dbg_msg("mastersrv", "expired: %s", aAddrStr); m_aServers[i] = m_aServers[m_NumServers-1]; m_NumServers--; } else i++; } } void ReloadBans() { m_NetBan.UnbanAll(); m_pConsole->ExecuteFile("master.cfg"); } int main(int argc, const char **argv) // ignore_convention { int64 LastBuild = 0, LastBanReload = 0; ServerType Type = SERVERTYPE_INVALID; NETADDR BindAddr; dbg_logger_stdout(); net_init(); mem_copy(m_CountData.m_Header, SERVERBROWSE_COUNT, sizeof(SERVERBROWSE_COUNT)); mem_copy(m_CountDataLegacy.m_Header, SERVERBROWSE_COUNT_LEGACY, sizeof(SERVERBROWSE_COUNT_LEGACY)); IKernel *pKernel = IKernel::Create(); IStorage *pStorage = CreateStorage("Teeworlds", IStorage::STORAGETYPE_BASIC, argc, argv); IConfig *pConfig = CreateConfig(); m_pConsole = CreateConsole(CFGFLAG_MASTER); bool RegisterFail = !pKernel->RegisterInterface(pStorage); RegisterFail |= !pKernel->RegisterInterface(m_pConsole); RegisterFail |= !pKernel->RegisterInterface(pConfig); if(RegisterFail) return -1; pConfig->Init(); m_NetBan.Init(m_pConsole, pStorage); if(argc > 1) // ignore_convention m_pConsole->ParseArguments(argc-1, &argv[1]); // ignore_convention if(g_Config.m_Bindaddr[0] && net_host_lookup(g_Config.m_Bindaddr, &BindAddr, NETTYPE_ALL) == 0) { // got bindaddr BindAddr.type = NETTYPE_ALL; BindAddr.port = MASTERSERVER_PORT; } else { mem_zero(&BindAddr, sizeof(BindAddr)); BindAddr.type = NETTYPE_ALL; BindAddr.port = MASTERSERVER_PORT; } if(!m_NetOp.Open(BindAddr, 0)) { dbg_msg("mastersrv", "couldn't start network (op)"); return -1; } BindAddr.port = MASTERSERVER_PORT+1; if(!m_NetChecker.Open(BindAddr, 0)) { dbg_msg("mastersrv", "couldn't start network (checker)"); return -1; } // process pending commands m_pConsole->StoreCommands(false); dbg_msg("mastersrv", "started"); while(1) { m_NetOp.Update(); m_NetChecker.Update(); // process m_aPackets CNetChunk Packet; while(m_NetOp.Recv(&Packet)) { // check if the server is banned if(m_NetBan.IsBanned(&Packet.m_Address, 0, 0)) continue; if(Packet.m_DataSize == sizeof(SERVERBROWSE_HEARTBEAT)+2 && mem_comp(Packet.m_pData, SERVERBROWSE_HEARTBEAT, sizeof(SERVERBROWSE_HEARTBEAT)) == 0) { NETADDR Alt; unsigned char *d = (unsigned char *)Packet.m_pData; Alt = Packet.m_Address; Alt.port = (d[sizeof(SERVERBROWSE_HEARTBEAT)]<<8) | d[sizeof(SERVERBROWSE_HEARTBEAT)+1]; // add it AddCheckserver(&Packet.m_Address, &Alt, SERVERTYPE_NORMAL); } else if(Packet.m_DataSize == sizeof(SERVERBROWSE_HEARTBEAT_LEGACY)+2 && mem_comp(Packet.m_pData, SERVERBROWSE_HEARTBEAT_LEGACY, sizeof(SERVERBROWSE_HEARTBEAT_LEGACY)) == 0) { NETADDR Alt; unsigned char *d = (unsigned char *)Packet.m_pData; Alt = Packet.m_Address; Alt.port = (d[sizeof(SERVERBROWSE_HEARTBEAT)]<<8) | d[sizeof(SERVERBROWSE_HEARTBEAT)+1]; // add it AddCheckserver(&Packet.m_Address, &Alt, SERVERTYPE_LEGACY); } else if(Packet.m_DataSize == sizeof(SERVERBROWSE_GETCOUNT) && mem_comp(Packet.m_pData, SERVERBROWSE_GETCOUNT, sizeof(SERVERBROWSE_GETCOUNT)) == 0) { dbg_msg("mastersrv", "count requested, responding with %d", m_NumServers); CNetChunk p; p.m_ClientID = -1; p.m_Address = Packet.m_Address; p.m_Flags = NETSENDFLAG_CONNLESS; p.m_DataSize = sizeof(m_CountData); p.m_pData = &m_CountData; m_CountData.m_High = (m_NumServers>>8)&0xff; m_CountData.m_Low = m_NumServers&0xff; m_NetOp.Send(&p); } else if(Packet.m_DataSize == sizeof(SERVERBROWSE_GETCOUNT_LEGACY) && mem_comp(Packet.m_pData, SERVERBROWSE_GETCOUNT_LEGACY, sizeof(SERVERBROWSE_GETCOUNT_LEGACY)) == 0) { dbg_msg("mastersrv", "count requested, responding with %d", m_NumServers); CNetChunk p; p.m_ClientID = -1; p.m_Address = Packet.m_Address; p.m_Flags = NETSENDFLAG_CONNLESS; p.m_DataSize = sizeof(m_CountData); p.m_pData = &m_CountDataLegacy; m_CountDataLegacy.m_High = (m_NumServers>>8)&0xff; m_CountDataLegacy.m_Low = m_NumServers&0xff; m_NetOp.Send(&p); } else if(Packet.m_DataSize == sizeof(SERVERBROWSE_GETLIST) && mem_comp(Packet.m_pData, SERVERBROWSE_GETLIST, sizeof(SERVERBROWSE_GETLIST)) == 0) { // someone requested the list dbg_msg("mastersrv", "requested, responding with %d m_aServers", m_NumServers); CNetChunk p; p.m_ClientID = -1; p.m_Address = Packet.m_Address; p.m_Flags = NETSENDFLAG_CONNLESS; for(int i = 0; i < m_NumPackets; i++) { p.m_DataSize = m_aPackets[i].m_Size; p.m_pData = &m_aPackets[i].m_Data; m_NetOp.Send(&p); } } else if(Packet.m_DataSize == sizeof(SERVERBROWSE_GETLIST_LEGACY) && mem_comp(Packet.m_pData, SERVERBROWSE_GETLIST_LEGACY, sizeof(SERVERBROWSE_GETLIST_LEGACY)) == 0) { // someone requested the list dbg_msg("mastersrv", "requested, responding with %d m_aServers", m_NumServers); CNetChunk p; p.m_ClientID = -1; p.m_Address = Packet.m_Address; p.m_Flags = NETSENDFLAG_CONNLESS; for(int i = 0; i < m_NumPacketsLegacy; i++) { p.m_DataSize = m_aPacketsLegacy[i].m_Size; p.m_pData = &m_aPacketsLegacy[i].m_Data; m_NetOp.Send(&p); } } } // process m_aPackets while(m_NetChecker.Recv(&Packet)) { // check if the server is banned if(m_NetBan.IsBanned(&Packet.m_Address, 0, 0)) continue; if(Packet.m_DataSize == sizeof(SERVERBROWSE_FWRESPONSE) && mem_comp(Packet.m_pData, SERVERBROWSE_FWRESPONSE, sizeof(SERVERBROWSE_FWRESPONSE)) == 0) { Type = SERVERTYPE_INVALID; // remove it from checking for(int i = 0; i < m_NumCheckServers; i++) { if(net_addr_comp(&m_aCheckServers[i].m_Address, &Packet.m_Address) == 0 || net_addr_comp(&m_aCheckServers[i].m_AltAddress, &Packet.m_Address) == 0) { Type = m_aCheckServers[i].m_Type; m_NumCheckServers--; m_aCheckServers[i] = m_aCheckServers[m_NumCheckServers]; break; } } // drops servers that were not in the CheckServers list if(Type == SERVERTYPE_INVALID) continue; AddServer(&Packet.m_Address, Type); SendOk(&Packet.m_Address); } } if(time_get()-LastBanReload > time_freq()*300) { LastBanReload = time_get(); ReloadBans(); } if(time_get()-LastBuild > time_freq()*5) { LastBuild = time_get(); PurgeServers(); UpdateServers(); BuildPackets(); } // be nice to the CPU thread_sleep(1); } return 0; } ================================================ FILE: src/mastersrv/mastersrv.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef MASTERSRV_MASTERSRV_H #define MASTERSRV_MASTERSRV_H static const int MASTERSERVER_PORT = 8300; enum ServerType { SERVERTYPE_INVALID = -1, SERVERTYPE_NORMAL, SERVERTYPE_LEGACY }; struct CMastersrvAddr { unsigned char m_aIp[16]; unsigned char m_aPort[2]; }; static const unsigned char SERVERBROWSE_HEARTBEAT[] = {255, 255, 255, 255, 'b', 'e', 'a', '2'}; static const unsigned char SERVERBROWSE_GETLIST[] = {255, 255, 255, 255, 'r', 'e', 'q', '2'}; static const unsigned char SERVERBROWSE_LIST[] = {255, 255, 255, 255, 'l', 'i', 's', '2'}; static const unsigned char SERVERBROWSE_GETCOUNT[] = {255, 255, 255, 255, 'c', 'o', 'u', '2'}; static const unsigned char SERVERBROWSE_COUNT[] = {255, 255, 255, 255, 's', 'i', 'z', '2'}; static const unsigned char SERVERBROWSE_GETINFO[] = {255, 255, 255, 255, 'g', 'i', 'e', '3'}; static const unsigned char SERVERBROWSE_INFO[] = {255, 255, 255, 255, 'i', 'n', 'f', '3'}; static const unsigned char SERVERBROWSE_FWCHECK[] = {255, 255, 255, 255, 'f', 'w', '?', '?'}; static const unsigned char SERVERBROWSE_FWRESPONSE[] = {255, 255, 255, 255, 'f', 'w', '!', '!'}; static const unsigned char SERVERBROWSE_FWOK[] = {255, 255, 255, 255, 'f', 'w', 'o', 'k'}; static const unsigned char SERVERBROWSE_FWERROR[] = {255, 255, 255, 255, 'f', 'w', 'e', 'r'}; // packet headers for the 0.5 branch struct CMastersrvAddrLegacy { unsigned char m_aIp[4]; unsigned char m_aPort[2]; }; static const unsigned char SERVERBROWSE_HEARTBEAT_LEGACY[] = {255, 255, 255, 255, 'b', 'e', 'a', 't'}; static const unsigned char SERVERBROWSE_GETLIST_LEGACY[] = {255, 255, 255, 255, 'r', 'e', 'q', 't'}; static const unsigned char SERVERBROWSE_LIST_LEGACY[] = {255, 255, 255, 255, 'l', 'i', 's', 't'}; static const unsigned char SERVERBROWSE_GETCOUNT_LEGACY[] = {255, 255, 255, 255, 'c', 'o', 'u', 'n'}; static const unsigned char SERVERBROWSE_COUNT_LEGACY[] = {255, 255, 255, 255, 's', 'i', 'z', 'e'}; #endif ================================================ FILE: src/osxlaunch/client.h ================================================ #ifndef OSXLAUNCH_CLIENT_H #define OSXLAUNCH_CLIENT_H /* SDLMain.m - main entry point for our Cocoa-ized SDL app Initial Version: Darrell Walisser <dwaliss1@purdue.edu> Non-NIB-Code & other changes: Max Horn <max@quendi.de> Feel free to customize this file to suit your needs */ #import <Cocoa/Cocoa.h> @interface SDLMain : NSObject @end #endif ================================================ FILE: src/osxlaunch/client.m ================================================ /* SDLMain.m - main entry point for our Cocoa-ized SDL app Initial Version: Darrell Walisser <dwaliss1@purdue.edu> Non-NIB-Code & other changes: Max Horn <max@quendi.de> Feel free to customize this file to suit your needs */ #import <SDL.h> #import "client.h" #import <sys/param.h> /* for MAXPATHLEN */ #import <unistd.h> /* For some reaon, Apple removed setAppleMenu from the headers in 10.4, but the method still is there and works. To avoid warnings, we declare it ourselves here. */ @interface NSApplication(SDL_Missing_Methods) - (void)setAppleMenu:(NSMenu *)menu; @end /* Use this flag to determine whether we use SDLMain.nib or not */ #define SDL_USE_NIB_FILE 0 /* Use this flag to determine whether we use CPS (docking) or not */ #define SDL_USE_CPS 1 #ifdef SDL_USE_CPS /* Portions of CPS.h */ typedef struct CPSProcessSerNum { UInt32 lo; UInt32 hi; } CPSProcessSerNum; extern OSErr CPSGetCurrentProcess( CPSProcessSerNum *psn); extern OSErr CPSEnableForegroundOperation( CPSProcessSerNum *psn, UInt32 _arg2, UInt32 _arg3, UInt32 _arg4, UInt32 _arg5); extern OSErr CPSSetFrontProcess( CPSProcessSerNum *psn); #endif /* SDL_USE_CPS */ static int gArgc; static char **gArgv; static BOOL gFinderLaunch; static BOOL gCalledAppMainline = FALSE; static NSString *getApplicationName(void) { NSDictionary *dict; NSString *appName = 0; /* Determine the application name */ dict = (NSDictionary *)CFBundleGetInfoDictionary(CFBundleGetMainBundle()); if (dict) appName = [dict objectForKey: @"CFBundleName"]; if (![appName length]) appName = [[NSProcessInfo processInfo] processName]; return appName; } #if SDL_USE_NIB_FILE /* A helper category for NSString */ @interface NSString (ReplaceSubString) - (NSString *)stringByReplacingRange:(NSRange)aRange with:(NSString *)aString; @end #endif @interface SDLApplication : NSApplication @end @implementation SDLApplication /* Invoked from the Quit menu item */ - (void)terminate:(id)sender { /* Post a SDL_QUIT event */ SDL_Event event; event.type = SDL_QUIT; SDL_PushEvent(&event); } @end /* The main class of the application, the application's delegate */ @implementation SDLMain /* Set the working directory to the .app's parent directory */ - (void) setupWorkingDirectory:(BOOL)shouldChdir { NSString *resourcePath = [[NSBundle mainBundle] resourcePath]; [[NSFileManager defaultManager] changeCurrentDirectoryPath:resourcePath]; } #if SDL_USE_NIB_FILE /* Fix menu to contain the real app name instead of "SDL App" */ - (void)fixMenu:(NSMenu *)aMenu withAppName:(NSString *)appName { NSRange aRange; NSEnumerator *enumerator; NSMenuItem *menuItem; aRange = [[aMenu title] rangeOfString:@"SDL App"]; if (aRange.length != 0) [aMenu setTitle: [[aMenu title] stringByReplacingRange:aRange with:appName]]; enumerator = [[aMenu itemArray] objectEnumerator]; while ((menuItem = [enumerator nextObject])) { aRange = [[menuItem title] rangeOfString:@"SDL App"]; if (aRange.length != 0) [menuItem setTitle: [[menuItem title] stringByReplacingRange:aRange with:appName]]; if ([menuItem hasSubmenu]) [self fixMenu:[menuItem submenu] withAppName:appName]; } [ aMenu sizeToFit ]; } #else static void setApplicationMenu(void) { /* warning: this code is very odd */ NSMenu *appleMenu; NSMenuItem *menuItem; NSString *title; NSString *appName; appName = getApplicationName(); appleMenu = [[NSMenu alloc] initWithTitle:@""]; /* Add menu items */ title = [@"About " stringByAppendingString:appName]; [appleMenu addItemWithTitle:title action:@selector(orderFrontStandardAboutPanel:) keyEquivalent:@""]; [appleMenu addItem:[NSMenuItem separatorItem]]; title = [@"Hide " stringByAppendingString:appName]; [appleMenu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h"]; menuItem = (NSMenuItem *)[appleMenu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; [menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)]; [appleMenu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; [appleMenu addItem:[NSMenuItem separatorItem]]; title = [@"Quit " stringByAppendingString:appName]; [appleMenu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q"]; /* Put menu into the menubar */ menuItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""]; [menuItem setSubmenu:appleMenu]; [[NSApp mainMenu] addItem:menuItem]; /* Tell the application object that this is now the application menu */ [NSApp setAppleMenu:appleMenu]; /* Finally give up our references to the objects */ [appleMenu release]; [menuItem release]; } /* Create a window menu */ static void setupWindowMenu(void) { NSMenu *windowMenu; NSMenuItem *windowMenuItem; NSMenuItem *menuItem; windowMenu = [[NSMenu alloc] initWithTitle:@"Window"]; /* "Minimize" item */ menuItem = [[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"]; [windowMenu addItem:menuItem]; [menuItem release]; /* Put menu into the menubar */ windowMenuItem = [[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""]; [windowMenuItem setSubmenu:windowMenu]; [[NSApp mainMenu] addItem:windowMenuItem]; /* Tell the application object that this is now the window menu */ [NSApp setWindowsMenu:windowMenu]; /* Finally give up our references to the objects */ [windowMenu release]; [windowMenuItem release]; } /* Replacement for NSApplicationMain */ static void CustomApplicationMain (int argc, char **argv) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; SDLMain *sdlMain; /* Ensure the application object is initialised */ [SDLApplication sharedApplication]; #ifdef SDL_USE_CPS { CPSProcessSerNum PSN; /* Tell the dock about us */ if (!CPSGetCurrentProcess(&PSN)) if (!CPSEnableForegroundOperation(&PSN,0x03,0x3C,0x2C,0x1103)) if (!CPSSetFrontProcess(&PSN)) [SDLApplication sharedApplication]; } #endif /* SDL_USE_CPS */ /* Set up the menubar */ [NSApp setMainMenu:[[NSMenu alloc] init]]; setApplicationMenu(); setupWindowMenu(); /* Create SDLMain and make it the app delegate */ sdlMain = [[SDLMain alloc] init]; [NSApp setDelegate:sdlMain]; /* Start the main event loop */ [NSApp run]; [sdlMain release]; [pool release]; } #endif /* * Catch document open requests...this lets us notice files when the app * was launched by double-clicking a document, or when a document was * dragged/dropped on the app's icon. You need to have a * CFBundleDocumentsType section in your Info.plist to get this message, * apparently. * * Files are added to gArgv, so to the app, they'll look like command line * arguments. Previously, apps launched from the finder had nothing but * an argv[0]. * * This message may be received multiple times to open several docs on launch. * * This message is ignored once the app's mainline has been called. */ - (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename { const char *temparg; size_t arglen; char *arg; char **newargv; if (!gFinderLaunch) /* MacOS is passing command line args. */ return FALSE; if (gCalledAppMainline) /* app has started, ignore this document. */ return FALSE; temparg = [filename UTF8String]; arglen = SDL_strlen(temparg) + 1; arg = (char *) SDL_malloc(arglen); if (arg == NULL) return FALSE; newargv = (char **) realloc(gArgv, sizeof (char *) * (gArgc + 2)); if (newargv == NULL) { SDL_free(arg); return FALSE; } gArgv = newargv; SDL_strlcpy(arg, temparg, arglen); gArgv[gArgc++] = arg; gArgv[gArgc] = NULL; return TRUE; } /* Called when the internal event loop has just started running */ - (void) applicationDidFinishLaunching: (NSNotification *) note { int status; /* Set the working directory to the .app's parent directory */ [self setupWorkingDirectory:gFinderLaunch]; #if SDL_USE_NIB_FILE /* Set the main menu to contain the real app name instead of "SDL App" */ [self fixMenu:[NSApp mainMenu] withAppName:getApplicationName()]; #endif /* Hand off to main application code */ gCalledAppMainline = TRUE; status = SDL_main (gArgc, gArgv); /* We're done, thank you for playing */ exit(status); } @end @implementation NSString (ReplaceSubString) - (NSString *)stringByReplacingRange:(NSRange)aRange with:(NSString *)aString { unsigned int bufferSize; unsigned int selfLen = [self length]; unsigned int aStringLen = [aString length]; unichar *buffer; NSRange localRange; NSString *result; bufferSize = selfLen + aStringLen - aRange.length; buffer = NSAllocateMemoryPages(bufferSize*sizeof(unichar)); /* Get first part into buffer */ localRange.location = 0; localRange.length = aRange.location; [self getCharacters:buffer range:localRange]; /* Get middle part into buffer */ localRange.location = 0; localRange.length = aStringLen; [aString getCharacters:(buffer+aRange.location) range:localRange]; /* Get last part into buffer */ localRange.location = aRange.location + aRange.length; localRange.length = selfLen - localRange.location; [self getCharacters:(buffer+aRange.location+aStringLen) range:localRange]; /* Build output string */ result = [NSString stringWithCharacters:buffer length:bufferSize]; NSDeallocateMemoryPages(buffer, bufferSize); return result; } @end #ifdef main #undef main #endif /* Main entry point to executable - should *not* be SDL_main! */ int main (int argc, char **argv) { /* Copy the arguments into a global variable */ /* This is passed if we are launched by double-clicking */ if ( argc >= 2 && strncmp (argv[1], "-psn", 4) == 0 ) { gArgv = (char **) SDL_malloc(sizeof (char *) * 2); gArgv[0] = argv[0]; gArgv[1] = NULL; gArgc = 1; gFinderLaunch = YES; } else { int i; gArgc = argc; gArgv = (char **) SDL_malloc(sizeof (char *) * (argc+1)); for (i = 0; i <= argc; i++) gArgv[i] = argv[i]; gFinderLaunch = NO; } #if SDL_USE_NIB_FILE [SDLApplication poseAsClass:[NSApplication class]]; NSApplicationMain (argc, argv); #else CustomApplicationMain (argc, argv); #endif return 0; } ================================================ FILE: src/osxlaunch/server.m ================================================ #import <Cocoa/Cocoa.h> @interface ServerView : NSTextView { NSTask *task; NSFileHandle *file; } - (void)listenTo: (NSTask*)t; @end @implementation ServerView - (void)listenTo: (NSTask*)t; { NSPipe *pipe; task = t; pipe = [NSPipe pipe]; [task setStandardOutput: pipe]; file = [pipe fileHandleForReading]; [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(outputNotification:) name: NSFileHandleReadCompletionNotification object: file]; [file readInBackgroundAndNotify]; } - (void) outputNotification: (NSNotification *) notification { NSData *data = [[[notification userInfo] objectForKey: NSFileHandleNotificationDataItem] retain]; NSString *string = [[NSString alloc] initWithData: data encoding: NSASCIIStringEncoding]; NSAttributedString *attrstr = [[NSAttributedString alloc] initWithString: string]; [[self textStorage] appendAttributedString: attrstr]; int length = [[self textStorage] length]; NSRange range = NSMakeRange(length, 0); [self scrollRangeToVisible: range]; [attrstr release]; [string release]; [file readInBackgroundAndNotify]; } -(void)windowWillClose:(NSNotification *)notification { [task terminate]; [NSApp terminate:self]; } @end void runServer() { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSApp = [NSApplication sharedApplication]; NSBundle* mainBundle = [NSBundle mainBundle]; NSTask *task; task = [[NSTask alloc] init]; [task setCurrentDirectoryPath: [mainBundle resourcePath]]; // get a server config NSOpenPanel* openDlg = [NSOpenPanel openPanel]; [openDlg setCanChooseFiles:YES]; if([openDlg runModalForDirectory:nil file:nil] != NSOKButton) return; NSArray* filenames = [openDlg filenames]; if([filenames count] != 1) return; NSString* filename = [filenames objectAtIndex: 0]; NSArray* arguments = [NSArray arrayWithObjects: @"-f", filename, nil]; // run server NSWindow *window; ServerView *view; NSRect graphicsRect; graphicsRect = NSMakeRect(100.0, 1000.0, 600.0, 400.0); window = [[NSWindow alloc] initWithContentRect: graphicsRect styleMask: NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask backing: NSBackingStoreBuffered defer: NO]; [window setTitle: @"Teeworlds Server"]; view = [[[ServerView alloc] initWithFrame: graphicsRect] autorelease]; [view setEditable: NO]; [view setRulerVisible: YES]; [window setContentView: view]; [window setDelegate: view]; [window makeKeyAndOrderFront: nil]; [view listenTo: task]; [task setLaunchPath: [mainBundle pathForAuxiliaryExecutable: @"teeworlds_srv"]]; [task setArguments: arguments]; [task launch]; [NSApp run]; [task terminate]; [NSApp release]; [pool release]; } int main (int argc, char **argv) { runServer(); return 0; } ================================================ FILE: src/tools/crapnet.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <base/system.h> #include <cstdlib> struct CPacket { CPacket *m_pPrev; CPacket *m_pNext; NETADDR m_SendTo; int64 m_Timestamp; int m_ID; int m_DataSize; char m_aData[1]; }; static CPacket *m_pFirst = (CPacket *)0; static CPacket *m_pLast = (CPacket *)0; static int m_CurrentLatency = 0; struct CPingConfig { int m_Base; int m_Flux; int m_Spike; int m_Loss; int m_Delay; int m_DelayFreq; }; static CPingConfig m_aConfigPings[] = { // base flux spike loss delay delayfreq {0, 0, 0, 0, 0, 0}, {40, 20, 100, 0, 0, 0}, {140, 40, 200, 0, 0, 0}, }; static int m_ConfigNumpingconfs = sizeof(m_aConfigPings)/sizeof(CPingConfig); static int m_ConfigInterval = 10; // seconds between different pingconfigs static int m_ConfigLog = 0; static int m_ConfigReorder = 0; void Run(unsigned short Port, NETADDR Dest) { NETADDR Src = {NETTYPE_IPV4, {0,0,0,0}, Port}; NETSOCKET Socket = net_udp_create(Src); char aBuffer[1024*2]; int ID = 0; int Delaycounter = 0; while(1) { static int Lastcfg = 0; int n = ((time_get()/time_freq())/m_ConfigInterval) % m_ConfigNumpingconfs; CPingConfig Ping = m_aConfigPings[n]; if(n != Lastcfg) dbg_msg("crapnet", "cfg = %d", n); Lastcfg = n; // handle incomming packets while(1) { // fetch data int DataTrash = 0; NETADDR From; int Bytes = net_udp_recv(Socket, &From, aBuffer, 1024*2); if(Bytes <= 0) break; if((rand()%100) < Ping.m_Loss) // drop the packet { if(m_ConfigLog) dbg_msg("crapnet", "dropped packet"); continue; } // create new packet CPacket *p = (CPacket *)mem_alloc(sizeof(CPacket)+Bytes, 1); if(net_addr_comp(&From, &Dest) == 0) p->m_SendTo = Src; // from the server else { Src = From; // from the client p->m_SendTo = Dest; } // queue packet p->m_pPrev = m_pLast; p->m_pNext = 0; if(m_pLast) m_pLast->m_pNext = p; else { m_pFirst = p; m_pLast = p; } m_pLast = p; // set data in packet p->m_Timestamp = time_get(); p->m_DataSize = Bytes; p->m_ID = ID++; mem_copy(p->m_aData, aBuffer, Bytes); if(ID > 20 && Bytes > 6 && DataTrash) { p->m_aData[6+(rand()%(Bytes-6))] = rand()&255; // modify a byte if((rand()%10) == 0) { p->m_DataSize -= rand()%32; if(p->m_DataSize < 6) p->m_DataSize = 6; } } if(Delaycounter <= 0) { if(Ping.m_Delay) p->m_Timestamp += (time_freq()*1000)/Ping.m_Delay; Delaycounter = Ping.m_DelayFreq; } Delaycounter--; if(m_ConfigLog) { char aAddrStr[NETADDR_MAXSTRSIZE]; net_addr_str(&From, aAddrStr, sizeof(aAddrStr), true); dbg_msg("crapnet", "<< %08d %s (%d)", p->m_ID, aAddrStr, p->m_DataSize); } } // /*while(1) {*/ CPacket *p = 0; CPacket *pNext = m_pFirst; while(1) { p = pNext; if(!p) break; pNext = p->m_pNext; if((time_get()-p->m_Timestamp) > m_CurrentLatency) { char aFlags[] = " "; if(m_ConfigReorder && (rand()%2) == 0 && p->m_pNext) { aFlags[0] = 'R'; p = m_pFirst->m_pNext; } if(p->m_pNext) p->m_pNext->m_pPrev = p->m_pPrev; else m_pLast = p->m_pPrev; if(p->m_pPrev) p->m_pPrev->m_pNext = p->m_pNext; else m_pFirst = p->m_pNext; /*CPacket *cur = first; while(cur) { dbg_assert(cur != p, "p still in list"); cur = cur->next; }*/ // send and remove packet //if((rand()%20) != 0) // heavy packetloss net_udp_send(Socket, &p->m_SendTo, p->m_aData, p->m_DataSize); // update lag double Flux = rand()/(double)RAND_MAX; int MsSpike = Ping.m_Spike; int MsFlux = Ping.m_Flux; int MsPing = Ping.m_Base; m_CurrentLatency = ((time_freq()*MsPing)/1000) + (int64)(((time_freq()*MsFlux)/1000)*Flux); // 50ms if(MsSpike && (p->m_ID%100) == 0) { m_CurrentLatency += (time_freq()*MsSpike)/1000; aFlags[1] = 'S'; } if(m_ConfigLog) { char aAddrStr[NETADDR_MAXSTRSIZE]; net_addr_str(&p->m_SendTo, aAddrStr, sizeof(aAddrStr), true); dbg_msg("crapnet", ">> %08d %s (%d) %s", p->m_ID, aAddrStr, p->m_DataSize, aFlags); } mem_free(p); } } thread_sleep(1); } } int main(int argc, char **argv) // ignore_convention { NETADDR Addr = {NETTYPE_IPV4, {127,0,0,1},8303}; dbg_logger_stdout(); Run(8302, Addr); return 0; } ================================================ FILE: src/tools/dilate.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <base/system.h> #include <base/math.h> #include <engine/external/pnglite/pnglite.h> typedef struct { unsigned char r, g, b, a; } CPixel; static void Dilate(int w, int h, CPixel *pSrc, CPixel *pDest) { int ix, iy; const int xo[] = {0, -1, 1, 0}; const int yo[] = {-1, 0, 0, 1}; int m = 0; for(int y = 0; y < h; y++) { for(int x = 0; x < w; x++, m++) { pDest[m] = pSrc[m]; if(pSrc[m].a) continue; for(int c = 0; c < 4; c++) { ix = clamp(x + xo[c], 0, w-1); iy = clamp(y + yo[c], 0, h-1); int k = iy*w+ix; if(pSrc[k].a) { pDest[m] = pSrc[k]; pDest[m].a = 255; break; } } } } } static void CopyAlpha(int w, int h, CPixel *pSrc, CPixel *pDest) { int m = 0; for(int y = 0; y < h; y++) for(int x = 0; x < w; x++, m++) pDest[m].a = pSrc[m].a; } int DilateFile(const char *pFileName) { png_t Png; CPixel *pBuffer[3] = {0,0,0}; png_init(0, 0); png_open_file(&Png, pFileName); if(Png.color_type != PNG_TRUECOLOR_ALPHA) { dbg_msg("dilate", "%s: not an RGBA image", pFileName); return 1; } pBuffer[0] = (CPixel*)mem_alloc(Png.width*Png.height*sizeof(CPixel), 1); pBuffer[1] = (CPixel*)mem_alloc(Png.width*Png.height*sizeof(CPixel), 1); pBuffer[2] = (CPixel*)mem_alloc(Png.width*Png.height*sizeof(CPixel), 1); png_get_data(&Png, (unsigned char *)pBuffer[0]); png_close_file(&Png); int w = Png.width; int h = Png.height; Dilate(w, h, pBuffer[0], pBuffer[1]); for(int i = 0; i < 5; i++) { Dilate(w, h, pBuffer[1], pBuffer[2]); Dilate(w, h, pBuffer[2], pBuffer[1]); } CopyAlpha(w, h, pBuffer[0], pBuffer[1]); // save here png_open_file_write(&Png, pFileName); png_set_data(&Png, w, h, 8, PNG_TRUECOLOR_ALPHA, (unsigned char *)pBuffer[1]); png_close_file(&Png); return 0; } int main(int argc, const char **argv) { dbg_logger_stdout(); if(argc == 1) { dbg_msg("Usage", "%s FILE1 [ FILE2... ]", argv[0]); return -1; } for(int i = 1; i < argc; i++) DilateFile(argv[i]); return 0; } ================================================ FILE: src/tools/fake_server.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <stdlib.h> //rand #include <base/system.h> #include <engine/shared/config.h> #include <engine/shared/network.h> #include <mastersrv/mastersrv.h> CNetServer *pNet; int Progression = 50; int GameType = 0; int Flags = 0; const char *pVersion = "trunk"; const char *pMap = "somemap"; const char *pServerName = "unnamed server"; NETADDR aMasterServers[16] = {{0,{0},0}}; int NumMasters = 0; const char *PlayerNames[16] = {0}; int PlayerScores[16] = {0}; int NumPlayers = 0; int MaxPlayers = 0; char aInfoMsg[1024]; int aInfoMsgSize; static void SendHeartBeats() { static unsigned char aData[sizeof(SERVERBROWSE_HEARTBEAT) + 2]; CNetChunk Packet; mem_copy(aData, SERVERBROWSE_HEARTBEAT, sizeof(SERVERBROWSE_HEARTBEAT)); Packet.m_ClientID = -1; Packet.m_Flags = NETSENDFLAG_CONNLESS; Packet.m_DataSize = sizeof(SERVERBROWSE_HEARTBEAT) + 2; Packet.m_pData = &aData; /* supply the set port that the master can use if it has problems */ aData[sizeof(SERVERBROWSE_HEARTBEAT)] = 0; aData[sizeof(SERVERBROWSE_HEARTBEAT)+1] = 0; for(int i = 0; i < NumMasters; i++) { Packet.m_Address = aMasterServers[i]; pNet->Send(&Packet); } } static void WriteStr(const char *pStr) { int l = str_length(pStr)+1; mem_copy(&aInfoMsg[aInfoMsgSize], pStr, l); aInfoMsgSize += l; } static void WriteInt(int i) { char aBuf[64]; str_format(aBuf, sizeof(aBuf), "%d", i); WriteStr(aBuf); } static void BuildInfoMsg() { aInfoMsgSize = sizeof(SERVERBROWSE_INFO); mem_copy(aInfoMsg, SERVERBROWSE_INFO, aInfoMsgSize); WriteInt(-1); WriteStr(pVersion); WriteStr(pServerName); WriteStr(pMap); WriteInt(GameType); WriteInt(Flags); WriteInt(Progression); WriteInt(NumPlayers); WriteInt(MaxPlayers); for(int i = 0; i < NumPlayers; i++) { WriteStr(PlayerNames[i]); WriteInt(PlayerScores[i]); } } static void SendServerInfo(NETADDR *pAddr) { CNetChunk p; p.m_ClientID = -1; p.m_Address = *pAddr; p.m_Flags = NETSENDFLAG_CONNLESS; p.m_DataSize = aInfoMsgSize; p.m_pData = aInfoMsg; pNet->Send(&p); } static void SendFWCheckResponse(NETADDR *pAddr) { CNetChunk p; p.m_ClientID = -1; p.m_Address = *pAddr; p.m_Flags = NETSENDFLAG_CONNLESS; p.m_DataSize = sizeof(SERVERBROWSE_FWRESPONSE); p.m_pData = SERVERBROWSE_FWRESPONSE; pNet->Send(&p); } static int Run() { int64 NextHeartBeat = 0; NETADDR BindAddr = {NETTYPE_IPV4, {0},0}; if(!pNet->Open(BindAddr, 0, 0, 0, 0)) return 0; while(1) { CNetChunk p; pNet->Update(); while(pNet->Recv(&p)) { if(p.m_ClientID == -1) { if(p.m_DataSize == sizeof(SERVERBROWSE_GETINFO) && mem_comp(p.m_pData, SERVERBROWSE_GETINFO, sizeof(SERVERBROWSE_GETINFO)) == 0) { SendServerInfo(&p.m_Address); } else if(p.m_DataSize == sizeof(SERVERBROWSE_FWCHECK) && mem_comp(p.m_pData, SERVERBROWSE_FWCHECK, sizeof(SERVERBROWSE_FWCHECK)) == 0) { SendFWCheckResponse(&p.m_Address); } } } /* send heartbeats if needed */ if(NextHeartBeat < time_get()) { NextHeartBeat = time_get()+time_freq()*(15+(rand()%15)); SendHeartBeats(); } thread_sleep(100); } } int main(int argc, char **argv) { pNet = new CNetServer; while(argc) { // ? /*if(str_comp(*argv, "-m") == 0) { argc--; argv++; net_host_lookup(*argv, &aMasterServers[NumMasters], NETTYPE_IPV4); argc--; argv++; aMasterServers[NumMasters].port = str_toint(*argv); NumMasters++; } else */if(str_comp(*argv, "-p") == 0) { argc--; argv++; PlayerNames[NumPlayers++] = *argv; argc--; argv++; PlayerScores[NumPlayers] = str_toint(*argv); } else if(str_comp(*argv, "-a") == 0) { argc--; argv++; pMap = *argv; } else if(str_comp(*argv, "-x") == 0) { argc--; argv++; MaxPlayers = str_toint(*argv); } else if(str_comp(*argv, "-t") == 0) { argc--; argv++; GameType = str_toint(*argv); } else if(str_comp(*argv, "-g") == 0) { argc--; argv++; Progression = str_toint(*argv); } else if(str_comp(*argv, "-f") == 0) { argc--; argv++; Flags = str_toint(*argv); } else if(str_comp(*argv, "-n") == 0) { argc--; argv++; pServerName = *argv; } argc--; argv++; } BuildInfoMsg(); int RunReturn = Run(); delete pNet; return RunReturn; } ================================================ FILE: src/tools/map_resave.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <base/system.h> #include <engine/shared/datafile.h> #include <engine/storage.h> int main(int argc, const char **argv) { IStorage *pStorage = CreateStorage("Teeworlds", IStorage::STORAGETYPE_BASIC, argc, argv); int Index, ID = 0, Type = 0, Size; void *pPtr; char aFileName[1024]; CDataFileReader DataFile; CDataFileWriter df; if(!pStorage || argc != 3) return -1; str_format(aFileName, sizeof(aFileName), "%s", argv[2]); if(!DataFile.Open(pStorage, argv[1], IStorage::TYPE_ALL)) return -1; if(!df.Open(pStorage, aFileName)) return -1; // add all items for(Index = 0; Index < DataFile.NumItems(); Index++) { pPtr = DataFile.GetItem(Index, &Type, &ID); Size = DataFile.GetItemSize(Index); df.AddItem(Type, ID, Size, pPtr); } // add all data for(Index = 0; Index < DataFile.NumData(); Index++) { pPtr = DataFile.GetData(Index); Size = DataFile.GetDataSize(Index); df.AddData(Size, pPtr); } DataFile.Close(); df.Finish(); return 0; } ================================================ FILE: src/tools/map_version.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <base/math.h> #include <base/system.h> #include <engine/kernel.h> #include <engine/map.h> #include <engine/storage.h> static IOHANDLE s_File = 0; static IStorage *s_pStorage = 0; static IEngineMap *s_pEngineMap = 0; int MaplistCallback(const char *pName, int IsDir, int DirType, void *pUser) { int l = str_length(pName); if(l < 4 || IsDir || str_comp(pName+l-4, ".map") != 0) return 0; char aBuf[128]; str_format(aBuf, sizeof(aBuf), "maps/%s", pName); if(!s_pEngineMap->Load(aBuf)) return 0; unsigned MapCrc = s_pEngineMap->Crc(); s_pEngineMap->Unload(); IOHANDLE MapFile = s_pStorage->OpenFile(aBuf, IOFLAG_READ, DirType); unsigned MapSize = io_length(MapFile); io_close(MapFile); char aMapName[8]; str_copy(aMapName, pName, min((int)sizeof(aMapName),l-3)); str_format(aBuf, sizeof(aBuf), "\t{\"%s\", {0x%02x, 0x%02x, 0x%02x, 0x%02x}, {0x%02x, 0x%02x, 0x%02x, 0x%02x}},\n", aMapName, (MapCrc>>24)&0xff, (MapCrc>>16)&0xff, (MapCrc>>8)&0xff, MapCrc&0xff, (MapSize>>24)&0xff, (MapSize>>16)&0xff, (MapSize>>8)&0xff, MapSize&0xff); io_write(s_File, aBuf, str_length(aBuf)); return 0; } int main(int argc, const char **argv) // ignore_convention { IKernel *pKernel = IKernel::Create(); s_pStorage = CreateStorage("Teeworlds", IStorage::STORAGETYPE_BASIC, argc, argv); s_pEngineMap = CreateEngineMap(); bool RegisterFail = !pKernel->RegisterInterface(s_pStorage); RegisterFail |= !pKernel->RegisterInterface(s_pEngineMap); if(RegisterFail) return -1; s_File = s_pStorage->OpenFile("map_version.txt", IOFLAG_WRITE, 1); if(s_File) { io_write(s_File, "static CMapVersion s_aMapVersionList[] = {\n", str_length("static CMapVersion s_aMapVersionList[] = {\n")); s_pStorage->ListDirectory(1, "maps", MaplistCallback, 0); io_write(s_File, "};\n", str_length("};\n")); io_close(s_File); } return 0; } ================================================ FILE: src/tools/packetgen.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <base/system.h> enum { NUM_SOCKETS = 64 }; void Run(NETADDR Dest) { NETSOCKET aSockets[NUM_SOCKETS]; for(int i = 0; i < NUM_SOCKETS; i++) { NETADDR BindAddr = {NETTYPE_IPV4, {0}, 0}; aSockets[i] = net_udp_create(BindAddr); } while(1) { unsigned char aData[1024]; int Size = 0; int SocketToUse = 0; io_read(io_stdin(), &Size, 2); io_read(io_stdin(), &SocketToUse, 1); Size %= 256; SocketToUse %= NUM_SOCKETS; io_read(io_stdin(), aData, Size); net_udp_send(aSockets[SocketToUse], &Dest, aData, Size); } } int main(int argc, char **argv) { NETADDR Dest = {NETTYPE_IPV4, {127,0,0,1}, 8303}; Run(Dest); return 0; } ================================================ FILE: src/tools/tileset_borderop.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <base/math.h> #include <base/system.h> #include <engine/external/pnglite/pnglite.h> enum { OP_ADD=0, OP_FIX, OP_REM, OP_SET }; typedef struct { unsigned char r, g, b, a; } CPixel; void TilesetBorderAdd(int w, int h, CPixel *pSrc, CPixel *pDest) { int TileW = w/16; int TileH = h/16; for(int tx = 0; tx < 16; tx++) { for(int ty = 0; ty < 16; ty++) { for(int x = 0; x < TileW + 4; x++) { for(int y = 0; y < TileH + 4; y++) { int SourceX = tx * TileW + clamp(x - 2, 0, TileW - 1); int SourceY = ty * TileH + clamp(y - 2, 0, TileH - 1); int DestX = tx * (TileW + 4) + x; int DestY = ty * (TileH + 4) + y; int SourceI = SourceY * w + SourceX; int DestI = DestY * (w + 16 * 4) + DestX; pDest[DestI] = pSrc[SourceI]; } } } } } CPixel Sample(int x, int y, int w, int h, CPixel *pData, int Pitch, float u, float v) { x = x + (int)(w*u); y = y + (int)(h*v); return pData[y*Pitch+x]; } void TilesetBorderFix(int w, int h, CPixel *pSrc, CPixel *pDest) { int TileW = w/16; int TileH = h/16; mem_zero(pDest, sizeof(CPixel)*w*h); for(int ty = 0; ty < 16; ty++) { for(int tx = 0; tx < 16; tx++) { for(int y = 0; y < TileH-2; y++) { for(int x = 0; x < TileW-2; x++) { float u = 0.5f/TileW + x/(float)(TileW-2); float v = 0.5f/TileH + y/(float)(TileH-2); int k = (ty*TileH+1+y)*w + tx*TileW+x+1; pDest[k] = Sample(tx*TileW, ty*TileH, TileW, TileH, pSrc, w, u, v); if(x == 0) pDest[k-1] = pDest[k]; if(x == TileW-2-1) pDest[k+1] = pDest[k]; if(y == 0) pDest[k-w] = pDest[k]; if(y == TileH-2-1) pDest[k+w] = pDest[k]; if(x == 0 && y == 0) pDest[k-w-1] = pDest[k]; if(x == TileW-2-1 && y == 0) pDest[k-w+1] = pDest[k]; if(x == 0 && y == TileH-2-1) pDest[k+w-1] = pDest[k]; if(x == TileW-2-1 && y == TileH-2-1) pDest[k+w+1] = pDest[k]; } } } } } void TilesetBorderRem(int w, int h, CPixel *pSrc, CPixel *pDest) { int TileW = w/16; int TileH = h/16; for(int tx = 0; tx < 16; tx++) { for(int ty = 0; ty < 16; ty++) { for(int x = 0; x < TileW - 4; x++) { for(int y = 0; y < TileH - 4; y++) { int SourceX = tx * TileW + x + 2; int SourceY = ty * TileH + y + 2; int DestX = tx * (TileW - 4) + x; int DestY = ty * (TileH - 4) + y; int SourceI = SourceY * w + SourceX; int DestI = DestY * (w - 16 * 4) + DestX; pDest[DestI] = pSrc[SourceI]; } } } } } void TilesetBorderSet(int w, int h, CPixel *pSrc, CPixel *pDest) { int TileW = w/16; int TileH = h/16; for(int tx = 0; tx < 16; tx++) { for(int ty = 0; ty < 16; ty++) { for(int x = 0; x < TileW; x++) { for(int y = 0; y < TileH; y++) { #define TILE_INDEX(tx_, ty_, x_, y_) (((ty_) * TileH + (y_)) * w + (tx_) * TileW + (x_)) pDest[TILE_INDEX(tx, ty, x, y)] = pSrc[TILE_INDEX(tx, ty, clamp(x, 2, TileW - 3), clamp(y, 2, TileH - 3))]; } } } } } void ProcessFile(const char *pFileName, int WidthMod, int HeightMod, int Operator) { png_t Png; CPixel *pBuffer[2] = {0,0}; png_init(0, 0); png_open_file(&Png, pFileName); if(Png.color_type != PNG_TRUECOLOR_ALPHA) { dbg_msg("tileset_borderop", "%s: not an RGBA image", pFileName); return; } int w = Png.width; int h = Png.height; pBuffer[0] = (CPixel*)mem_alloc(w*h*sizeof(CPixel), 1); pBuffer[1] = (CPixel*)mem_alloc((w+WidthMod)*(h+HeightMod)*sizeof(CPixel), 1); png_get_data(&Png, (unsigned char *)pBuffer[0]); png_close_file(&Png); switch(Operator) { case OP_ADD: TilesetBorderAdd(w, h, pBuffer[0], pBuffer[1]); break; case OP_FIX: TilesetBorderFix(w, h, pBuffer[0], pBuffer[1]); break; case OP_REM: TilesetBorderRem(w, h, pBuffer[0], pBuffer[1]); break; case OP_SET: TilesetBorderSet(w, h, pBuffer[0], pBuffer[1]); break; } // save here png_open_file_write(&Png, pFileName); png_set_data(&Png, w + WidthMod, h + HeightMod, 8, PNG_TRUECOLOR_ALPHA, (unsigned char *)pBuffer[1]); png_close_file(&Png); } int main(int argc, const char **argv) { dbg_logger_stdout(); if(argc < 3) { dbg_msg("Usage", "%s OPERATION FILE1 [ FILE2... ]", argv[0]); dbg_msg("Usage", "OPERATION - ADD, FIX, REM, SET"); return -1; } int WidthMod, HeightMod, Operator; if(str_comp_nocase(argv[1], "ADD") == 0) { WidthMod = 16*4; HeightMod = 16*4; Operator = OP_ADD; } else if(str_comp_nocase(argv[1], "FIX") == 0) { WidthMod = 0; HeightMod = 0; Operator = OP_FIX; } else if(str_comp_nocase(argv[1], "REM") == 0) { WidthMod = -16*4; HeightMod = -16*4; Operator = OP_REM; } else if(str_comp_nocase(argv[1], "SET") == 0) { WidthMod = 0; HeightMod = 0; Operator = OP_SET; } else { dbg_msg("Usage", "invalid OPERATION (ADD, FIX, REM, SET)"); return -1; } for(int i = 2; i < argc; i++) ProcessFile(argv[i], WidthMod, HeightMod, Operator); return 0; } ================================================ FILE: src/versionsrv/mapversions.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef VERSIONSRV_MAPVERSIONS_H #define VERSIONSRV_MAPVERSIONS_H static CMapVersion s_aMapVersionList[] = { {"ctf1", {0x06, 0xb5, 0xf1, 0x17}, {0x00, 0x00, 0x12, 0x38}}, {"ctf2", {0x27, 0xbc, 0x5e, 0xac}, {0x00, 0x00, 0x64, 0x1a}}, {"ctf3", {0xa3, 0x73, 0x9d, 0x41}, {0x00, 0x00, 0x17, 0x0f}}, {"ctf4", {0xbe, 0x7c, 0x4d, 0xb9}, {0x00, 0x00, 0x2e, 0xfe}}, {"ctf5", {0xd9, 0x21, 0x29, 0xa0}, {0x00, 0x00, 0x2f, 0x4c}}, {"ctf6", {0x28, 0xc8, 0x43, 0x51}, {0x00, 0x00, 0x69, 0x2f}}, {"ctf7", {0x1d, 0x35, 0x98, 0x72}, {0x00, 0x00, 0x15, 0x87}}, {"dm1", {0xf2, 0x15, 0x9e, 0x6e}, {0x00, 0x00, 0x16, 0xad}}, {"dm2", {0x71, 0x83, 0x98, 0x78}, {0x00, 0x00, 0x21, 0xdf}}, {"dm6", {0x47, 0x4d, 0xa2, 0x35}, {0x00, 0x00, 0x1e, 0x95}}, {"dm7", {0x42, 0x6d, 0xa1, 0x67}, {0x00, 0x00, 0x27, 0x2a}}, {"dm8", {0x2f, 0x74, 0xd9, 0x18}, {0x00, 0x00, 0xa1, 0xa1}}, {"dm9", {0x42, 0xd4, 0x77, 0x7e}, {0x00, 0x00, 0x20, 0x11}}, }; static const int s_NumMapVersionItems = sizeof(s_aMapVersionList)/sizeof(CMapVersion); #endif ================================================ FILE: src/versionsrv/versionsrv.cpp ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <base/system.h> #include <engine/shared/network.h> #include <game/version.h> #include "versionsrv.h" #include "mapversions.h" enum { MAX_MAPS_PER_PACKET=48, MAX_PACKETS=16, MAX_MAPS=MAX_MAPS_PER_PACKET*MAX_PACKETS, }; struct CPacketData { int m_Size; struct { unsigned char m_aHeader[sizeof(VERSIONSRV_MAPLIST)]; CMapVersion m_aMaplist[MAX_MAPS_PER_PACKET]; } m_Data; }; CPacketData m_aPackets[MAX_PACKETS]; static int m_NumPackets = 0; static CNetClient g_NetOp; // main void BuildPackets() { CMapVersion *pCurrent = &s_aMapVersionList[0]; int ServersLeft = s_NumMapVersionItems; m_NumPackets = 0; while(ServersLeft && m_NumPackets < MAX_PACKETS) { int Chunk = ServersLeft; if(Chunk > MAX_MAPS_PER_PACKET) Chunk = MAX_MAPS_PER_PACKET; ServersLeft -= Chunk; // copy header mem_copy(m_aPackets[m_NumPackets].m_Data.m_aHeader, VERSIONSRV_MAPLIST, sizeof(VERSIONSRV_MAPLIST)); // copy map versions for(int i = 0; i < Chunk; i++) { m_aPackets[m_NumPackets].m_Data.m_aMaplist[i] = *pCurrent; pCurrent++; } m_aPackets[m_NumPackets].m_Size = sizeof(VERSIONSRV_MAPLIST) + sizeof(CMapVersion)*Chunk; m_NumPackets++; } } void SendVer(NETADDR *pAddr) { CNetChunk p; unsigned char aData[sizeof(VERSIONSRV_VERSION) + sizeof(GAME_RELEASE_VERSION)]; mem_copy(aData, VERSIONSRV_VERSION, sizeof(VERSIONSRV_VERSION)); mem_copy(aData + sizeof(VERSIONSRV_VERSION), GAME_RELEASE_VERSION, sizeof(GAME_RELEASE_VERSION)); p.m_ClientID = -1; p.m_Address = *pAddr; p.m_Flags = NETSENDFLAG_CONNLESS; p.m_pData = aData; p.m_DataSize = sizeof(aData); g_NetOp.Send(&p); } int main(int argc, char **argv) // ignore_convention { NETADDR BindAddr; dbg_logger_stdout(); net_init(); mem_zero(&BindAddr, sizeof(BindAddr)); BindAddr.type = NETTYPE_ALL; BindAddr.port = VERSIONSRV_PORT; if(!g_NetOp.Open(BindAddr, 0)) { dbg_msg("mastersrv", "couldn't start network"); return -1; } BuildPackets(); dbg_msg("versionsrv", "started"); while(1) { g_NetOp.Update(); // process packets CNetChunk Packet; while(g_NetOp.Recv(&Packet)) { if(Packet.m_DataSize == sizeof(VERSIONSRV_GETVERSION) && mem_comp(Packet.m_pData, VERSIONSRV_GETVERSION, sizeof(VERSIONSRV_GETVERSION)) == 0) { SendVer(&Packet.m_Address); } if(Packet.m_DataSize == sizeof(VERSIONSRV_GETMAPLIST) && mem_comp(Packet.m_pData, VERSIONSRV_GETMAPLIST, sizeof(VERSIONSRV_GETMAPLIST)) == 0) { CNetChunk p; p.m_ClientID = -1; p.m_Address = Packet.m_Address; p.m_Flags = NETSENDFLAG_CONNLESS; for(int i = 0; i < m_NumPackets; i++) { p.m_DataSize = m_aPackets[i].m_Size; p.m_pData = &m_aPackets[i].m_Data; g_NetOp.Send(&p); } } } // be nice to the CPU thread_sleep(1); } return 0; } ================================================ FILE: src/versionsrv/versionsrv.h ================================================ /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef VERSIONSRV_VERSIONSRV_H #define VERSIONSRV_VERSIONSRV_H static const int VERSIONSRV_PORT = 8302; struct CMapVersion { char m_aName[8]; unsigned char m_aCrc[4]; unsigned char m_aSize[4]; }; static const unsigned char VERSIONSRV_GETVERSION[] = {255, 255, 255, 255, 'v', 'e', 'r', 'g'}; static const unsigned char VERSIONSRV_VERSION[] = {255, 255, 255, 255, 'v', 'e', 'r', 's'}; static const unsigned char VERSIONSRV_GETMAPLIST[] = {255, 255, 255, 255, 'v', 'm', 'l', 'g'}; static const unsigned char VERSIONSRV_MAPLIST[] = {255, 255, 255, 255, 'v', 'm', 'l', 's'}; #endif ================================================ FILE: storage.cfg ================================================ #### # This specifies where and in which order Teeworlds looks # for its data (sounds, skins, ...). The search goes top # down which means the first path has the highest priority. # Furthermore the top entry also defines the save path where # all data (settings.cfg, screenshots, ...) are stored. # There are 3 special paths available: # $USERDIR # - ~/.appname on UNIX based systems # - ~/Library/Applications Support/appname on Mac OS X # - %APPDATA%/Appname on Windows based systems # $DATADIR # - the 'data' directory which is part of an official # release # $CURRENTDIR # - current working directory # # # The default file has the following entries: # add_path $USERDIR # add_path $DATADIR # add_path $CURRENTDIR # # A customised one could look like this: # add_path user # add_path mods/mymod #### add_path $USERDIR add_path $DATADIR add_path $CURRENTDIR